Mon Mar 12 2012 21:20:11

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 - 2006, 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: 354210 $")
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 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 cc_handle_publish_error(struct sip_pvt *pvt, const int resp, struct sip_request *req, struct sip_epa_entry *epa_entry);
00879 
00880 static void cc_epa_destructor(void *data)
00881 {
00882    struct sip_epa_entry *epa_entry = data;
00883    struct cc_epa_entry *cc_entry = epa_entry->instance_data;
00884    ast_free(cc_entry);
00885 }
00886 
00887 static const struct epa_static_data cc_epa_static_data  = {
00888    .event = CALL_COMPLETION,
00889    .name = "call-completion",
00890    .handle_error = cc_handle_publish_error,
00891    .destructor = cc_epa_destructor,
00892 };
00893 
00894 static const struct epa_static_data *find_static_data(const char * const event_package)
00895 {
00896    const struct epa_backend *backend = NULL;
00897 
00898    AST_LIST_LOCK(&epa_static_data_list);
00899    AST_LIST_TRAVERSE(&epa_static_data_list, backend, next) {
00900       if (!strcmp(backend->static_data->name, event_package)) {
00901          break;
00902       }
00903    }
00904    AST_LIST_UNLOCK(&epa_static_data_list);
00905    return backend ? backend->static_data : NULL;
00906 }
00907 
00908 static struct sip_epa_entry *create_epa_entry (const char * const event_package, const char * const destination)
00909 {
00910    struct sip_epa_entry *epa_entry;
00911    const struct epa_static_data *static_data;
00912 
00913    if (!(static_data = find_static_data(event_package))) {
00914       return NULL;
00915    }
00916 
00917    if (!(epa_entry = ao2_t_alloc(sizeof(*epa_entry), static_data->destructor, "Allocate new EPA entry"))) {
00918       return NULL;
00919    }
00920 
00921    epa_entry->static_data = static_data;
00922    ast_copy_string(epa_entry->destination, destination, sizeof(epa_entry->destination));
00923    return epa_entry;
00924 }
00925 
00926 /*!
00927  * Used to create new entity IDs by ESCs.
00928  */
00929 static int esc_etag_counter;
00930 static const int DEFAULT_PUBLISH_EXPIRES = 3600;
00931 
00932 #ifdef HAVE_LIBXML2
00933 static int cc_esc_publish_handler(struct sip_pvt *pvt, struct sip_request *req, struct event_state_compositor *esc, struct sip_esc_entry *esc_entry);
00934 
00935 static const struct sip_esc_publish_callbacks cc_esc_publish_callbacks = {
00936    .initial_handler = cc_esc_publish_handler,
00937    .modify_handler = cc_esc_publish_handler,
00938 };
00939 #endif
00940 
00941 /*!
00942  * \brief The Event State Compositors
00943  *
00944  * An Event State Compositor is an entity which
00945  * accepts PUBLISH requests and acts appropriately
00946  * based on these requests.
00947  *
00948  * The actual event_state_compositor structure is simply
00949  * an ao2_container of sip_esc_entrys. When an incoming
00950  * PUBLISH is received, we can match the appropriate sip_esc_entry
00951  * using the entity ID of the incoming PUBLISH.
00952  */
00953 static struct event_state_compositor {
00954    enum subscriptiontype event;
00955    const char * name;
00956    const struct sip_esc_publish_callbacks *callbacks;
00957    struct ao2_container *compositor;
00958 } event_state_compositors [] = {
00959 #ifdef HAVE_LIBXML2
00960    {CALL_COMPLETION, "call-completion", &cc_esc_publish_callbacks},
00961 #endif
00962 };
00963 
00964 static const int ESC_MAX_BUCKETS = 37;
00965 
00966 static void esc_entry_destructor(void *obj)
00967 {
00968    struct sip_esc_entry *esc_entry = obj;
00969    if (esc_entry->sched_id > -1) {
00970       AST_SCHED_DEL(sched, esc_entry->sched_id);
00971    }
00972 }
00973 
00974 static int esc_hash_fn(const void *obj, const int flags)
00975 {
00976    const struct sip_esc_entry *entry = obj;
00977    return ast_str_hash(entry->entity_tag);
00978 }
00979 
00980 static int esc_cmp_fn(void *obj, void *arg, int flags)
00981 {
00982    struct sip_esc_entry *entry1 = obj;
00983    struct sip_esc_entry *entry2 = arg;
00984 
00985    return (!strcmp(entry1->entity_tag, entry2->entity_tag)) ? (CMP_MATCH | CMP_STOP) : 0;
00986 }
00987 
00988 static struct event_state_compositor *get_esc(const char * const event_package) {
00989    int i;
00990    for (i = 0; i < ARRAY_LEN(event_state_compositors); i++) {
00991       if (!strcasecmp(event_package, event_state_compositors[i].name)) {
00992          return &event_state_compositors[i];
00993       }
00994    }
00995    return NULL;
00996 }
00997 
00998 static struct sip_esc_entry *get_esc_entry(const char * entity_tag, struct event_state_compositor *esc) {
00999    struct sip_esc_entry *entry;
01000    struct sip_esc_entry finder;
01001 
01002    ast_copy_string(finder.entity_tag, entity_tag, sizeof(finder.entity_tag));
01003 
01004    entry = ao2_find(esc->compositor, &finder, OBJ_POINTER);
01005 
01006    return entry;
01007 }
01008 
01009 static int publish_expire(const void *data)
01010 {
01011    struct sip_esc_entry *esc_entry = (struct sip_esc_entry *) data;
01012    struct event_state_compositor *esc = get_esc(esc_entry->event);
01013 
01014    ast_assert(esc != NULL);
01015 
01016    ao2_unlink(esc->compositor, esc_entry);
01017    ao2_ref(esc_entry, -1);
01018    return 0;
01019 }
01020 
01021 static void create_new_sip_etag(struct sip_esc_entry *esc_entry, int is_linked)
01022 {
01023    int new_etag = ast_atomic_fetchadd_int(&esc_etag_counter, +1);
01024    struct event_state_compositor *esc = get_esc(esc_entry->event);
01025 
01026    ast_assert(esc != NULL);
01027    if (is_linked) {
01028       ao2_unlink(esc->compositor, esc_entry);
01029    }
01030    snprintf(esc_entry->entity_tag, sizeof(esc_entry->entity_tag), "%d", new_etag);
01031    ao2_link(esc->compositor, esc_entry);
01032 }
01033 
01034 static struct sip_esc_entry *create_esc_entry(struct event_state_compositor *esc, struct sip_request *req, const int expires)
01035 {
01036    struct sip_esc_entry *esc_entry;
01037    int expires_ms;
01038 
01039    if (!(esc_entry = ao2_alloc(sizeof(*esc_entry), esc_entry_destructor))) {
01040       return NULL;
01041    }
01042 
01043    esc_entry->event = esc->name;
01044 
01045    expires_ms = expires * 1000;
01046    /* Bump refcount for scheduler */
01047    ao2_ref(esc_entry, +1);
01048    esc_entry->sched_id = ast_sched_add(sched, expires_ms, publish_expire, esc_entry);
01049 
01050    /* Note: This links the esc_entry into the ESC properly */
01051    create_new_sip_etag(esc_entry, 0);
01052 
01053    return esc_entry;
01054 }
01055 
01056 static int initialize_escs(void)
01057 {
01058    int i, res = 0;
01059    for (i = 0; i < ARRAY_LEN(event_state_compositors); i++) {
01060       if (!((event_state_compositors[i].compositor) =
01061                ao2_container_alloc(ESC_MAX_BUCKETS, esc_hash_fn, esc_cmp_fn))) {
01062          res = -1;
01063       }
01064    }
01065    return res;
01066 }
01067 
01068 static void destroy_escs(void)
01069 {
01070    int i;
01071    for (i = 0; i < ARRAY_LEN(event_state_compositors); i++) {
01072       ao2_ref(event_state_compositors[i].compositor, -1);
01073    }
01074 }
01075 
01076 /*!
01077  * \details
01078  * This container holds the dialogs that will be destroyed immediately.
01079  */
01080 struct ao2_container *dialogs_to_destroy;
01081 
01082 /*! \brief
01083  * Here we implement the container for dialogs (sip_pvt), defining
01084  * generic wrapper functions to ease the transition from the current
01085  * implementation (a single linked list) to a different container.
01086  * In addition to a reference to the container, we need functions to lock/unlock
01087  * the container and individual items, and functions to add/remove
01088  * references to the individual items.
01089  */
01090 static struct ao2_container *dialogs;
01091 #define sip_pvt_lock(x) ao2_lock(x)
01092 #define sip_pvt_trylock(x) ao2_trylock(x)
01093 #define sip_pvt_unlock(x) ao2_unlock(x)
01094 
01095 /*! \brief  The table of TCP threads */
01096 static struct ao2_container *threadt;
01097 
01098 /*! \brief  The peer list: Users, Peers and Friends */
01099 static struct ao2_container *peers;
01100 static struct ao2_container *peers_by_ip;
01101 
01102 /*! \brief  The register list: Other SIP proxies we register with and receive calls from */
01103 static struct ast_register_list {
01104    ASTOBJ_CONTAINER_COMPONENTS(struct sip_registry);
01105    int recheck;
01106 } regl;
01107 
01108 /*! \brief  The MWI subscription list */
01109 static struct ast_subscription_mwi_list {
01110    ASTOBJ_CONTAINER_COMPONENTS(struct sip_subscription_mwi);
01111 } submwil;
01112 static int temp_pvt_init(void *);
01113 static void temp_pvt_cleanup(void *);
01114 
01115 /*! \brief A per-thread temporary pvt structure */
01116 AST_THREADSTORAGE_CUSTOM(ts_temp_pvt, temp_pvt_init, temp_pvt_cleanup);
01117 
01118 /*! \brief Authentication container for realm authentication */
01119 static struct sip_auth_container *authl = NULL;
01120 /*! \brief Global authentication container protection while adjusting the references. */
01121 AST_MUTEX_DEFINE_STATIC(authl_lock);
01122 
01123 /* --- Sockets and networking --------------*/
01124 
01125 /*! \brief Main socket for UDP SIP communication.
01126  *
01127  * sipsock is shared between the SIP manager thread (which handles reload
01128  * requests), the udp io handler (sipsock_read()) and the user routines that
01129  * issue udp writes (using __sip_xmit()).
01130  * The socket is -1 only when opening fails (this is a permanent condition),
01131  * or when we are handling a reload() that changes its address (this is
01132  * a transient situation during which we might have a harmless race, see
01133  * below). Because the conditions for the race to be possible are extremely
01134  * rare, we don't want to pay the cost of locking on every I/O.
01135  * Rather, we remember that when the race may occur, communication is
01136  * bound to fail anyways, so we just live with this event and let
01137  * the protocol handle this above us.
01138  */
01139 static int sipsock  = -1;
01140 
01141 struct ast_sockaddr bindaddr; /*!< UDP: The address we bind to */
01142 
01143 /*! \brief our (internal) default address/port to put in SIP/SDP messages
01144  *  internip is initialized picking a suitable address from one of the
01145  * interfaces, and the same port number we bind to. It is used as the
01146  * default address/port in SIP messages, and as the default address
01147  * (but not port) in SDP messages.
01148  */
01149 static struct ast_sockaddr internip;
01150 
01151 /*! \brief our external IP address/port for SIP sessions.
01152  * externaddr.sin_addr is only set when we know we might be behind
01153  * a NAT, and this is done using a variety of (mutually exclusive)
01154  * ways from the config file:
01155  *
01156  * + with "externaddr = host[:port]" we specify the address/port explicitly.
01157  *   The address is looked up only once when (re)loading the config file;
01158  *
01159  * + with "externhost = host[:port]" we do a similar thing, but the
01160  *   hostname is stored in externhost, and the hostname->IP mapping
01161  *   is refreshed every 'externrefresh' seconds;
01162  *
01163  * Other variables (externhost, externexpire, externrefresh) are used
01164  * to support the above functions.
01165  */
01166 static struct ast_sockaddr externaddr;      /*!< External IP address if we are behind NAT */
01167 static struct ast_sockaddr media_address; /*!< External RTP IP address if we are behind NAT */
01168 
01169 static char externhost[MAXHOSTNAMELEN];   /*!< External host name */
01170 static time_t externexpire;             /*!< Expiration counter for re-resolving external host name in dynamic DNS */
01171 static int externrefresh = 10;          /*!< Refresh timer for DNS-based external address (dyndns) */
01172 static uint16_t externtcpport;          /*!< external tcp port */ 
01173 static uint16_t externtlsport;          /*!< external tls port */
01174 
01175 /*! \brief  List of local networks
01176  * We store "localnet" addresses from the config file into an access list,
01177  * marked as 'DENY', so the call to ast_apply_ha() will return
01178  * AST_SENSE_DENY for 'local' addresses, and AST_SENSE_ALLOW for 'non local'
01179  * (i.e. presumably public) addresses.
01180  */
01181 static struct ast_ha *localaddr;    /*!< List of local networks, on the same side of NAT as this Asterisk */
01182 
01183 static int ourport_tcp;             /*!< The port used for TCP connections */
01184 static int ourport_tls;             /*!< The port used for TCP/TLS connections */
01185 static struct ast_sockaddr debugaddr;
01186 
01187 static struct ast_config *notify_types = NULL;    /*!< The list of manual NOTIFY types we know how to send */
01188 
01189 /*! some list management macros. */
01190 
01191 #define UNLINK(element, head, prev) do {  \
01192    if (prev)            \
01193       (prev)->next = (element)->next;  \
01194    else              \
01195       (head) = (element)->next;  \
01196    } while (0)
01197 
01198 /*---------------------------- Forward declarations of functions in chan_sip.c */
01199 /* Note: This is added to help splitting up chan_sip.c into several files
01200    in coming releases. */
01201 
01202 /*--- PBX interface functions */
01203 static struct ast_channel *sip_request_call(const char *type, format_t format, const struct ast_channel *requestor, void *data, int *cause);
01204 static int sip_devicestate(void *data);
01205 static int sip_sendtext(struct ast_channel *ast, const char *text);
01206 static int sip_call(struct ast_channel *ast, char *dest, int timeout);
01207 static int sip_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen);
01208 static int sip_hangup(struct ast_channel *ast);
01209 static int sip_answer(struct ast_channel *ast);
01210 static struct ast_frame *sip_read(struct ast_channel *ast);
01211 static int sip_write(struct ast_channel *ast, struct ast_frame *frame);
01212 static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen);
01213 static int sip_transfer(struct ast_channel *ast, const char *dest);
01214 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
01215 static int sip_senddigit_begin(struct ast_channel *ast, char digit);
01216 static int sip_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration);
01217 static int sip_setoption(struct ast_channel *chan, int option, void *data, int datalen);
01218 static int sip_queryoption(struct ast_channel *chan, int option, void *data, int *datalen);
01219 static const char *sip_get_callid(struct ast_channel *chan);
01220 
01221 static int handle_request_do(struct sip_request *req, struct ast_sockaddr *addr);
01222 static int sip_standard_port(enum sip_transport type, int port);
01223 static int sip_prepare_socket(struct sip_pvt *p);
01224 static int get_address_family_filter(const struct ast_sockaddr *addr);
01225 
01226 /*--- Transmitting responses and requests */
01227 static int sipsock_read(int *id, int fd, short events, void *ignore);
01228 static int __sip_xmit(struct sip_pvt *p, struct ast_str *data);
01229 static int __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, struct ast_str *data, int fatal, int sipmethod);
01230 static void add_cc_call_info_to_response(struct sip_pvt *p, struct sip_request *resp);
01231 static int __transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
01232 static int retrans_pkt(const void *data);
01233 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);
01234 static int transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req);
01235 static int transmit_response_reliable(struct sip_pvt *p, const char *msg, const struct sip_request *req);
01236 static int transmit_response_with_date(struct sip_pvt *p, const char *msg, const struct sip_request *req);
01237 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);
01238 static int transmit_response_with_unsupported(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *unsupported);
01239 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);
01240 static int transmit_provisional_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, int with_sdp);
01241 static int transmit_response_with_allow(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
01242 static void transmit_fake_auth_response(struct sip_pvt *p, int sipmethod, struct sip_request *req, enum xmittype reliable);
01243 static int transmit_request(struct sip_pvt *p, int sipmethod, int inc, enum xmittype reliable, int newbranch);
01244 static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, int seqno, enum xmittype reliable, int newbranch);
01245 static int transmit_publish(struct sip_epa_entry *epa_entry, enum sip_publish_type publish_type, const char * const explicit_uri);
01246 static int transmit_invite(struct sip_pvt *p, int sipmethod, int sdp, int init, const char * const explicit_uri);
01247 static int transmit_reinvite_with_sdp(struct sip_pvt *p, int t38version, int oldsdp);
01248 static int transmit_info_with_aoc(struct sip_pvt *p, struct ast_aoc_decoded *decoded);
01249 static int transmit_info_with_digit(struct sip_pvt *p, const char digit, unsigned int duration);
01250 static int transmit_info_with_vidupdate(struct sip_pvt *p);
01251 static int transmit_message_with_text(struct sip_pvt *p, const char *text);
01252 static int transmit_refer(struct sip_pvt *p, const char *dest);
01253 static int transmit_notify_with_mwi(struct sip_pvt *p, int newmsgs, int oldmsgs, const char *vmexten);
01254 static int transmit_notify_with_sipfrag(struct sip_pvt *p, int cseq, char *message, int terminate);
01255 static int transmit_cc_notify(struct ast_cc_agent *agent, struct sip_pvt *subscription, enum sip_cc_notify_state state);
01256 static int transmit_register(struct sip_registry *r, int sipmethod, const char *auth, const char *authheader);
01257 static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno);
01258 static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno);
01259 static void copy_request(struct sip_request *dst, const struct sip_request *src);
01260 static void receive_message(struct sip_pvt *p, struct sip_request *req);
01261 static void parse_moved_contact(struct sip_pvt *p, struct sip_request *req, char **name, char **number, int set_call_forward);
01262 static int sip_send_mwi_to_peer(struct sip_peer *peer, int cache_only);
01263 
01264 /* Misc dialog routines */
01265 static int __sip_autodestruct(const void *data);
01266 static void *registry_unref(struct sip_registry *reg, char *tag);
01267 static int update_call_counter(struct sip_pvt *fup, int event);
01268 static int auto_congest(const void *arg);
01269 static struct sip_pvt *find_call(struct sip_request *req, struct ast_sockaddr *addr, const int intended_method);
01270 static void free_old_route(struct sip_route *route);
01271 static void list_route(struct sip_route *route);
01272 static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards);
01273 static enum check_auth_result register_verify(struct sip_pvt *p, struct ast_sockaddr *addr,
01274                      struct sip_request *req, const char *uri);
01275 static struct sip_pvt *get_sip_pvt_byid_locked(const char *callid, const char *totag, const char *fromtag);
01276 static void check_pendings(struct sip_pvt *p);
01277 static void *sip_park_thread(void *stuff);
01278 static int sip_park(struct ast_channel *chan1, struct ast_channel *chan2, struct sip_request *req, int seqno, const char *park_exten, const char *park_context);
01279 
01280 static void *sip_pickup_thread(void *stuff);
01281 static int sip_pickup(struct ast_channel *chan);
01282 
01283 static int sip_sipredirect(struct sip_pvt *p, const char *dest);
01284 static int is_method_allowed(unsigned int *allowed_methods, enum sipmethod method);
01285 
01286 /*--- Codec handling / SDP */
01287 static void try_suggested_sip_codec(struct sip_pvt *p);
01288 static const char *get_sdp_iterate(int* start, struct sip_request *req, const char *name);
01289 static char get_sdp_line(int *start, int stop, struct sip_request *req, const char **value);
01290 static int find_sdp(struct sip_request *req);
01291 static int process_sdp(struct sip_pvt *p, struct sip_request *req, int t38action);
01292 static int process_sdp_o(const char *o, struct sip_pvt *p);
01293 static int process_sdp_c(const char *c, struct ast_sockaddr *addr);
01294 static int process_sdp_a_sendonly(const char *a, int *sendonly);
01295 static int process_sdp_a_audio(const char *a, struct sip_pvt *p, struct ast_rtp_codecs *newaudiortp, int *last_rtpmap_codec);
01296 static int process_sdp_a_video(const char *a, struct sip_pvt *p, struct ast_rtp_codecs *newvideortp, int *last_rtpmap_codec);
01297 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);
01298 static int process_sdp_a_image(const char *a, struct sip_pvt *p);
01299 static void add_codec_to_sdp(const struct sip_pvt *p, format_t codec,
01300               struct ast_str **m_buf, struct ast_str **a_buf,
01301               int debug, int *min_packet_size);
01302 static void add_noncodec_to_sdp(const struct sip_pvt *p, int format,
01303             struct ast_str **m_buf, struct ast_str **a_buf,
01304             int debug);
01305 static enum sip_result add_sdp(struct sip_request *resp, struct sip_pvt *p, int oldsdp, int add_audio, int add_t38);
01306 static void do_setnat(struct sip_pvt *p);
01307 static void stop_media_flows(struct sip_pvt *p);
01308 
01309 /*--- Authentication stuff */
01310 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod, char *digest, int digest_len);
01311 static int build_reply_digest(struct sip_pvt *p, int method, char *digest, int digest_len);
01312 static enum check_auth_result check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
01313                 const char *secret, const char *md5secret, int sipmethod,
01314                 const char *uri, enum xmittype reliable, int ignore);
01315 static enum check_auth_result check_user_full(struct sip_pvt *p, struct sip_request *req,
01316                      int sipmethod, const char *uri, enum xmittype reliable,
01317                      struct ast_sockaddr *addr, struct sip_peer **authpeer);
01318 static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, const char *uri, enum xmittype reliable, struct ast_sockaddr *addr);
01319 
01320 /*--- Domain handling */
01321 static int check_sip_domain(const char *domain, char *context, size_t len); /* Check if domain is one of our local domains */
01322 static int add_sip_domain(const char *domain, const enum domain_mode mode, const char *context);
01323 static void clear_sip_domains(void);
01324 
01325 /*--- SIP realm authentication */
01326 static void add_realm_authentication(struct sip_auth_container **credentials, const char *configuration, int lineno);
01327 static struct sip_auth *find_realm_authentication(struct sip_auth_container *credentials, const char *realm);
01328 
01329 /*--- Misc functions */
01330 static void check_rtp_timeout(struct sip_pvt *dialog, time_t t);
01331 static int reload_config(enum channelreloadreason reason);
01332 static void add_diversion_header(struct sip_request *req, struct sip_pvt *pvt);
01333 static int expire_register(const void *data);
01334 static void *do_monitor(void *data);
01335 static int restart_monitor(void);
01336 static void peer_mailboxes_to_str(struct ast_str **mailbox_str, struct sip_peer *peer);
01337 static struct ast_variable *copy_vars(struct ast_variable *src);
01338 static int dialog_find_multiple(void *obj, void *arg, int flags);
01339 static struct ast_channel *sip_pvt_lock_full(struct sip_pvt *pvt);
01340 /* static int sip_addrcmp(char *name, struct sockaddr_in *sin);   Support for peer matching */
01341 static int sip_refer_allocate(struct sip_pvt *p);
01342 static int sip_notify_allocate(struct sip_pvt *p);
01343 static void ast_quiet_chan(struct ast_channel *chan);
01344 static int attempt_transfer(struct sip_dual *transferer, struct sip_dual *target);
01345 static int do_magic_pickup(struct ast_channel *channel, const char *extension, const char *context);
01346 
01347 /*--- Device monitoring and Device/extension state/event handling */
01348 static int cb_extensionstate(char *context, char* exten, int state, void *data);
01349 static int sip_devicestate(void *data);
01350 static int sip_poke_noanswer(const void *data);
01351 static int sip_poke_peer(struct sip_peer *peer, int force);
01352 static void sip_poke_all_peers(void);
01353 static void sip_peer_hold(struct sip_pvt *p, int hold);
01354 static void mwi_event_cb(const struct ast_event *, void *);
01355 static void network_change_event_cb(const struct ast_event *, void *);
01356 
01357 /*--- Applications, functions, CLI and manager command helpers */
01358 static const char *sip_nat_mode(const struct sip_pvt *p);
01359 static char *sip_show_inuse(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01360 static char *transfermode2str(enum transfermodes mode) attribute_const;
01361 static int peer_status(struct sip_peer *peer, char *status, int statuslen);
01362 static char *sip_show_sched(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01363 static char * _sip_show_peers(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char *argv[]);
01364 static char *sip_show_peers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01365 static char *sip_show_objects(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01366 static void  print_group(int fd, ast_group_t group, int crlf);
01367 static const char *dtmfmode2str(int mode) attribute_const;
01368 static int str2dtmfmode(const char *str) attribute_unused;
01369 static const char *insecure2str(int mode) attribute_const;
01370 static const char *allowoverlap2str(int mode) attribute_const;
01371 static void cleanup_stale_contexts(char *new, char *old);
01372 static void print_codec_to_cli(int fd, struct ast_codec_pref *pref);
01373 static const char *domain_mode_to_text(const enum domain_mode mode);
01374 static char *sip_show_domains(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01375 static char *_sip_show_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[]);
01376 static char *sip_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01377 static char *_sip_qualify_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[]);
01378 static char *sip_qualify_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01379 static char *sip_show_registry(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01380 static char *sip_unregister(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01381 static char *sip_show_settings(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01382 static char *sip_show_mwi(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01383 static const char *subscription_type2str(enum subscriptiontype subtype) attribute_pure;
01384 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
01385 static char *complete_sip_peer(const char *word, int state, int flags2);
01386 static char *complete_sip_registered_peer(const char *word, int state, int flags2);
01387 static char *complete_sip_show_history(const char *line, const char *word, int pos, int state);
01388 static char *complete_sip_show_peer(const char *line, const char *word, int pos, int state);
01389 static char *complete_sip_unregister(const char *line, const char *word, int pos, int state);
01390 static char *complete_sipnotify(const char *line, const char *word, int pos, int state);
01391 static char *sip_show_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01392 static char *sip_show_channelstats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01393 static char *sip_show_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01394 static char *sip_do_debug_ip(int fd, const char *arg);
01395 static char *sip_do_debug_peer(int fd, const char *arg);
01396 static char *sip_do_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01397 static char *sip_cli_notify(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01398 static char *sip_set_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01399 static int sip_dtmfmode(struct ast_channel *chan, const char *data);
01400 static int sip_addheader(struct ast_channel *chan, const char *data);
01401 static int sip_do_reload(enum channelreloadreason reason);
01402 static char *sip_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01403 static int ast_sockaddr_resolve_first_af(struct ast_sockaddr *addr,
01404                   const char *name, int flag, int family);
01405 static int ast_sockaddr_resolve_first(struct ast_sockaddr *addr,
01406                   const char *name, int flag);
01407 
01408 /*--- Debugging
01409    Functions for enabling debug per IP or fully, or enabling history logging for
01410    a SIP dialog
01411 */
01412 static void sip_dump_history(struct sip_pvt *dialog); /* Dump history to debuglog at end of dialog, before destroying data */
01413 static inline int sip_debug_test_addr(const struct ast_sockaddr *addr);
01414 static inline int sip_debug_test_pvt(struct sip_pvt *p);
01415 static void append_history_full(struct sip_pvt *p, const char *fmt, ...);
01416 static void sip_dump_history(struct sip_pvt *dialog);
01417 
01418 /*--- Device object handling */
01419 static struct sip_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime, int devstate_only);
01420 static int update_call_counter(struct sip_pvt *fup, int event);
01421 static void sip_destroy_peer(struct sip_peer *peer);
01422 static void sip_destroy_peer_fn(void *peer);
01423 static void set_peer_defaults(struct sip_peer *peer);
01424 static struct sip_peer *temp_peer(const char *name);
01425 static void register_peer_exten(struct sip_peer *peer, int onoff);
01426 static struct sip_peer *find_peer(const char *peer, struct ast_sockaddr *addr, int realtime, int forcenamematch, int devstate_only, int transport);
01427 static int sip_poke_peer_s(const void *data);
01428 static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *p, struct sip_request *req);
01429 static void reg_source_db(struct sip_peer *peer);
01430 static void destroy_association(struct sip_peer *peer);
01431 static void set_insecure_flags(struct ast_flags *flags, const char *value, int lineno);
01432 static int handle_common_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v);
01433 static void set_socket_transport(struct sip_socket *socket, int transport);
01434 
01435 /* Realtime device support */
01436 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);
01437 static void update_peer(struct sip_peer *p, int expire);
01438 static struct ast_variable *get_insecure_variable_from_config(struct ast_config *config);
01439 static const char *get_name_from_variable(const struct ast_variable *var);
01440 static struct sip_peer *realtime_peer(const char *peername, struct ast_sockaddr *sin, int devstate_only, int which_objects);
01441 static char *sip_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01442 
01443 /*--- Internal UA client handling (outbound registrations) */
01444 static void ast_sip_ouraddrfor(const struct ast_sockaddr *them, struct ast_sockaddr *us, struct sip_pvt *p);
01445 static void sip_registry_destroy(struct sip_registry *reg);
01446 static int sip_register(const char *value, int lineno);
01447 static const char *regstate2str(enum sipregistrystate regstate) attribute_const;
01448 static int sip_reregister(const void *data);
01449 static int __sip_do_register(struct sip_registry *r);
01450 static int sip_reg_timeout(const void *data);
01451 static void sip_send_all_registers(void);
01452 static int sip_reinvite_retry(const void *data);
01453 
01454 /*--- Parsing SIP requests and responses */
01455 static void append_date(struct sip_request *req);  /* Append date to SIP packet */
01456 static int determine_firstline_parts(struct sip_request *req);
01457 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
01458 static const char *gettag(const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize);
01459 static int find_sip_method(const char *msg);
01460 static unsigned int parse_allowed_methods(struct sip_request *req);
01461 static unsigned int set_pvt_allowed_methods(struct sip_pvt *pvt, struct sip_request *req);
01462 static int parse_request(struct sip_request *req);
01463 static const char *get_header(const struct sip_request *req, const char *name);
01464 static const char *referstatus2str(enum referstatus rstatus) attribute_pure;
01465 static int method_match(enum sipmethod id, const char *name);
01466 static void parse_copy(struct sip_request *dst, const struct sip_request *src);
01467 static const char *find_alias(const char *name, const char *_default);
01468 static const char *__get_header(const struct sip_request *req, const char *name, int *start);
01469 static void lws2sws(struct ast_str *msgbuf);
01470 static void extract_uri(struct sip_pvt *p, struct sip_request *req);
01471 static char *remove_uri_parameters(char *uri);
01472 static int get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req);
01473 static int get_also_info(struct sip_pvt *p, struct sip_request *oreq);
01474 static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req);
01475 static int set_address_from_contact(struct sip_pvt *pvt);
01476 static void check_via(struct sip_pvt *p, struct sip_request *req);
01477 static int get_rpid(struct sip_pvt *p, struct sip_request *oreq);
01478 static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq, char **name, char **number, int *reason);
01479 static enum sip_get_dest_result get_destination(struct sip_pvt *p, struct sip_request *oreq, int *cc_recall_core_id);
01480 static int get_msg_text(char *buf, int len, struct sip_request *req);
01481 static int transmit_state_notify(struct sip_pvt *p, int state, int full, int timeout);
01482 static void update_connectedline(struct sip_pvt *p, const void *data, size_t datalen);
01483 static void update_redirecting(struct sip_pvt *p, const void *data, size_t datalen);
01484 static int get_domain(const char *str, char *domain, int len);
01485 static void get_realm(struct sip_pvt *p, const struct sip_request *req);
01486 
01487 /*-- TCP connection handling ---*/
01488 static void *_sip_tcp_helper_thread(struct sip_pvt *pvt, struct ast_tcptls_session_instance *tcptls_session);
01489 static void *sip_tcp_worker_fn(void *);
01490 
01491 /*--- Constructing requests and responses */
01492 static void initialize_initreq(struct sip_pvt *p, struct sip_request *req);
01493 static int init_req(struct sip_request *req, int sipmethod, const char *recip);
01494 static void deinit_req(struct sip_request *req);
01495 static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, int seqno, int newbranch);
01496 static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, const char * const explicit_uri);
01497 static int init_resp(struct sip_request *resp, const char *msg);
01498 static inline int resp_needs_contact(const char *msg, enum sipmethod method);
01499 static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req);
01500 static const struct ast_sockaddr *sip_real_dst(const struct sip_pvt *p);
01501 static void build_via(struct sip_pvt *p);
01502 static int create_addr_from_peer(struct sip_pvt *r, struct sip_peer *peer);
01503 static int create_addr(struct sip_pvt *dialog, const char *opeer, struct ast_sockaddr *addr, int newdialog, struct ast_sockaddr *remote_address);
01504 static char *generate_random_string(char *buf, size_t size);
01505 static void build_callid_pvt(struct sip_pvt *pvt);
01506 static void change_callid_pvt(struct sip_pvt *pvt, const char *callid);
01507 static void build_callid_registry(struct sip_registry *reg, const struct ast_sockaddr *ourip, const char *fromdomain);
01508 static void make_our_tag(char *tagbuf, size_t len);
01509 static int add_header(struct sip_request *req, const char *var, const char *value);
01510 static int add_header_max_forwards(struct sip_pvt *dialog, struct sip_request *req);
01511 static int add_content(struct sip_request *req, const char *line);
01512 static int finalize_content(struct sip_request *req);
01513 static int add_text(struct sip_request *req, const char *text);
01514 static int add_digit(struct sip_request *req, char digit, unsigned int duration, int mode);
01515 static int add_rpid(struct sip_request *req, struct sip_pvt *p);
01516 static int add_vidupdate(struct sip_request *req);
01517 static void add_route(struct sip_request *req, struct sip_route *route);
01518 static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field);
01519 static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field);
01520 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field);
01521 static void set_destination(struct sip_pvt *p, char *uri);
01522 static void append_date(struct sip_request *req);
01523 static void build_contact(struct sip_pvt *p);
01524 
01525 /*------Request handling functions */
01526 static int handle_incoming(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, int *recount, int *nounlock);
01527 static int handle_request_update(struct sip_pvt *p, struct sip_request *req);
01528 static int handle_request_invite(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, struct ast_sockaddr *addr, int *recount, const char *e, int *nounlock);
01529 static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, int *nounlock);
01530 static int handle_request_bye(struct sip_pvt *p, struct sip_request *req);
01531 static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *sin, const char *e);
01532 static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req);
01533 static int handle_request_message(struct sip_pvt *p, struct sip_request *req);
01534 static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, int seqno, const char *e);
01535 static void handle_request_info(struct sip_pvt *p, struct sip_request *req);
01536 static int handle_request_options(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, const char *e);
01537 static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, struct ast_sockaddr *addr, int *nounlock);
01538 static int handle_request_notify(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, int seqno, const char *e);
01539 static int local_attended_transfer(struct sip_pvt *transferer, struct sip_dual *current, struct sip_request *req, int seqno, int *nounlock);
01540 
01541 /*------Response handling functions */
01542 static void handle_response_publish(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno);
01543 static void handle_response_invite(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno);
01544 static void handle_response_notify(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno);
01545 static void handle_response_refer(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno);
01546 static void handle_response_subscribe(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno);
01547 static int handle_response_register(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno);
01548 static void handle_response(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno);
01549 
01550 /*------ SRTP Support -------- */
01551 static int setup_srtp(struct sip_srtp **srtp);
01552 static int process_crypto(struct sip_pvt *p, struct ast_rtp_instance *rtp, struct sip_srtp **srtp, const char *a);
01553 
01554 /*------ T38 Support --------- */
01555 static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans);
01556 static struct ast_udptl *sip_get_udptl_peer(struct ast_channel *chan);
01557 static int sip_set_udptl_peer(struct ast_channel *chan, struct ast_udptl *udptl);
01558 static void change_t38_state(struct sip_pvt *p, int state);
01559 
01560 /*------ Session-Timers functions --------- */
01561 static void proc_422_rsp(struct sip_pvt *p, struct sip_request *rsp);
01562 static int  proc_session_timer(const void *vp);
01563 static void stop_session_timer(struct sip_pvt *p);
01564 static void start_session_timer(struct sip_pvt *p);
01565 static void restart_session_timer(struct sip_pvt *p);
01566 static const char *strefresher2str(enum st_refresher r);
01567 static int parse_session_expires(const char *p_hdrval, int *const p_interval, enum st_refresher *const p_ref);
01568 static int parse_minse(const char *p_hdrval, int *const p_interval);
01569 static int st_get_se(struct sip_pvt *, int max);
01570 static enum st_refresher st_get_refresher(struct sip_pvt *);
01571 static enum st_mode st_get_mode(struct sip_pvt *, int no_cached);
01572 static struct sip_st_dlg* sip_st_alloc(struct sip_pvt *const p);
01573 
01574 /*------- RTP Glue functions -------- */
01575 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);
01576 
01577 /*!--- SIP MWI Subscription support */
01578 static int sip_subscribe_mwi(const char *value, int lineno);
01579 static void sip_subscribe_mwi_destroy(struct sip_subscription_mwi *mwi);
01580 static void sip_send_all_mwi_subscriptions(void);
01581 static int sip_subscribe_mwi_do(const void *data);
01582 static int __sip_subscribe_mwi_do(struct sip_subscription_mwi *mwi);
01583 
01584 /*! \brief Definition of this channel for PBX channel registration */
01585 const struct ast_channel_tech sip_tech = {
01586    .type = "SIP",
01587    .description = "Session Initiation Protocol (SIP)",
01588    .capabilities = AST_FORMAT_AUDIO_MASK, /* all audio formats */
01589    .properties = AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER,
01590    .requester = sip_request_call,         /* called with chan unlocked */
01591    .devicestate = sip_devicestate,        /* called with chan unlocked (not chan-specific) */
01592    .call = sip_call,       /* called with chan locked */
01593    .send_html = sip_sendhtml,
01594    .hangup = sip_hangup,         /* called with chan locked */
01595    .answer = sip_answer,         /* called with chan locked */
01596    .read = sip_read,       /* called with chan locked */
01597    .write = sip_write,        /* called with chan locked */
01598    .write_video = sip_write,     /* called with chan locked */
01599    .write_text = sip_write,
01600    .indicate = sip_indicate,     /* called with chan locked */
01601    .transfer = sip_transfer,     /* called with chan locked */
01602    .fixup = sip_fixup,        /* called with chan locked */
01603    .send_digit_begin = sip_senddigit_begin,  /* called with chan unlocked */
01604    .send_digit_end = sip_senddigit_end,
01605    .bridge = ast_rtp_instance_bridge,        /* XXX chan unlocked ? */
01606    .early_bridge = ast_rtp_instance_early_bridge,
01607    .send_text = sip_sendtext,    /* called with chan locked */
01608    .func_channel_read = sip_acf_channel_read,
01609    .setoption = sip_setoption,
01610    .queryoption = sip_queryoption,
01611    .get_pvt_uniqueid = sip_get_callid,
01612 };
01613 
01614 /*! \brief This version of the sip channel tech has no send_digit_begin
01615  * callback so that the core knows that the channel does not want
01616  * DTMF BEGIN frames.
01617  * The struct is initialized just before registering the channel driver,
01618  * and is for use with channels using SIP INFO DTMF.
01619  */
01620 struct ast_channel_tech sip_tech_info;
01621 
01622 static int sip_cc_agent_init(struct ast_cc_agent *agent, struct ast_channel *chan);
01623 static int sip_cc_agent_start_offer_timer(struct ast_cc_agent *agent);
01624 static int sip_cc_agent_stop_offer_timer(struct ast_cc_agent *agent);
01625 static void sip_cc_agent_respond(struct ast_cc_agent *agent, enum ast_cc_agent_response_reason reason);
01626 static int sip_cc_agent_status_request(struct ast_cc_agent *agent);
01627 static int sip_cc_agent_start_monitoring(struct ast_cc_agent *agent);
01628 static int sip_cc_agent_recall(struct ast_cc_agent *agent);
01629 static void sip_cc_agent_destructor(struct ast_cc_agent *agent);
01630 
01631 static struct ast_cc_agent_callbacks sip_cc_agent_callbacks = {
01632    .type = "SIP",
01633    .init = sip_cc_agent_init,
01634    .start_offer_timer = sip_cc_agent_start_offer_timer,
01635    .stop_offer_timer = sip_cc_agent_stop_offer_timer,
01636    .respond = sip_cc_agent_respond,
01637    .status_request = sip_cc_agent_status_request,
01638    .start_monitoring = sip_cc_agent_start_monitoring,
01639    .callee_available = sip_cc_agent_recall,
01640    .destructor = sip_cc_agent_destructor,
01641 };
01642 
01643 static int find_by_notify_uri_helper(void *obj, void *arg, int flags)
01644 {
01645    struct ast_cc_agent *agent = obj;
01646    struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01647    const char *uri = arg;
01648 
01649    return !sip_uri_cmp(agent_pvt->notify_uri, uri) ? CMP_MATCH | CMP_STOP : 0;
01650 }
01651 
01652 static struct ast_cc_agent *find_sip_cc_agent_by_notify_uri(const char * const uri)
01653 {
01654    struct ast_cc_agent *agent = ast_cc_agent_callback(0, find_by_notify_uri_helper, (char *)uri, "SIP");
01655    return agent;
01656 }
01657 
01658 static int find_by_subscribe_uri_helper(void *obj, void *arg, int flags)
01659 {
01660    struct ast_cc_agent *agent = obj;
01661    struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01662    const char *uri = arg;
01663 
01664    return !sip_uri_cmp(agent_pvt->subscribe_uri, uri) ? CMP_MATCH | CMP_STOP : 0;
01665 }
01666 
01667 static struct ast_cc_agent *find_sip_cc_agent_by_subscribe_uri(const char * const uri)
01668 {
01669    struct ast_cc_agent *agent = ast_cc_agent_callback(0, find_by_subscribe_uri_helper, (char *)uri, "SIP");
01670    return agent;
01671 }
01672 
01673 static int find_by_callid_helper(void *obj, void *arg, int flags)
01674 {
01675    struct ast_cc_agent *agent = obj;
01676    struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01677    struct sip_pvt *call_pvt = arg;
01678 
01679    return !strcmp(agent_pvt->original_callid, call_pvt->callid) ? CMP_MATCH | CMP_STOP : 0;
01680 }
01681 
01682 static struct ast_cc_agent *find_sip_cc_agent_by_original_callid(struct sip_pvt *pvt)
01683 {
01684    struct ast_cc_agent *agent = ast_cc_agent_callback(0, find_by_callid_helper, pvt, "SIP");
01685    return agent;
01686 }
01687 
01688 static int sip_cc_agent_init(struct ast_cc_agent *agent, struct ast_channel *chan)
01689 {
01690    struct sip_cc_agent_pvt *agent_pvt = ast_calloc(1, sizeof(*agent_pvt));
01691    struct sip_pvt *call_pvt = chan->tech_pvt;
01692 
01693    if (!agent_pvt) {
01694       return -1;
01695    }
01696 
01697    ast_assert(!strcmp(chan->tech->type, "SIP"));
01698 
01699    ast_copy_string(agent_pvt->original_callid, call_pvt->callid, sizeof(agent_pvt->original_callid));
01700    ast_copy_string(agent_pvt->original_exten, call_pvt->exten, sizeof(agent_pvt->original_exten));
01701    agent_pvt->offer_timer_id = -1;
01702    agent->private_data = agent_pvt;
01703    sip_pvt_lock(call_pvt);
01704    ast_set_flag(&call_pvt->flags[0], SIP_OFFER_CC);
01705    sip_pvt_unlock(call_pvt);
01706    return 0;
01707 }
01708 
01709 static int sip_offer_timer_expire(const void *data)
01710 {
01711    struct ast_cc_agent *agent = (struct ast_cc_agent *) data;
01712    struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01713 
01714    agent_pvt->offer_timer_id = -1;
01715 
01716    return ast_cc_failed(agent->core_id, "SIP agent %s's offer timer expired", agent->device_name);
01717 }
01718 
01719 static int sip_cc_agent_start_offer_timer(struct ast_cc_agent *agent)
01720 {
01721    struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01722    int when;
01723 
01724    when = ast_get_cc_offer_timer(agent->cc_params) * 1000;
01725    agent_pvt->offer_timer_id = ast_sched_add(sched, when, sip_offer_timer_expire, agent);
01726    return 0;
01727 }
01728 
01729 static int sip_cc_agent_stop_offer_timer(struct ast_cc_agent *agent)
01730 {
01731    struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01732 
01733    AST_SCHED_DEL(sched, agent_pvt->offer_timer_id);
01734    return 0;
01735 }
01736 
01737 static void sip_cc_agent_respond(struct ast_cc_agent *agent, enum ast_cc_agent_response_reason reason)
01738 {
01739    struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01740 
01741    sip_pvt_lock(agent_pvt->subscribe_pvt);
01742    ast_set_flag(&agent_pvt->subscribe_pvt->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
01743    if (reason == AST_CC_AGENT_RESPONSE_SUCCESS || !ast_strlen_zero(agent_pvt->notify_uri)) {
01744       /* The second half of this if statement may be a bit hard to grasp,
01745        * so here's an explanation. When a subscription comes into
01746        * chan_sip, as long as it is not malformed, it will be passed
01747        * to the CC core. If the core senses an out-of-order state transition,
01748        * then the core will call this callback with the "reason" set to a
01749        * failure condition.
01750        * However, an out-of-order state transition will occur during a resubscription
01751        * for CC. In such a case, we can see that we have already generated a notify_uri
01752        * and so we can detect that this isn't a *real* failure. Rather, it is just
01753        * something the core doesn't recognize as a legitimate SIP state transition.
01754        * Thus we respond with happiness and flowers.
01755        */
01756       transmit_response(agent_pvt->subscribe_pvt, "200 OK", &agent_pvt->subscribe_pvt->initreq);
01757       transmit_cc_notify(agent, agent_pvt->subscribe_pvt, CC_QUEUED);
01758    } else {
01759       transmit_response(agent_pvt->subscribe_pvt, "500 Internal Error", &agent_pvt->subscribe_pvt->initreq);
01760    }
01761    sip_pvt_unlock(agent_pvt->subscribe_pvt);
01762    agent_pvt->is_available = TRUE;
01763 }
01764 
01765 static int sip_cc_agent_status_request(struct ast_cc_agent *agent)
01766 {
01767    struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01768    enum ast_device_state state = agent_pvt->is_available ? AST_DEVICE_NOT_INUSE : AST_DEVICE_INUSE;
01769    return ast_cc_agent_status_response(agent->core_id, state);
01770 }
01771 
01772 static int sip_cc_agent_start_monitoring(struct ast_cc_agent *agent)
01773 {
01774    /* To start monitoring just means to wait for an incoming PUBLISH
01775     * to tell us that the caller has become available again. No special
01776     * action is needed
01777     */
01778    return 0;
01779 }
01780 
01781 static int sip_cc_agent_recall(struct ast_cc_agent *agent)
01782 {
01783    struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01784    /* If we have received a PUBLISH beforehand stating that the caller in question
01785     * is not available, we can save ourself a bit of effort here and just report
01786     * the caller as busy
01787     */
01788    if (!agent_pvt->is_available) {
01789       return ast_cc_agent_caller_busy(agent->core_id, "Caller %s is busy, reporting to the core",
01790             agent->device_name);
01791    }
01792    /* Otherwise, we transmit a NOTIFY to the caller and await either
01793     * a PUBLISH or an INVITE
01794     */
01795    sip_pvt_lock(agent_pvt->subscribe_pvt);
01796    transmit_cc_notify(agent, agent_pvt->subscribe_pvt, CC_READY);
01797    sip_pvt_unlock(agent_pvt->subscribe_pvt);
01798    return 0;
01799 }
01800 
01801 static void sip_cc_agent_destructor(struct ast_cc_agent *agent)
01802 {
01803    struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01804 
01805    if (!agent_pvt) {
01806       /* The agent constructor probably failed. */
01807       return;
01808    }
01809 
01810    sip_cc_agent_stop_offer_timer(agent);
01811    if (agent_pvt->subscribe_pvt) {
01812       sip_pvt_lock(agent_pvt->subscribe_pvt);
01813       if (!ast_test_flag(&agent_pvt->subscribe_pvt->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED)) {
01814          /* If we haven't sent a 200 OK for the SUBSCRIBE dialog yet, then we need to send a response letting
01815           * the subscriber know something went wrong
01816           */
01817          transmit_response(agent_pvt->subscribe_pvt, "500 Internal Server Error", &agent_pvt->subscribe_pvt->initreq);
01818       }
01819       sip_pvt_unlock(agent_pvt->subscribe_pvt);
01820       agent_pvt->subscribe_pvt = dialog_unref(agent_pvt->subscribe_pvt, "SIP CC agent destructor: Remove ref to subscription");
01821    }
01822    ast_free(agent_pvt);
01823 }
01824 
01825 struct ao2_container *sip_monitor_instances;
01826 
01827 static int sip_monitor_instance_hash_fn(const void *obj, const int flags)
01828 {
01829    const struct sip_monitor_instance *monitor_instance = obj;
01830    return monitor_instance->core_id;
01831 }
01832 
01833 static int sip_monitor_instance_cmp_fn(void *obj, void *arg, int flags)
01834 {
01835    struct sip_monitor_instance *monitor_instance1 = obj;
01836    struct sip_monitor_instance *monitor_instance2 = arg;
01837 
01838    return monitor_instance1->core_id == monitor_instance2->core_id ? CMP_MATCH | CMP_STOP : 0;
01839 }
01840 
01841 static void sip_monitor_instance_destructor(void *data)
01842 {
01843    struct sip_monitor_instance *monitor_instance = data;
01844    if (monitor_instance->subscription_pvt) {
01845       sip_pvt_lock(monitor_instance->subscription_pvt);
01846       monitor_instance->subscription_pvt->expiry = 0;
01847       transmit_invite(monitor_instance->subscription_pvt, SIP_SUBSCRIBE, FALSE, 0, monitor_instance->subscribe_uri);
01848       sip_pvt_unlock(monitor_instance->subscription_pvt);
01849       dialog_unref(monitor_instance->subscription_pvt, "Unref monitor instance ref of subscription pvt");
01850    }
01851    if (monitor_instance->suspension_entry) {
01852       monitor_instance->suspension_entry->body[0] = '\0';
01853       transmit_publish(monitor_instance->suspension_entry, SIP_PUBLISH_REMOVE ,monitor_instance->notify_uri);
01854       ao2_t_ref(monitor_instance->suspension_entry, -1, "Decrementing suspension entry refcount in sip_monitor_instance_destructor");
01855    }
01856    ast_string_field_free_memory(monitor_instance);
01857 }
01858 
01859 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)
01860 {
01861    struct sip_monitor_instance *monitor_instance = ao2_alloc(sizeof(*monitor_instance), sip_monitor_instance_destructor);
01862 
01863    if (!monitor_instance) {
01864       return NULL;
01865    }
01866 
01867    if (ast_string_field_init(monitor_instance, 256)) {
01868       ao2_ref(monitor_instance, -1);
01869       return NULL;
01870    }
01871 
01872    ast_string_field_set(monitor_instance, subscribe_uri, subscribe_uri);
01873    ast_string_field_set(monitor_instance, peername, peername);
01874    ast_string_field_set(monitor_instance, device_name, device_name);
01875    monitor_instance->core_id = core_id;
01876    ao2_link(sip_monitor_instances, monitor_instance);
01877    return monitor_instance;
01878 }
01879 
01880 static int find_sip_monitor_instance_by_subscription_pvt(void *obj, void *arg, int flags)
01881 {
01882    struct sip_monitor_instance *monitor_instance = obj;
01883    return monitor_instance->subscription_pvt == arg ? CMP_MATCH | CMP_STOP : 0;
01884 }
01885 
01886 static int find_sip_monitor_instance_by_suspension_entry(void *obj, void *arg, int flags)
01887 {
01888    struct sip_monitor_instance *monitor_instance = obj;
01889    return monitor_instance->suspension_entry == arg ? CMP_MATCH | CMP_STOP : 0;
01890 }
01891 
01892 static int sip_cc_monitor_request_cc(struct ast_cc_monitor *monitor, int *available_timer_id);
01893 static int sip_cc_monitor_suspend(struct ast_cc_monitor *monitor);
01894 static int sip_cc_monitor_unsuspend(struct ast_cc_monitor *monitor);
01895 static int sip_cc_monitor_cancel_available_timer(struct ast_cc_monitor *monitor, int *sched_id);
01896 static void sip_cc_monitor_destructor(void *private_data);
01897 
01898 static struct ast_cc_monitor_callbacks sip_cc_monitor_callbacks = {
01899    .type = "SIP",
01900    .request_cc = sip_cc_monitor_request_cc,
01901    .suspend = sip_cc_monitor_suspend,
01902    .unsuspend = sip_cc_monitor_unsuspend,
01903    .cancel_available_timer = sip_cc_monitor_cancel_available_timer,
01904    .destructor = sip_cc_monitor_destructor,
01905 };
01906 
01907 static int sip_cc_monitor_request_cc(struct ast_cc_monitor *monitor, int *available_timer_id)
01908 {
01909    struct sip_monitor_instance *monitor_instance = monitor->private_data;
01910    enum ast_cc_service_type service = monitor->service_offered;
01911    int when;
01912 
01913    if (!monitor_instance) {
01914       return -1;
01915    }
01916 
01917    if (!(monitor_instance->subscription_pvt = sip_alloc(NULL, NULL, 0, SIP_SUBSCRIBE, NULL))) {
01918       return -1;
01919    }
01920 
01921    when = service == AST_CC_CCBS ? ast_get_ccbs_available_timer(monitor->interface->config_params) :
01922       ast_get_ccnr_available_timer(monitor->interface->config_params);
01923 
01924    sip_pvt_lock(monitor_instance->subscription_pvt);
01925    ast_set_flag(&monitor_instance->subscription_pvt->flags[0], SIP_OUTGOING);
01926    create_addr(monitor_instance->subscription_pvt, monitor_instance->peername, 0, 1, NULL);
01927    ast_sip_ouraddrfor(&monitor_instance->subscription_pvt->sa, &monitor_instance->subscription_pvt->ourip, monitor_instance->subscription_pvt);
01928    monitor_instance->subscription_pvt->subscribed = CALL_COMPLETION;
01929    monitor_instance->subscription_pvt->expiry = when;
01930 
01931    transmit_invite(monitor_instance->subscription_pvt, SIP_SUBSCRIBE, FALSE, 2, monitor_instance->subscribe_uri);
01932    sip_pvt_unlock(monitor_instance->subscription_pvt);
01933 
01934    ao2_t_ref(monitor, +1, "Adding a ref to the monitor for the scheduler");
01935    *available_timer_id = ast_sched_add(sched, when * 1000, ast_cc_available_timer_expire, monitor);
01936    return 0;
01937 }
01938 
01939 static int construct_pidf_body(enum sip_cc_publish_state state, char *pidf_body, size_t size, const char *presentity)
01940 {
01941    struct ast_str *body = ast_str_alloca(size);
01942    char tuple_id[32];
01943 
01944    generate_random_string(tuple_id, sizeof(tuple_id));
01945 
01946    /* We'll make this a bare-bones pidf body. In state_notify_build_xml, the PIDF
01947     * body gets a lot more extra junk that isn't necessary, so we'll leave it out here.
01948     */
01949    ast_str_append(&body, 0, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
01950    /* XXX The entity attribute is currently set to the peer name associated with the
01951     * dialog. This is because we currently only call this function for call-completion
01952     * PUBLISH bodies. In such cases, the entity is completely disregarded. For other
01953     * event packages, it may be crucial to have a proper URI as the presentity so this
01954     * should be revisited as support is expanded.
01955     */
01956    ast_str_append(&body, 0, "<presence xmlns=\"urn:ietf:params:xml:ns:pidf\" entity=\"%s\">\n", presentity);
01957    ast_str_append(&body, 0, "<tuple id=\"%s\">\n", tuple_id);
01958    ast_str_append(&body, 0, "<status><basic>%s</basic></status>\n", state == CC_OPEN ? "open" : "closed");
01959    ast_str_append(&body, 0, "</tuple>\n");
01960    ast_str_append(&body, 0, "</presence>\n");
01961    ast_copy_string(pidf_body, ast_str_buffer(body), size);
01962    return 0;
01963 }
01964 
01965 static int sip_cc_monitor_suspend(struct ast_cc_monitor *monitor)
01966 {
01967    struct sip_monitor_instance *monitor_instance = monitor->private_data;
01968    enum sip_publish_type publish_type;
01969    struct cc_epa_entry *cc_entry;
01970 
01971    if (!monitor_instance) {
01972       return -1;
01973    }
01974 
01975    if (!monitor_instance->suspension_entry) {
01976       /* We haven't yet allocated the suspension entry, so let's give it a shot */
01977       if (!(monitor_instance->suspension_entry = create_epa_entry("call-completion", monitor_instance->peername))) {
01978          ast_log(LOG_WARNING, "Unable to allocate sip EPA entry for call-completion\n");
01979          ao2_ref(monitor_instance, -1);
01980          return -1;
01981       }
01982       if (!(cc_entry = ast_calloc(1, sizeof(*cc_entry)))) {
01983          ast_log(LOG_WARNING, "Unable to allocate space for instance data of EPA entry for call-completion\n");
01984          ao2_ref(monitor_instance, -1);
01985          return -1;
01986       }
01987       cc_entry->core_id = monitor->core_id;
01988       monitor_instance->suspension_entry->instance_data = cc_entry;
01989       publish_type = SIP_PUBLISH_INITIAL;
01990    } else {
01991       publish_type = SIP_PUBLISH_MODIFY;
01992       cc_entry = monitor_instance->suspension_entry->instance_data;
01993    }
01994 
01995    cc_entry->current_state = CC_CLOSED;
01996 
01997    if (ast_strlen_zero(monitor_instance->notify_uri)) {
01998       /* If we have no set notify_uri, then what this means is that we have
01999        * not received a NOTIFY from this destination stating that he is
02000        * currently available.
02001        *
02002        * This situation can arise when the core calls the suspend callbacks
02003        * of multiple destinations. If one of the other destinations aside
02004        * from this one notified Asterisk that he is available, then there
02005        * is no reason to take any suspension action on this device. Rather,
02006        * we should return now and if we receive a NOTIFY while monitoring
02007        * is still "suspended" then we can immediately respond with the
02008        * proper PUBLISH to let this endpoint know what is going on.
02009        */
02010       return 0;
02011    }
02012    construct_pidf_body(CC_CLOSED, monitor_instance->suspension_entry->body, sizeof(monitor_instance->suspension_entry->body), monitor_instance->peername);
02013    return transmit_publish(monitor_instance->suspension_entry, publish_type, monitor_instance->notify_uri);
02014 }
02015 
02016 static int sip_cc_monitor_unsuspend(struct ast_cc_monitor *monitor)
02017 {
02018    struct sip_monitor_instance *monitor_instance = monitor->private_data;
02019    struct cc_epa_entry *cc_entry;
02020 
02021    if (!monitor_instance) {
02022       return -1;
02023    }
02024 
02025    ast_assert(monitor_instance->suspension_entry != NULL);
02026 
02027    cc_entry = monitor_instance->suspension_entry->instance_data;
02028    cc_entry->current_state = CC_OPEN;
02029    if (ast_strlen_zero(monitor_instance->notify_uri)) {
02030       /* This means we are being asked to unsuspend a call leg we never
02031        * sent a PUBLISH on. As such, there is no reason to send another
02032        * PUBLISH at this point either. We can just return instead.
02033        */
02034       return 0;
02035    }
02036    construct_pidf_body(CC_OPEN, monitor_instance->suspension_entry->body, sizeof(monitor_instance->suspension_entry->body), monitor_instance->peername);
02037    return transmit_publish(monitor_instance->suspension_entry, SIP_PUBLISH_MODIFY, monitor_instance->notify_uri);
02038 }
02039 
02040 static int sip_cc_monitor_cancel_available_timer(struct ast_cc_monitor *monitor, int *sched_id)
02041 {
02042    if (*sched_id != -1) {
02043       AST_SCHED_DEL(sched, *sched_id);
02044       ao2_t_ref(monitor, -1, "Removing scheduler's reference to the monitor");
02045    }
02046    return 0;
02047 }
02048 
02049 static void sip_cc_monitor_destructor(void *private_data)
02050 {
02051    struct sip_monitor_instance *monitor_instance = private_data;
02052    ao2_unlink(sip_monitor_instances, monitor_instance);
02053    ast_module_unref(ast_module_info->self);
02054 }
02055 
02056 static int sip_get_cc_information(struct sip_request *req, char *subscribe_uri, size_t size, enum ast_cc_service_type *service)
02057 {
02058    char *call_info = ast_strdupa(get_header(req, "Call-Info"));
02059    char *uri;
02060    char *purpose;
02061    char *service_str;
02062    static const char cc_purpose[] = "purpose=call-completion";
02063    static const int cc_purpose_len = sizeof(cc_purpose) - 1;
02064 
02065    if (ast_strlen_zero(call_info)) {
02066       /* No Call-Info present. Definitely no CC offer */
02067       return -1;
02068    }
02069 
02070    uri = strsep(&call_info, ";");
02071 
02072    while ((purpose = strsep(&call_info, ";"))) {
02073       if (!strncmp(purpose, cc_purpose, cc_purpose_len)) {
02074          break;
02075       }
02076    }
02077    if (!purpose) {
02078       /* We didn't find the appropriate purpose= parameter. Oh well */
02079       return -1;
02080    }
02081 
02082    /* Okay, call-completion has been offered. Let's figure out what type of service this is */
02083    while ((service_str = strsep(&call_info, ";"))) {
02084       if (!strncmp(service_str, "m=", 2)) {
02085          break;
02086       }
02087    }
02088    if (!service_str) {
02089       /* So they didn't offer a particular service, We'll just go with CCBS since it really
02090        * doesn't matter anyway
02091        */
02092       service_str = "BS";
02093    } else {
02094       /* We already determined that there is an "m=" so no need to check
02095        * the result of this strsep
02096        */
02097       strsep(&service_str, "=");
02098    }
02099 
02100    if ((*service = service_string_to_service_type(service_str)) == AST_CC_NONE) {
02101       /* Invalid service offered */
02102       return -1;
02103    }
02104 
02105    ast_copy_string(subscribe_uri, get_in_brackets(uri), size);
02106 
02107    return 0;
02108 }
02109 
02110 /*
02111  * \brief Determine what, if any, CC has been offered and queue a CC frame if possible
02112  *
02113  * After taking care of some formalities to be sure that this call is eligible for CC,
02114  * we first try to see if we can make use of native CC. We grab the information from
02115  * the passed-in sip_request (which is always a response to an INVITE). If we can
02116  * use native CC monitoring for the call, then so be it.
02117  *
02118  * If native cc monitoring is not possible or not supported, then we will instead attempt
02119  * to use generic monitoring. Falling back to generic from a failed attempt at using native
02120  * monitoring will only work if the monitor policy of the endpoint is "always"
02121  *
02122  * \param pvt The current dialog. Contains CC parameters for the endpoint
02123  * \param req The response to the INVITE we want to inspect
02124  * \param service The service to use if generic monitoring is to be used. For native
02125  * monitoring, we get the service from the SIP response itself
02126  */
02127 static void sip_handle_cc(struct sip_pvt *pvt, struct sip_request *req, enum ast_cc_service_type service)
02128 {
02129    enum ast_cc_monitor_policies monitor_policy = ast_get_cc_monitor_policy(pvt->cc_params);
02130    int core_id;
02131    char interface_name[AST_CHANNEL_NAME];
02132 
02133    if (monitor_policy == AST_CC_MONITOR_NEVER) {
02134       /* Don't bother, just return */
02135       return;
02136    }
02137 
02138    if ((core_id = ast_cc_get_current_core_id(pvt->owner)) == -1) {
02139       /* For some reason, CC is invalid, so don't try it! */
02140       return;
02141    }
02142 
02143    ast_channel_get_device_name(pvt->owner, interface_name, sizeof(interface_name));
02144 
02145    if (monitor_policy == AST_CC_MONITOR_ALWAYS || monitor_policy == AST_CC_MONITOR_NATIVE) {
02146       char subscribe_uri[SIPBUFSIZE];
02147       char device_name[AST_CHANNEL_NAME];
02148       enum ast_cc_service_type offered_service;
02149       struct sip_monitor_instance *monitor_instance;
02150       if (sip_get_cc_information(req, subscribe_uri, sizeof(subscribe_uri), &offered_service)) {
02151          /* If CC isn't being offered to us, or for some reason the CC offer is
02152           * not formatted correctly, then it may still be possible to use generic
02153           * call completion since the monitor policy may be "always"
02154           */
02155          goto generic;
02156       }
02157       ast_channel_get_device_name(pvt->owner, device_name, sizeof(device_name));
02158       if (!(monitor_instance = sip_monitor_instance_init(core_id, subscribe_uri, pvt->peername, device_name))) {
02159          /* Same deal. We can try using generic still */
02160          goto generic;
02161       }
02162       /* We bump the refcount of chan_sip because once we queue this frame, the CC core
02163        * will have a reference to callbacks in this module. We decrement the module
02164        * refcount once the monitor destructor is called
02165        */
02166       ast_module_ref(ast_module_info->self);
02167       ast_queue_cc_frame(pvt->owner, "SIP", pvt->dialstring, offered_service, monitor_instance);
02168       ao2_ref(monitor_instance, -1);
02169       return;
02170    }
02171 
02172 generic:
02173    if (monitor_policy == AST_CC_MONITOR_GENERIC || monitor_policy == AST_CC_MONITOR_ALWAYS) {
02174       ast_queue_cc_frame(pvt->owner, AST_CC_GENERIC_MONITOR_TYPE, interface_name, service, NULL);
02175    }
02176 }
02177 
02178 /*! \brief Working TLS connection configuration */
02179 static struct ast_tls_config sip_tls_cfg;
02180 
02181 /*! \brief Default TLS connection configuration */
02182 static struct ast_tls_config default_tls_cfg;
02183 
02184 /*! \brief The TCP server definition */
02185 static struct ast_tcptls_session_args sip_tcp_desc = {
02186    .accept_fd = -1,
02187    .master = AST_PTHREADT_NULL,
02188    .tls_cfg = NULL,
02189    .poll_timeout = -1,
02190    .name = "SIP TCP server",
02191    .accept_fn = ast_tcptls_server_root,
02192    .worker_fn = sip_tcp_worker_fn,
02193 };
02194 
02195 /*! \brief The TCP/TLS server definition */
02196 static struct ast_tcptls_session_args sip_tls_desc = {
02197    .accept_fd = -1,
02198    .master = AST_PTHREADT_NULL,
02199    .tls_cfg = &sip_tls_cfg,
02200    .poll_timeout = -1,
02201    .name = "SIP TLS server",
02202    .accept_fn = ast_tcptls_server_root,
02203    .worker_fn = sip_tcp_worker_fn,
02204 };
02205 
02206 /*! \brief Append to SIP dialog history
02207    \return Always returns 0 */
02208 #define append_history(p, event, fmt , args... )   append_history_full(p, "%-15s " fmt, event, ## args)
02209 
02210 struct sip_pvt *dialog_ref_debug(struct sip_pvt *p, char *tag, char *file, int line, const char *func)
02211 {
02212    if (p)
02213 #ifdef REF_DEBUG
02214       __ao2_ref_debug(p, 1, tag, file, line, func);
02215 #else
02216       ao2_ref(p, 1);
02217 #endif
02218    else
02219       ast_log(LOG_ERROR, "Attempt to Ref a null pointer\n");
02220    return p;
02221 }
02222 
02223 struct sip_pvt *dialog_unref_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    return NULL;
02232 }
02233 
02234 /*! \brief map from an integer value to a string.
02235  * If no match is found, return errorstring
02236  */
02237 static const char *map_x_s(const struct _map_x_s *table, int x, const char *errorstring)
02238 {
02239    const struct _map_x_s *cur;
02240 
02241    for (cur = table; cur->s; cur++)
02242       if (cur->x == x)
02243          return cur->s;
02244    return errorstring;
02245 }
02246 
02247 /*! \brief map from a string to an integer value, case insensitive.
02248  * If no match is found, return errorvalue.
02249  */
02250 static int map_s_x(const struct _map_x_s *table, const char *s, int errorvalue)
02251 {
02252    const struct _map_x_s *cur;
02253 
02254    for (cur = table; cur->s; cur++)
02255       if (!strcasecmp(cur->s, s))
02256          return cur->x;
02257    return errorvalue;
02258 }
02259 
02260 static enum AST_REDIRECTING_REASON sip_reason_str_to_code(const char *text)
02261 {
02262    enum AST_REDIRECTING_REASON ast = AST_REDIRECTING_REASON_UNKNOWN;
02263    int i;
02264 
02265    for (i = 0; i < ARRAY_LEN(sip_reason_table); ++i) {
02266       if (!strcasecmp(text, sip_reason_table[i].text)) {
02267          ast = sip_reason_table[i].code;
02268          break;
02269       }
02270    }
02271 
02272    return ast;
02273 }
02274 
02275 static const char *sip_reason_code_to_str(enum AST_REDIRECTING_REASON code)
02276 {
02277    if (code >= 0 && code < ARRAY_LEN(sip_reason_table)) {
02278       return sip_reason_table[code].text;
02279    }
02280 
02281    return "unknown";
02282 }
02283 
02284 /*!
02285  * \brief generic function for determining if a correct transport is being
02286  * used to contact a peer
02287  *
02288  * this is done as a macro so that the "tmpl" var can be passed either a
02289  * sip_request or a sip_peer
02290  */
02291 #define check_request_transport(peer, tmpl) ({ \
02292    int ret = 0; \
02293    if (peer->socket.type == tmpl->socket.type) \
02294       ; \
02295    else if (!(peer->transports & tmpl->socket.type)) {\
02296       ast_log(LOG_ERROR, \
02297          "'%s' is not a valid transport for '%s'. we only use '%s'! ending call.\n", \
02298          get_transport(tmpl->socket.type), peer->name, get_transport_list(peer->transports) \
02299          ); \
02300       ret = 1; \
02301    } else if (peer->socket.type & SIP_TRANSPORT_TLS) { \
02302       ast_log(LOG_WARNING, \
02303          "peer '%s' HAS NOT USED (OR SWITCHED TO) TLS in favor of '%s' (but this was allowed in sip.conf)!\n", \
02304          peer->name, get_transport(tmpl->socket.type) \
02305       ); \
02306    } else { \
02307       ast_debug(1, \
02308          "peer '%s' has contacted us over %s even though we prefer %s.\n", \
02309          peer->name, get_transport(tmpl->socket.type), get_transport(peer->socket.type) \
02310       ); \
02311    }\
02312    (ret); \
02313 })
02314 
02315 /*! \brief
02316  * duplicate a list of channel variables, \return the copy.
02317  */
02318 static struct ast_variable *copy_vars(struct ast_variable *src)
02319 {
02320    struct ast_variable *res = NULL, *tmp, *v = NULL;
02321 
02322    for (v = src ; v ; v = v->next) {
02323       if ((tmp = ast_variable_new(v->name, v->value, v->file))) {
02324          tmp->next = res;
02325          res = tmp;
02326       }
02327    }
02328    return res;
02329 }
02330 
02331 static void tcptls_packet_destructor(void *obj)
02332 {
02333    struct tcptls_packet *packet = obj;
02334 
02335    ast_free(packet->data);
02336 }
02337 
02338 static void sip_tcptls_client_args_destructor(void *obj)
02339 {
02340    struct ast_tcptls_session_args *args = obj;
02341    if (args->tls_cfg) {
02342       ast_free(args->tls_cfg->certfile);
02343       ast_free(args->tls_cfg->pvtfile);
02344       ast_free(args->tls_cfg->cipher);
02345       ast_free(args->tls_cfg->cafile);
02346       ast_free(args->tls_cfg->capath);
02347    }
02348    ast_free(args->tls_cfg);
02349    ast_free((char *) args->name);
02350 }
02351 
02352 static void sip_threadinfo_destructor(void *obj)
02353 {
02354    struct sip_threadinfo *th = obj;
02355    struct tcptls_packet *packet;
02356    if (th->alert_pipe[1] > -1) {
02357       close(th->alert_pipe[0]);
02358    }
02359    if (th->alert_pipe[1] > -1) {
02360       close(th->alert_pipe[1]);
02361    }
02362    th->alert_pipe[0] = th->alert_pipe[1] = -1;
02363 
02364    while ((packet = AST_LIST_REMOVE_HEAD(&th->packet_q, entry))) {
02365       ao2_t_ref(packet, -1, "thread destruction, removing packet from frame queue");
02366    }
02367 
02368    if (th->tcptls_session) {
02369       ao2_t_ref(th->tcptls_session, -1, "remove tcptls_session for sip_threadinfo object");
02370    }
02371 }
02372 
02373 /*! \brief creates a sip_threadinfo object and links it into the threadt table. */
02374 static struct sip_threadinfo *sip_threadinfo_create(struct ast_tcptls_session_instance *tcptls_session, int transport)
02375 {
02376    struct sip_threadinfo *th;
02377 
02378    if (!tcptls_session || !(th = ao2_alloc(sizeof(*th), sip_threadinfo_destructor))) {
02379       return NULL;
02380    }
02381 
02382    th->alert_pipe[0] = th->alert_pipe[1] = -1;
02383 
02384    if (pipe(th->alert_pipe) == -1) {
02385       ao2_t_ref(th, -1, "Failed to open alert pipe on sip_threadinfo");
02386       ast_log(LOG_ERROR, "Could not create sip alert pipe in tcptls thread, error %s\n", strerror(errno));
02387       return NULL;
02388    }
02389    ao2_t_ref(tcptls_session, +1, "tcptls_session ref for sip_threadinfo object");
02390    th->tcptls_session = tcptls_session;
02391    th->type = transport ? transport : (tcptls_session->ssl ? SIP_TRANSPORT_TLS: SIP_TRANSPORT_TCP);
02392    ao2_t_link(threadt, th, "Adding new tcptls helper thread");
02393    ao2_t_ref(th, -1, "Decrementing threadinfo ref from alloc, only table ref remains");
02394    return th;
02395 }
02396 
02397 /*! \brief used to indicate to a tcptls thread that data is ready to be written */
02398 static int sip_tcptls_write(struct ast_tcptls_session_instance *tcptls_session, const void *buf, size_t len)
02399 {
02400    int res = len;
02401    struct sip_threadinfo *th = NULL;
02402    struct tcptls_packet *packet = NULL;
02403    struct sip_threadinfo tmp = {
02404       .tcptls_session = tcptls_session,
02405    };
02406    enum sip_tcptls_alert alert = TCPTLS_ALERT_DATA;
02407 
02408    if (!tcptls_session) {
02409       return XMIT_ERROR;
02410    }
02411 
02412    ast_mutex_lock(&tcptls_session->lock);
02413 
02414    if ((tcptls_session->fd == -1) ||
02415       !(th = ao2_t_find(threadt, &tmp, OBJ_POINTER, "ao2_find, getting sip_threadinfo in tcp helper thread")) ||
02416       !(packet = ao2_alloc(sizeof(*packet), tcptls_packet_destructor)) ||
02417       !(packet->data = ast_str_create(len))) {
02418       goto tcptls_write_setup_error;
02419    }
02420 
02421    /* goto tcptls_write_error should _NOT_ be used beyond this point */
02422    ast_str_set(&packet->data, 0, "%s", (char *) buf);
02423    packet->len = len;
02424 
02425    /* alert tcptls thread handler that there is a packet to be sent.
02426     * must lock the thread info object to guarantee control of the
02427     * packet queue */
02428    ao2_lock(th);
02429    if (write(th->alert_pipe[1], &alert, sizeof(alert)) == -1) {
02430       ast_log(LOG_ERROR, "write() to alert pipe failed: %s\n", strerror(errno));
02431       ao2_t_ref(packet, -1, "could not write to alert pipe, remove packet");
02432       packet = NULL;
02433       res = XMIT_ERROR;
02434    } else { /* it is safe to queue the frame after issuing the alert when we hold the threadinfo lock */
02435       AST_LIST_INSERT_TAIL(&th->packet_q, packet, entry);
02436    }
02437    ao2_unlock(th);
02438 
02439    ast_mutex_unlock(&tcptls_session->lock);
02440    ao2_t_ref(th, -1, "In sip_tcptls_write, unref threadinfo object after finding it");
02441    return res;
02442 
02443 tcptls_write_setup_error:
02444    if (th) {
02445       ao2_t_ref(th, -1, "In sip_tcptls_write, unref threadinfo obj, could not create packet");
02446    }
02447    if (packet) {
02448       ao2_t_ref(packet, -1, "could not allocate packet's data");
02449    }
02450    ast_mutex_unlock(&tcptls_session->lock);
02451 
02452    return XMIT_ERROR;
02453 }
02454 
02455 /*! \brief SIP TCP connection handler */
02456 static void *sip_tcp_worker_fn(void *data)
02457 {
02458    struct ast_tcptls_session_instance *tcptls_session = data;
02459 
02460    return _sip_tcp_helper_thread(NULL, tcptls_session);
02461 }
02462 
02463 /*! \brief Check if the authtimeout has expired.
02464  * \param start the time when the session started
02465  *
02466  * \retval 0 the timeout has expired
02467  * \retval -1 error
02468  * \return the number of milliseconds until the timeout will expire
02469  */
02470 static int sip_check_authtimeout(time_t start)
02471 {
02472    int timeout;
02473    time_t now;
02474    if(time(&now) == -1) {
02475       ast_log(LOG_ERROR, "error executing time(): %s\n", strerror(errno));
02476       return -1;
02477    }
02478 
02479    timeout = (authtimeout - (now - start)) * 1000;
02480    if (timeout < 0) {
02481       /* we have timed out */
02482       return 0;
02483    }
02484 
02485    return timeout;
02486 }
02487 
02488 /*! \brief SIP TCP thread management function
02489    This function reads from the socket, parses the packet into a request
02490 */
02491 static void *_sip_tcp_helper_thread(struct sip_pvt *pvt, struct ast_tcptls_session_instance *tcptls_session)
02492 {
02493    int res, cl, timeout = -1, authenticated = 0, flags, after_poll = 0, need_poll = 1;
02494    time_t start;
02495    struct sip_request req = { 0, } , reqcpy = { 0, };
02496    struct sip_threadinfo *me = NULL;
02497    char buf[1024] = "";
02498    struct pollfd fds[2] = { { 0 }, { 0 }, };
02499    struct ast_tcptls_session_args *ca = NULL;
02500 
02501    /* If this is a server session, then the connection has already been
02502     * setup. Check if the authlimit has been reached and if not create the
02503     * threadinfo object so we can access this thread for writing.
02504     *
02505     * if this is a client connection more work must be done.
02506     * 1. We own the parent session args for a client connection.  This pointer needs
02507     *    to be held on to so we can decrement it's ref count on thread destruction.
02508     * 2. The threadinfo object was created before this thread was launched, however
02509     *    it must be found within the threadt table.
02510     * 3. Last, the tcptls_session must be started.
02511     */
02512    if (!tcptls_session->client) {
02513       if (ast_atomic_fetchadd_int(&unauth_sessions, +1) >= authlimit) {
02514          /* unauth_sessions is decremented in the cleanup code */
02515          goto cleanup;
02516       }
02517 
02518       if ((flags = fcntl(tcptls_session->fd, F_GETFL)) == -1) {
02519          ast_log(LOG_ERROR, "error setting socket to non blocking mode, fcntl() failed: %s\n", strerror(errno));
02520          goto cleanup;
02521       }
02522 
02523       flags |= O_NONBLOCK;
02524       if (fcntl(tcptls_session->fd, F_SETFL, flags) == -1) {
02525          ast_log(LOG_ERROR, "error setting socket to non blocking mode, fcntl() failed: %s\n", strerror(errno));
02526          goto cleanup;
02527       }
02528 
02529       if (!(me = sip_threadinfo_create(tcptls_session, tcptls_session->ssl ? SIP_TRANSPORT_TLS : SIP_TRANSPORT_TCP))) {
02530          goto cleanup;
02531       }
02532       ao2_t_ref(me, +1, "Adding threadinfo ref for tcp_helper_thread");
02533    } else {
02534       struct sip_threadinfo tmp = {
02535          .tcptls_session = tcptls_session,
02536       };
02537 
02538       if ((!(ca = tcptls_session->parent)) ||
02539          (!(me = ao2_t_find(threadt, &tmp, OBJ_POINTER, "ao2_find, getting sip_threadinfo in tcp helper thread"))) ||
02540          (!(tcptls_session = ast_tcptls_client_start(tcptls_session)))) {
02541          goto cleanup;
02542       }
02543    }
02544 
02545    flags = 1;
02546    if (setsockopt(tcptls_session->fd, SOL_SOCKET, SO_KEEPALIVE, &flags, sizeof(flags))) {
02547       ast_log(LOG_ERROR, "error enabling TCP keep-alives on sip socket: %s\n", strerror(errno));
02548       goto cleanup;
02549    }
02550 
02551    me->threadid = pthread_self();
02552    ast_debug(2, "Starting thread for %s server\n", tcptls_session->ssl ? "SSL" : "TCP");
02553 
02554    /* set up pollfd to watch for reads on both the socket and the alert_pipe */
02555    fds[0].fd = tcptls_session->fd;
02556    fds[1].fd = me->alert_pipe[0];
02557    fds[0].events = fds[1].events = POLLIN | POLLPRI;
02558 
02559    if (!(req.data = ast_str_create(SIP_MIN_PACKET))) {
02560       goto cleanup;
02561    }
02562    if (!(reqcpy.data = ast_str_create(SIP_MIN_PACKET))) {
02563       goto cleanup;
02564    }
02565 
02566    if(time(&start) == -1) {
02567       ast_log(LOG_ERROR, "error executing time(): %s\n", strerror(errno));
02568       goto cleanup;
02569    }
02570 
02571    for (;;) {
02572       struct ast_str *str_save;
02573 
02574       if (!tcptls_session->client && req.authenticated && !authenticated) {
02575          authenticated = 1;
02576          ast_atomic_fetchadd_int(&unauth_sessions, -1);
02577       }
02578 
02579       /* calculate the timeout for unauthenticated server sessions */
02580       if (!tcptls_session->client && !authenticated ) {
02581          if ((timeout = sip_check_authtimeout(start)) < 0) {
02582             goto cleanup;
02583          }
02584 
02585          if (timeout == 0) {
02586             ast_debug(2, "SIP %s server timed out\n", tcptls_session->ssl ? "SSL": "TCP");
02587             goto cleanup;
02588          }
02589       } else {
02590          timeout = -1;
02591       }
02592 
02593       res = ast_poll(fds, 2, timeout); /* polls for both socket and alert_pipe */
02594       if (res < 0) {
02595          ast_debug(2, "SIP %s server :: ast_wait_for_input returned %d\n", tcptls_session->ssl ? "SSL": "TCP", res);
02596          goto cleanup;
02597       } else if (res == 0) {
02598          /* timeout */
02599          ast_debug(2, "SIP %s server timed out\n", tcptls_session->ssl ? "SSL": "TCP");
02600          goto cleanup;
02601       }
02602 
02603       /* handle the socket event, check for both reads from the socket fd,
02604        * and writes from alert_pipe fd */
02605       if (fds[0].revents) { /* there is data on the socket to be read */
02606          after_poll = 1;
02607 
02608          fds[0].revents = 0;
02609 
02610          /* clear request structure */
02611          str_save = req.data;
02612          memset(&req, 0, sizeof(req));
02613          req.data = str_save;
02614          ast_str_reset(req.data);
02615 
02616          str_save = reqcpy.data;
02617          memset(&reqcpy, 0, sizeof(reqcpy));
02618          reqcpy.data = str_save;
02619          ast_str_reset(reqcpy.data);
02620 
02621          memset(buf, 0, sizeof(buf));
02622 
02623          if (tcptls_session->ssl) {
02624             set_socket_transport(&req.socket, SIP_TRANSPORT_TLS);
02625             req.socket.port = htons(ourport_tls);
02626          } else {
02627             set_socket_transport(&req.socket, SIP_TRANSPORT_TCP);
02628             req.socket.port = htons(ourport_tcp);
02629          }
02630          req.socket.fd = tcptls_session->fd;
02631 
02632          /* Read in headers one line at a time */
02633          while (ast_str_strlen(req.data) < 4 || strncmp(REQ_OFFSET_TO_STR(&req, data->used - 4), "\r\n\r\n", 4)) {
02634             if (!tcptls_session->client && !authenticated ) {
02635                if ((timeout = sip_check_authtimeout(start)) < 0) {
02636                   goto cleanup;
02637                }
02638 
02639                if (timeout == 0) {
02640                   ast_debug(2, "SIP %s server timed out\n", tcptls_session->ssl ? "SSL": "TCP");
02641                   goto cleanup;
02642                }
02643             } else {
02644                timeout = -1;
02645             }
02646 
02647             /* special polling behavior is required for TLS
02648              * sockets because of the buffering done in the
02649              * TLS layer */
02650             if (!tcptls_session->ssl || need_poll) {
02651                need_poll = 0;
02652                after_poll = 1;
02653                res = ast_wait_for_input(tcptls_session->fd, timeout);
02654                if (res < 0) {
02655                   ast_debug(2, "SIP TCP server :: ast_wait_for_input returned %d\n", res);
02656                   goto cleanup;
02657                } else if (res == 0) {
02658                   /* timeout */
02659                   ast_debug(2, "SIP TCP server timed out\n");
02660                   goto cleanup;
02661                }
02662             }
02663 
02664             ast_mutex_lock(&tcptls_session->lock);
02665             if (!fgets(buf, sizeof(buf), tcptls_session->f)) {
02666                ast_mutex_unlock(&tcptls_session->lock);
02667                if (after_poll) {
02668                   goto cleanup;
02669                } else {
02670                   need_poll = 1;
02671                   continue;
02672                }
02673             }
02674             ast_mutex_unlock(&tcptls_session->lock);
02675             after_poll = 0;
02676             if (me->stop) {
02677                 goto cleanup;
02678             }
02679             ast_str_append(&req.data, 0, "%s", buf);
02680          }
02681          copy_request(&reqcpy, &req);
02682          parse_request(&reqcpy);
02683          /* In order to know how much to read, we need the content-length header */
02684          if (sscanf(get_header(&reqcpy, "Content-Length"), "%30d", &cl)) {
02685             while (cl > 0) {
02686                size_t bytes_read;
02687                if (!tcptls_session->client && !authenticated ) {
02688                   if ((timeout = sip_check_authtimeout(start)) < 0) {
02689                      goto cleanup;
02690                   }
02691 
02692                   if (timeout == 0) {
02693                      ast_debug(2, "SIP %s server timed out\n", tcptls_session->ssl ? "SSL": "TCP");
02694                      goto cleanup;
02695                   }
02696                } else {
02697                   timeout = -1;
02698                }
02699 
02700                if (!tcptls_session->ssl || need_poll) {
02701                   need_poll = 0;
02702                   after_poll = 1;
02703                   res = ast_wait_for_input(tcptls_session->fd, timeout);
02704                   if (res < 0) {
02705                      ast_debug(2, "SIP TCP server :: ast_wait_for_input returned %d\n", res);
02706                      goto cleanup;
02707                   } else if (res == 0) {
02708                      /* timeout */
02709                      ast_debug(2, "SIP TCP server timed out\n");
02710                      goto cleanup;
02711                   }
02712                }
02713 
02714                ast_mutex_lock(&tcptls_session->lock);
02715                if (!(bytes_read = fread(buf, 1, MIN(sizeof(buf) - 1, cl), tcptls_session->f))) {
02716                   ast_mutex_unlock(&tcptls_session->lock);
02717                   if (after_poll) {
02718                      goto cleanup;
02719                   } else {
02720                      need_poll = 1;
02721                      continue;
02722                   }
02723                }
02724                buf[bytes_read] = '\0';
02725                ast_mutex_unlock(&tcptls_session->lock);
02726                after_poll = 0;
02727                if (me->stop) {
02728                   goto cleanup;
02729                }
02730                cl -= strlen(buf);
02731                ast_str_append(&req.data, 0, "%s", buf);
02732             }
02733          }
02734          /*! \todo XXX If there's no Content-Length or if the content-length and what
02735                we receive is not the same - we should generate an error */
02736 
02737          req.socket.tcptls_session = tcptls_session;
02738          handle_request_do(&req, &tcptls_session->remote_address);
02739       }
02740 
02741       if (fds[1].revents) { /* alert_pipe indicates there is data in the send queue to be sent */
02742          enum sip_tcptls_alert alert;
02743          struct tcptls_packet *packet;
02744 
02745          fds[1].revents = 0;
02746 
02747          if (read(me->alert_pipe[0], &alert, sizeof(alert)) == -1) {
02748             ast_log(LOG_ERROR, "read() failed: %s\n", strerror(errno));
02749             continue;
02750          }
02751 
02752          switch (alert) {
02753          case TCPTLS_ALERT_STOP:
02754             goto cleanup;
02755          case TCPTLS_ALERT_DATA:
02756             ao2_lock(me);
02757             if (!(packet = AST_LIST_REMOVE_HEAD(&me->packet_q, entry))) {
02758                ast_log(LOG_WARNING, "TCPTLS thread alert_pipe indicated packet should be sent, but frame_q is empty");
02759             }
02760             ao2_unlock(me);
02761 
02762             if (packet) {
02763                if (ast_tcptls_server_write(tcptls_session, ast_str_buffer(packet->data), packet->len) == -1) {
02764                   ast_log(LOG_WARNING, "Failure to write to tcp/tls socket\n");
02765                }
02766                ao2_t_ref(packet, -1, "tcptls packet sent, this is no longer needed");
02767             }
02768             break;
02769          default:
02770             ast_log(LOG_ERROR, "Unknown tcptls thread alert '%d'\n", alert);
02771          }
02772       }
02773    }
02774 
02775    ast_debug(2, "Shutting down thread for %s server\n", tcptls_session->ssl ? "SSL" : "TCP");
02776 
02777 cleanup:
02778    if (tcptls_session && !tcptls_session->client && !authenticated) {
02779       ast_atomic_fetchadd_int(&unauth_sessions, -1);
02780    }
02781 
02782    if (me) {
02783       ao2_t_unlink(threadt, me, "Removing tcptls helper thread, thread is closing");
02784       ao2_t_ref(me, -1, "Removing tcp_helper_threads threadinfo ref");
02785    }
02786    deinit_req(&reqcpy);
02787    deinit_req(&req);
02788 
02789    /* if client, we own the parent session arguments and must decrement ref */
02790    if (ca) {
02791       ao2_t_ref(ca, -1, "closing tcptls thread, getting rid of client tcptls_session arguments");
02792    }
02793 
02794    if (tcptls_session) {
02795       ast_mutex_lock(&tcptls_session->lock);
02796       ast_tcptls_close_session_file(tcptls_session);
02797       tcptls_session->parent = NULL;
02798       ast_mutex_unlock(&tcptls_session->lock);
02799 
02800       ao2_ref(tcptls_session, -1);
02801       tcptls_session = NULL;
02802    }
02803    return NULL;
02804 }
02805 
02806 #ifdef REF_DEBUG
02807 #define ref_peer(arg1,arg2) _ref_peer((arg1),(arg2), __FILE__, __LINE__, __PRETTY_FUNCTION__)
02808 #define unref_peer(arg1,arg2) _unref_peer((arg1),(arg2), __FILE__, __LINE__, __PRETTY_FUNCTION__)
02809 static struct sip_peer *_ref_peer(struct sip_peer *peer, char *tag, char *file, int line, const char *func)
02810 {
02811    if (peer)
02812       __ao2_ref_debug(peer, 1, tag, file, line, func);
02813    else
02814       ast_log(LOG_ERROR, "Attempt to Ref a null peer pointer\n");
02815    return peer;
02816 }
02817 
02818 static struct sip_peer *_unref_peer(struct sip_peer *peer, char *tag, char *file, int line, const char *func)
02819 {
02820    if (peer)
02821       __ao2_ref_debug(peer, -1, tag, file, line, func);
02822    return NULL;
02823 }
02824 #else
02825 /*!
02826  * helper functions to unreference various types of objects.
02827  * By handling them this way, we don't have to declare the
02828  * destructor on each call, which removes the chance of errors.
02829  */
02830 static void *unref_peer(struct sip_peer *peer, char *tag)
02831 {
02832    ao2_t_ref(peer, -1, tag);
02833    return NULL;
02834 }
02835 
02836 static struct sip_peer *ref_peer(struct sip_peer *peer, char *tag)
02837 {
02838    ao2_t_ref(peer, 1, tag);
02839    return peer;
02840 }
02841 #endif /* REF_DEBUG */
02842 
02843 static void peer_sched_cleanup(struct sip_peer *peer)
02844 {
02845    if (peer->pokeexpire != -1) {
02846       AST_SCHED_DEL_UNREF(sched, peer->pokeexpire,
02847             unref_peer(peer, "removing poke peer ref"));
02848    }
02849    if (peer->expire != -1) {
02850       AST_SCHED_DEL_UNREF(sched, peer->expire,
02851             unref_peer(peer, "remove register expire ref"));
02852    }
02853 }
02854 
02855 typedef enum {
02856    SIP_PEERS_MARKED,
02857    SIP_PEERS_ALL,
02858 } peer_unlink_flag_t;
02859 
02860 /* this func is used with ao2_callback to unlink/delete all marked or linked
02861    peers, depending on arg */
02862 static int match_and_cleanup_peer_sched(void *peerobj, void *arg, int flags)
02863 {
02864    struct sip_peer *peer = peerobj;
02865    peer_unlink_flag_t which = *(peer_unlink_flag_t *)arg;
02866 
02867    if (which == SIP_PEERS_ALL || peer->the_mark) {
02868       peer_sched_cleanup(peer);
02869       return CMP_MATCH;
02870    }
02871    return 0;
02872 }
02873 
02874 static void unlink_peers_from_tables(peer_unlink_flag_t flag)
02875 {
02876    ao2_t_callback(peers, OBJ_NODATA | OBJ_UNLINK | OBJ_MULTIPLE,
02877       match_and_cleanup_peer_sched, &flag, "initiating callback to remove marked peers");
02878    ao2_t_callback(peers_by_ip, OBJ_NODATA | OBJ_UNLINK | OBJ_MULTIPLE,
02879       match_and_cleanup_peer_sched, &flag, "initiating callback to remove marked peers");
02880 }
02881 
02882 /* \brief Unlink all marked peers from ao2 containers */
02883 static void unlink_marked_peers_from_tables(void)
02884 {
02885    unlink_peers_from_tables(SIP_PEERS_MARKED);
02886 }
02887 
02888 static void unlink_all_peers_from_tables(void)
02889 {
02890    unlink_peers_from_tables(SIP_PEERS_ALL);
02891 }
02892 
02893 /* \brief Unlink single peer from all ao2 containers */
02894 static void unlink_peer_from_tables(struct sip_peer *peer)
02895 {
02896    ao2_t_unlink(peers, peer, "ao2_unlink of peer from peers table");
02897    if (!ast_sockaddr_isnull(&peer->addr)) {
02898       ao2_t_unlink(peers_by_ip, peer, "ao2_unlink of peer from peers_by_ip table");
02899    }
02900 }
02901 
02902 /*! \brief maintain proper refcounts for a sip_pvt's outboundproxy
02903  *
02904  * This function sets pvt's outboundproxy pointer to the one referenced
02905  * by the proxy parameter. Because proxy may be a refcounted object, and
02906  * because pvt's old outboundproxy may also be a refcounted object, we need
02907  * to maintain the proper refcounts.
02908  *
02909  * \param pvt The sip_pvt for which we wish to set the outboundproxy
02910  * \param proxy The sip_proxy which we will point pvt towards.
02911  * \return Returns void
02912  */
02913 static void ref_proxy(struct sip_pvt *pvt, struct sip_proxy *proxy)
02914 {
02915    struct sip_proxy *old_obproxy = pvt->outboundproxy;
02916    /* The sip_cfg.outboundproxy is statically allocated, and so
02917     * we don't ever need to adjust refcounts for it
02918     */
02919    if (proxy && proxy != &sip_cfg.outboundproxy) {
02920       ao2_ref(proxy, +1);
02921    }
02922    pvt->outboundproxy = proxy;
02923    if (old_obproxy && old_obproxy != &sip_cfg.outboundproxy) {
02924       ao2_ref(old_obproxy, -1);
02925    }
02926 }
02927 
02928 /*!
02929  * \brief Unlink a dialog from the dialogs container, as well as any other places
02930  * that it may be currently stored.
02931  *
02932  * \note A reference to the dialog must be held before calling this function, and this
02933  * function does not release that reference.
02934  */
02935 void dialog_unlink_all(struct sip_pvt *dialog)
02936 {
02937    struct sip_pkt *cp;
02938    struct ast_channel *owner;
02939 
02940    dialog_ref(dialog, "Let's bump the count in the unlink so it doesn't accidentally become dead before we are done");
02941 
02942    ao2_t_unlink(dialogs, dialog, "unlinking dialog via ao2_unlink");
02943 
02944    /* Unlink us from the owner (channel) if we have one */
02945    owner = sip_pvt_lock_full(dialog);
02946    if (owner) {
02947       ast_debug(1, "Detaching from channel %s\n", owner->name);
02948       owner->tech_pvt = dialog_unref(owner->tech_pvt, "resetting channel dialog ptr in unlink_all");
02949       ast_channel_unlock(owner);
02950       ast_channel_unref(owner);
02951       dialog->owner = NULL;
02952    }
02953    sip_pvt_unlock(dialog);
02954 
02955    if (dialog->registry) {
02956       if (dialog->registry->call == dialog) {
02957          dialog->registry->call = dialog_unref(dialog->registry->call, "nulling out the registry's call dialog field in unlink_all");
02958       }
02959       dialog->registry = registry_unref(dialog->registry, "delete dialog->registry");
02960    }
02961    if (dialog->stateid != -1) {
02962       ast_extension_state_del(dialog->stateid, cb_extensionstate);
02963       dialog->stateid = -1;
02964    }
02965    /* Remove link from peer to subscription of MWI */
02966    if (dialog->relatedpeer && dialog->relatedpeer->mwipvt == dialog) {
02967       dialog->relatedpeer->mwipvt = dialog_unref(dialog->relatedpeer->mwipvt, "delete ->relatedpeer->mwipvt");
02968    }
02969    if (dialog->relatedpeer && dialog->relatedpeer->call == dialog) {
02970       dialog->relatedpeer->call = dialog_unref(dialog->relatedpeer->call, "unset the relatedpeer->call field in tandem with relatedpeer field itself");
02971    }
02972 
02973    /* remove all current packets in this dialog */
02974    while((cp = dialog->packets)) {
02975       dialog->packets = dialog->packets->next;
02976       AST_SCHED_DEL(sched, cp->retransid);
02977       dialog_unref(cp->owner, "remove all current packets in this dialog, and the pointer to the dialog too as part of __sip_destroy");
02978       if (cp->data) {
02979          ast_free(cp->data);
02980       }
02981       ast_free(cp);
02982    }
02983 
02984    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"));
02985 
02986    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"));
02987    
02988    if (dialog->autokillid > -1) {
02989       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"));
02990    }
02991 
02992    if (dialog->request_queue_sched_id > -1) {
02993       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"));
02994    }
02995 
02996    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"));
02997 
02998    if (dialog->t38id > -1) {
02999       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"));
03000    }
03001 
03002    if (dialog->stimer) {
03003       stop_session_timer(dialog);
03004    }
03005 
03006    dialog_unref(dialog, "Let's unbump the count in the unlink so the poor pvt can disappear if it is time");
03007 }
03008 
03009 void *registry_unref(struct sip_registry *reg, char *tag)
03010 {
03011    ast_debug(3, "SIP Registry %s: refcount now %d\n", reg->hostname, reg->refcount - 1);
03012    ASTOBJ_UNREF(reg, sip_registry_destroy);
03013    return NULL;
03014 }
03015 
03016 /*! \brief Add object reference to SIP registry */
03017 static struct sip_registry *registry_addref(struct sip_registry *reg, char *tag)
03018 {
03019    ast_debug(3, "SIP Registry %s: refcount now %d\n", reg->hostname, reg->refcount + 1);
03020    return ASTOBJ_REF(reg); /* Add pointer to registry in packet */
03021 }
03022 
03023 /*! \brief Interface structure with callbacks used to connect to UDPTL module*/
03024 static struct ast_udptl_protocol sip_udptl = {
03025    type: "SIP",
03026    get_udptl_info: sip_get_udptl_peer,
03027    set_udptl_peer: sip_set_udptl_peer,
03028 };
03029 
03030 static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
03031    __attribute__((format(printf, 2, 3)));
03032 
03033 
03034 /*! \brief Convert transfer status to string */
03035 static const char *referstatus2str(enum referstatus rstatus)
03036 {
03037    return map_x_s(referstatusstrings, rstatus, "");
03038 }
03039 
03040 static inline void pvt_set_needdestroy(struct sip_pvt *pvt, const char *reason)
03041 {
03042    if (pvt->final_destruction_scheduled) {
03043       return; /* This is already scheduled for final destruction, let the scheduler take care of it. */
03044    }
03045    append_history(pvt, "NeedDestroy", "Setting needdestroy because %s", reason);
03046    pvt->needdestroy = 1;
03047 }
03048 
03049 /*! \brief Initialize the initital request packet in the pvt structure.
03050    This packet is used for creating replies and future requests in
03051    a dialog */
03052 static void initialize_initreq(struct sip_pvt *p, struct sip_request *req)
03053 {
03054    if (p->initreq.headers) {
03055       ast_debug(1, "Initializing already initialized SIP dialog %s (presumably reinvite)\n", p->callid);
03056    } else {
03057       ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
03058    }
03059    /* Use this as the basis */
03060    copy_request(&p->initreq, req);
03061    parse_request(&p->initreq);
03062    if (req->debug) {
03063       ast_verbose("Initreq: %d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
03064    }
03065 }
03066 
03067 /*! \brief Encapsulate setting of SIP_ALREADYGONE to be able to trace it with debugging */
03068 static void sip_alreadygone(struct sip_pvt *dialog)
03069 {
03070    ast_debug(3, "Setting SIP_ALREADYGONE on dialog %s\n", dialog->callid);
03071    dialog->alreadygone = 1;
03072 }
03073 
03074 /*! Resolve DNS srv name or host name in a sip_proxy structure */
03075 static int proxy_update(struct sip_proxy *proxy)
03076 {
03077    /* if it's actually an IP address and not a name,
03078            there's no need for a managed lookup */
03079    if (!ast_sockaddr_parse(&proxy->ip, proxy->name, 0)) {
03080       /* Ok, not an IP address, then let's check if it's a domain or host */
03081       /* XXX Todo - if we have proxy port, don't do SRV */
03082       proxy->ip.ss.ss_family = get_address_family_filter(&bindaddr); /* Filter address family */
03083       if (ast_get_ip_or_srv(&proxy->ip, proxy->name, sip_cfg.srvlookup ? "_sip._udp" : NULL) < 0) {
03084             ast_log(LOG_WARNING, "Unable to locate host '%s'\n", proxy->name);
03085             return FALSE;
03086       }
03087 
03088    }
03089 
03090    ast_sockaddr_set_port(&proxy->ip, proxy->port);
03091 
03092    proxy->last_dnsupdate = time(NULL);
03093    return TRUE;
03094 }
03095 
03096 /*! \brief converts ascii port to int representation. If no
03097  *  pt buffer is provided or the pt has errors when being converted
03098  *  to an int value, the port provided as the standard is used.
03099  */
03100 unsigned int port_str2int(const char *pt, unsigned int standard)
03101 {
03102    int port = standard;
03103    if (ast_strlen_zero(pt) || (sscanf(pt, "%30d", &port) != 1) || (port < 1) || (port > 65535)) {
03104       port = standard;
03105    }
03106 
03107    return port;
03108 }
03109 
03110 /*! \brief Get default outbound proxy or global proxy */
03111 static struct sip_proxy *obproxy_get(struct sip_pvt *dialog, struct sip_peer *peer)
03112 {
03113    if (peer && peer->outboundproxy) {
03114       if (sipdebug) {
03115          ast_debug(1, "OBPROXY: Applying peer OBproxy to this call\n");
03116       }
03117       append_history(dialog, "OBproxy", "Using peer obproxy %s", peer->outboundproxy->name);
03118       return peer->outboundproxy;
03119    }
03120    if (sip_cfg.outboundproxy.name[0]) {
03121       if (sipdebug) {
03122          ast_debug(1, "OBPROXY: Applying global OBproxy to this call\n");
03123       }
03124       append_history(dialog, "OBproxy", "Using global obproxy %s", sip_cfg.outboundproxy.name);
03125       return &sip_cfg.outboundproxy;
03126    }
03127    if (sipdebug) {
03128       ast_debug(1, "OBPROXY: Not applying OBproxy to this call\n");
03129    }
03130    return NULL;
03131 }
03132 
03133 /*! \brief returns true if 'name' (with optional trailing whitespace)
03134  * matches the sip method 'id'.
03135  * Strictly speaking, SIP methods are case SENSITIVE, but we do
03136  * a case-insensitive comparison to be more tolerant.
03137  * following Jon Postel's rule: Be gentle in what you accept, strict with what you send
03138  */
03139 static int method_match(enum sipmethod id, const char *name)
03140 {
03141    int len = strlen(sip_methods[id].text);
03142    int l_name = name ? strlen(name) : 0;
03143    /* true if the string is long enough, and ends with whitespace, and matches */
03144    return (l_name >= len && name[len] < 33 &&
03145       !strncasecmp(sip_methods[id].text, name, len));
03146 }
03147 
03148 /*! \brief  find_sip_method: Find SIP method from header */
03149 static int find_sip_method(const char *msg)
03150 {
03151    int i, res = 0;
03152    
03153    if (ast_strlen_zero(msg)) {
03154       return 0;
03155    }
03156    for (i = 1; i < ARRAY_LEN(sip_methods) && !res; i++) {
03157       if (method_match(i, msg)) {
03158          res = sip_methods[i].id;
03159       }
03160    }
03161    return res;
03162 }
03163 
03164 /*! \brief See if we pass debug IP filter */
03165 static inline int sip_debug_test_addr(const struct ast_sockaddr *addr)
03166 {
03167    /* Can't debug if sipdebug is not enabled */
03168    if (!sipdebug) {
03169       return 0;
03170    }
03171 
03172    /* A null debug_addr means we'll debug any address */
03173    if (ast_sockaddr_isnull(&debugaddr)) {
03174       return 1;
03175    }
03176 
03177    /* If no port was specified for a debug address, just compare the
03178     * addresses, otherwise compare the address and port
03179     */
03180    if (ast_sockaddr_port(&debugaddr)) {
03181       return !ast_sockaddr_cmp(&debugaddr, addr);
03182    } else {
03183       return !ast_sockaddr_cmp_addr(&debugaddr, addr);
03184    }
03185 }
03186 
03187 /*! \brief The real destination address for a write */
03188 static const struct ast_sockaddr *sip_real_dst(const struct sip_pvt *p)
03189 {
03190    if (p->outboundproxy) {
03191       return &p->outboundproxy->ip;
03192    }
03193 
03194    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;
03195 }
03196 
03197 /*! \brief Display SIP nat mode */
03198 static const char *sip_nat_mode(const struct sip_pvt *p)
03199 {
03200    return ast_test_flag(&p->flags[0], SIP_NAT_FORCE_RPORT) ? "NAT" : "no NAT";
03201 }
03202 
03203 /*! \brief Test PVT for debugging output */
03204 static inline int sip_debug_test_pvt(struct sip_pvt *p)
03205 {
03206    if (!sipdebug) {
03207       return 0;
03208    }
03209    return sip_debug_test_addr(sip_real_dst(p));
03210 }
03211 
03212 /*! \brief Return int representing a bit field of transport types found in const char *transport */
03213 static int get_transport_str2enum(const char *transport)
03214 {
03215    int res = 0;
03216 
03217    if (ast_strlen_zero(transport)) {
03218       return res;
03219    }
03220 
03221    if (!strcasecmp(transport, "udp")) {
03222       res |= SIP_TRANSPORT_UDP;
03223    }
03224    if (!strcasecmp(transport, "tcp")) {
03225       res |= SIP_TRANSPORT_TCP;
03226    }
03227    if (!strcasecmp(transport, "tls")) {
03228       res |= SIP_TRANSPORT_TLS;
03229    }
03230 
03231    return res;
03232 }
03233 
03234 /*! \brief Return configuration of transports for a device */
03235 static inline const char *get_transport_list(unsigned int transports) {
03236    switch (transports) {
03237       case SIP_TRANSPORT_UDP:
03238          return "UDP";
03239       case SIP_TRANSPORT_TCP:
03240          return "TCP";
03241       case SIP_TRANSPORT_TLS:
03242          return "TLS";
03243       case SIP_TRANSPORT_UDP | SIP_TRANSPORT_TCP:
03244          return "TCP,UDP";
03245       case SIP_TRANSPORT_UDP | SIP_TRANSPORT_TLS:
03246          return "TLS,UDP";
03247       case SIP_TRANSPORT_TCP | SIP_TRANSPORT_TLS:
03248          return "TLS,TCP";
03249       default:
03250          return transports ?
03251             "TLS,TCP,UDP" : "UNKNOWN"; 
03252    }
03253 }
03254 
03255 /*! \brief Return transport as string */
03256 static inline const char *get_transport(enum sip_transport t)
03257 {
03258    switch (t) {
03259    case SIP_TRANSPORT_UDP:
03260       return "UDP";
03261    case SIP_TRANSPORT_TCP:
03262       return "TCP";
03263    case SIP_TRANSPORT_TLS:
03264       return "TLS";
03265    }
03266 
03267    return "UNKNOWN";
03268 }
03269 
03270 /*! \brief Return protocol string for srv dns query */
03271 static inline const char *get_srv_protocol(enum sip_transport t)
03272 {
03273    switch (t) {
03274    case SIP_TRANSPORT_UDP:
03275       return "udp";
03276    case SIP_TRANSPORT_TLS:
03277    case SIP_TRANSPORT_TCP:
03278       return "tcp";
03279    }
03280 
03281    return "udp";
03282 }
03283 
03284 /*! \brief Return service string for srv dns query */
03285 static inline const char *get_srv_service(enum sip_transport t)
03286 {
03287    switch (t) {
03288    case SIP_TRANSPORT_TCP:
03289    case SIP_TRANSPORT_UDP:
03290       return "sip";
03291    case SIP_TRANSPORT_TLS:
03292       return "sips";
03293    }
03294    return "sip";
03295 }
03296 
03297 /*! \brief Return transport of dialog.
03298    \note this is based on a false assumption. We don't always use the
03299    outbound proxy for all requests in a dialog. It depends on the
03300    "force" parameter. The FIRST request is always sent to the ob proxy.
03301    \todo Fix this function to work correctly
03302 */
03303 static inline const char *get_transport_pvt(struct sip_pvt *p)
03304 {
03305    if (p->outboundproxy && p->outboundproxy->transport) {
03306       set_socket_transport(&p->socket, p->outboundproxy->transport);
03307    }
03308 
03309    return get_transport(p->socket.type);
03310 }
03311 
03312 /*!
03313  * \internal
03314  * \brief Transmit SIP message
03315  *
03316  * \details
03317  * Sends a SIP request or response on a given socket (in the pvt)
03318  * \note
03319  * Called by retrans_pkt, send_request, send_response and __sip_reliable_xmit
03320  *
03321  * \return length of transmitted message, XMIT_ERROR on known network failures -1 on other failures.
03322  */
03323 static int __sip_xmit(struct sip_pvt *p, struct ast_str *data)
03324 {
03325    int res = 0;
03326    const struct ast_sockaddr *dst = sip_real_dst(p);
03327 
03328    ast_debug(2, "Trying to put '%.11s' onto %s socket destined for %s\n", data->str, get_transport_pvt(p), ast_sockaddr_stringify(dst));
03329 
03330    if (sip_prepare_socket(p) < 0) {
03331       return XMIT_ERROR;
03332    }
03333 
03334    if (p->socket.type == SIP_TRANSPORT_UDP) {
03335       res = ast_sendto(p->socket.fd, data->str, ast_str_strlen(data), 0, dst);
03336    } else if (p->socket.tcptls_session) {
03337       res = sip_tcptls_write(p->socket.tcptls_session, data->str, ast_str_strlen(data));
03338    } else {
03339       ast_debug(2, "Socket type is TCP but no tcptls_session is present to write to\n");
03340       return XMIT_ERROR;
03341    }
03342 
03343    if (res == -1) {
03344       switch (errno) {
03345       case EBADF:       /* Bad file descriptor - seems like this is generated when the host exist, but doesn't accept the UDP packet */
03346       case EHOSTUNREACH:   /* Host can't be reached */
03347       case ENETDOWN:       /* Interface down */
03348       case ENETUNREACH: /* Network failure */
03349       case ECONNREFUSED:      /* ICMP port unreachable */
03350          res = XMIT_ERROR; /* Don't bother with trying to transmit again */
03351       }
03352    }
03353    if (res != ast_str_strlen(data)) {
03354       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));
03355    }
03356 
03357    return res;
03358 }
03359 
03360 /*! \brief Build a Via header for a request */
03361 static void build_via(struct sip_pvt *p)
03362 {
03363    /* Work around buggy UNIDEN UIP200 firmware */
03364    const char *rport = (ast_test_flag(&p->flags[0], SIP_NAT_FORCE_RPORT) || ast_test_flag(&p->flags[0], SIP_NAT_RPORT_PRESENT)) ? ";rport" : "";
03365 
03366    /* z9hG4bK is a magic cookie.  See RFC 3261 section 8.1.1.7 */
03367    snprintf(p->via, sizeof(p->via), "SIP/2.0/%s %s;branch=z9hG4bK%08x%s",
03368        get_transport_pvt(p),
03369        ast_sockaddr_stringify_remote(&p->ourip),
03370        (int) p->branch, rport);
03371 }
03372 
03373 /*! \brief NAT fix - decide which IP address to use for Asterisk server?
03374  *
03375  * Using the localaddr structure built up with localnet statements in sip.conf
03376  * apply it to their address to see if we need to substitute our
03377  * externaddr or can get away with our internal bindaddr
03378  * 'us' is always overwritten.
03379  */
03380 static void ast_sip_ouraddrfor(const struct ast_sockaddr *them, struct ast_sockaddr *us, struct sip_pvt *p)
03381 {
03382    struct ast_sockaddr theirs;
03383 
03384    /* Set want_remap to non-zero if we want to remap 'us' to an externally
03385     * reachable IP address and port. This is done if:
03386     * 1. we have a localaddr list (containing 'internal' addresses marked
03387     *    as 'deny', so ast_apply_ha() will return AST_SENSE_DENY on them,
03388     *    and AST_SENSE_ALLOW on 'external' ones);
03389     * 2. externaddr is set, so we know what to use as the
03390     *    externally visible address;
03391     * 3. the remote address, 'them', is external;
03392     * 4. the address returned by ast_ouraddrfor() is 'internal' (AST_SENSE_DENY
03393     *    when passed to ast_apply_ha() so it does need to be remapped.
03394     *    This fourth condition is checked later.
03395     */
03396    int want_remap = 0;
03397 
03398    ast_sockaddr_copy(us, &internip); /* starting guess for the internal address */
03399    /* now ask the system what would it use to talk to 'them' */
03400    ast_ouraddrfor(them, us);
03401    ast_sockaddr_copy(&theirs, them);
03402 
03403    if (ast_sockaddr_is_ipv6(&theirs)) {
03404       if (localaddr && !ast_sockaddr_isnull(&externaddr)) {
03405          ast_log(LOG_WARNING, "Address remapping activated in sip.conf "
03406             "but we're using IPv6, which doesn't need it. Please "
03407             "remove \"localnet\" and/or \"externaddr\" settings.\n");
03408       }
03409    } else {
03410       want_remap = localaddr &&
03411          !ast_sockaddr_isnull(&externaddr) &&
03412          ast_apply_ha(localaddr, &theirs) == AST_SENSE_ALLOW ;
03413    }
03414 
03415    if (want_remap &&
03416        (!sip_cfg.matchexternaddrlocally || !ast_apply_ha(localaddr, us)) ) {
03417       /* if we used externhost, see if it is time to refresh the info */
03418       if (externexpire && time(NULL) >= externexpire) {
03419          if (ast_sockaddr_resolve_first(&externaddr, externhost, 0)) {
03420             ast_log(LOG_NOTICE, "Warning: Re-lookup of '%s' failed!\n", externhost);
03421          }
03422          externexpire = time(NULL) + externrefresh;
03423       }
03424       if (!ast_sockaddr_isnull(&externaddr)) {
03425          ast_sockaddr_copy(us, &externaddr);
03426          switch (p->socket.type) {
03427          case SIP_TRANSPORT_TCP:
03428             if (!externtcpport && ast_sockaddr_port(&externaddr)) {
03429                /* for consistency, default to the externaddr port */
03430                externtcpport = ast_sockaddr_port(&externaddr);
03431             }
03432             ast_sockaddr_set_port(us, externtcpport);
03433             break;
03434          case SIP_TRANSPORT_TLS:
03435             ast_sockaddr_set_port(us, externtlsport);
03436             break;
03437          case SIP_TRANSPORT_UDP:
03438             if (!ast_sockaddr_port(&externaddr)) {
03439                ast_sockaddr_set_port(us, ast_sockaddr_port(&bindaddr));
03440             }
03441             break;
03442          default:
03443             break;
03444          }
03445       }
03446       ast_debug(1, "Target address %s is not local, substituting externaddr\n",
03447            ast_sockaddr_stringify(them));
03448    } else if (p) {
03449       /* no remapping, but we bind to a specific address, so use it. */
03450       switch (p->socket.type) {
03451       case SIP_TRANSPORT_TCP:
03452          if (!ast_sockaddr_is_any(&sip_tcp_desc.local_address)) {
03453             ast_sockaddr_copy(us,
03454                     &sip_tcp_desc.local_address);
03455          } else {
03456             ast_sockaddr_set_port(us,
03457                         ast_sockaddr_port(&sip_tcp_desc.local_address));
03458          }
03459          break;
03460       case SIP_TRANSPORT_TLS:
03461          if (!ast_sockaddr_is_any(&sip_tls_desc.local_address)) {
03462             ast_sockaddr_copy(us,
03463                     &sip_tls_desc.local_address);
03464          } else {
03465             ast_sockaddr_set_port(us,
03466                         ast_sockaddr_port(&sip_tls_desc.local_address));
03467          }
03468          break;
03469       case SIP_TRANSPORT_UDP:
03470          /* fall through on purpose */
03471       default:
03472          if (!ast_sockaddr_is_any(&bindaddr)) {
03473             ast_sockaddr_copy(us, &bindaddr);
03474          }
03475          if (!ast_sockaddr_port(us)) {
03476             ast_sockaddr_set_port(us, ast_sockaddr_port(&bindaddr));
03477          }
03478       }
03479    } else if (!ast_sockaddr_is_any(&bindaddr)) {
03480       ast_sockaddr_copy(us, &bindaddr);
03481    }
03482    ast_debug(3, "Setting SIP_TRANSPORT_%s with address %s\n", get_transport(p->socket.type), ast_sockaddr_stringify(us));
03483 }
03484 
03485 /*! \brief Append to SIP dialog history with arg list  */
03486 static __attribute__((format(printf, 2, 0))) void append_history_va(struct sip_pvt *p, const char *fmt, va_list ap)
03487 {
03488    char buf[80], *c = buf; /* max history length */
03489    struct sip_history *hist;
03490    int l;
03491 
03492    vsnprintf(buf, sizeof(buf), fmt, ap);
03493    strsep(&c, "\r\n"); /* Trim up everything after \r or \n */
03494    l = strlen(buf) + 1;
03495    if (!(hist = ast_calloc(1, sizeof(*hist) + l))) {
03496       return;
03497    }
03498    if (!p->history && !(p->history = ast_calloc(1, sizeof(*p->history)))) {
03499       ast_free(hist);
03500       return;
03501    }
03502    memcpy(hist->event, buf, l);
03503    if (p->history_entries == MAX_HISTORY_ENTRIES) {
03504       struct sip_history *oldest;
03505       oldest = AST_LIST_REMOVE_HEAD(p->history, list);
03506       p->history_entries--;
03507       ast_free(oldest);
03508    }
03509    AST_LIST_INSERT_TAIL(p->history, hist, list);
03510    p->history_entries++;
03511 }
03512 
03513 /*! \brief Append to SIP dialog history with arg list  */
03514 static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
03515 {
03516    va_list ap;
03517 
03518    if (!p) {
03519       return;
03520    }
03521 
03522    if (!p->do_history && !recordhistory && !dumphistory) {
03523       return;
03524    }
03525 
03526    va_start(ap, fmt);
03527    append_history_va(p, fmt, ap);
03528    va_end(ap);
03529 
03530    return;
03531 }
03532 
03533 /*! \brief Retransmit SIP message if no answer (Called from scheduler) */
03534 static int retrans_pkt(const void *data)
03535 {
03536    struct sip_pkt *pkt = (struct sip_pkt *)data, *prev, *cur = NULL;
03537    int reschedule = DEFAULT_RETRANS;
03538    int xmitres = 0;
03539    /* how many ms until retrans timeout is reached */
03540    int64_t diff = pkt->retrans_stop_time - ast_tvdiff_ms(ast_tvnow(), pkt->time_sent);
03541 
03542    /* Do not retransmit if time out is reached. This will be negative if the time between
03543     * the first transmission and now is larger than our timeout period. This is a fail safe
03544     * check in case the scheduler gets behind or the clock is changed. */
03545    if ((diff <= 0) || (diff > pkt->retrans_stop_time)) {
03546       pkt->retrans_stop = 1;
03547    }
03548 
03549    /* Lock channel PVT */
03550    sip_pvt_lock(pkt->owner);
03551 
03552    if (!pkt->retrans_stop) {
03553       pkt->retrans++;
03554       if (!pkt->timer_t1) {   /* Re-schedule using timer_a and timer_t1 */
03555          if (sipdebug) {
03556             ast_debug(4, "SIP TIMER: Not rescheduling id #%d:%s (Method %d) (No timer T1)\n",
03557                pkt->retransid,
03558                sip_methods[pkt->method].text,
03559                pkt->method);
03560          }
03561       } else {
03562          int siptimer_a;
03563 
03564          if (sipdebug) {
03565             ast_debug(4, "SIP TIMER: Rescheduling retransmission #%d (%d) %s - %d\n",
03566                pkt->retransid,
03567                pkt->retrans,
03568                sip_methods[pkt->method].text,
03569                pkt->method);
03570          }
03571          if (!pkt->timer_a) {
03572             pkt->timer_a = 2 ;
03573          } else {
03574             pkt->timer_a = 2 * pkt->timer_a;
03575          }
03576 
03577          /* For non-invites, a maximum of 4 secs */
03578          siptimer_a = pkt->timer_t1 * pkt->timer_a;   /* Double each time */
03579          if (pkt->method != SIP_INVITE && siptimer_a > 4000) {
03580             siptimer_a = 4000;
03581          }
03582 
03583          /* Reschedule re-transmit */
03584          reschedule = siptimer_a;
03585          ast_debug(4, "** SIP timers: Rescheduling retransmission %d to %d ms (t1 %d ms (Retrans id #%d)) \n",
03586             pkt->retrans + 1,
03587             siptimer_a,
03588             pkt->timer_t1,
03589             pkt->retransid);
03590       }
03591 
03592       if (sip_debug_test_pvt(pkt->owner)) {
03593          const struct ast_sockaddr *dst = sip_real_dst(pkt->owner);
03594          ast_verbose("Retransmitting #%d (%s) to %s:\n%s\n---\n",
03595             pkt->retrans, sip_nat_mode(pkt->owner),
03596             ast_sockaddr_stringify(dst),
03597             pkt->data->str);
03598       }
03599 
03600       append_history(pkt->owner, "ReTx", "%d %s", reschedule, pkt->data->str);
03601       xmitres = __sip_xmit(pkt->owner, pkt->data);
03602 
03603       /* If there was no error during the network transmission, schedule the next retransmission,
03604        * but if the next retransmission is going to be beyond our timeout period, mark the packet's
03605        * stop_retrans value and set the next retransmit to be the exact time of timeout.  This will
03606        * allow any responses to the packet to be processed before the packet is destroyed on the next
03607        * call to this function by the scheduler. */
03608       if (xmitres != XMIT_ERROR) {
03609          if (reschedule >= diff) {
03610             pkt->retrans_stop = 1;
03611             reschedule = diff;
03612          }
03613          sip_pvt_unlock(pkt->owner);
03614          return  reschedule;
03615       }
03616    }
03617 
03618    /* At this point, either the packet's retransmission timed out, or there was a
03619     * transmission error, either way destroy the scheduler item and this packet. */
03620 
03621    pkt->retransid = -1; /* Kill this scheduler item */
03622 
03623    if (pkt->owner && pkt->method != SIP_OPTIONS && xmitres == 0) {
03624       if (pkt->is_fatal || sipdebug) { /* Tell us if it's critical or if we're debugging */
03625          ast_log(LOG_WARNING, "Retransmission timeout reached on transmission %s for seqno %d (%s %s) -- See https://wiki.asterisk.org/wiki/display/AST/SIP+Retransmissions\n"
03626             "Packet timed out after %dms with no response\n",
03627             pkt->owner->callid,
03628             pkt->seqno,
03629             pkt->is_fatal ? "Critical" : "Non-critical",
03630             pkt->is_resp ? "Response" : "Request",
03631             (int) ast_tvdiff_ms(ast_tvnow(), pkt->time_sent));
03632       }
03633    } else if (pkt->method == SIP_OPTIONS && sipdebug) {
03634       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);
03635    }
03636 
03637    if (xmitres == XMIT_ERROR) {
03638       ast_log(LOG_WARNING, "Transmit error :: Cancelling transmission on Call ID %s\n", pkt->owner->callid);
03639       append_history(pkt->owner, "XmitErr", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
03640    } else {
03641       append_history(pkt->owner, "MaxRetries", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
03642    }
03643 
03644    if (pkt->is_fatal) {
03645       while(pkt->owner->owner && ast_channel_trylock(pkt->owner->owner)) {
03646          sip_pvt_unlock(pkt->owner);   /* SIP_PVT, not channel */
03647          usleep(1);
03648          sip_pvt_lock(pkt->owner);
03649       }
03650       if (pkt->owner->owner && !pkt->owner->owner->hangupcause) {
03651          pkt->owner->owner->hangupcause = AST_CAUSE_NO_USER_RESPONSE;
03652       }
03653       if (pkt->owner->owner) {
03654          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);
03655 
03656          if (pkt->is_resp &&
03657             (pkt->response_code >= 200) &&
03658             (pkt->response_code < 300) &&
03659             pkt->owner->pendinginvite &&
03660             ast_test_flag(&pkt->owner->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED)) {
03661             /* This is a timeout of the 2XX response to a pending INVITE.  In this case terminate the INVITE
03662              * transaction just as if we received the ACK, but immediately hangup with a BYE (sip_hangup
03663              * will send the BYE as long as the dialog is not set as "alreadygone")
03664              * RFC 3261 section 13.3.1.4.
03665              * "If the server retransmits the 2xx response for 64*T1 seconds without receiving
03666              * an ACK, the dialog is confirmed, but the session SHOULD be terminated.  This is
03667              * accomplished with a BYE, as described in Section 15." */
03668             pkt->owner->invitestate = INV_TERMINATED;
03669             pkt->owner->pendinginvite = 0;
03670          } else {
03671             /* there is nothing left to do, mark the dialog as gone */
03672             sip_alreadygone(pkt->owner);
03673          }
03674          ast_queue_hangup_with_cause(pkt->owner->owner, AST_CAUSE_PROTOCOL_ERROR);
03675          ast_channel_unlock(pkt->owner->owner);
03676       } else {
03677          /* If no channel owner, destroy now */
03678 
03679          /* Let the peerpoke system expire packets when the timer expires for poke_noanswer */
03680          if (pkt->method != SIP_OPTIONS && pkt->method != SIP_REGISTER) {
03681             pvt_set_needdestroy(pkt->owner, "no response to critical packet");
03682             sip_alreadygone(pkt->owner);
03683             append_history(pkt->owner, "DialogKill", "Killing this failed dialog immediately");
03684          }
03685       }
03686    }
03687 
03688    if (pkt->method == SIP_BYE) {
03689       /* We're not getting answers on SIP BYE's.  Tear down the call anyway. */
03690       sip_alreadygone(pkt->owner);
03691       if (pkt->owner->owner) {
03692          ast_channel_unlock(pkt->owner->owner);
03693       }
03694       append_history(pkt->owner, "ByeFailure", "Remote peer doesn't respond to bye. Destroying call anyway.");
03695       pvt_set_needdestroy(pkt->owner, "no response to BYE");
03696    }
03697 
03698    /* Remove the packet */
03699    for (prev = NULL, cur = pkt->owner->packets; cur; prev = cur, cur = cur->next) {
03700       if (cur == pkt) {
03701          UNLINK(cur, pkt->owner->packets, prev);
03702          sip_pvt_unlock(pkt->owner);
03703          if (pkt->owner) {
03704             pkt->owner = dialog_unref(pkt->owner,"pkt is being freed, its dialog ref is dead now");
03705          }
03706          if (pkt->data) {
03707             ast_free(pkt->data);
03708          }
03709          pkt->data = NULL;
03710          ast_free(pkt);
03711          return 0;
03712       }
03713    }
03714    /* error case */
03715    ast_log(LOG_WARNING, "Weird, couldn't find packet owner!\n");
03716    sip_pvt_unlock(pkt->owner);
03717    return 0;
03718 }
03719 
03720 /*!
03721  * \internal
03722  * \brief Transmit packet with retransmits
03723  * \return 0 on success, -1 on failure to allocate packet
03724  */
03725 static enum sip_result __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, struct ast_str *data, int fatal, int sipmethod)
03726 {
03727    struct sip_pkt *pkt = NULL;
03728    int siptimer_a = DEFAULT_RETRANS;
03729    int xmitres = 0;
03730    int respid;
03731 
03732    if (sipmethod == SIP_INVITE) {
03733       /* Note this is a pending invite */
03734       p->pendinginvite = seqno;
03735    }
03736 
03737    /* If the transport is something reliable (TCP or TLS) then don't really send this reliably */
03738    /* I removed the code from retrans_pkt that does the same thing so it doesn't get loaded into the scheduler */
03739    /*! \todo According to the RFC some packets need to be retransmitted even if its TCP, so this needs to get revisited */
03740    if (!(p->socket.type & SIP_TRANSPORT_UDP)) {
03741       xmitres = __sip_xmit(p, data);   /* Send packet */
03742       if (xmitres == XMIT_ERROR) {  /* Serious network trouble, no need to try again */
03743          append_history(p, "XmitErr", "%s", fatal ? "(Critical)" : "(Non-critical)");
03744          return AST_FAILURE;
03745       } else {
03746          return AST_SUCCESS;
03747       }
03748    }
03749 
03750    if (!(pkt = ast_calloc(1, sizeof(*pkt)))) {
03751       return AST_FAILURE;
03752    }
03753    /* copy data, add a terminator and save length */
03754    if (!(pkt->data = ast_str_create(ast_str_strlen(data)))) {
03755       ast_free(pkt);
03756       return AST_FAILURE;
03757    }
03758    ast_str_set(&pkt->data, 0, "%s%s", data->str, "\0");
03759    /* copy other parameters from the caller */
03760    pkt->method = sipmethod;
03761    pkt->seqno = seqno;
03762    pkt->is_resp = resp;
03763    pkt->is_fatal = fatal;
03764    pkt->owner = dialog_ref(p, "__sip_reliable_xmit: setting pkt->owner");
03765    pkt->next = p->packets;
03766    p->packets = pkt; /* Add it to the queue */
03767    if (resp) {
03768       /* Parse out the response code */
03769       if (sscanf(ast_str_buffer(pkt->data), "SIP/2.0 %30u", &respid) == 1) {
03770          pkt->response_code = respid;
03771       }
03772    }
03773    pkt->timer_t1 = p->timer_t1;  /* Set SIP timer T1 */
03774    pkt->retransid = -1;
03775    if (pkt->timer_t1) {
03776       siptimer_a = pkt->timer_t1;
03777    }
03778 
03779    pkt->time_sent = ast_tvnow(); /* time packet was sent */
03780    pkt->retrans_stop_time = 64 * (pkt->timer_t1 ? pkt->timer_t1 : DEFAULT_TIMER_T1); /* time in ms after pkt->time_sent to stop retransmission */
03781 
03782    /* Schedule retransmission */
03783    AST_SCHED_REPLACE_VARIABLE(pkt->retransid, sched, siptimer_a, retrans_pkt, pkt, 1);
03784    if (sipdebug) {
03785       ast_debug(4, "*** SIP TIMER: Initializing retransmit timer on packet: Id  #%d\n", pkt->retransid);
03786    }
03787 
03788    xmitres = __sip_xmit(pkt->owner, pkt->data); /* Send packet */
03789 
03790    if (xmitres == XMIT_ERROR) {  /* Serious network trouble, no need to try again */
03791       append_history(pkt->owner, "XmitErr", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
03792       ast_log(LOG_ERROR, "Serious Network Trouble; __sip_xmit returns error for pkt data\n");
03793       AST_SCHED_DEL(sched, pkt->retransid);
03794       p->packets = pkt->next;
03795       pkt->owner = dialog_unref(pkt->owner,"pkt is being freed, its dialog ref is dead now");
03796       ast_free(pkt->data);
03797       ast_free(pkt);
03798       return AST_FAILURE;
03799    } else {
03800       /* This is odd, but since the retrans timer starts at 500ms and the do_monitor thread
03801        * only wakes up every 1000ms by default, we have to poke the thread here to make
03802        * sure it successfully detects this must be retransmitted in less time than
03803        * it usually sleeps for. Otherwise it might not retransmit this packet for 1000ms. */
03804       if (monitor_thread != AST_PTHREADT_NULL) {
03805          pthread_kill(monitor_thread, SIGURG);
03806       }
03807       return AST_SUCCESS;
03808    }
03809 }
03810 
03811 /*! \brief Kill a SIP dialog (called only by the scheduler)
03812  * The scheduler has a reference to this dialog when p->autokillid != -1,
03813  * and we are called using that reference. So if the event is not
03814  * rescheduled, we need to call dialog_unref().
03815  */
03816 static int __sip_autodestruct(const void *data)
03817 {
03818    struct sip_pvt *p = (struct sip_pvt *)data;
03819    struct ast_channel *owner;
03820 
03821    /* If this is a subscription, tell the phone that we got a timeout */
03822    if (p->subscribed && p->subscribed != MWI_NOTIFICATION && p->subscribed != CALL_COMPLETION) {
03823       transmit_state_notify(p, AST_EXTENSION_DEACTIVATED, 1, TRUE);  /* Send last notification */
03824       p->subscribed = NONE;
03825       append_history(p, "Subscribestatus", "timeout");
03826       ast_debug(3, "Re-scheduled destruction of SIP subscription %s\n", p->callid ? p->callid : "<unknown>");
03827       return 10000;  /* Reschedule this destruction so that we know that it's gone */
03828    }
03829 
03830    /* If there are packets still waiting for delivery, delay the destruction */
03831    if (p->packets) {
03832       if (!p->needdestroy) {
03833          char method_str[31];
03834          ast_debug(3, "Re-scheduled destruction of SIP call %s\n", p->callid ? p->callid : "<unknown>");
03835          append_history(p, "ReliableXmit", "timeout");
03836          if (sscanf(p->lastmsg, "Tx: %30s", method_str) == 1 || sscanf(p->lastmsg, "Rx: %30s", method_str) == 1) {
03837             if (method_match(SIP_CANCEL, method_str) || method_match(SIP_BYE, method_str)) {
03838                pvt_set_needdestroy(p, "autodestruct");
03839             }
03840          }
03841          return 10000;
03842       } else {
03843          /* They've had their chance to respond. Time to bail */
03844          __sip_pretend_ack(p);
03845       }
03846    }
03847 
03848    /* Reset schedule ID */
03849    p->autokillid = -1;
03850 
03851 
03852    /*
03853     * Lock both the pvt and the channel safely so that we can queue up a frame.
03854     */
03855    owner = sip_pvt_lock_full(p);
03856    if (owner) {
03857       ast_log(LOG_WARNING, "Autodestruct on dialog '%s' with owner in place (Method: %s)\n", p->callid, sip_methods[p->method].text);
03858       ast_queue_hangup_with_cause(owner, AST_CAUSE_PROTOCOL_ERROR);
03859       ast_channel_unlock(owner);
03860       ast_channel_unref(owner);
03861    } else if (p->refer && !p->alreadygone) {
03862       ast_debug(3, "Finally hanging up channel after transfer: %s\n", p->callid);
03863       stop_media_flows(p);
03864       transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
03865       append_history(p, "ReferBYE", "Sending BYE on transferer call leg %s", p->callid);
03866       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
03867    } else {
03868       append_history(p, "AutoDestroy", "%s", p->callid);
03869       ast_debug(3, "Auto destroying SIP dialog '%s'\n", p->callid);
03870       sip_pvt_unlock(p);
03871       dialog_unlink_all(p); /* once it's unlinked and unrefd everywhere, it'll be freed automagically */
03872       sip_pvt_lock(p);
03873       /* dialog_unref(p, "unref dialog-- no other matching conditions"); -- unlink all now should finish off the dialog's references and free it. */
03874       /* sip_destroy(p); */      /* Go ahead and destroy dialog. All attempts to recover is done */
03875       /* sip_destroy also absorbs the reference */
03876    }
03877 
03878    sip_pvt_unlock(p);
03879 
03880    dialog_unref(p, "The ref to a dialog passed to this sched callback is going out of scope; unref it.");
03881 
03882    return 0;
03883 }
03884 
03885 /*! \brief Schedule final destruction of SIP dialog.  This can not be canceled.
03886  *  This function is used to keep a dialog around for a period of time in order
03887  *  to properly respond to any retransmits. */
03888 void sip_scheddestroy_final(struct sip_pvt *p, int ms)
03889 {
03890    if (p->final_destruction_scheduled) {
03891       return; /* already set final destruction */
03892    }
03893 
03894    sip_scheddestroy(p, ms);
03895    if (p->autokillid != -1) {
03896       p->final_destruction_scheduled = 1;
03897    }
03898 }
03899 
03900 /*! \brief Schedule destruction of SIP dialog */
03901 void sip_scheddestroy(struct sip_pvt *p, int ms)
03902 {
03903    if (p->final_destruction_scheduled) {
03904       return; /* already set final destruction */
03905    }
03906 
03907    if (ms < 0) {
03908       if (p->timer_t1 == 0) {
03909          p->timer_t1 = global_t1;   /* Set timer T1 if not set (RFC 3261) */
03910       }
03911       if (p->timer_b == 0) {
03912          p->timer_b = global_timer_b;  /* Set timer B if not set (RFC 3261) */
03913       }
03914       ms = p->timer_t1 * 64;
03915    }
03916    if (sip_debug_test_pvt(p)) {
03917       ast_verbose("Scheduling destruction of SIP dialog '%s' in %d ms (Method: %s)\n", p->callid, ms, sip_methods[p->method].text);
03918    }
03919    if (sip_cancel_destroy(p)) {
03920       ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
03921    }
03922 
03923    if (p->do_history) {
03924       append_history(p, "SchedDestroy", "%d ms", ms);
03925    }
03926    p->autokillid = ast_sched_add(sched, ms, __sip_autodestruct, dialog_ref(p, "setting ref as passing into ast_sched_add for __sip_autodestruct"));
03927 
03928    if (p->stimer && p->stimer->st_active == TRUE && p->stimer->st_schedid > 0) {
03929       stop_session_timer(p);
03930    }
03931 }
03932 
03933 /*! \brief Cancel destruction of SIP dialog.
03934  * Be careful as this also absorbs the reference - if you call it
03935  * from within the scheduler, this might be the last reference.
03936  */
03937 int sip_cancel_destroy(struct sip_pvt *p)
03938 {
03939    if (p->final_destruction_scheduled) {
03940       return 0;
03941    }
03942 
03943    if (p->autokillid > -1) {
03944       append_history(p, "CancelDestroy", "");
03945       AST_SCHED_DEL_UNREF(sched, p->autokillid, dialog_unref(p, "remove ref for autokillid"));
03946    }
03947    return 0;
03948 }
03949 
03950 /*! \brief Acknowledges receipt of a packet and stops retransmission
03951  * called with p locked*/
03952 int __sip_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod)
03953 {
03954    struct sip_pkt *cur, *prev = NULL;
03955    const char *msg = "Not Found";   /* used only for debugging */
03956    int res = FALSE;
03957 
03958    /* If we have an outbound proxy for this dialog, then delete it now since
03959      the rest of the requests in this dialog needs to follow the routing.
03960      If obforcing is set, we will keep the outbound proxy during the whole
03961      dialog, regardless of what the SIP rfc says
03962    */
03963    if (p->outboundproxy && !p->outboundproxy->force){
03964       ref_proxy(p, NULL);
03965    }
03966 
03967    for (cur = p->packets; cur; prev = cur, cur = cur->next) {
03968       if (cur->seqno != seqno || cur->is_resp != resp) {
03969          continue;
03970       }
03971       if (cur->is_resp || cur->method == sipmethod) {
03972          res = TRUE;
03973          msg = "Found";
03974          if (!resp && (seqno == p->pendinginvite)) {
03975             ast_debug(1, "Acked pending invite %d\n", p->pendinginvite);
03976             p->pendinginvite = 0;
03977          }
03978          if (cur->retransid > -1) {
03979             if (sipdebug)
03980                ast_debug(4, "** SIP TIMER: Cancelling retransmit of packet (reply received) Retransid #%d\n", cur->retransid);
03981          }
03982          /* This odd section is designed to thwart a
03983           * race condition in the packet scheduler. There are
03984           * two conditions under which deleting the packet from the
03985           * scheduler can fail.
03986           *
03987           * 1. The packet has been removed from the scheduler because retransmission
03988           * is being attempted. The problem is that if the packet is currently attempting
03989           * retransmission and we are at this point in the code, then that MUST mean
03990           * that retrans_pkt is waiting on p's lock. Therefore we will relinquish the
03991           * lock temporarily to allow retransmission.
03992           *
03993           * 2. The packet has reached its maximum number of retransmissions and has
03994           * been permanently removed from the packet scheduler. If this is the case, then
03995           * the packet's retransid will be set to -1. The atomicity of the setting and checking
03996           * of the retransid to -1 is ensured since in both cases p's lock is held.
03997           */
03998          while (cur->retransid > -1 && ast_sched_del(sched, cur->retransid)) {
03999             sip_pvt_unlock(p);
04000             usleep(1);
04001             sip_pvt_lock(p);
04002          }
04003          UNLINK(cur, p->packets, prev);
04004          dialog_unref(cur->owner, "unref pkt cur->owner dialog from sip ack before freeing pkt");
04005          if (cur->data) {
04006             ast_free(cur->data);
04007          }
04008          ast_free(cur);
04009          break;
04010       }
04011    }
04012    ast_debug(1, "Stopping retransmission on '%s' of %s %d: Match %s\n",
04013       p->callid, resp ? "Response" : "Request", seqno, msg);
04014    return res;
04015 }
04016 
04017 /*! \brief Pretend to ack all packets
04018  * called with p locked */
04019 void __sip_pretend_ack(struct sip_pvt *p)
04020 {
04021    struct sip_pkt *cur = NULL;
04022 
04023    while (p->packets) {
04024       int method;
04025       if (cur == p->packets) {
04026          ast_log(LOG_WARNING, "Have a packet that doesn't want to give up! %s\n", sip_methods[cur->method].text);
04027          return;
04028       }
04029       cur = p->packets;
04030       method = (cur->method) ? cur->method : find_sip_method(cur->data->str);
04031       __sip_ack(p, cur->seqno, cur->is_resp, method);
04032    }
04033 }
04034 
04035 /*! \brief Acks receipt of packet, keep it around (used for provisional responses) */
04036 int __sip_semi_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod)
04037 {
04038    struct sip_pkt *cur;
04039    int res = FALSE;
04040 
04041    for (cur = p->packets; cur; cur = cur->next) {
04042       if (cur->seqno == seqno && cur->is_resp == resp &&
04043          (cur->is_resp || method_match(sipmethod, cur->data->str))) {
04044          /* this is our baby */
04045          if (cur->retransid > -1) {
04046             if (sipdebug)
04047                ast_debug(4, "*** SIP TIMER: Cancelling retransmission #%d - %s (got response)\n", cur->retransid, sip_methods[sipmethod].text);
04048          }
04049          AST_SCHED_DEL(sched, cur->retransid);
04050          res = TRUE;
04051          break;
04052       }
04053    }
04054    ast_debug(1, "(Provisional) Stopping retransmission (but retaining packet) on '%s' %s %d: %s\n", p->callid, resp ? "Response" : "Request", seqno, res == -1 ? "Not Found" : "Found");
04055    return res;
04056 }
04057 
04058 
04059 /*! \brief Copy SIP request, parse it */
04060 static void parse_copy(struct sip_request *dst, const struct sip_request *src)
04061 {
04062    copy_request(dst, src);
04063    parse_request(dst);
04064 }
04065 
04066 /*! \brief add a blank line if no body */
04067 static void add_blank(struct sip_request *req)
04068 {
04069    if (!req->lines) {
04070       /* Add extra empty return. add_header() reserves 4 bytes so cannot be truncated */
04071       ast_str_append(&req->data, 0, "\r\n");
04072    }
04073 }
04074 
04075 static int send_provisional_keepalive_full(struct sip_pvt *pvt, int with_sdp)
04076 {
04077    const char *msg = NULL;
04078 
04079    if (!pvt->last_provisional || !strncasecmp(pvt->last_provisional, "100", 3)) {
04080       msg = "183 Session Progress";
04081    }
04082 
04083    if (pvt->invitestate < INV_COMPLETED) {
04084       if (with_sdp) {
04085          transmit_response_with_sdp(pvt, S_OR(msg, pvt->last_provisional), &pvt->initreq, XMIT_UNRELIABLE, FALSE, FALSE);
04086       } else {
04087          transmit_response(pvt, S_OR(msg, pvt->last_provisional), &pvt->initreq);
04088       }
04089       return PROVIS_KEEPALIVE_TIMEOUT;
04090    }
04091 
04092    return 0;
04093 }
04094 
04095 static int send_provisional_keepalive(const void *data) {
04096    struct sip_pvt *pvt = (struct sip_pvt *) data;
04097 
04098    return send_provisional_keepalive_full(pvt, 0);
04099 }
04100 
04101 static int send_provisional_keepalive_with_sdp(const void *data) {
04102    struct sip_pvt *pvt = (void *)data;
04103 
04104    return send_provisional_keepalive_full(pvt, 1);
04105 }
04106 
04107 static void update_provisional_keepalive(struct sip_pvt *pvt, int with_sdp)
04108 {
04109    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"));
04110 
04111    pvt->provisional_keepalive_sched_id = ast_sched_add(sched, PROVIS_KEEPALIVE_TIMEOUT,
04112       with_sdp ? send_provisional_keepalive_with_sdp : send_provisional_keepalive, dialog_ref(pvt, "Increment refcount to pass dialog pointer to sched callback"));
04113 }
04114 
04115 /*! \brief Transmit response on SIP request*/
04116 static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno)
04117 {
04118    int res;
04119 
04120    finalize_content(req);
04121    add_blank(req);
04122    if (sip_debug_test_pvt(p)) {
04123       const struct ast_sockaddr *dst = sip_real_dst(p);
04124 
04125       ast_verbose("\n<--- %sTransmitting (%s) to %s --->\n%s\n<------------>\n",
04126          reliable ? "Reliably " : "", sip_nat_mode(p),
04127          ast_sockaddr_stringify(dst),
04128          req->data->str);
04129    }
04130    if (p->do_history) {
04131       struct sip_request tmp = { .rlPart1 = 0, };
04132       parse_copy(&tmp, req);
04133       append_history(p, reliable ? "TxRespRel" : "TxResp", "%s / %s - %s", tmp.data->str, get_header(&tmp, "CSeq"),
04134          (tmp.method == SIP_RESPONSE || tmp.method == SIP_UNKNOWN) ? REQ_OFFSET_TO_STR(&tmp, rlPart2) : sip_methods[tmp.method].text);
04135       deinit_req(&tmp);
04136    }
04137 
04138    /* If we are sending a final response to an INVITE, stop retransmitting provisional responses */
04139    if (p->initreq.method == SIP_INVITE && reliable == XMIT_CRITICAL) {
04140       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"));
04141    }
04142 
04143    res = (reliable) ?
04144        __sip_reliable_xmit(p, seqno, 1, req->data, (reliable == XMIT_CRITICAL), req->method) :
04145       __sip_xmit(p, req->data);
04146    deinit_req(req);
04147    if (res > 0) {
04148       return 0;
04149    }
04150    return res;
04151 }
04152 
04153 /*!
04154  * \internal
04155  * \brief Send SIP Request to the other part of the dialogue
04156  * \return see \ref __sip_xmit
04157  */
04158 static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno)
04159 {
04160    int res;
04161 
04162    /* If we have an outbound proxy, reset peer address
04163       Only do this once.
04164    */
04165    if (p->outboundproxy) {
04166       p->sa = p->outboundproxy->ip;
04167    }
04168 
04169    finalize_content(req);
04170    add_blank(req);
04171    if (sip_debug_test_pvt(p)) {
04172       if (ast_test_flag(&p->flags[0], SIP_NAT_FORCE_RPORT)) {
04173          ast_verbose("%sTransmitting (NAT) to %s:\n%s\n---\n", reliable ? "Reliably " : "", ast_sockaddr_stringify(&p->recv), req->data->str);
04174       } else {
04175          ast_verbose("%sTransmitting (no NAT) to %s:\n%s\n---\n", reliable ? "Reliably " : "", ast_sockaddr_stringify(&p->sa), req->data->str);
04176       }
04177    }
04178    if (p->do_history) {
04179       struct sip_request tmp = { .rlPart1 = 0, };
04180       parse_copy(&tmp, req);
04181       append_history(p, reliable ? "TxReqRel" : "TxReq", "%s / %s - %s", tmp.data->str, get_header(&tmp, "CSeq"), sip_methods[tmp.method].text);
04182       deinit_req(&tmp);
04183    }
04184    res = (reliable) ?
04185       __sip_reliable_xmit(p, seqno, 0, req->data, (reliable == XMIT_CRITICAL), req->method) :
04186       __sip_xmit(p, req->data);
04187    deinit_req(req);
04188    return res;
04189 }
04190 
04191 static void enable_dsp_detect(struct sip_pvt *p)
04192 {
04193    int features = 0;
04194 
04195    if (p->dsp) {
04196       return;
04197    }
04198 
04199    if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) ||
04200        (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO)) {
04201       if (p->rtp) {
04202          ast_rtp_instance_dtmf_mode_set(p->rtp, AST_RTP_DTMF_MODE_INBAND);
04203       }
04204       features |= DSP_FEATURE_DIGIT_DETECT;
04205    }
04206 
04207    if (ast_test_flag(&p->flags[1], SIP_PAGE2_FAX_DETECT_CNG)) {
04208       features |= DSP_FEATURE_FAX_DETECT;
04209    }
04210 
04211    if (!features) {
04212       return;
04213    }
04214 
04215    if (!(p->dsp = ast_dsp_new())) {
04216       return;
04217    }
04218 
04219    ast_dsp_set_features(p->dsp, features);
04220    if (global_relaxdtmf) {
04221       ast_dsp_set_digitmode(p->dsp, DSP_DIGITMODE_DTMF | DSP_DIGITMODE_RELAXDTMF);
04222    }
04223 }
04224 
04225 static void disable_dsp_detect(struct sip_pvt *p)
04226 {
04227    if (p->dsp) {
04228       ast_dsp_free(p->dsp);
04229       p->dsp = NULL;
04230    }
04231 }
04232 
04233 /*! \brief Set an option on a SIP dialog */
04234 static int sip_setoption(struct ast_channel *chan, int option, void *data, int datalen)
04235 {
04236    int res = -1;
04237    struct sip_pvt *p = chan->tech_pvt;
04238 
04239         if (!p) {
04240          ast_log(LOG_ERROR, "Attempt to Ref a null pointer.  sip private structure is gone!\n");
04241          return -1;
04242         }
04243 
04244    sip_pvt_lock(p);
04245 
04246    switch (option) {
04247    case AST_OPTION_FORMAT_READ:
04248       if (p->rtp) {
04249          res = ast_rtp_instance_set_read_format(p->rtp, *(int *) data);
04250       }
04251       break;
04252    case AST_OPTION_FORMAT_WRITE:
04253       if (p->rtp) {
04254          res = ast_rtp_instance_set_write_format(p->rtp, *(int *) data);
04255       }
04256       break;
04257    case AST_OPTION_MAKE_COMPATIBLE:
04258       if (p->rtp) {
04259          res = ast_rtp_instance_make_compatible(chan, p->rtp, (struct ast_channel *) data);
04260       }
04261       break;
04262    case AST_OPTION_DIGIT_DETECT:
04263       if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) ||
04264           (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO)) {
04265          char *cp = (char *) data;
04266 
04267          ast_debug(1, "%sabling digit detection on %s\n", *cp ? "En" : "Dis", chan->name);
04268          if (*cp) {
04269             enable_dsp_detect(p);
04270          } else {
04271             disable_dsp_detect(p);
04272          }
04273          res = 0;
04274       }
04275       break;
04276    case AST_OPTION_SECURE_SIGNALING:
04277       p->req_secure_signaling = *(unsigned int *) data;
04278       res = 0;
04279       break;
04280    case AST_OPTION_SECURE_MEDIA:
04281       ast_set2_flag(&p->flags[1], *(unsigned int *) data, SIP_PAGE2_USE_SRTP);
04282       res = 0;
04283       break;
04284    default:
04285       break;
04286    }
04287 
04288    sip_pvt_unlock(p);
04289 
04290    return res;
04291 }
04292 
04293 /*! \brief Query an option on a SIP dialog */
04294 static int sip_queryoption(struct ast_channel *chan, int option, void *data, int *datalen)
04295 {
04296    int res = -1;
04297    enum ast_t38_state state = T38_STATE_UNAVAILABLE;
04298    struct sip_pvt *p = (struct sip_pvt *) chan->tech_pvt;
04299    char *cp;
04300 
04301    sip_pvt_lock(p);
04302 
04303    switch (option) {
04304    case AST_OPTION_T38_STATE:
04305       /* Make sure we got an ast_t38_state enum passed in */
04306       if (*datalen != sizeof(enum ast_t38_state)) {
04307          ast_log(LOG_ERROR, "Invalid datalen for AST_OPTION_T38_STATE option. Expected %d, got %d\n", (int)sizeof(enum ast_t38_state), *datalen);
04308          break;
04309       }
04310 
04311       /* 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 */
04312       if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT)) {
04313          switch (p->t38.state) {
04314          case T38_LOCAL_REINVITE:
04315          case T38_PEER_REINVITE:
04316             state = T38_STATE_NEGOTIATING;
04317             break;
04318          case T38_ENABLED:
04319             state = T38_STATE_NEGOTIATED;
04320             break;
04321          default:
04322             state = T38_STATE_UNKNOWN;
04323          }
04324       }
04325 
04326       *((enum ast_t38_state *) data) = state;
04327       res = 0;
04328 
04329       break;
04330    case AST_OPTION_DIGIT_DETECT:
04331       cp = (char *) data;
04332       *cp = p->dsp ? 1 : 0;
04333       ast_debug(1, "Reporting digit detection %sabled on %s\n", *cp ? "en" : "dis", chan->name);
04334       break;
04335    case AST_OPTION_SECURE_SIGNALING:
04336       *((unsigned int *) data) = p->req_secure_signaling;
04337       res = 0;
04338       break;
04339    case AST_OPTION_SECURE_MEDIA:
04340       *((unsigned int *) data) = ast_test_flag(&p->flags[1], SIP_PAGE2_USE_SRTP) ? 1 : 0;
04341       res = 0;
04342       break;
04343    case AST_OPTION_DEVICE_NAME:
04344       if (p && p->outgoing_call) {
04345          cp = (char *) data;
04346          ast_copy_string(cp, p->dialstring, *datalen);
04347          res = 0;
04348       }
04349       /* We purposely break with a return of -1 in the
04350        * implied else case here
04351        */
04352       break;
04353    default:
04354       break;
04355    }
04356 
04357    sip_pvt_unlock(p);
04358 
04359    return res;
04360 }
04361 
04362 /*! \brief Locate closing quote in a string, skipping escaped quotes.
04363  * optionally with a limit on the search.
04364  * start must be past the first quote.
04365  */
04366 const char *find_closing_quote(const char *start, const char *lim)
04367 {
04368    char last_char = '\0';
04369    const char *s;
04370    for (s = start; *s && s != lim; last_char = *s++) {
04371       if (*s == '"' && last_char != '\\')
04372          break;
04373    }
04374    return s;
04375 }
04376 
04377 /*! \brief Send message with Access-URL header, if this is an HTML URL only! */
04378 static int sip_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen)
04379 {
04380    struct sip_pvt *p = chan->tech_pvt;
04381 
04382    if (subclass != AST_HTML_URL)
04383       return -1;
04384 
04385    ast_string_field_build(p, url, "<%s>;mode=active", data);
04386 
04387    if (sip_debug_test_pvt(p))
04388       ast_debug(1, "Send URL %s, state = %d!\n", data, chan->_state);
04389 
04390    switch (chan->_state) {
04391    case AST_STATE_RING:
04392       transmit_response(p, "100 Trying", &p->initreq);
04393       break;
04394    case AST_STATE_RINGING:
04395       transmit_response(p, "180 Ringing", &p->initreq);
04396       break;
04397    case AST_STATE_UP:
04398       if (!p->pendinginvite) {      /* We are up, and have no outstanding invite */
04399          transmit_reinvite_with_sdp(p, FALSE, FALSE);
04400       } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
04401          ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);   
04402       }  
04403       break;
04404    default:
04405       ast_log(LOG_WARNING, "Don't know how to send URI when state is %d!\n", chan->_state);
04406    }
04407 
04408    return 0;
04409 }
04410 
04411 /*! \brief Deliver SIP call ID for the call */
04412 static const char *sip_get_callid(struct ast_channel *chan)
04413 {
04414    return chan->tech_pvt ? ((struct sip_pvt *) chan->tech_pvt)->callid : "";
04415 }
04416 
04417 /*!
04418  * \internal
04419  * \brief Send SIP MESSAGE text within a call
04420  * \note Called from PBX core sendtext() application
04421  */
04422 static int sip_sendtext(struct ast_channel *ast, const char *text)
04423 {
04424    struct sip_pvt *dialog = ast->tech_pvt;
04425    int debug = sip_debug_test_pvt(dialog);
04426 
04427    if (!dialog)
04428       return -1;
04429    /* NOT ast_strlen_zero, because a zero-length message is specifically
04430     * allowed by RFC 3428 (See section 10, Examples) */
04431    if (!text)
04432       return 0;
04433    if(!is_method_allowed(&dialog->allowed_methods, SIP_MESSAGE)) {
04434       ast_debug(2, "Trying to send MESSAGE to device that does not support it.\n");
04435       return(0);
04436    }
04437    if (debug)
04438       ast_verbose("Sending text %s on %s\n", text, ast->name);
04439    transmit_message_with_text(dialog, text);
04440    return 0;   
04441 }
04442 
04443 /*! \brief Update peer object in realtime storage
04444    If the Asterisk system name is set in asterisk.conf, we will use
04445    that name and store that in the "regserver" field in the sippeers
04446    table to facilitate multi-server setups.
04447 */
04448 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)
04449 {
04450    char port[10];
04451    char ipaddr[INET6_ADDRSTRLEN];
04452    char regseconds[20];
04453    char *tablename = NULL;
04454    char str_lastms[20];
04455 
04456    const char *sysname = ast_config_AST_SYSTEM_NAME;
04457    char *syslabel = NULL;
04458 
04459    time_t nowtime = time(NULL) + expirey;
04460    const char *fc = fullcontact ? "fullcontact" : NULL;
04461 
04462    int realtimeregs = ast_check_realtime("sipregs");
04463 
04464    tablename = realtimeregs ? "sipregs" : "sippeers";
04465    
04466 
04467    snprintf(str_lastms, sizeof(str_lastms), "%d", lastms);
04468    snprintf(regseconds, sizeof(regseconds), "%d", (int)nowtime);  /* Expiration time */
04469    ast_copy_string(ipaddr, ast_sockaddr_stringify_addr(addr), sizeof(ipaddr));
04470    ast_copy_string(port, ast_sockaddr_stringify_port(addr), sizeof(port));
04471 
04472    if (ast_strlen_zero(sysname)) /* No system name, disable this */
04473       sysname = NULL;
04474    else if (sip_cfg.rtsave_sysname)
04475       syslabel = "regserver";
04476 
04477    /* XXX IMPORTANT: Anytime you add a new parameter to be updated, you
04478          *  must also add it to contrib/scripts/asterisk.ldap-schema,
04479          *  contrib/scripts/asterisk.ldif,
04480          *  and to configs/res_ldap.conf.sample as described in
04481          *  bugs 15156 and 15895 
04482          */
04483    if (fc) {
04484       ast_update_realtime(tablename, "name", peername, "ipaddr", ipaddr,
04485          "port", port, "regseconds", regseconds,
04486          deprecated_username ? "username" : "defaultuser", defaultuser,
04487          "useragent", useragent, "lastms", str_lastms,
04488          fc, fullcontact, syslabel, sysname, SENTINEL); /* note fc and syslabel _can_ be NULL */
04489    } else {
04490       ast_update_realtime(tablename, "name", peername, "ipaddr", ipaddr,
04491          "port", port, "regseconds", regseconds,
04492          "useragent", useragent, "lastms", str_lastms,
04493          deprecated_username ? "username" : "defaultuser", defaultuser,
04494          syslabel, sysname, SENTINEL); /* note syslabel _can_ be NULL */
04495    }
04496 }
04497 
04498 /*! \brief Automatically add peer extension to dial plan */
04499 static void register_peer_exten(struct sip_peer *peer, int onoff)
04500 {
04501    char multi[256];
04502    char *stringp, *ext, *context;
04503    struct pbx_find_info q = { .stacklen = 0 };
04504 
04505    /* XXX note that sip_cfg.regcontext is both a global 'enable' flag and
04506     * the name of the global regexten context, if not specified
04507     * individually.
04508     */
04509    if (ast_strlen_zero(sip_cfg.regcontext))
04510       return;
04511 
04512    ast_copy_string(multi, S_OR(peer->regexten, peer->name), sizeof(multi));
04513    stringp = multi;
04514    while ((ext = strsep(&stringp, "&"))) {
04515       if ((context = strchr(ext, '@'))) {
04516          *context++ = '\0';   /* split ext@context */
04517          if (!ast_context_find(context)) {
04518             ast_log(LOG_WARNING, "Context %s must exist in regcontext= in sip.conf!\n", context);
04519             continue;
04520          }
04521       } else {
04522          context = sip_cfg.regcontext;
04523       }
04524       if (onoff) {
04525          if (!ast_exists_extension(NULL, context, ext, 1, NULL)) {
04526             ast_add_extension(context, 1, ext, 1, NULL, NULL, "Noop",
04527                 ast_strdup(peer->name), ast_free_ptr, "SIP");
04528          }
04529       } else if (pbx_find_extension(NULL, NULL, &q, context, ext, 1, NULL, "", E_MATCH)) {
04530          ast_context_remove_extension(context, ext, 1, NULL);
04531       }
04532    }
04533 }
04534 
04535 /*! Destroy mailbox subscriptions */
04536 static void destroy_mailbox(struct sip_mailbox *mailbox)
04537 {
04538    if (mailbox->event_sub)
04539       ast_event_unsubscribe(mailbox->event_sub);
04540    ast_free(mailbox);
04541 }
04542 
04543 /*! Destroy all peer-related mailbox subscriptions */
04544 static void clear_peer_mailboxes(struct sip_peer *peer)
04545 {
04546    struct sip_mailbox *mailbox;
04547 
04548    while ((mailbox = AST_LIST_REMOVE_HEAD(&peer->mailboxes, entry)))
04549       destroy_mailbox(mailbox);
04550 }
04551 
04552 static void sip_destroy_peer_fn(void *peer)
04553 {
04554    sip_destroy_peer(peer);
04555 }
04556 
04557 /*! \brief Destroy peer object from memory */
04558 static void sip_destroy_peer(struct sip_peer *peer)
04559 {
04560    ast_debug(3, "Destroying SIP peer %s\n", peer->name);
04561 
04562    /*
04563     * Remove any mailbox event subscriptions for this peer before
04564     * we destroy anything.  An event subscription callback may be
04565     * happening right now.
04566     */
04567    clear_peer_mailboxes(peer);
04568 
04569    if (peer->outboundproxy) {
04570       ao2_ref(peer->outboundproxy, -1);
04571       peer->outboundproxy = NULL;
04572    }
04573 
04574    /* Delete it, it needs to disappear */
04575    if (peer->call) {
04576       dialog_unlink_all(peer->call);
04577       peer->call = dialog_unref(peer->call, "peer->call is being unset");
04578    }
04579 
04580    if (peer->mwipvt) {  /* We have an active subscription, delete it */
04581       dialog_unlink_all(peer->mwipvt);
04582       peer->mwipvt = dialog_unref(peer->mwipvt, "unreffing peer->mwipvt");
04583    }
04584    
04585    if (peer->chanvars) {
04586       ast_variables_destroy(peer->chanvars);
04587       peer->chanvars = NULL;
04588    }
04589    
04590    register_peer_exten(peer, FALSE);
04591    ast_free_ha(peer->ha);
04592    ast_free_ha(peer->directmediaha);
04593    if (peer->selfdestruct)
04594       ast_atomic_fetchadd_int(&apeerobjs, -1);
04595    else if (!ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) && peer->is_realtime) {
04596       ast_atomic_fetchadd_int(&rpeerobjs, -1);
04597       ast_debug(3, "-REALTIME- peer Destroyed. Name: %s. Realtime Peer objects: %d\n", peer->name, rpeerobjs);
04598    } else
04599       ast_atomic_fetchadd_int(&speerobjs, -1);
04600    if (peer->auth) {
04601       ao2_t_ref(peer->auth, -1, "Removing peer authentication");
04602       peer->auth = NULL;
04603    }
04604    if (peer->dnsmgr)
04605       ast_dnsmgr_release(peer->dnsmgr);
04606 
04607    if (peer->socket.tcptls_session) {
04608       ao2_ref(peer->socket.tcptls_session, -1);
04609       peer->socket.tcptls_session = NULL;
04610    }
04611 
04612    ast_cc_config_params_destroy(peer->cc_params);
04613 
04614    ast_string_field_free_memory(peer);
04615 }
04616 
04617 /*! \brief Update peer data in database (if used) */
04618 static void update_peer(struct sip_peer *p, int expire)
04619 {
04620    int rtcachefriends = ast_test_flag(&p->flags[1], SIP_PAGE2_RTCACHEFRIENDS);
04621    if (sip_cfg.peer_rtupdate &&
04622        (p->is_realtime || rtcachefriends)) {
04623       realtime_update_peer(p->name, &p->addr, p->username, p->fullcontact, p->useragent, expire, p->deprecated_username, p->lastms);
04624    }
04625 }
04626 
04627 static struct ast_variable *get_insecure_variable_from_config(struct ast_config *cfg)
04628 {
04629    struct ast_variable *var = NULL;
04630    struct ast_flags flags = {0};
04631    char *cat = NULL;
04632    const char *insecure;
04633    while ((cat = ast_category_browse(cfg, cat))) {
04634       insecure = ast_variable_retrieve(cfg, cat, "insecure");
04635       set_insecure_flags(&flags, insecure, -1);
04636       if (ast_test_flag(&flags, SIP_INSECURE_PORT)) {
04637          var = ast_category_root(cfg, cat);
04638          break;
04639       }
04640    }
04641    return var;
04642 }
04643 
04644 static struct ast_variable *get_insecure_variable_from_sippeers(const char *column, const char *value)
04645 {
04646    struct ast_config *peerlist;
04647    struct ast_variable *var = NULL;
04648    if ((peerlist = ast_load_realtime_multientry("sippeers", column, value, "insecure LIKE", "%port%", SENTINEL))) {
04649       if ((var = get_insecure_variable_from_config(peerlist))) {
04650          /* Must clone, because var will get freed along with
04651           * peerlist. */
04652          var = ast_variables_dup(var);
04653       }
04654       ast_config_destroy(peerlist);
04655    }
04656    return var;
04657 }
04658 
04659 /* Yes.. the only column that makes sense to pass is "ipaddr", but for
04660  * consistency's sake, we require the column name to be passed. As extra
04661  * argument, we take a pointer to var. We already got the info, so we better
04662  * return it and save the caller a query. If return value is nonzero, then *var
04663  * is nonzero too (and the other way around). */
04664 static struct ast_variable *get_insecure_variable_from_sipregs(const char *column, const char *value, struct ast_variable **var)
04665 {
04666    struct ast_variable *varregs = NULL;
04667    struct ast_config *regs, *peers;
04668    char *regscat;
04669    const char *regname;
04670 
04671    if (!(regs = ast_load_realtime_multientry("sipregs", column, value, SENTINEL))) {
04672       return NULL;
04673    }
04674 
04675    /* Load *all* peers that are probably insecure=port */
04676    if (!(peers = ast_load_realtime_multientry("sippeers", "insecure LIKE", "%port%", SENTINEL))) {
04677       ast_config_destroy(regs);
04678       return NULL;
04679    }
04680 
04681    /* Loop over the sipregs that match IP address and attempt to find an
04682     * insecure=port match to it in sippeers. */
04683    regscat = NULL;
04684    while ((regscat = ast_category_browse(regs, regscat)) && (regname = ast_variable_retrieve(regs, regscat, "name"))) {
04685       char *peerscat;
04686       const char *peername;
04687 
04688       peerscat = NULL;
04689       while ((peerscat = ast_category_browse(peers, peerscat)) && (peername = ast_variable_retrieve(peers, peerscat, "name"))) {
04690          if (!strcasecmp(regname, peername)) {
04691             /* Ensure that it really is insecure=port and
04692              * not something else. */
04693             const char *insecure = ast_variable_retrieve(peers, peerscat, "insecure");
04694             struct ast_flags flags = {0};
04695             set_insecure_flags(&flags, insecure, -1);
04696             if (ast_test_flag(&flags, SIP_INSECURE_PORT)) {
04697                /* ENOMEM checks till the bitter end. */
04698                if ((varregs = ast_variables_dup(ast_category_root(regs, regscat)))) {
04699                   if (!(*var = ast_variables_dup(ast_category_root(peers, peerscat)))) {
04700                      ast_variables_destroy(varregs);
04701                      varregs = NULL;
04702                   }
04703                }
04704                goto done;
04705             }
04706          }
04707       }
04708    }
04709 
04710 done:
04711    ast_config_destroy(regs);
04712    ast_config_destroy(peers);
04713    return varregs;
04714 }
04715 
04716 static const char *get_name_from_variable(const struct ast_variable *var)
04717 {
04718    /* Don't expect this to return non-NULL. Both NULL and empty
04719     * values can cause the option to get removed from the variable
04720     * list. This is called on ast_variables gotten from both
04721     * ast_load_realtime and ast_load_realtime_multientry.
04722     * - ast_load_realtime removes options with empty values
04723     * - ast_load_realtime_multientry does not!
04724     * For consistent behaviour, we check for the empty name and
04725     * return NULL instead. */
04726    const struct ast_variable *tmp;
04727    for (tmp = var; tmp; tmp = tmp->next) {
04728       if (!strcasecmp(tmp->name, "name")) {
04729          if (!ast_strlen_zero(tmp->value)) {
04730             return tmp->value;
04731          }
04732          break;
04733       }
04734    }
04735    return NULL;
04736 }
04737 
04738 /* If varregs is NULL, we don't use sipregs.
04739  * Using empty if-bodies instead of goto's while avoiding unnecessary indents */
04740 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)
04741 {
04742    /* Peer by name and host=dynamic */
04743    if ((*var = ast_load_realtime("sippeers", "name", *name, "host", "dynamic", SENTINEL))) {
04744       ;
04745    /* Peer by name and host=IP */
04746    } else if (addr && !(*var = ast_load_realtime("sippeers", "name", *name, "host", ipaddr, SENTINEL))) {
04747       ;
04748    /* Peer by name and host=HOSTNAME */
04749    } else if ((*var = ast_load_realtime("sippeers", "name", *name, SENTINEL))) {
04750       /*!\note
04751        * If this one loaded something, then we need to ensure that the host
04752        * field matched.  The only reason why we can't have this as a criteria
04753        * is because we only have the IP address and the host field might be
04754        * set as a name (and the reverse PTR might not match).
04755        */
04756       if (addr) {
04757          struct ast_variable *tmp;
04758          for (tmp = *var; tmp; tmp = tmp->next) {
04759             if (!strcasecmp(tmp->name, "host")) {
04760                struct ast_sockaddr *addrs = NULL;
04761 
04762                if (ast_sockaddr_resolve(&addrs,
04763                          tmp->value,
04764                          PARSE_PORT_FORBID,
04765                          get_address_family_filter(&bindaddr)) <= 0 ||
04766                          ast_sockaddr_cmp(&addrs[0], addr)) {
04767                   /* No match */
04768                   ast_variables_destroy(*var);
04769                   *var = NULL;
04770                }
04771                ast_free(addrs);
04772                break;
04773             }
04774          }
04775       }
04776    }
04777 
04778    /* Did we find anything? */
04779    if (*var) {
04780       if (varregs) {
04781          *varregs = ast_load_realtime("sipregs", "name", *name, SENTINEL);
04782       }
04783       return 1;
04784    }
04785    return 0;
04786 }
04787 
04788 /* Another little helper function for backwards compatibility: this
04789  * checks/fetches the sippeer that belongs to the sipreg. If none is
04790  * found, we free the sipreg and return false. This way we can do the
04791  * check inside the if-condition below. In the old code, not finding
04792  * the sippeer also had it continue look for another match, so we do
04793  * the same. */
04794 static struct ast_variable *realtime_peer_get_sippeer_helper(const char **name, struct ast_variable **varregs) {
04795    struct ast_variable *var = NULL;
04796    const char *old_name = *name;
04797    *name = get_name_from_variable(*varregs);
04798    if (!*name || !(var = ast_load_realtime("sippeers", "name", *name, SENTINEL))) {
04799       if (!*name) {
04800          ast_log(LOG_WARNING, "Found sipreg but it has no name\n");
04801       }
04802       ast_variables_destroy(*varregs);
04803       *varregs = NULL;
04804       *name = old_name;
04805    }
04806    return var;
04807 }
04808 
04809 /* If varregs is NULL, we don't use sipregs. If we return true, then *name is
04810  * set. Using empty if-bodies instead of goto's while avoiding unnecessary
04811  * indents. */
04812 static int realtime_peer_by_addr(const char **name, struct ast_sockaddr *addr, const char *ipaddr, struct ast_variable **var, struct ast_variable **varregs)
04813 {
04814    char portstring[6]; /* up to 5 digits plus null terminator */
04815    ast_copy_string(portstring, ast_sockaddr_stringify_port(addr), sizeof(portstring));
04816 
04817    /* We're not finding this peer by this name anymore. Reset it. */
04818    *name = NULL;
04819 
04820    /* First check for fixed IP hosts */
04821    if ((*var = ast_load_realtime("sippeers", "host", ipaddr, "port", portstring, SENTINEL))) {
04822       ;
04823    /* Check for registered hosts (in sipregs) */
04824    } else if (varregs && (*varregs = ast_load_realtime("sipregs", "ipaddr", ipaddr, "port", portstring, SENTINEL)) &&
04825          (*var = realtime_peer_get_sippeer_helper(name, varregs))) {
04826       ;
04827    /* Check for registered hosts (in sippeers) */
04828    } else if (!varregs && (*var = ast_load_realtime("sippeers", "ipaddr", ipaddr, "port", portstring, SENTINEL))) {
04829       ;
04830    /* We couldn't match on ipaddress and port, so we need to check if port is insecure */
04831    } else if ((*var = get_insecure_variable_from_sippeers("host", ipaddr))) {
04832       ;
04833    /* Same as above, but try the IP address field (in sipregs)
04834     * Observe that it fetches the name/var at the same time, without the
04835     * realtime_peer_get_sippeer_helper. Also note that it is quite inefficient.
04836     * Avoid sipregs if possible. */
04837    } else if (varregs && (*varregs = get_insecure_variable_from_sipregs("ipaddr", ipaddr, var))) {
04838       ;
04839    /* Same as above, but try the IP address field (in sippeers) */
04840    } else if (!varregs && (*var = get_insecure_variable_from_sippeers("ipaddr", ipaddr))) {
04841       ;
04842    }
04843 
04844    /* Nothing found? */
04845    if (!*var) {
04846       return 0;
04847    }
04848 
04849    /* Check peer name. It must not be empty. There may exist a
04850     * different match that does have a name, but it's too late for
04851     * that now. */
04852    if (!*name && !(*name = get_name_from_variable(*var))) {
04853       ast_log(LOG_WARNING, "Found peer for IP %s but it has no name\n", ipaddr);
04854       ast_variables_destroy(*var);
04855       *var = NULL;
04856       if (varregs && *varregs) {
04857          ast_variables_destroy(*varregs);
04858          *varregs = NULL;
04859       }
04860       return 0;
04861    }
04862 
04863    /* Make sure varregs is populated if var is. The inverse,
04864     * ensuring that var is set when varregs is, is taken
04865     * care of by realtime_peer_get_sippeer_helper(). */
04866    if (varregs && !*varregs) {
04867       *varregs = ast_load_realtime("sipregs", "name", *name, SENTINEL);
04868    }
04869    return 1;
04870 }
04871 
04872 /*! \brief  realtime_peer: Get peer from realtime storage
04873  * Checks the "sippeers" realtime family from extconfig.conf
04874  * Checks the "sipregs" realtime family from extconfig.conf if it's configured.
04875  * This returns a pointer to a peer and because we use build_peer, we can rest
04876  * assured that the refcount is bumped.
04877  * 
04878  * \note This is never called with both newpeername and addr at the same time.
04879  * If you do, be prepared to get a peer with a different name than newpeername.
04880  */
04881 static struct sip_peer *realtime_peer(const char *newpeername, struct ast_sockaddr *addr, int devstate_only, int which_objects)
04882 {
04883    struct sip_peer *peer = NULL;
04884    struct ast_variable *var = NULL;
04885    struct ast_variable *varregs = NULL;
04886    char ipaddr[INET6_ADDRSTRLEN];
04887    int realtimeregs = ast_check_realtime("sipregs");
04888 
04889    if (addr) {
04890       ast_copy_string(ipaddr, ast_sockaddr_stringify_addr(addr), sizeof(ipaddr));
04891    } else {
04892       ipaddr[0] = '\0';
04893    }
04894 
04895    if (newpeername && realtime_peer_by_name(&newpeername, addr, ipaddr, &var, realtimeregs ? &varregs : NULL)) {
04896       ;
04897    } else if (addr && realtime_peer_by_addr(&newpeername, addr, ipaddr, &var, realtimeregs ? &varregs : NULL)) {
04898       ;
04899    } else {
04900       return NULL;
04901    }
04902 
04903    /* If we're looking for users, don't return peers (although this check
04904     * should probably be done in realtime_peer_by_* instead...) */
04905    if (which_objects == FINDUSERS) {
04906       struct ast_variable *tmp;
04907       for (tmp = var; tmp; tmp = tmp->next) {
04908          if (!strcasecmp(tmp->name, "type") && (!strcasecmp(tmp->value, "peer"))) {
04909             goto cleanup;
04910          }
04911       }
04912    }
04913 
04914    /* Peer found in realtime, now build it in memory */
04915    peer = build_peer(newpeername, var, varregs, TRUE, devstate_only);
04916    if (!peer) {
04917       goto cleanup;
04918    }
04919 
04920    ast_debug(3, "-REALTIME- loading peer from database to memory. Name: %s. Peer objects: %d\n", peer->name, rpeerobjs);
04921 
04922    if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) && !devstate_only) {
04923       /* Cache peer */
04924       ast_copy_flags(&peer->flags[1], &global_flags[1], SIP_PAGE2_RTAUTOCLEAR|SIP_PAGE2_RTCACHEFRIENDS);
04925       if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTAUTOCLEAR)) {
04926          AST_SCHED_REPLACE_UNREF(peer->expire, sched, sip_cfg.rtautoclear * 1000, expire_register, peer,
04927                unref_peer(_data, "remove registration ref"),
04928                unref_peer(peer, "remove registration ref"),
04929                ref_peer(peer, "add registration ref"));
04930       }
04931       ao2_t_link(peers, peer, "link peer into peers table");
04932       if (!ast_sockaddr_isnull(&peer->addr)) {
04933          ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
04934       }
04935    }
04936    peer->is_realtime = 1;
04937 
04938 cleanup:
04939    ast_variables_destroy(var);
04940    ast_variables_destroy(varregs);
04941    return peer;
04942 }
04943 
04944 /* Function to assist finding peers by name only */
04945 static int find_by_name(void *obj, void *arg, void *data, int flags)
04946 {
04947    struct sip_peer *search = obj, *match = arg;
04948    int *which_objects = data;
04949 
04950    /* Usernames in SIP uri's are case sensitive. Domains are not */
04951    if (strcmp(search->name, match->name)) {
04952       return 0;
04953    }
04954 
04955    switch (*which_objects) {
04956    case FINDUSERS:
04957       if (!(search->type & SIP_TYPE_USER)) {
04958          return 0;
04959       }
04960       break;
04961    case FINDPEERS:
04962       if (!(search->type & SIP_TYPE_PEER)) {
04963          return 0;
04964       }
04965       break;
04966    case FINDALLDEVICES:
04967       break;
04968    }
04969 
04970    return CMP_MATCH | CMP_STOP;
04971 }
04972 
04973 /*!
04974  * \brief Locate device by name or ip address
04975  * \param peer, sin, realtime, devstate_only, transport
04976  * \param which_objects Define which objects should be matched when doing a lookup
04977  *        by name.  Valid options are FINDUSERS, FINDPEERS, or FINDALLDEVICES.
04978  *        Note that this option is not used at all when doing a lookup by IP.
04979  *
04980  * This is used on find matching device on name or ip/port.
04981  * If the device was declared as type=peer, we don't match on peer name on incoming INVITEs.
04982  *
04983  * \note Avoid using this function in new functions if there is a way to avoid it,
04984  * since it might cause a database lookup.
04985  */
04986 static struct sip_peer *find_peer(const char *peer, struct ast_sockaddr *addr, int realtime, int which_objects, int devstate_only, int transport)
04987 {
04988    struct sip_peer *p = NULL;
04989    struct sip_peer tmp_peer;
04990 
04991    if (peer) {
04992       ast_copy_string(tmp_peer.name, peer, sizeof(tmp_peer.name));
04993       p = ao2_t_callback_data(peers, OBJ_POINTER, find_by_name, &tmp_peer, &which_objects, "ao2_find in peers table");
04994    } else if (addr) { /* search by addr? */
04995       ast_sockaddr_copy(&tmp_peer.addr, addr);
04996       tmp_peer.flags[0].flags = 0;
04997       tmp_peer.transports = transport;
04998       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); */
04999       if (!p) {
05000          ast_set_flag(&tmp_peer.flags[0], SIP_INSECURE_PORT);
05001          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); */
05002          if (p) {
05003             return p;
05004          }
05005       }
05006    }
05007 
05008    if (!p && (realtime || devstate_only)) {
05009       p = realtime_peer(peer, addr, devstate_only, which_objects);
05010       if (p) {
05011          switch (which_objects) {
05012          case FINDUSERS:
05013             if (!(p->type & SIP_TYPE_USER)) {
05014                unref_peer(p, "Wrong type of realtime SIP endpoint");
05015                return NULL;
05016             }
05017             break;
05018          case FINDPEERS:
05019             if (!(p->type & SIP_TYPE_PEER)) {
05020                unref_peer(p, "Wrong type of realtime SIP endpoint");
05021                return NULL;
05022             }
05023             break;
05024          case FINDALLDEVICES:
05025             break;
05026          }
05027       }
05028    }
05029 
05030    return p;
05031 }
05032 
05033 /*! \brief Set nat mode on the various data sockets */
05034 static void do_setnat(struct sip_pvt *p)
05035 {
05036    const char *mode;
05037    int natflags;
05038 
05039    natflags = ast_test_flag(&p->flags[1], SIP_PAGE2_SYMMETRICRTP);
05040    mode = natflags ? "On" : "Off";
05041 
05042    if (p->rtp) {
05043       ast_debug(1, "Setting NAT on RTP to %s\n", mode);
05044       ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_NAT, natflags);
05045    }
05046    if (p->vrtp) {
05047       ast_debug(1, "Setting NAT on VRTP to %s\n", mode);
05048       ast_rtp_instance_set_prop(p->vrtp, AST_RTP_PROPERTY_NAT, natflags);
05049    }
05050    if (p->udptl) {
05051       ast_debug(1, "Setting NAT on UDPTL to %s\n", mode);
05052       ast_udptl_setnat(p->udptl, natflags);
05053    }
05054    if (p->trtp) {
05055       ast_debug(1, "Setting NAT on TRTP to %s\n", mode);
05056       ast_rtp_instance_set_prop(p->trtp, AST_RTP_PROPERTY_NAT, natflags);
05057    }
05058 }
05059 
05060 /*! \brief Change the T38 state on a SIP dialog */
05061 static void change_t38_state(struct sip_pvt *p, int state)
05062 {
05063    int old = p->t38.state;
05064    struct ast_channel *chan = p->owner;
05065    struct ast_control_t38_parameters parameters = { .request_response = 0 };
05066 
05067    /* Don't bother changing if we are already in the state wanted */
05068    if (old == state)
05069       return;
05070 
05071    p->t38.state = state;
05072    ast_debug(2, "T38 state changed to %d on channel %s\n", p->t38.state, chan ? chan->name : "<none>");
05073 
05074    /* If no channel was provided we can't send off a control frame */
05075    if (!chan)
05076       return;
05077 
05078    /* Given the state requested and old state determine what control frame we want to queue up */
05079    switch (state) {
05080    case T38_PEER_REINVITE:
05081       parameters = p->t38.their_parms;
05082       parameters.max_ifp = ast_udptl_get_far_max_ifp(p->udptl);
05083       parameters.request_response = AST_T38_REQUEST_NEGOTIATE;
05084       ast_udptl_set_tag(p->udptl, "%s", chan->name);
05085       break;
05086    case T38_ENABLED:
05087       parameters = p->t38.their_parms;
05088       parameters.max_ifp = ast_udptl_get_far_max_ifp(p->udptl);
05089       parameters.request_response = AST_T38_NEGOTIATED;
05090       ast_udptl_set_tag(p->udptl, "%s", chan->name);
05091       break;
05092    case T38_DISABLED:
05093       if (old == T38_ENABLED) {
05094          parameters.request_response = AST_T38_TERMINATED;
05095       } else if (old == T38_LOCAL_REINVITE) {
05096          parameters.request_response = AST_T38_REFUSED;
05097       }
05098       break;
05099    case T38_LOCAL_REINVITE:
05100       /* wait until we get a peer response before responding to local reinvite */
05101       break;
05102    }
05103 
05104    /* Woot we got a message, create a control frame and send it on! */
05105    if (parameters.request_response)
05106       ast_queue_control_data(chan, AST_CONTROL_T38_PARAMETERS, &parameters, sizeof(parameters));
05107 }
05108 
05109 /*! \brief Set the global T38 capabilities on a SIP dialog structure */
05110 static void set_t38_capabilities(struct sip_pvt *p)
05111 {
05112    if (p->udptl) {
05113       if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) == SIP_PAGE2_T38SUPPORT_UDPTL_REDUNDANCY) {
05114                         ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_REDUNDANCY);
05115       } else if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) == SIP_PAGE2_T38SUPPORT_UDPTL_FEC) {
05116          ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_FEC);
05117       } else if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) == SIP_PAGE2_T38SUPPORT_UDPTL) {
05118          ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_NONE);
05119       }
05120    }
05121 }
05122 
05123 static void copy_socket_data(struct sip_socket *to_sock, const struct sip_socket *from_sock)
05124 {
05125    if (to_sock->tcptls_session) {
05126       ao2_ref(to_sock->tcptls_session, -1);
05127       to_sock->tcptls_session = NULL;
05128    }
05129 
05130    if (from_sock->tcptls_session) {
05131       ao2_ref(from_sock->tcptls_session, +1);
05132    }
05133 
05134    *to_sock = *from_sock;
05135 }
05136 
05137 /*! \brief Initialize RTP portion of a dialog
05138  * \return -1 on failure, 0 on success
05139  */
05140 static int dialog_initialize_rtp(struct sip_pvt *dialog)
05141 {
05142    struct ast_sockaddr bindaddr_tmp;
05143 
05144    if (!sip_methods[dialog->method].need_rtp) {
05145       return 0;
05146    }
05147 
05148    ast_sockaddr_copy(&bindaddr_tmp, &bindaddr);
05149    if (!(dialog->rtp = ast_rtp_instance_new(dialog->engine, sched, &bindaddr_tmp, NULL))) {
05150       return -1;
05151    }
05152 
05153    if (ast_test_flag(&dialog->flags[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS) ||
05154          (ast_test_flag(&dialog->flags[1], SIP_PAGE2_VIDEOSUPPORT) && (dialog->capability & AST_FORMAT_VIDEO_MASK))) {
05155       if (!(dialog->vrtp = ast_rtp_instance_new(dialog->engine, sched, &bindaddr_tmp, NULL))) {
05156          return -1;
05157       }
05158       ast_rtp_instance_set_timeout(dialog->vrtp, dialog->rtptimeout);
05159       ast_rtp_instance_set_hold_timeout(dialog->vrtp, dialog->rtpholdtimeout);
05160       ast_rtp_instance_set_keepalive(dialog->vrtp, dialog->rtpkeepalive);
05161 
05162       ast_rtp_instance_set_prop(dialog->vrtp, AST_RTP_PROPERTY_RTCP, 1);
05163    }
05164 
05165    if (ast_test_flag(&dialog->flags[1], SIP_PAGE2_TEXTSUPPORT)) {
05166       if (!(dialog->trtp = ast_rtp_instance_new(dialog->engine, sched, &bindaddr_tmp, NULL))) {
05167          return -1;
05168       }
05169       /* Do not timeout text as its not constant*/
05170       ast_rtp_instance_set_keepalive(dialog->trtp, dialog->rtpkeepalive);
05171 
05172       ast_rtp_instance_set_prop(dialog->trtp, AST_RTP_PROPERTY_RTCP, 1);
05173    }
05174 
05175    ast_rtp_instance_set_timeout(dialog->rtp, dialog->rtptimeout);
05176    ast_rtp_instance_set_hold_timeout(dialog->rtp, dialog->rtpholdtimeout);
05177    ast_rtp_instance_set_keepalive(dialog->rtp, dialog->rtpkeepalive);
05178 
05179    ast_rtp_instance_set_prop(dialog->rtp, AST_RTP_PROPERTY_RTCP, 1);
05180    ast_rtp_instance_set_prop(dialog->rtp, AST_RTP_PROPERTY_DTMF, ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
05181    ast_rtp_instance_set_prop(dialog->rtp, AST_RTP_PROPERTY_DTMF_COMPENSATE, ast_test_flag(&dialog->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
05182 
05183    ast_rtp_instance_set_qos(dialog->rtp, global_tos_audio, global_cos_audio, "SIP RTP");
05184 
05185    do_setnat(dialog);
05186 
05187    return 0;
05188 }
05189 
05190 /*! \brief Create address structure from peer reference.
05191  * This function copies data from peer to the dialog, so we don't have to look up the peer
05192  * again from memory or database during the life time of the dialog.
05193  *
05194  * \return -1 on error, 0 on success.
05195  *
05196  */
05197 static int create_addr_from_peer(struct sip_pvt *dialog, struct sip_peer *peer)
05198 {
05199    struct sip_auth_container *credentials;
05200 
05201    /* this checks that the dialog is contacting the peer on a valid
05202     * transport type based on the peers transport configuration,
05203     * otherwise, this function bails out */
05204    if (dialog->socket.type && check_request_transport(peer, dialog))
05205       return -1;
05206    copy_socket_data(&dialog->socket, &peer->socket);
05207 
05208    if (!(ast_sockaddr_isnull(&peer->addr) && ast_sockaddr_isnull(&peer->defaddr)) &&
05209        (!peer->maxms || ((peer->lastms >= 0)  && (peer->lastms <= peer->maxms)))) {
05210       dialog->sa = ast_sockaddr_isnull(&peer->addr) ? peer->defaddr : peer->addr;
05211       dialog->recv = dialog->sa;
05212    } else
05213       return -1;
05214 
05215    /* XXX TODO: get flags directly from peer only as they are needed using dialog->relatedpeer */
05216    ast_copy_flags(&dialog->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
05217    ast_copy_flags(&dialog->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
05218    ast_copy_flags(&dialog->flags[2], &peer->flags[2], SIP_PAGE3_FLAGS_TO_COPY);
05219    dialog->capability = peer->capability;
05220    dialog->prefs = peer->prefs;
05221    if (ast_test_flag(&dialog->flags[1], SIP_PAGE2_T38SUPPORT)) {
05222       /* t38pt_udptl was enabled in the peer and not in [general] */
05223       if (dialog->udptl || (!dialog->udptl && (dialog->udptl = ast_udptl_new_with_bindaddr(sched, io, 0, &bindaddr)))) {
05224          dialog->t38_maxdatagram = peer->t38_maxdatagram;
05225          set_t38_capabilities(dialog);
05226       } else {
05227          /* It is impossible to support T38 without udptl */
05228          ast_debug(1, "UDPTL creation failed on dialog.\n");
05229          ast_clear_flag(&dialog->flags[1], SIP_PAGE2_T38SUPPORT);
05230       }
05231    } else if (dialog->udptl) {
05232       ast_udptl_destroy(dialog->udptl);
05233       dialog->udptl = NULL;
05234    }
05235 
05236    ast_string_field_set(dialog, engine, peer->engine);
05237 
05238    dialog->rtptimeout = peer->rtptimeout;
05239    dialog->rtpholdtimeout = peer->rtpholdtimeout;
05240    dialog->rtpkeepalive = peer->rtpkeepalive;
05241    if (dialog_initialize_rtp(dialog)) {
05242       return -1;
05243    }
05244 
05245    if (dialog->rtp) { /* Audio */
05246       ast_rtp_instance_set_prop(dialog->rtp, AST_RTP_PROPERTY_DTMF, ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
05247       ast_rtp_instance_set_prop(dialog->rtp, AST_RTP_PROPERTY_DTMF_COMPENSATE, ast_test_flag(&dialog->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
05248       /* Set Frame packetization */
05249       ast_rtp_codecs_packetization_set(ast_rtp_instance_get_codecs(dialog->rtp), dialog->rtp, &dialog->prefs);
05250       dialog->autoframing = peer->autoframing;
05251    }
05252 
05253    /* XXX TODO: get fields directly from peer only as they are needed using dialog->relatedpeer */
05254    ast_string_field_set(dialog, peername, peer->name);
05255    ast_string_field_set(dialog, authname, peer->username);
05256    ast_string_field_set(dialog, username, peer->username);
05257    ast_string_field_set(dialog, peersecret, peer->secret);
05258    ast_string_field_set(dialog, peermd5secret, peer->md5secret);
05259    ast_string_field_set(dialog, mohsuggest, peer->mohsuggest);
05260    ast_string_field_set(dialog, mohinterpret, peer->mohinterpret);
05261    ast_string_field_set(dialog, tohost, peer->tohost);
05262    ast_string_field_set(dialog, fullcontact, peer->fullcontact);
05263    ast_string_field_set(dialog, accountcode, peer->accountcode);
05264    ast_string_field_set(dialog, context, peer->context);
05265    ast_string_field_set(dialog, cid_num, peer->cid_num);
05266    ast_string_field_set(dialog, cid_name, peer->cid_name);
05267    ast_string_field_set(dialog, cid_tag, peer->cid_tag);
05268    ast_string_field_set(dialog, mwi_from, peer->mwi_from);
05269    if (!ast_strlen_zero(peer->parkinglot)) {
05270       ast_string_field_set(dialog, parkinglot, peer->parkinglot);
05271    }
05272    ast_string_field_set(dialog, engine, peer->engine);
05273    ref_proxy(dialog, obproxy_get(dialog, peer));
05274    dialog->callgroup = peer->callgroup;
05275    dialog->pickupgroup = peer->pickupgroup;
05276    dialog->allowtransfer = peer->allowtransfer;
05277    dialog->jointnoncodeccapability = dialog->noncodeccapability;
05278 
05279    /* Update dialog authorization credentials */
05280    ao2_lock(peer);
05281    credentials = peer->auth;
05282    if (credentials) {
05283       ao2_t_ref(credentials, +1, "Ref peer auth for dialog");
05284    }
05285    ao2_unlock(peer);
05286    ao2_lock(dialog);
05287    if (dialog->peerauth) {
05288       ao2_t_ref(dialog->peerauth, -1, "Unref old dialog peer auth");
05289    }
05290    dialog->peerauth = credentials;
05291    ao2_unlock(dialog);
05292 
05293    dialog->maxcallbitrate = peer->maxcallbitrate;
05294    dialog->disallowed_methods = peer->disallowed_methods;
05295    ast_cc_copy_config_params(dialog->cc_params, peer->cc_params);
05296    if (ast_strlen_zero(dialog->tohost))
05297       ast_string_field_set(dialog, tohost, ast_sockaddr_stringify_host_remote(&dialog->sa));
05298    if (!ast_strlen_zero(peer->fromdomain)) {
05299       ast_string_field_set(dialog, fromdomain, peer->fromdomain);
05300       if (!dialog->initreq.headers) {
05301          char *new_callid;
05302          char *tmpcall = ast_strdupa(dialog->callid);
05303          /* this sure looks to me like we are going to change the callid on this dialog!! */
05304          new_callid = strchr(tmpcall, '@');
05305          if (new_callid) {
05306             int callid_size;
05307 
05308             *new_callid = '\0';
05309 
05310             /* Change the dialog callid. */
05311             callid_size = strlen(tmpcall) + strlen(peer->fromdomain) + 2;
05312             new_callid = alloca(callid_size);
05313             snprintf(new_callid, callid_size, "%s@%s", tmpcall, peer->fromdomain);
05314             change_callid_pvt(dialog, new_callid);
05315          }
05316       }
05317    }
05318    if (!ast_strlen_zero(peer->fromuser))
05319       ast_string_field_set(dialog, fromuser, peer->fromuser);
05320    if (!ast_strlen_zero(peer->language))
05321       ast_string_field_set(dialog, language, peer->language);
05322    /* Set timer T1 to RTT for this peer (if known by qualify=) */
05323    /* Minimum is settable or default to 100 ms */
05324    /* If there is a maxms and lastms from a qualify use that over a manual T1
05325       value. Otherwise, use the peer's T1 value. */
05326    if (peer->maxms && peer->lastms)
05327       dialog->timer_t1 = peer->lastms < global_t1min ? global_t1min : peer->lastms;
05328    else
05329       dialog->timer_t1 = peer->timer_t1;
05330 
05331    /* Set timer B to control transaction timeouts, the peer setting is the default and overrides
05332       the known timer */
05333    if (peer->timer_b)
05334       dialog->timer_b = peer->timer_b;
05335    else
05336       dialog->timer_b = 64 * dialog->timer_t1;
05337 
05338    if ((ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
05339        (ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
05340       dialog->noncodeccapability |= AST_RTP_DTMF;
05341    else
05342       dialog->noncodeccapability &= ~AST_RTP_DTMF;
05343    dialog->directmediaha = ast_duplicate_ha_list(peer->directmediaha);
05344    if (peer->call_limit)
05345       ast_set_flag(&dialog->flags[0], SIP_CALL_LIMIT);
05346    if (!dialog->portinuri)
05347       dialog->portinuri = peer->portinuri;
05348    dialog->chanvars = copy_vars(peer->chanvars);
05349    if (peer->fromdomainport)
05350       dialog->fromdomainport = peer->fromdomainport;
05351 
05352    return 0;
05353 }
05354 
05355 /*! \brief create address structure from device name
05356  *      Or, if peer not found, find it in the global DNS
05357  *      returns TRUE (-1) on failure, FALSE on success */
05358 static int create_addr(struct sip_pvt *dialog, const char *opeer, struct ast_sockaddr *addr, int newdialog, struct ast_sockaddr *remote_address)
05359 {
05360    struct sip_peer *peer;
05361    char *peername, *peername2, *hostn;
05362    char host[MAXHOSTNAMELEN];
05363    char service[MAXHOSTNAMELEN];
05364    int srv_ret = 0;
05365    int tportno;
05366 
05367    AST_DECLARE_APP_ARGS(hostport,
05368       AST_APP_ARG(host);
05369       AST_APP_ARG(port);
05370    );
05371 
05372    peername = ast_strdupa(opeer);
05373    peername2 = ast_strdupa(opeer);
05374    AST_NONSTANDARD_RAW_ARGS(hostport, peername2, ':');
05375 
05376    if (hostport.port)
05377       dialog->portinuri = 1;
05378 
05379    dialog->timer_t1 = global_t1; /* Default SIP retransmission timer T1 (RFC 3261) */
05380    dialog->timer_b = global_timer_b; /* Default SIP transaction timer B (RFC 3261) */
05381    peer = find_peer(peername, NULL, TRUE, FINDPEERS, FALSE, 0);
05382 
05383    if (peer) {
05384       int res;
05385       if (newdialog) {
05386          set_socket_transport(&dialog->socket, 0);
05387       }
05388       res = create_addr_from_peer(dialog, peer);
05389       if (!ast_sockaddr_isnull(remote_address)) {
05390          ast_sockaddr_copy(&dialog->sa, remote_address);
05391       }
05392       dialog->relatedpeer = ref_peer(peer, "create_addr: setting dialog's relatedpeer pointer");
05393       unref_peer(peer, "create_addr: unref peer from find_peer hashtab lookup");
05394       return res;
05395    } else if (ast_check_digits(peername)) {
05396       /* Although an IPv4 hostname *could* be represented as a 32-bit integer, it is uncommon and
05397        * it makes dialing SIP/${EXTEN} for a peer that isn't defined resolve to an IP that is
05398        * almost certainly not intended. It is much better to just reject purely numeric hostnames */
05399       ast_log(LOG_WARNING, "Purely numeric hostname (%s), and not a peer--rejecting!\n", peername);
05400       return -1;
05401    } else {
05402       dialog->rtptimeout = global_rtptimeout;
05403       dialog->rtpholdtimeout = global_rtpholdtimeout;
05404       dialog->rtpkeepalive = global_rtpkeepalive;
05405       if (dialog_initialize_rtp(dialog)) {
05406          return -1;
05407       }
05408    }
05409 
05410    ast_string_field_set(dialog, tohost, hostport.host);
05411    dialog->allowed_methods &= ~sip_cfg.disallowed_methods;
05412 
05413    /* Get the outbound proxy information */
05414    ref_proxy(dialog, obproxy_get(dialog, NULL));
05415 
05416    if (addr) {
05417       /* This address should be updated using dnsmgr */
05418       ast_sockaddr_copy(&dialog->sa, addr);
05419    } else {
05420 
05421       /* Let's see if we can find the host in DNS. First try DNS SRV records,
05422          then hostname lookup */
05423       /*! \todo Fix this function. When we ask for SRV, we should check all transports
05424            In the future, we should first check NAPTR to find out transport preference
05425        */
05426       hostn = peername;
05427       /* Section 4.2 of RFC 3263 specifies that if a port number is specified, then
05428        * an A record lookup should be used instead of SRV.
05429        */
05430       if (!hostport.port && sip_cfg.srvlookup) {
05431          snprintf(service, sizeof(service), "_%s._%s.%s", 
05432              get_srv_service(dialog->socket.type),
05433              get_srv_protocol(dialog->socket.type), peername);
05434          if ((srv_ret = ast_get_srv(NULL, host, sizeof(host), &tportno,
05435                      service)) > 0) {
05436             hostn = host;
05437          }
05438       }
05439 
05440       if (ast_sockaddr_resolve_first(&dialog->sa, hostn, 0)) {
05441          ast_log(LOG_WARNING, "No such host: %s\n", peername);
05442          return -1;
05443       }
05444 
05445       if (srv_ret > 0) {
05446          ast_sockaddr_set_port(&dialog->sa, tportno);
05447       }
05448    }
05449 
05450    if (!dialog->socket.type)
05451       set_socket_transport(&dialog->socket, SIP_TRANSPORT_UDP);
05452    if (!dialog->socket.port) {
05453       dialog->socket.port = htons(ast_sockaddr_port(&bindaddr));
05454    }
05455 
05456    if (!ast_sockaddr_port(&dialog->sa)) {
05457       ast_sockaddr_set_port(&dialog->sa,
05458                   (dialog->socket.type == SIP_TRANSPORT_TLS) ?
05459                   STANDARD_TLS_PORT : STANDARD_SIP_PORT);
05460    }
05461    ast_sockaddr_copy(&dialog->recv, &dialog->sa);
05462    return 0;
05463 }
05464 
05465 /*! \brief Scheduled congestion on a call.
05466  * Only called by the scheduler, must return the reference when done.
05467  */
05468 static int auto_congest(const void *arg)
05469 {
05470    struct sip_pvt *p = (struct sip_pvt *)arg;
05471 
05472    sip_pvt_lock(p);
05473    p->initid = -1;   /* event gone, will not be rescheduled */
05474    if (p->owner) {
05475       /* XXX fails on possible deadlock */
05476       if (!ast_channel_trylock(p->owner)) {
05477          append_history(p, "Cong", "Auto-congesting (timer)");
05478          ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
05479          ast_channel_unlock(p->owner);
05480       }
05481 
05482       /* Give the channel a chance to act before we proceed with destruction */
05483       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
05484    }
05485    sip_pvt_unlock(p);
05486    dialog_unref(p, "unreffing arg passed into auto_congest callback (p->initid)");
05487    return 0;
05488 }
05489 
05490 
05491 /*! \brief Initiate SIP call from PBX
05492  *      used from the dial() application      */
05493 static int sip_call(struct ast_channel *ast, char *dest, int timeout)
05494 {
05495    int res;
05496    struct sip_pvt *p = ast->tech_pvt;  /* chan is locked, so the reference cannot go away */
05497    struct varshead *headp;
05498    struct ast_var_t *current;
05499    const char *referer = NULL;   /* SIP referrer */
05500    int cc_core_id;
05501    char uri[SIPBUFSIZE] = "";
05502 
05503    if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
05504       ast_log(LOG_WARNING, "sip_call called on %s, neither down nor reserved\n", ast->name);
05505       return -1;
05506    }
05507 
05508    if (ast_cc_is_recall(ast, &cc_core_id, "SIP")) {
05509       char device_name[AST_CHANNEL_NAME];
05510       struct ast_cc_monitor *recall_monitor;
05511       struct sip_monitor_instance *monitor_instance;
05512       ast_channel_get_device_name(ast, device_name, sizeof(device_name));
05513       if ((recall_monitor = ast_cc_get_monitor_by_recall_core_id(cc_core_id, device_name))) {
05514          monitor_instance = recall_monitor->private_data;
05515          ast_copy_string(uri, monitor_instance->notify_uri, sizeof(uri));
05516          ao2_t_ref(recall_monitor, -1, "Got the URI we need so unreffing monitor");
05517       }
05518    }
05519 
05520    /* Check whether there is vxml_url, distinctive ring variables */
05521    headp=&ast->varshead;
05522    AST_LIST_TRAVERSE(headp, current, entries) {
05523       /* Check whether there is a VXML_URL variable */
05524       if (!p->options->vxml_url && !strcasecmp(ast_var_name(current), "VXML_URL")) {
05525          p->options->vxml_url = ast_var_value(current);
05526       } else if (!p->options->uri_options && !strcasecmp(ast_var_name(current), "SIP_URI_OPTIONS")) {
05527          p->options->uri_options = ast_var_value(current);
05528       } else if (!p->options->addsipheaders && !strncasecmp(ast_var_name(current), "SIPADDHEADER", strlen("SIPADDHEADER"))) {
05529          /* Check whether there is a variable with a name starting with SIPADDHEADER */
05530          p->options->addsipheaders = 1;
05531       } else if (!strcasecmp(ast_var_name(current), "SIPFROMDOMAIN")) {
05532          ast_string_field_set(p, fromdomain, ast_var_value(current));
05533       } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER")) {
05534          /* This is a transfered call */
05535          p->options->transfer = 1;
05536       } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER_REFERER")) {
05537          /* This is the referrer */
05538          referer = ast_var_value(current);
05539       } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER_REPLACES")) {
05540          /* We're replacing a call. */
05541          p->options->replaces = ast_var_value(current);
05542       } else if (!strcasecmp(ast_var_name(current), "SIP_MAX_FORWARDS")) {
05543          if (sscanf(ast_var_value(current), "%d", &(p->maxforwards)) != 1) {
05544             ast_log(LOG_WARNING, "The SIP_MAX_FORWARDS channel variable is not a valid integer.");
05545          }
05546       }
05547    }
05548 
05549    /* Check to see if we should try to force encryption */
05550    if (p->req_secure_signaling && p->socket.type != SIP_TRANSPORT_TLS) {
05551       ast_log(LOG_WARNING, "Encrypted signaling is required\n");
05552       ast->hangupcause = AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
05553       return -1;
05554    }
05555 
05556    if (ast_test_flag(&p->flags[1], SIP_PAGE2_USE_SRTP)) {
05557       if (ast_test_flag(&p->flags[0], SIP_REINVITE)) {
05558          ast_debug(1, "Direct media not possible when using SRTP, ignoring canreinvite setting\n");
05559          ast_clear_flag(&p->flags[0], SIP_REINVITE);
05560       }
05561 
05562       if (p->rtp && !p->srtp && setup_srtp(&p->srtp) < 0) {
05563          ast_log(LOG_WARNING, "SRTP audio setup failed\n");
05564          return -1;
05565       }
05566 
05567       if (p->vrtp && !p->vsrtp && setup_srtp(&p->vsrtp) < 0) {
05568          ast_log(LOG_WARNING, "SRTP video setup failed\n");
05569          return -1;
05570       }
05571 
05572       if (p->trtp && !p->tsrtp && setup_srtp(&p->tsrtp) < 0) {
05573          ast_log(LOG_WARNING, "SRTP text setup failed\n");
05574          return -1;
05575       }
05576    }
05577 
05578    res = 0;
05579    ast_set_flag(&p->flags[0], SIP_OUTGOING);
05580 
05581    /* T.38 re-INVITE FAX detection should never be done for outgoing calls,
05582     * so ensure it is disabled.
05583     */
05584    ast_clear_flag(&p->flags[1], SIP_PAGE2_FAX_DETECT_T38);
05585 
05586    if (p->options->transfer) {
05587       char buf[SIPBUFSIZE/2];
05588 
05589       if (referer) {
05590          if (sipdebug)
05591             ast_debug(3, "Call for %s transfered by %s\n", p->username, referer);
05592          snprintf(buf, sizeof(buf)-1, "-> %s (via %s)", p->cid_name, referer);
05593       } else
05594          snprintf(buf, sizeof(buf)-1, "-> %s", p->cid_name);
05595       ast_string_field_set(p, cid_name, buf);
05596    }
05597    ast_debug(1, "Outgoing Call for %s\n", p->username);
05598 
05599    res = update_call_counter(p, INC_CALL_RINGING);
05600 
05601    if (res == -1) {
05602       ast->hangupcause = AST_CAUSE_USER_BUSY;
05603       return res;
05604    }
05605    p->callingpres = ast_party_id_presentation(&ast->caller.id);
05606    p->jointcapability = ast_rtp_instance_available_formats(p->rtp, p->capability, p->prefcodec);
05607    p->jointnoncodeccapability = p->noncodeccapability;
05608 
05609    /* If there are no audio formats left to offer, punt */
05610    if (!(p->jointcapability & AST_FORMAT_AUDIO_MASK)) {
05611       ast_log(LOG_WARNING, "No audio format found to offer. Cancelling call to %s\n", p->username);
05612       res = -1;
05613    } else {
05614       int xmitres;
05615       struct ast_party_connected_line connected;
05616       struct ast_set_party_connected_line update_connected;
05617 
05618       sip_pvt_lock(p);
05619 
05620       /* Supply initial connected line information if available. */
05621       memset(&update_connected, 0, sizeof(update_connected));
05622       ast_party_connected_line_init(&connected);
05623       if (!ast_strlen_zero(p->cid_num)
05624          || (p->callingpres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED) {
05625          update_connected.id.number = 1;
05626          connected.id.number.valid = 1;
05627          connected.id.number.str = (char *) p->cid_num;
05628          connected.id.number.presentation = p->callingpres;
05629       }
05630       if (!ast_strlen_zero(p->cid_name)
05631          || (p->callingpres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED) {
05632          update_connected.id.name = 1;
05633          connected.id.name.valid = 1;
05634          connected.id.name.str = (char *) p->cid_name;
05635          connected.id.name.presentation = p->callingpres;
05636       }
05637       if (update_connected.id.number || update_connected.id.name) {
05638          connected.id.tag = (char *) p->cid_tag;
05639          connected.source = AST_CONNECTED_LINE_UPDATE_SOURCE_ANSWER;
05640          ast_channel_queue_connected_line_update(ast, &connected, &update_connected);
05641       }
05642 
05643       xmitres = transmit_invite(p, SIP_INVITE, 1, 2, uri);
05644       sip_pvt_unlock(p);
05645       if (xmitres == XMIT_ERROR)
05646          return -1;
05647       p->invitestate = INV_CALLING;
05648 
05649       /* Initialize auto-congest time */
05650       AST_SCHED_REPLACE_UNREF(p->initid, sched, p->timer_b, auto_congest, p,
05651                         dialog_unref(_data, "dialog ptr dec when SCHED_REPLACE del op succeeded"),
05652                         dialog_unref(p, "dialog ptr dec when SCHED_REPLACE add failed"),
05653                         dialog_ref(p, "dialog ptr inc when SCHED_REPLACE add succeeded") );
05654    }
05655    return res;
05656 }
05657 
05658 /*! \brief Destroy registry object
05659    Objects created with the register= statement in static configuration */
05660 static void sip_registry_destroy(struct sip_registry *reg)
05661 {
05662    /* Really delete */
05663    ast_debug(3, "Destroying registry entry for %s@%s\n", reg->username, reg->hostname);
05664 
05665    if (reg->call) {
05666       /* Clear registry before destroying to ensure
05667          we don't get reentered trying to grab the registry lock */
05668       reg->call->registry = registry_unref(reg->call->registry, "destroy reg->call->registry");
05669       ast_debug(3, "Destroying active SIP dialog for registry %s@%s\n", reg->username, reg->hostname);
05670       dialog_unlink_all(reg->call);
05671       reg->call = dialog_unref(reg->call, "unref reg->call");
05672       /* reg->call = sip_destroy(reg->call); */
05673    }
05674    AST_SCHED_DEL(sched, reg->expire);  
05675    AST_SCHED_DEL(sched, reg->timeout);
05676    
05677    ast_string_field_free_memory(reg);
05678    ast_atomic_fetchadd_int(&regobjs, -1);
05679    ast_dnsmgr_release(reg->dnsmgr);
05680    ast_free(reg);
05681 }
05682 
05683 /*! \brief Destroy MWI subscription object */
05684 static void sip_subscribe_mwi_destroy(struct sip_subscription_mwi *mwi)
05685 {
05686    if (mwi->call) {
05687       mwi->call->mwi = NULL;
05688       sip_destroy(mwi->call);
05689    }
05690    
05691    AST_SCHED_DEL(sched, mwi->resub);
05692    ast_string_field_free_memory(mwi);
05693    ast_dnsmgr_release(mwi->dnsmgr);
05694    ast_free(mwi);
05695 }
05696 
05697 /*! \brief Execute destruction of SIP dialog structure, release memory */
05698 void __sip_destroy(struct sip_pvt *p, int lockowner, int lockdialoglist)
05699 {
05700    struct sip_request *req;
05701 
05702    /* Destroy Session-Timers if allocated */
05703    if (p->stimer) {
05704       p->stimer->quit_flag = 1;
05705       stop_session_timer(p);
05706       ast_free(p->stimer);
05707       p->stimer = NULL;
05708    }
05709 
05710    if (sip_debug_test_pvt(p))
05711       ast_verbose("Really destroying SIP dialog '%s' Method: %s\n", p->callid, sip_methods[p->method].text);
05712 
05713    if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
05714       update_call_counter(p, DEC_CALL_LIMIT);
05715       ast_debug(2, "This call did not properly clean up call limits. Call ID %s\n", p->callid);
05716    }
05717 
05718    /* Unlink us from the owner if we have one */
05719    if (p->owner) {
05720       if (lockowner)
05721          ast_channel_lock(p->owner);
05722       ast_debug(1, "Detaching from %s\n", p->owner->name);
05723       p->owner->tech_pvt = NULL;
05724       /* Make sure that the channel knows its backend is going away */
05725       p->owner->_softhangup |= AST_SOFTHANGUP_DEV;
05726       if (lockowner)
05727          ast_channel_unlock(p->owner);
05728       /* Give the channel a chance to react before deallocation */
05729       usleep(1);
05730    }
05731 
05732    /* Remove link from peer to subscription of MWI */
05733    if (p->relatedpeer && p->relatedpeer->mwipvt)
05734       p->relatedpeer->mwipvt = dialog_unref(p->relatedpeer->mwipvt, "delete ->relatedpeer->mwipvt");
05735    if (p->relatedpeer && p->relatedpeer->call == p)
05736       p->relatedpeer->call = dialog_unref(p->relatedpeer->call, "unset the relatedpeer->call field in tandem with relatedpeer field itself");
05737    
05738    if (p->relatedpeer)
05739       p->relatedpeer = unref_peer(p->relatedpeer,"unsetting a dialog relatedpeer field in sip_destroy");
05740    
05741    if (p->registry) {
05742       if (p->registry->call == p)
05743          p->registry->call = dialog_unref(p->registry->call, "nulling out the registry's call dialog field in unlink_all");
05744       p->registry = registry_unref(p->registry, "delete p->registry");
05745    }
05746    
05747    if (p->mwi) {
05748       p->mwi->call = NULL;
05749    }
05750 
05751    if (dumphistory)
05752       sip_dump_history(p);
05753 
05754    if (p->options)
05755       ast_free(p->options);
05756 
05757    if (p->notify) {
05758       ast_variables_destroy(p->notify->headers);
05759       ast_free(p->notify->content);
05760       ast_free(p->notify);
05761    }
05762    if (p->rtp) {
05763       ast_rtp_instance_destroy(p->rtp);
05764    }
05765    if (p->vrtp) {
05766       ast_rtp_instance_destroy(p->vrtp);
05767    }
05768    if (p->trtp) {
05769       ast_rtp_instance_destroy(p->trtp);
05770    }
05771    if (p->udptl)
05772       ast_udptl_destroy(p->udptl);
05773    if (p->refer)
05774       ast_free(p->refer);
05775    if (p->route) {
05776       free_old_route(p->route);
05777       p->route = NULL;
05778    }
05779    deinit_req(&p->initreq);
05780 
05781    /* Clear history */
05782    if (p->history) {
05783       struct sip_history *hist;
05784       while ( (hist = AST_LIST_REMOVE_HEAD(p->history, list)) ) {
05785          ast_free(hist);
05786          p->history_entries--;
05787       }
05788       ast_free(p->history);
05789       p->history = NULL;
05790    }
05791 
05792    while ((req = AST_LIST_REMOVE_HEAD(&p->request_queue, next))) {
05793       ast_free(req);
05794    }
05795 
05796    if (p->chanvars) {
05797       ast_variables_destroy(p->chanvars);
05798       p->chanvars = NULL;
05799    }
05800 
05801    if (p->srtp) {
05802       sip_srtp_destroy(p->srtp);
05803       p->srtp = NULL;
05804    }
05805 
05806    if (p->vsrtp) {
05807       sip_srtp_destroy(p->vsrtp);
05808       p->vsrtp = NULL;
05809    }
05810 
05811    if (p->tsrtp) {
05812       sip_srtp_destroy(p->tsrtp);
05813       p->tsrtp = NULL;
05814    }
05815 
05816    if (p->directmediaha) {
05817       ast_free_ha(p->directmediaha);
05818       p->directmediaha = NULL;
05819    }
05820 
05821    ast_string_field_free_memory(p);
05822 
05823    ast_cc_config_params_destroy(p->cc_params);
05824 
05825    if (p->epa_entry) {
05826       ao2_ref(p->epa_entry, -1);
05827       p->epa_entry = NULL;
05828    }
05829 
05830    if (p->socket.tcptls_session) {
05831       ao2_ref(p->socket.tcptls_session, -1);
05832       p->socket.tcptls_session = NULL;
05833    }
05834 
05835    if (p->peerauth) {
05836       ao2_t_ref(p->peerauth, -1, "Removing active peer authentication");
05837       p->peerauth = NULL;
05838    }
05839 }
05840 
05841 /*! \brief  update_call_counter: Handle call_limit for SIP devices
05842  * Setting a call-limit will cause calls above the limit not to be accepted.
05843  *
05844  * Remember that for a type=friend, there's one limit for the user and
05845  * another for the peer, not a combined call limit.
05846  * This will cause unexpected behaviour in subscriptions, since a "friend"
05847  * is *two* devices in Asterisk, not one.
05848  *
05849  * Thought: For realtime, we should probably update storage with inuse counter...
05850  *
05851  * \return 0 if call is ok (no call limit, below threshold)
05852  * -1 on rejection of call
05853  *
05854  */
05855 static int update_call_counter(struct sip_pvt *fup, int event)
05856 {
05857    char name[256];
05858    int *inuse = NULL, *call_limit = NULL, *inringing = NULL;
05859    int outgoing = fup->outgoing_call;
05860    struct sip_peer *p = NULL;
05861 
05862    ast_debug(3, "Updating call counter for %s call\n", outgoing ? "outgoing" : "incoming");
05863 
05864 
05865    /* Test if we need to check call limits, in order to avoid
05866       realtime lookups if we do not need it */
05867    if (!ast_test_flag(&fup->flags[0], SIP_CALL_LIMIT) && !ast_test_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD))
05868       return 0;
05869 
05870    ast_copy_string(name, fup->username, sizeof(name));
05871 
05872    /* Check the list of devices */
05873    if (fup->relatedpeer) {
05874       p = ref_peer(fup->relatedpeer, "ref related peer for update_call_counter");
05875       inuse = &p->inUse;
05876       call_limit = &p->call_limit;
05877       inringing = &p->inRinging;
05878       ast_copy_string(name, fup->peername, sizeof(name));
05879    }
05880    if (!p) {
05881       ast_debug(2, "%s is not a local device, no call limit\n", name);
05882       return 0;
05883    }
05884 
05885    switch(event) {
05886    /* incoming and outgoing affects the inUse counter */
05887    case DEC_CALL_LIMIT:
05888       /* Decrement inuse count if applicable */
05889       if (inuse) {
05890          sip_pvt_lock(fup);
05891          ao2_lock(p);
05892          if (*inuse > 0) {
05893             if (ast_test_flag(&fup->flags[0], SIP_INC_COUNT)) {
05894                (*inuse)--;
05895                ast_clear_flag(&fup->flags[0], SIP_INC_COUNT);
05896             }
05897          } else {
05898             *inuse = 0;
05899          }
05900          ao2_unlock(p);
05901          sip_pvt_unlock(fup);
05902       }
05903 
05904       /* Decrement ringing count if applicable */
05905       if (inringing) {
05906          sip_pvt_lock(fup);
05907          ao2_lock(p);
05908          if (*inringing > 0) {
05909             if (ast_test_flag(&fup->flags[0], SIP_INC_RINGING)) {
05910                (*inringing)--;
05911                ast_clear_flag(&fup->flags[0], SIP_INC_RINGING);
05912             }
05913          } else {
05914             *inringing = 0;
05915          }
05916          ao2_unlock(p);
05917          sip_pvt_unlock(fup);
05918       }
05919 
05920       /* Decrement onhold count if applicable */
05921       sip_pvt_lock(fup);
05922       ao2_lock(p);
05923       if (ast_test_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD) && sip_cfg.notifyhold) {
05924          ast_clear_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD);
05925          ao2_unlock(p);
05926          sip_pvt_unlock(fup);
05927          sip_peer_hold(fup, FALSE);
05928       } else {
05929          ao2_unlock(p);
05930          sip_pvt_unlock(fup);
05931       }
05932       if (sipdebug)
05933          ast_debug(2, "Call %s %s '%s' removed from call limit %d\n", outgoing ? "to" : "from", "peer", name, *call_limit);
05934       break;
05935 
05936    case INC_CALL_RINGING:
05937    case INC_CALL_LIMIT:
05938       /* If call limit is active and we have reached the limit, reject the call */
05939       if (*call_limit > 0 ) {
05940          if (*inuse >= *call_limit) {
05941             ast_log(LOG_NOTICE, "Call %s %s '%s' rejected due to usage limit of %d\n", outgoing ? "to" : "from", "peer", name, *call_limit);
05942             unref_peer(p, "update_call_counter: unref peer p, call limit exceeded");
05943             return -1;
05944          }
05945       }
05946       if (inringing && (event == INC_CALL_RINGING)) {
05947          sip_pvt_lock(fup);
05948          ao2_lock(p);
05949          if (!ast_test_flag(&fup->flags[0], SIP_INC_RINGING)) {
05950             (*inringing)++;
05951             ast_set_flag(&fup->flags[0], SIP_INC_RINGING);
05952          }
05953          ao2_unlock(p);
05954          sip_pvt_unlock(fup);
05955       }
05956       if (inuse) {
05957          sip_pvt_lock(fup);
05958          ao2_lock(p);
05959          if (!ast_test_flag(&fup->flags[0], SIP_INC_COUNT)) {
05960             (*inuse)++;
05961             ast_set_flag(&fup->flags[0], SIP_INC_COUNT);
05962          }
05963          ao2_unlock(p);
05964          sip_pvt_unlock(fup);
05965       }
05966       if (sipdebug) {
05967          ast_debug(2, "Call %s %s '%s' is %d out of %d\n", outgoing ? "to" : "from", "peer", name, *inuse, *call_limit);
05968       }
05969       break;
05970 
05971    case DEC_CALL_RINGING:
05972       if (inringing) {
05973          sip_pvt_lock(fup);
05974          ao2_lock(p);
05975          if (ast_test_flag(&fup->flags[0], SIP_INC_RINGING)) {
05976             if (*inringing > 0) {
05977                (*inringing)--;
05978             }
05979             ast_clear_flag(&fup->flags[0], SIP_INC_RINGING);
05980          }
05981          ao2_unlock(p);
05982          sip_pvt_unlock(fup);
05983       }
05984       break;
05985 
05986    default:
05987       ast_log(LOG_ERROR, "update_call_counter(%s, %d) called with no event!\n", name, event);
05988    }
05989 
05990    if (p) {
05991       ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", p->name);
05992       unref_peer(p, "update_call_counter: unref_peer from call counter");
05993    }
05994    return 0;
05995 }
05996 
05997 
05998 static void sip_destroy_fn(void *p)
05999 {
06000    sip_destroy(p);
06001 }
06002 
06003 /*! \brief Destroy SIP call structure.
06004  * Make it return NULL so the caller can do things like
06005  * foo = sip_destroy(foo);
06006  * and reduce the chance of bugs due to dangling pointers.
06007  */
06008 struct sip_pvt *sip_destroy(struct sip_pvt *p)
06009 {
06010    ast_debug(3, "Destroying SIP dialog %s\n", p->callid);
06011    __sip_destroy(p, TRUE, TRUE);
06012    return NULL;
06013 }
06014 
06015 /*! \brief Convert SIP hangup causes to Asterisk hangup causes */
06016 int hangup_sip2cause(int cause)
06017 {
06018    /* Possible values taken from causes.h */
06019 
06020    switch(cause) {
06021       case 401:   /* Unauthorized */
06022          return AST_CAUSE_CALL_REJECTED;
06023       case 403:   /* Not found */
06024          return AST_CAUSE_CALL_REJECTED;
06025       case 404:   /* Not found */
06026          return AST_CAUSE_UNALLOCATED;
06027       case 405:   /* Method not allowed */
06028          return AST_CAUSE_INTERWORKING;
06029       case 407:   /* Proxy authentication required */
06030          return AST_CAUSE_CALL_REJECTED;
06031       case 408:   /* No reaction */
06032          return AST_CAUSE_NO_USER_RESPONSE;
06033       case 409:   /* Conflict */
06034          return AST_CAUSE_NORMAL_TEMPORARY_FAILURE;
06035       case 410:   /* Gone */
06036          return AST_CAUSE_NUMBER_CHANGED;
06037       case 411:   /* Length required */
06038          return AST_CAUSE_INTERWORKING;
06039       case 413:   /* Request entity too large */
06040          return AST_CAUSE_INTERWORKING;
06041       case 414:   /* Request URI too large */
06042          return AST_CAUSE_INTERWORKING;
06043       case 415:   /* Unsupported media type */
06044          return AST_CAUSE_INTERWORKING;
06045       case 420:   /* Bad extension */
06046          return AST_CAUSE_NO_ROUTE_DESTINATION;
06047       case 480:   /* No answer */
06048          return AST_CAUSE_NO_ANSWER;
06049       case 481:   /* No answer */
06050          return AST_CAUSE_INTERWORKING;
06051       case 482:   /* Loop detected */
06052          return AST_CAUSE_INTERWORKING;
06053       case 483:   /* Too many hops */
06054          return AST_CAUSE_NO_ANSWER;
06055       case 484:   /* Address incomplete */
06056          return AST_CAUSE_INVALID_NUMBER_FORMAT;
06057       case 485:   /* Ambiguous */
06058          return AST_CAUSE_UNALLOCATED;
06059       case 486:   /* Busy everywhere */
06060          return AST_CAUSE_BUSY;
06061       case 487:   /* Request terminated */
06062          return AST_CAUSE_INTERWORKING;
06063       case 488:   /* No codecs approved */
06064          return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
06065       case 491:   /* Request pending */
06066          return AST_CAUSE_INTERWORKING;
06067       case 493:   /* Undecipherable */
06068          return AST_CAUSE_INTERWORKING;
06069       case 500:   /* Server internal failure */
06070          return AST_CAUSE_FAILURE;
06071       case 501:   /* Call rejected */
06072          return AST_CAUSE_FACILITY_REJECTED;
06073       case 502:
06074          return AST_CAUSE_DESTINATION_OUT_OF_ORDER;
06075       case 503:   /* Service unavailable */
06076          return AST_CAUSE_CONGESTION;
06077       case 504:   /* Gateway timeout */
06078          return AST_CAUSE_RECOVERY_ON_TIMER_EXPIRE;
06079       case 505:   /* SIP version not supported */
06080          return AST_CAUSE_INTERWORKING;
06081       case 600:   /* Busy everywhere */
06082          return AST_CAUSE_USER_BUSY;
06083       case 603:   /* Decline */
06084          return AST_CAUSE_CALL_REJECTED;
06085       case 604:   /* Does not exist anywhere */
06086          return AST_CAUSE_UNALLOCATED;
06087       case 606:   /* Not acceptable */
06088          return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
06089       default:
06090          if (cause < 500 && cause >= 400) {
06091             /* 4xx class error that is unknown - someting wrong with our request */
06092             return AST_CAUSE_INTERWORKING;
06093          } else if (cause < 600 && cause >= 500) {
06094             /* 5xx class error - problem in the remote end */
06095             return AST_CAUSE_CONGESTION;
06096          } else if (cause < 700 && cause >= 600) {
06097             /* 6xx - global errors in the 4xx class */
06098             return AST_CAUSE_INTERWORKING;
06099          }
06100          return AST_CAUSE_NORMAL;
06101    }
06102    /* Never reached */
06103    return 0;
06104 }
06105 
06106 /*! \brief Convert Asterisk hangup causes to SIP codes
06107 \verbatim
06108  Possible values from causes.h
06109         AST_CAUSE_NOTDEFINED    AST_CAUSE_NORMAL        AST_CAUSE_BUSY
06110         AST_CAUSE_FAILURE       AST_CAUSE_CONGESTION    AST_CAUSE_UNALLOCATED
06111 
06112    In addition to these, a lot of PRI codes is defined in causes.h
06113    ...should we take care of them too ?
06114 
06115    Quote RFC 3398
06116 
06117    ISUP Cause value                        SIP response
06118    ----------------                        ------------
06119    1  unallocated number                   404 Not Found
06120    2  no route to network                  404 Not found
06121    3  no route to destination              404 Not found
06122    16 normal call clearing                 --- (*)
06123    17 user busy                            486 Busy here
06124    18 no user responding                   408 Request Timeout
06125    19 no answer from the user              480 Temporarily unavailable
06126    20 subscriber absent                    480 Temporarily unavailable
06127    21 call rejected                        403 Forbidden (+)
06128    22 number changed (w/o diagnostic)      410 Gone
06129    22 number changed (w/ diagnostic)       301 Moved Permanently
06130    23 redirection to new destination       410 Gone
06131    26 non-selected user clearing           404 Not Found (=)
06132    27 destination out of order             502 Bad Gateway
06133    28 address incomplete                   484 Address incomplete
06134    29 facility rejected                    501 Not implemented
06135    31 normal unspecified                   480 Temporarily unavailable
06136 \endverbatim
06137 */
06138 const char *hangup_cause2sip(int cause)
06139 {
06140    switch (cause) {
06141       case AST_CAUSE_UNALLOCATED:      /* 1 */
06142       case AST_CAUSE_NO_ROUTE_DESTINATION:   /* 3 IAX2: Can't find extension in context */
06143       case AST_CAUSE_NO_ROUTE_TRANSIT_NET:   /* 2 */
06144          return "404 Not Found";
06145       case AST_CAUSE_CONGESTION:    /* 34 */
06146       case AST_CAUSE_SWITCH_CONGESTION:   /* 42 */
06147          return "503 Service Unavailable";
06148       case AST_CAUSE_NO_USER_RESPONSE: /* 18 */
06149          return "408 Request Timeout";
06150       case AST_CAUSE_NO_ANSWER:     /* 19 */
06151       case AST_CAUSE_UNREGISTERED:        /* 20 */
06152          return "480 Temporarily unavailable";
06153       case AST_CAUSE_CALL_REJECTED:    /* 21 */
06154          return "403 Forbidden";
06155       case AST_CAUSE_NUMBER_CHANGED:      /* 22 */
06156          return "410 Gone";
06157       case AST_CAUSE_NORMAL_UNSPECIFIED:  /* 31 */
06158          return "480 Temporarily unavailable";
06159       case AST_CAUSE_INVALID_NUMBER_FORMAT:
06160          return "484 Address incomplete";
06161       case AST_CAUSE_USER_BUSY:
06162          return "486 Busy here";
06163       case AST_CAUSE_FAILURE:
06164          return "500 Server internal failure";
06165       case AST_CAUSE_FACILITY_REJECTED:   /* 29 */
06166          return "501 Not Implemented";
06167       case AST_CAUSE_CHAN_NOT_IMPLEMENTED:
06168          return "503 Service Unavailable";
06169       /* Used in chan_iax2 */
06170       case AST_CAUSE_DESTINATION_OUT_OF_ORDER:
06171          return "502 Bad Gateway";
06172       case AST_CAUSE_BEARERCAPABILITY_NOTAVAIL: /* Can't find codec to connect to host */
06173          return "488 Not Acceptable Here";
06174          
06175       case AST_CAUSE_NOTDEFINED:
06176       default:
06177          ast_debug(1, "AST hangup cause %d (no match found in SIP)\n", cause);
06178          return NULL;
06179    }
06180 
06181    /* Never reached */
06182    return 0;
06183 }
06184 
06185 /*! \brief  sip_hangup: Hangup SIP call
06186  * Part of PBX interface, called from ast_hangup */
06187 static int sip_hangup(struct ast_channel *ast)
06188 {
06189    struct sip_pvt *p = ast->tech_pvt;
06190    int needcancel = FALSE;
06191    int needdestroy = 0;
06192    struct ast_channel *oldowner = ast;
06193 
06194    if (!p) {
06195       ast_debug(1, "Asked to hangup channel that was not connected\n");
06196       return 0;
06197    }
06198    if (ast_test_flag(ast, AST_FLAG_ANSWERED_ELSEWHERE) || ast->hangupcause == AST_CAUSE_ANSWERED_ELSEWHERE) {
06199       ast_debug(1, "This call was answered elsewhere");
06200       if (ast->hangupcause == AST_CAUSE_ANSWERED_ELSEWHERE) {
06201          ast_debug(1, "####### It's the cause code, buddy. The cause code!!!\n");
06202       }
06203       append_history(p, "Cancel", "Call answered elsewhere");
06204       p->answered_elsewhere = TRUE;
06205    }
06206 
06207    /* Store hangupcause locally in PVT so we still have it before disconnect */
06208    if (p->owner)
06209       p->hangupcause = p->owner->hangupcause;
06210 
06211    if (ast_test_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER)) {
06212       if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
06213          if (sipdebug)
06214             ast_debug(1, "update_call_counter(%s) - decrement call limit counter on hangup\n", p->username);
06215          update_call_counter(p, DEC_CALL_LIMIT);
06216       }
06217       ast_debug(4, "SIP Transfer: Not hanging up right now... Rescheduling hangup for %s.\n", p->callid);
06218       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
06219       ast_clear_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER); /* Really hang up next time */
06220       p->needdestroy = 0;
06221       p->owner->tech_pvt = dialog_unref(p->owner->tech_pvt, "unref p->owner->tech_pvt");
06222       sip_pvt_lock(p);
06223       p->owner = NULL;  /* Owner will be gone after we return, so take it away */
06224       sip_pvt_unlock(p);
06225       ast_module_unref(ast_module_info->self);
06226       return 0;
06227    }
06228 
06229    if (ast_test_flag(ast, AST_FLAG_ZOMBIE)) {
06230       if (p->refer)
06231          ast_debug(1, "SIP Transfer: Hanging up Zombie channel %s after transfer ... Call-ID: %s\n", ast->name, p->callid);
06232       else
06233          ast_debug(1, "Hanging up zombie call. Be scared.\n");
06234    } else
06235       ast_debug(1, "Hangup call %s, SIP callid %s\n", ast->name, p->callid);
06236 
06237    sip_pvt_lock(p);
06238    if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
06239       if (sipdebug)
06240          ast_debug(1, "update_call_counter(%s) - decrement call limit counter on hangup\n", p->username);
06241       update_call_counter(p, DEC_CALL_LIMIT);
06242    }
06243 
06244    /* Determine how to disconnect */
06245    if (p->owner != ast) {
06246       ast_log(LOG_WARNING, "Huh?  We aren't the owner? Can't hangup call.\n");
06247       sip_pvt_unlock(p);
06248       return 0;
06249    }
06250    /* If the call is not UP, we need to send CANCEL instead of BYE */
06251    /* In case of re-invites, the call might be UP even though we have an incomplete invite transaction */
06252    if (p->invitestate < INV_COMPLETED && p->owner->_state != AST_STATE_UP) {
06253       needcancel = TRUE;
06254       ast_debug(4, "Hanging up channel in state %s (not UP)\n", ast_state2str(ast->_state));
06255    }
06256 
06257    stop_media_flows(p); /* Immediately stop RTP, VRTP and UDPTL as applicable */
06258 
06259    append_history(p, needcancel ? "Cancel" : "Hangup", "Cause %s", p->owner ? ast_cause2str(p->hangupcause) : "Unknown");
06260 
06261    /* Disconnect */
06262    disable_dsp_detect(p);
06263 
06264    p->owner = NULL;
06265    ast->tech_pvt = dialog_unref(ast->tech_pvt, "unref ast->tech_pvt");
06266 
06267    ast_module_unref(ast_module_info->self);
06268    /* Do not destroy this pvt until we have timeout or
06269       get an answer to the BYE or INVITE/CANCEL
06270       If we get no answer during retransmit period, drop the call anyway.
06271       (Sorry, mother-in-law, you can't deny a hangup by sending
06272       603 declined to BYE...)
06273    */
06274    if (p->alreadygone)
06275       needdestroy = 1;  /* Set destroy flag at end of this function */
06276    else if (p->invitestate != INV_CALLING)
06277       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
06278 
06279    /* Start the process if it's not already started */
06280    if (!p->alreadygone && p->initreq.data && !ast_strlen_zero(p->initreq.data->str)) {
06281       if (needcancel) { /* Outgoing call, not up */
06282          if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06283             /* if we can't send right now, mark it pending */
06284             if (p->invitestate == INV_CALLING) {
06285                /* We can't send anything in CALLING state */
06286                ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
06287                /* 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. */
06288                sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
06289                append_history(p, "DELAY", "Not sending cancel, waiting for timeout");
06290             } else {
06291                struct sip_pkt *cur;
06292 
06293                for (cur = p->packets; cur; cur = cur->next) {
06294                   __sip_semi_ack(p, cur->seqno, cur->is_resp, cur->method ? cur->method : find_sip_method(cur->data->str));
06295                }
06296                p->invitestate = INV_CANCELLED;
06297                /* Send a new request: CANCEL */
06298                transmit_request(p, SIP_CANCEL, p->lastinvite, XMIT_RELIABLE, FALSE);
06299                /* Actually don't destroy us yet, wait for the 487 on our original
06300                   INVITE, but do set an autodestruct just in case we never get it. */
06301                needdestroy = 0;
06302                sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
06303             }
06304          } else { /* Incoming call, not up */
06305             const char *res;
06306             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"));
06307             if (p->hangupcause && (res = hangup_cause2sip(p->hangupcause)))
06308                transmit_response_reliable(p, res, &p->initreq);
06309             else
06310                transmit_response_reliable(p, "603 Declined", &p->initreq);
06311             p->invitestate = INV_TERMINATED;
06312          }
06313       } else { /* Call is in UP state, send BYE */
06314          if (p->stimer->st_active == TRUE) {
06315             stop_session_timer(p);
06316          }
06317 
06318          if (!p->pendinginvite) {
06319             struct ast_channel *bridge = ast_bridged_channel(oldowner);
06320             char quality_buf[AST_MAX_USER_FIELD], *quality;
06321 
06322             /* We need to get the lock on bridge because ast_rtp_instance_set_stats_vars will attempt
06323              * to lock the bridge. This may get hairy...
06324              */
06325             while (bridge && ast_channel_trylock(bridge)) {
06326                sip_pvt_unlock(p);
06327                do {
06328                   CHANNEL_DEADLOCK_AVOIDANCE(oldowner);
06329                } while (sip_pvt_trylock(p));
06330                bridge = ast_bridged_channel(oldowner);
06331             }
06332 
06333             if (p->rtp) {
06334                ast_rtp_instance_set_stats_vars(oldowner, p->rtp);
06335             }
06336 
06337             if (bridge) {
06338                struct sip_pvt *q = bridge->tech_pvt;
06339 
06340                if (IS_SIP_TECH(bridge->tech) && q && q->rtp) {
06341                   ast_rtp_instance_set_stats_vars(bridge, q->rtp);
06342                }
06343                ast_channel_unlock(bridge);
06344             }
06345 
06346             if (p->do_history || oldowner) {
06347                if (p->rtp && (quality = ast_rtp_instance_get_quality(p->rtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY, quality_buf, sizeof(quality_buf)))) {
06348                   if (p->do_history) {
06349                      append_history(p, "RTCPaudio", "Quality:%s", quality);
06350                   }
06351                   if (oldowner) {
06352                      pbx_builtin_setvar_helper(oldowner, "RTPAUDIOQOS", quality);
06353                   }
06354                }
06355                if (p->vrtp && (quality = ast_rtp_instance_get_quality(p->vrtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY, quality_buf, sizeof(quality_buf)))) {
06356                   if (p->do_history) {
06357                      append_history(p, "RTCPvideo", "Quality:%s", quality);
06358                   }
06359                   if (oldowner) {
06360                      pbx_builtin_setvar_helper(oldowner, "RTPVIDEOQOS", quality);
06361                   }
06362                }
06363                if (p->trtp && (quality = ast_rtp_instance_get_quality(p->trtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY, quality_buf, sizeof(quality_buf)))) {
06364                   if (p->do_history) {
06365                      append_history(p, "RTCPtext", "Quality:%s", quality);
06366                   }
06367                   if (oldowner) {
06368                      pbx_builtin_setvar_helper(oldowner, "RTPTEXTQOS", quality);
06369                   }
06370                }
06371             }
06372 
06373             /* Send a hangup */
06374             if (oldowner->_state == AST_STATE_UP) {
06375                transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
06376             }
06377 
06378          } else {
06379             /* Note we will need a BYE when this all settles out
06380                but we can't send one while we have "INVITE" outstanding. */
06381             ast_set_flag(&p->flags[0], SIP_PENDINGBYE);  
06382             ast_clear_flag(&p->flags[0], SIP_NEEDREINVITE); 
06383             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"));
06384             if (sip_cancel_destroy(p))
06385                ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
06386          }
06387       }
06388    }
06389    if (needdestroy) {
06390       pvt_set_needdestroy(p, "hangup");
06391    }
06392    sip_pvt_unlock(p);
06393    return 0;
06394 }
06395 
06396 /*! \brief Try setting codec suggested by the SIP_CODEC channel variable */
06397 static void try_suggested_sip_codec(struct sip_pvt *p)
06398 {
06399    format_t fmt;
06400    const char *codec;
06401 
06402    if (p->outgoing_call) {
06403       codec = pbx_builtin_getvar_helper(p->owner, "SIP_CODEC_OUTBOUND");
06404    } else if (!(codec = pbx_builtin_getvar_helper(p->owner, "SIP_CODEC_INBOUND"))) {
06405       codec = pbx_builtin_getvar_helper(p->owner, "SIP_CODEC");
06406    }
06407 
06408    if (!codec) 
06409       return;
06410 
06411    fmt = ast_getformatbyname(codec);
06412    if (fmt) {
06413       ast_log(LOG_NOTICE, "Changing codec to '%s' for this call because of ${SIP_CODEC} variable\n", codec);
06414       if (p->jointcapability & fmt) {
06415          p->jointcapability &= fmt;
06416          p->capability &= fmt;
06417       } else
06418          ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because it is not shared by both ends.\n");
06419    } else
06420       ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because of unrecognized/not configured codec (check allow/disallow in sip.conf): %s\n", codec);
06421    return;  
06422 }
06423 
06424 /*! \brief  sip_answer: Answer SIP call , send 200 OK on Invite
06425  * Part of PBX interface */
06426 static int sip_answer(struct ast_channel *ast)
06427 {
06428    int res = 0;
06429    struct sip_pvt *p = ast->tech_pvt;
06430 
06431    sip_pvt_lock(p);
06432    if (ast->_state != AST_STATE_UP) {
06433       try_suggested_sip_codec(p);   
06434 
06435       ast_setstate(ast, AST_STATE_UP);
06436       ast_debug(1, "SIP answering channel: %s\n", ast->name);
06437       ast_rtp_instance_update_source(p->rtp);
06438       res = transmit_response_with_sdp(p, "200 OK", &p->initreq, XMIT_CRITICAL, FALSE, TRUE);
06439       ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
06440    }
06441    sip_pvt_unlock(p);
06442    return res;
06443 }
06444 
06445 /*! \brief Send frame to media channel (rtp) */
06446 static int sip_write(struct ast_channel *ast, struct ast_frame *frame)
06447 {
06448    struct sip_pvt *p = ast->tech_pvt;
06449    int res = 0;
06450 
06451    switch (frame->frametype) {
06452    case AST_FRAME_VOICE:
06453       if (!(frame->subclass.codec & ast->nativeformats)) {
06454          char s1[512], s2[512], s3[512];
06455          ast_log(LOG_WARNING, "Asked to transmit frame type %s, while native formats is %s read/write = %s/%s\n",
06456             ast_getformatname(frame->subclass.codec),
06457             ast_getformatname_multiple(s1, sizeof(s1), ast->nativeformats & AST_FORMAT_AUDIO_MASK),
06458             ast_getformatname_multiple(s2, sizeof(s2), ast->readformat),
06459             ast_getformatname_multiple(s3, sizeof(s3), ast->writeformat));
06460          return 0;
06461       }
06462       if (p) {
06463          sip_pvt_lock(p);
06464          if (p->t38.state == T38_ENABLED) {
06465             /* drop frame, can't sent VOICE frames while in T.38 mode */
06466             sip_pvt_unlock(p);
06467             break;
06468          } else if (p->rtp) {
06469             /* If channel is not up, activate early media session */
06470             if ((ast->_state != AST_STATE_UP) &&
06471                 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
06472                 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06473                ast_rtp_instance_update_source(p->rtp);
06474                if (!global_prematuremediafilter) {
06475                   p->invitestate = INV_EARLY_MEDIA;
06476                   transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
06477                   ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
06478                }
06479             }
06480             p->lastrtptx = time(NULL);
06481             res = ast_rtp_instance_write(p->rtp, frame);
06482          }
06483          sip_pvt_unlock(p);
06484       }
06485       break;
06486    case AST_FRAME_VIDEO:
06487       if (p) {
06488          sip_pvt_lock(p);
06489          if (p->vrtp) {
06490             /* Activate video early media */
06491             if ((ast->_state != AST_STATE_UP) &&
06492                 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
06493                 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06494                p->invitestate = INV_EARLY_MEDIA;
06495                transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
06496                ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
06497             }
06498             p->lastrtptx = time(NULL);
06499             res = ast_rtp_instance_write(p->vrtp, frame);
06500          }
06501          sip_pvt_unlock(p);
06502       }
06503       break;
06504    case AST_FRAME_TEXT:
06505       if (p) {
06506          sip_pvt_lock(p);
06507          if (p->red) {
06508             ast_rtp_red_buffer(p->trtp, frame);
06509          } else {
06510             if (p->trtp) {
06511                /* Activate text early media */
06512                if ((ast->_state != AST_STATE_UP) &&
06513                    !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
06514                    !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06515                   p->invitestate = INV_EARLY_MEDIA;
06516                   transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
06517                   ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
06518                }
06519                p->lastrtptx = time(NULL);
06520                res = ast_rtp_instance_write(p->trtp, frame);
06521             }
06522          }
06523          sip_pvt_unlock(p);
06524       }
06525       break;
06526    case AST_FRAME_IMAGE:
06527       return 0;
06528       break;
06529    case AST_FRAME_MODEM:
06530       if (p) {
06531          sip_pvt_lock(p);
06532          /* UDPTL requires two-way communication, so early media is not needed here.
06533             we simply forget the frames if we get modem frames before the bridge is up.
06534             Fax will re-transmit.
06535          */
06536          if ((ast->_state == AST_STATE_UP) &&
06537              p->udptl &&
06538              (p->t38.state == T38_ENABLED)) {
06539             res = ast_udptl_write(p->udptl, frame);
06540          }
06541          sip_pvt_unlock(p);
06542       }
06543       break;
06544    default:
06545       ast_log(LOG_WARNING, "Can't send %d type frames with SIP write\n", frame->frametype);
06546       return 0;
06547    }
06548 
06549    return res;
06550 }
06551 
06552 /*! \brief  sip_fixup: Fix up a channel:  If a channel is consumed, this is called.
06553         Basically update any ->owner links */
06554 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
06555 {
06556    int ret = -1;
06557    struct sip_pvt *p;
06558 
06559    if (newchan && ast_test_flag(newchan, AST_FLAG_ZOMBIE))
06560       ast_debug(1, "New channel is zombie\n");
06561    if (oldchan && ast_test_flag(oldchan, AST_FLAG_ZOMBIE))
06562       ast_debug(1, "Old channel is zombie\n");
06563 
06564    if (!newchan || !newchan->tech_pvt) {
06565       if (!newchan)
06566          ast_log(LOG_WARNING, "No new channel! Fixup of %s failed.\n", oldchan->name);
06567       else
06568          ast_log(LOG_WARNING, "No SIP tech_pvt! Fixup of %s failed.\n", oldchan->name);
06569       return -1;
06570    }
06571    p = newchan->tech_pvt;
06572 
06573    sip_pvt_lock(p);
06574    append_history(p, "Masq", "Old channel: %s\n", oldchan->name);
06575    append_history(p, "Masq (cont)", "...new owner: %s\n", newchan->name);
06576    if (p->owner != oldchan)
06577       ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, p->owner);
06578    else {
06579       p->owner = newchan;
06580       /* Re-invite RTP back to Asterisk. Needed if channel is masqueraded out of a native
06581          RTP bridge (i.e., RTP not going through Asterisk): RTP bridge code might not be
06582          able to do this if the masquerade happens before the bridge breaks (e.g., AMI
06583          redirect of both channels). Note that a channel can not be masqueraded *into*
06584          a native bridge. So there is no danger that this breaks a native bridge that
06585          should stay up. */
06586       sip_set_rtp_peer(newchan, NULL, NULL, 0, 0, 0);
06587       ret = 0;
06588    }
06589    ast_debug(3, "SIP Fixup: New owner for dialogue %s: %s (Old parent: %s)\n", p->callid, p->owner->name, oldchan->name);
06590 
06591    sip_pvt_unlock(p);
06592    return ret;
06593 }
06594 
06595 static int sip_senddigit_begin(struct ast_channel *ast, char digit)
06596 {
06597    struct sip_pvt *p = ast->tech_pvt;
06598    int res = 0;
06599 
06600    sip_pvt_lock(p);
06601    switch (ast_test_flag(&p->flags[0], SIP_DTMF)) {
06602    case SIP_DTMF_INBAND:
06603       res = -1; /* Tell Asterisk to generate inband indications */
06604       break;
06605    case SIP_DTMF_RFC2833:
06606       if (p->rtp)
06607          ast_rtp_instance_dtmf_begin(p->rtp, digit);
06608       break;
06609    default:
06610       break;
06611    }
06612    sip_pvt_unlock(p);
06613 
06614    return res;
06615 }
06616 
06617 /*! \brief Send DTMF character on SIP channel
06618    within one call, we're able to transmit in many methods simultaneously */
06619 static int sip_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration)
06620 {
06621    struct sip_pvt *p = ast->tech_pvt;
06622    int res = 0;
06623 
06624    sip_pvt_lock(p);
06625    switch (ast_test_flag(&p->flags[0], SIP_DTMF)) {
06626    case SIP_DTMF_INFO:
06627    case SIP_DTMF_SHORTINFO:
06628       transmit_info_with_digit(p, digit, duration);
06629       break;
06630    case SIP_DTMF_RFC2833:
06631       if (p->rtp)
06632          ast_rtp_instance_dtmf_end_with_duration(p->rtp, digit, duration);
06633       break;
06634    case SIP_DTMF_INBAND:
06635       res = -1; /* Tell Asterisk to stop inband indications */
06636       break;
06637    }
06638    sip_pvt_unlock(p);
06639 
06640    return res;
06641 }
06642 
06643 /*! \brief Transfer SIP call */
06644 static int sip_transfer(struct ast_channel *ast, const char *dest)
06645 {
06646    struct sip_pvt *p = ast->tech_pvt;
06647    int res;
06648 
06649    if (dest == NULL) /* functions below do not take a NULL */
06650       dest = "";
06651    sip_pvt_lock(p);
06652    if (ast->_state == AST_STATE_RING)
06653       res = sip_sipredirect(p, dest);
06654    else
06655       res = transmit_refer(p, dest);
06656    sip_pvt_unlock(p);
06657    return res;
06658 }
06659 
06660 /*! \brief Helper function which updates T.38 capability information and triggers a reinvite */
06661 static int interpret_t38_parameters(struct sip_pvt *p, const struct ast_control_t38_parameters *parameters)
06662 {
06663    int res = 0;
06664 
06665    if (!ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) || !p->udptl) {
06666       return -1;
06667    }
06668    switch (parameters->request_response) {
06669    case AST_T38_NEGOTIATED:
06670    case AST_T38_REQUEST_NEGOTIATE:         /* Request T38 */
06671       /* Negotiation can not take place without a valid max_ifp value. */
06672       if (!parameters->max_ifp) {
06673          change_t38_state(p, T38_DISABLED);
06674          if (p->t38.state == T38_PEER_REINVITE) {
06675             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"));
06676             transmit_response_reliable(p, "488 Not acceptable here", &p->initreq);
06677          }
06678          break;
06679       } else if (p->t38.state == T38_PEER_REINVITE) {
06680          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"));
06681          p->t38.our_parms = *parameters;
06682          /* modify our parameters to conform to the peer's parameters,
06683           * based on the rules in the ITU T.38 recommendation
06684           */
06685          if (!p->t38.their_parms.fill_bit_removal) {
06686             p->t38.our_parms.fill_bit_removal = FALSE;
06687          }
06688          if (!p->t38.their_parms.transcoding_mmr) {
06689             p->t38.our_parms.transcoding_mmr = FALSE;
06690          }
06691          if (!p->t38.their_parms.transcoding_jbig) {
06692             p->t38.our_parms.transcoding_jbig = FALSE;
06693          }
06694          p->t38.our_parms.version = MIN(p->t38.our_parms.version, p->t38.their_parms.version);
06695          p->t38.our_parms.rate_management = p->t38.their_parms.rate_management;
06696          ast_udptl_set_local_max_ifp(p->udptl, p->t38.our_parms.max_ifp);
06697          change_t38_state(p, T38_ENABLED);
06698          transmit_response_with_t38_sdp(p, "200 OK", &p->initreq, XMIT_CRITICAL);
06699       } else if (p->t38.state != T38_ENABLED) {
06700          p->t38.our_parms = *parameters;
06701          ast_udptl_set_local_max_ifp(p->udptl, p->t38.our_parms.max_ifp);
06702          change_t38_state(p, T38_LOCAL_REINVITE);
06703          if (!p->pendinginvite) {
06704             transmit_reinvite_with_sdp(p, TRUE, FALSE);
06705          } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
06706             ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
06707          }
06708       }
06709       break;
06710    case AST_T38_TERMINATED:
06711    case AST_T38_REFUSED:
06712    case AST_T38_REQUEST_TERMINATE:         /* Shutdown T38 */
06713       if (p->t38.state == T38_PEER_REINVITE) {
06714          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"));
06715          change_t38_state(p, T38_DISABLED);
06716          transmit_response_reliable(p, "488 Not acceptable here", &p->initreq);
06717       } else if (p->t38.state == T38_ENABLED)
06718          transmit_reinvite_with_sdp(p, FALSE, FALSE);
06719       break;
06720    case AST_T38_REQUEST_PARMS: {    /* Application wants remote's parameters re-sent */
06721       struct ast_control_t38_parameters parameters = p->t38.their_parms;
06722 
06723       if (p->t38.state == T38_PEER_REINVITE) {
06724          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"));
06725          parameters.max_ifp = ast_udptl_get_far_max_ifp(p->udptl);
06726          parameters.request_response = AST_T38_REQUEST_NEGOTIATE;
06727          ast_queue_control_data(p->owner, AST_CONTROL_T38_PARAMETERS, &parameters, sizeof(parameters));
06728          /* we need to return a positive value here, so that applications that
06729           * send this request can determine conclusively whether it was accepted or not...
06730           * older versions of chan_sip would just silently accept it and return zero.
06731           */
06732          res = AST_T38_REQUEST_PARMS;
06733       }
06734       break;
06735    }
06736    default:
06737       res = -1;
06738       break;
06739    }
06740 
06741    return res;
06742 }
06743 
06744 /*! \brief Play indication to user
06745  * With SIP a lot of indications is sent as messages, letting the device play
06746    the indication - busy signal, congestion etc
06747    \return -1 to force ast_indicate to send indication in audio, 0 if SIP can handle the indication by sending a message
06748 */
06749 static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen)
06750 {
06751    struct sip_pvt *p = ast->tech_pvt;
06752    int res = 0;
06753 
06754    sip_pvt_lock(p);
06755    switch(condition) {
06756    case AST_CONTROL_RINGING:
06757       if (ast->_state == AST_STATE_RING) {
06758          p->invitestate = INV_EARLY_MEDIA;
06759          if (!ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) ||
06760              (ast_test_flag(&p->flags[0], SIP_PROG_INBAND) == SIP_PROG_INBAND_NEVER)) {            
06761             /* Send 180 ringing if out-of-band seems reasonable */
06762             transmit_provisional_response(p, "180 Ringing", &p->initreq, 0);
06763             ast_set_flag(&p->flags[0], SIP_RINGING);
06764             if (ast_test_flag(&p->flags[0], SIP_PROG_INBAND) != SIP_PROG_INBAND_YES)
06765                break;
06766          } else {
06767             /* Well, if it's not reasonable, just send in-band */
06768          }
06769       }
06770       res = -1;
06771       break;
06772    case AST_CONTROL_BUSY:
06773       if (ast->_state != AST_STATE_UP) {
06774          transmit_response_reliable(p, "486 Busy Here", &p->initreq);
06775          p->invitestate = INV_COMPLETED;
06776          sip_alreadygone(p);
06777          ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
06778          break;
06779       }
06780       res = -1;
06781       break;
06782    case AST_CONTROL_CONGESTION:
06783       if (ast->_state != AST_STATE_UP) {
06784          transmit_response_reliable(p, "503 Service Unavailable", &p->initreq);
06785          p->invitestate = INV_COMPLETED;
06786          sip_alreadygone(p);
06787          ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
06788          break;
06789       }
06790       res = -1;
06791       break;
06792    case AST_CONTROL_INCOMPLETE:
06793       if (ast->_state != AST_STATE_UP) {
06794          switch (ast_test_flag(&p->flags[1], SIP_PAGE2_ALLOWOVERLAP)) {
06795          case SIP_PAGE2_ALLOWOVERLAP_YES:
06796             transmit_response_reliable(p, "484 Address Incomplete", &p->initreq);
06797             p->invitestate = INV_COMPLETED;
06798             sip_alreadygone(p);
06799             ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
06800             break;
06801          case SIP_PAGE2_ALLOWOVERLAP_DTMF:
06802             /* Just wait for inband DTMF digits */
06803             break;
06804          default:
06805             /* it actually means no support for overlap */
06806             transmit_response_reliable(p, "404 Not Found", &p->initreq);
06807             p->invitestate = INV_COMPLETED;
06808             sip_alreadygone(p);
06809             ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
06810             break;
06811          }
06812       }
06813       break;
06814    case AST_CONTROL_PROCEEDING:
06815       if ((ast->_state != AST_STATE_UP) &&
06816           !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
06817           !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06818          transmit_response(p, "100 Trying", &p->initreq);
06819          p->invitestate = INV_PROCEEDING;
06820          break;
06821       }
06822       res = -1;
06823       break;
06824    case AST_CONTROL_PROGRESS:
06825       if ((ast->_state != AST_STATE_UP) &&
06826           !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
06827           !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06828          p->invitestate = INV_EARLY_MEDIA;
06829          transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
06830          ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
06831          break;
06832       }
06833       res = -1;
06834       break;
06835    case AST_CONTROL_HOLD:
06836       ast_rtp_instance_update_source(p->rtp);
06837       ast_moh_start(ast, data, p->mohinterpret);
06838       break;
06839    case AST_CONTROL_UNHOLD:
06840       ast_rtp_instance_update_source(p->rtp);
06841       ast_moh_stop(ast);
06842       break;
06843    case AST_CONTROL_VIDUPDATE:   /* Request a video frame update */
06844       if (p->vrtp && !p->novideo) {
06845          transmit_info_with_vidupdate(p);
06846          /* ast_rtcp_send_h261fur(p->vrtp); */
06847       } else
06848          res = -1;
06849       break;
06850    case AST_CONTROL_T38_PARAMETERS:
06851       if (datalen != sizeof(struct ast_control_t38_parameters)) {
06852          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);
06853          res = -1;
06854       } else {
06855          const struct ast_control_t38_parameters *parameters = data;
06856          res = interpret_t38_parameters(p, parameters);
06857       }
06858       break;
06859    case AST_CONTROL_SRCUPDATE:
06860       ast_rtp_instance_update_source(p->rtp);
06861       break;
06862    case AST_CONTROL_SRCCHANGE:
06863       ast_rtp_instance_change_source(p->rtp);
06864       break;
06865    case AST_CONTROL_CONNECTED_LINE:
06866       update_connectedline(p, data, datalen);
06867       break;
06868    case AST_CONTROL_REDIRECTING:
06869       update_redirecting(p, data, datalen);
06870       break;
06871    case AST_CONTROL_AOC:
06872       {
06873          struct ast_aoc_decoded *decoded = ast_aoc_decode((struct ast_aoc_encoded *) data, datalen, ast);
06874          if (!decoded) {
06875             ast_log(LOG_ERROR, "Error decoding indicated AOC data\n");
06876             res = -1;
06877             break;
06878          }
06879          switch (ast_aoc_get_msg_type(decoded)) {
06880          case AST_AOC_REQUEST:
06881             if (ast_aoc_get_termination_request(decoded)) {
06882                /* TODO, once there is a way to get AOC-E on hangup, attempt that here
06883                 * before hanging up the channel.*/
06884 
06885                /* The other side has already initiated the hangup. This frame
06886                 * just says they are waiting to get AOC-E before completely tearing
06887                 * the call down.  Since SIP does not support this at the moment go
06888                 * ahead and terminate the call here to avoid an unnecessary timeout. */
06889                ast_debug(1, "AOC-E termination request received on %s. This is not yet supported on sip. Continue with hangup \n", p->owner->name);
06890                ast_softhangup_nolock(p->owner, AST_SOFTHANGUP_DEV);
06891             }
06892             break;
06893          case AST_AOC_D:
06894          case AST_AOC_E:
06895             if (ast_test_flag(&p->flags[2], SIP_PAGE3_SNOM_AOC)) {
06896                transmit_info_with_aoc(p, decoded);
06897             }
06898             break;
06899          case AST_AOC_S: /* S not supported yet */
06900          default:
06901             break;
06902          }
06903          ast_aoc_destroy_decoded(decoded);
06904       }
06905       break;
06906    case AST_CONTROL_UPDATE_RTP_PEER: /* Absorb this since it is handled by the bridge */
06907       break;
06908    case -1:
06909       res = -1;
06910       break;
06911    default:
06912       ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", condition);
06913       res = -1;
06914       break;
06915    }
06916    sip_pvt_unlock(p);
06917    return res;
06918 }
06919 
06920 /*!
06921  * \brief Initiate a call in the SIP channel
06922  *
06923  * \note called from sip_request_call (calls from the pbx ) for
06924  * outbound channels and from handle_request_invite for inbound
06925  * channels
06926  *
06927  * \pre i is locked
06928  *
06929  * \return New ast_channel locked.
06930  */
06931 static struct ast_channel *sip_new(struct sip_pvt *i, int state, const char *title, const char *linkedid)
06932 {
06933    struct ast_channel *tmp;
06934    struct ast_variable *v = NULL;
06935    format_t fmt;
06936    format_t what;
06937    format_t video;
06938    format_t text;
06939    format_t needvideo = 0;
06940    int needtext = 0;
06941    char buf[SIPBUFSIZE];
06942    char *exten;
06943 
06944    {
06945       const char *my_name; /* pick a good name */
06946    
06947       if (title) {
06948          my_name = title;
06949       } else {
06950          my_name = ast_strdupa(i->fromdomain);
06951       }
06952 
06953       sip_pvt_unlock(i);
06954       /* Don't hold a sip pvt lock while we allocate a channel */
06955       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));
06956    }
06957    if (!tmp) {
06958       ast_log(LOG_WARNING, "Unable to allocate AST channel structure for SIP channel\n");
06959       sip_pvt_lock(i);
06960       return NULL;
06961    }
06962    ast_channel_lock(tmp);
06963    sip_pvt_lock(i);
06964    ast_channel_cc_params_init(tmp, i->cc_params);
06965    tmp->caller.id.tag = ast_strdup(i->cid_tag);
06966 
06967    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;
06968 
06969    /* Select our native format based on codec preference until we receive
06970       something from another device to the contrary. */
06971    if (i->jointcapability) {  /* The joint capabilities of us and peer */
06972       what = i->jointcapability;
06973       video = i->jointcapability & AST_FORMAT_VIDEO_MASK;
06974       text = i->jointcapability & AST_FORMAT_TEXT_MASK;
06975    } else if (i->capability) {      /* Our configured capability for this peer */
06976       what = i->capability;
06977       video = i->capability & AST_FORMAT_VIDEO_MASK;
06978       text = i->capability & AST_FORMAT_TEXT_MASK;
06979    } else {
06980       what = sip_cfg.capability; /* Global codec support */
06981       video = sip_cfg.capability & AST_FORMAT_VIDEO_MASK;
06982       text = sip_cfg.capability & AST_FORMAT_TEXT_MASK;
06983    }
06984 
06985    /* Set the native formats for audio  and merge in video */
06986    tmp->nativeformats = ast_codec_choose(&i->prefs, what, 1) | video | text;
06987    ast_debug(3, "*** Our native formats are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, tmp->nativeformats));
06988    ast_debug(3, "*** Joint capabilities are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, i->jointcapability));
06989    ast_debug(3, "*** Our capabilities are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, i->capability));
06990    ast_debug(3, "*** AST_CODEC_CHOOSE formats are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, ast_codec_choose(&i->prefs, what, 1)));
06991    if (i->prefcodec)
06992       ast_debug(3, "*** Our preferred formats from the incoming channel are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, i->prefcodec));
06993 
06994    /* XXX Why are we choosing a codec from the native formats?? */
06995    fmt = ast_best_codec(tmp->nativeformats);
06996 
06997    /* If we have a prefcodec setting, we have an inbound channel that set a
06998       preferred format for this call. Otherwise, we check the jointcapability
06999       We also check for vrtp. If it's not there, we are not allowed do any video anyway.
07000     */
07001    if (i->vrtp) {
07002       if (ast_test_flag(&i->flags[1], SIP_PAGE2_VIDEOSUPPORT))
07003          needvideo = AST_FORMAT_VIDEO_MASK;
07004       else if (i->prefcodec)
07005          needvideo = i->prefcodec & AST_FORMAT_VIDEO_MASK;  /* Outbound call */
07006       else
07007          needvideo = i->jointcapability & AST_FORMAT_VIDEO_MASK;  /* Inbound call */
07008    }
07009 
07010    if (i->trtp) {
07011       if (i->prefcodec)
07012          needtext = i->prefcodec & AST_FORMAT_TEXT_MASK; /* Outbound call */
07013       else
07014          needtext = i->jointcapability & AST_FORMAT_TEXT_MASK; /* Inbound call */
07015    }
07016 
07017    if (needvideo)
07018       ast_debug(3, "This channel can handle video! HOLLYWOOD next!\n");
07019    else
07020       ast_debug(3, "This channel will not be able to handle video.\n");
07021 
07022    enable_dsp_detect(i);
07023 
07024    if ((ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) ||
07025        (ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_AUTO)) {
07026       if (i->rtp) {
07027          ast_rtp_instance_dtmf_mode_set(i->rtp, AST_RTP_DTMF_MODE_INBAND);
07028       }
07029    } else if (ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) {
07030       if (i->rtp) {
07031          ast_rtp_instance_dtmf_mode_set(i->rtp, AST_RTP_DTMF_MODE_RFC2833);
07032       }
07033    }
07034 
07035    /* Set file descriptors for audio, video, realtime text and UDPTL as needed */
07036    if (i->rtp) {
07037       ast_channel_set_fd(tmp, 0, ast_rtp_instance_fd(i->rtp, 0));
07038       ast_channel_set_fd(tmp, 1, ast_rtp_instance_fd(i->rtp, 1));
07039    }
07040    if (needvideo && i->vrtp) {
07041       ast_channel_set_fd(tmp, 2, ast_rtp_instance_fd(i->vrtp, 0));
07042       ast_channel_set_fd(tmp, 3, ast_rtp_instance_fd(i->vrtp, 1));
07043    }
07044    if (needtext && i->trtp)
07045       ast_channel_set_fd(tmp, 4, ast_rtp_instance_fd(i->trtp, 0));
07046    if (i->udptl)
07047       ast_channel_set_fd(tmp, 5, ast_udptl_fd(i->udptl));
07048 
07049    if (state == AST_STATE_RING)
07050       tmp->rings = 1;
07051    tmp->adsicpe = AST_ADSI_UNAVAILABLE;
07052 
07053    tmp->writeformat = fmt;
07054    tmp->rawwriteformat = fmt;
07055    ast_rtp_instance_set_write_format(i->rtp, fmt);
07056 
07057    tmp->readformat = fmt;
07058    tmp->rawreadformat = fmt;
07059    ast_rtp_instance_set_read_format(i->rtp, fmt);
07060 
07061    tmp->tech_pvt = dialog_ref(i, "sip_new: set chan->tech_pvt to i");
07062 
07063    tmp->callgroup = i->callgroup;
07064    tmp->pickupgroup = i->pickupgroup;
07065    tmp->caller.id.name.presentation = i->callingpres;
07066    tmp->caller.id.number.presentation = i->callingpres;
07067    if (!ast_strlen_zero(i->parkinglot))
07068       ast_string_field_set(tmp, parkinglot, i->parkinglot);
07069    if (!ast_strlen_zero(i->accountcode))
07070       ast_string_field_set(tmp, accountcode, i->accountcode);
07071    if (i->amaflags)
07072       tmp->amaflags = i->amaflags;
07073    if (!ast_strlen_zero(i->language))
07074       ast_string_field_set(tmp, language, i->language);
07075    i->owner = tmp;
07076    ast_module_ref(ast_module_info->self);
07077    ast_copy_string(tmp->context, i->context, sizeof(tmp->context));
07078    /*Since it is valid to have extensions in the dialplan that have unescaped characters in them
07079     * we should decode the uri before storing it in the channel, but leave it encoded in the sip_pvt
07080     * structure so that there aren't issues when forming URI's
07081     */
07082    exten = ast_strdupa(i->exten);
07083    sip_pvt_unlock(i);
07084    ast_channel_unlock(tmp);
07085    if (!ast_exists_extension(NULL, i->context, i->exten, 1, i->cid_num)) {
07086       ast_uri_decode(exten);
07087    }
07088    ast_channel_lock(tmp);
07089    sip_pvt_lock(i);
07090    ast_copy_string(tmp->exten, exten, sizeof(tmp->exten));
07091 
07092    /* Don't use ast_set_callerid() here because it will
07093     * generate an unnecessary NewCallerID event  */
07094    if (!ast_strlen_zero(i->cid_num)) {
07095       tmp->caller.ani.number.valid = 1;
07096       tmp->caller.ani.number.str = ast_strdup(i->cid_num);
07097    }
07098    if (!ast_strlen_zero(i->rdnis)) {
07099       tmp->redirecting.from.number.valid = 1;
07100       tmp->redirecting.from.number.str = ast_strdup(i->rdnis);
07101    }
07102 
07103    if (!ast_strlen_zero(i->exten) && strcmp(i->exten, "s")) {
07104       tmp->dialed.number.str = ast_strdup(i->exten);
07105    }
07106 
07107    tmp->priority = 1;
07108    if (!ast_strlen_zero(i->uri))
07109       pbx_builtin_setvar_helper(tmp, "SIPURI", i->uri);
07110    if (!ast_strlen_zero(i->domain))
07111       pbx_builtin_setvar_helper(tmp, "SIPDOMAIN", i->domain);
07112    if (!ast_strlen_zero(i->callid))
07113       pbx_builtin_setvar_helper(tmp, "SIPCALLID", i->callid);
07114    if (i->rtp)
07115       ast_jb_configure(tmp, &global_jbconf);
07116 
07117    /* Set channel variables for this call from configuration */
07118    for (v = i->chanvars ; v ; v = v->next) {
07119       char valuebuf[1024];
07120       pbx_builtin_setvar_helper(tmp, v->name, ast_get_encoded_str(v->value, valuebuf, sizeof(valuebuf)));
07121    }
07122 
07123    if (i->do_history)
07124       append_history(i, "NewChan", "Channel %s - from %s", tmp->name, i->callid);
07125 
07126    /* Inform manager user about new channel and their SIP call ID */
07127    if (sip_cfg.callevents)
07128       manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
07129          "Channel: %s\r\nUniqueid: %s\r\nChanneltype: %s\r\nSIPcallid: %s\r\nSIPfullcontact: %s\r\n",
07130          tmp->name, tmp->uniqueid, "SIP", i->callid, i->fullcontact);
07131 
07132    return tmp;
07133 }
07134 
07135 /*! \brief Reads one line of SIP message body */
07136 static char *get_body_by_line(const char *line, const char *name, int nameLen, char delimiter)
07137 {
07138    if (!strncasecmp(line, name, nameLen) && line[nameLen] == delimiter)
07139       return ast_skip_blanks(line + nameLen + 1);
07140 
07141    return "";
07142 }
07143 
07144 /*! \brief Lookup 'name' in the SDP starting
07145  * at the 'start' line. Returns the matching line, and 'start'
07146  * is updated with the next line number.
07147  */
07148 static const char *get_sdp_iterate(int *start, struct sip_request *req, const char *name)
07149 {
07150    int len = strlen(name);
07151 
07152    while (*start < (req->sdp_start + req->sdp_count)) {
07153       const char *r = get_body_by_line(REQ_OFFSET_TO_STR(req, line[(*start)++]), name, len, '=');
07154       if (r[0] != '\0')
07155          return r;
07156    }
07157 
07158    /* if the line was not found, ensure that *start points past the SDP */
07159    (*start)++;
07160 
07161    return "";
07162 }
07163 
07164 /*! \brief Fetches the next valid SDP line between the 'start' line
07165  * (inclusive) and the 'stop' line (exclusive). Returns the type
07166  * ('a', 'c', ...) and matching line in reference 'start' is updated
07167  * with the next line number.
07168  */
07169 static char get_sdp_line(int *start, int stop, struct sip_request *req, const char **value)
07170 {
07171    char type = '\0';
07172    const char *line = NULL;
07173 
07174    if (stop > (req->sdp_start + req->sdp_count)) {
07175       stop = req->sdp_start + req->sdp_count;
07176    }
07177 
07178    while (*start < stop) {
07179       line = REQ_OFFSET_TO_STR(req, line[(*start)++]);
07180       if (line[1] == '=') {
07181          type = line[0];
07182          *value = ast_skip_blanks(line + 2);
07183          break;
07184       }
07185    }
07186 
07187    return type;
07188 }
07189 
07190 /*! \brief Get a specific line from the message body */
07191 static char *get_body(struct sip_request *req, char *name, char delimiter)
07192 {
07193    int x;
07194    int len = strlen(name);
07195    char *r;
07196 
07197    for (x = 0; x < req->lines; x++) {
07198       r = get_body_by_line(REQ_OFFSET_TO_STR(req, line[x]), name, len, delimiter);
07199       if (r[0] != '\0')
07200          return r;
07201    }
07202 
07203    return "";
07204 }
07205 
07206 /*! \brief Find compressed SIP alias */
07207 static const char *find_alias(const char *name, const char *_default)
07208 {
07209    /*! \brief Structure for conversion between compressed SIP and "normal" SIP */
07210    static const struct cfalias {
07211       char * const fullname;
07212       char * const shortname;
07213    } aliases[] = {
07214       { "Content-Type",  "c" },
07215       { "Content-Encoding",    "e" },
07216       { "From",       "f" },
07217       { "Call-ID",       "i" },
07218       { "Contact",       "m" },
07219       { "Content-Length",   "l" },
07220       { "Subject",       "s" },
07221       { "To",         "t" },
07222       { "Supported",     "k" },
07223       { "Refer-To",      "r" },
07224       { "Referred-By",   "b" },
07225       { "Allow-Events",  "u" },
07226       { "Event",      "o" },
07227       { "Via",     "v" },
07228       { "Accept-Contact",      "a" },
07229       { "Reject-Contact",      "j" },
07230       { "Request-Disposition", "d" },
07231       { "Session-Expires",     "x" },
07232       { "Identity",            "y" },
07233       { "Identity-Info",       "n" },
07234    };
07235    int x;
07236 
07237    for (x = 0; x < ARRAY_LEN(aliases); x++) {
07238       if (!strcasecmp(aliases[x].fullname, name))
07239          return aliases[x].shortname;
07240    }
07241 
07242    return _default;
07243 }
07244 
07245 static const char *__get_header(const struct sip_request *req, const char *name, int *start)
07246 {
07247    int pass;
07248 
07249    /*
07250     * Technically you can place arbitrary whitespace both before and after the ':' in
07251     * a header, although RFC3261 clearly says you shouldn't before, and place just
07252     * one afterwards.  If you shouldn't do it, what absolute idiot decided it was
07253     * a good idea to say you can do it, and if you can do it, why in the hell would.
07254     * you say you shouldn't.
07255     * Anyways, pedanticsipchecking controls whether we allow spaces before ':',
07256     * and we always allow spaces after that for compatibility.
07257     */
07258    for (pass = 0; name && pass < 2;pass++) {
07259       int x, len = strlen(name);
07260       for (x = *start; x < req->headers; x++) {
07261          const char *header = REQ_OFFSET_TO_STR(req, header[x]);
07262          if (!strncasecmp(header, name, len)) {
07263             const char *r = header + len; /* skip name */
07264             if (sip_cfg.pedanticsipchecking)
07265                r = ast_skip_blanks(r);
07266 
07267             if (*r == ':') {
07268                *start = x+1;
07269                return ast_skip_blanks(r+1);
07270             }
07271          }
07272       }
07273       if (pass == 0) /* Try aliases */
07274          name = find_alias(name, NULL);
07275    }
07276 
07277    /* Don't return NULL, so get_header is always a valid pointer */
07278    return "";
07279 }
07280 
07281 /*! \brief Get header from SIP request
07282    \return Always return something, so don't check for NULL because it won't happen :-)
07283 */
07284 static const char *get_header(const struct sip_request *req, const char *name)
07285 {
07286    int start = 0;
07287    return __get_header(req, name, &start);
07288 }
07289 
07290 /*! \brief Read RTP from network */
07291 static struct ast_frame *sip_rtp_read(struct ast_channel *ast, struct sip_pvt *p, int *faxdetect)
07292 {
07293    /* Retrieve audio/etc from channel.  Assumes p->lock is already held. */
07294    struct ast_frame *f;
07295    
07296    if (!p->rtp) {
07297       /* We have no RTP allocated for this channel */
07298       return &ast_null_frame;
07299    }
07300 
07301    switch(ast->fdno) {
07302    case 0:
07303       f = ast_rtp_instance_read(p->rtp, 0);  /* RTP Audio */
07304       break;
07305    case 1:
07306       f = ast_rtp_instance_read(p->rtp, 1);  /* RTCP Control Channel */
07307       break;
07308    case 2:
07309       f = ast_rtp_instance_read(p->vrtp, 0); /* RTP Video */
07310       break;
07311    case 3:
07312       f = ast_rtp_instance_read(p->vrtp, 1); /* RTCP Control Channel for video */
07313       break;
07314    case 4:
07315       f = ast_rtp_instance_read(p->trtp, 0); /* RTP Text */
07316       if (sipdebug_text) {
07317          int i;
07318          unsigned char* arr = f->data.ptr;
07319          for (i=0; i < f->datalen; i++)
07320             ast_verbose("%c", (arr[i] > ' ' && arr[i] < '}') ? arr[i] : '.');
07321          ast_verbose(" -> ");
07322          for (i=0; i < f->datalen; i++)
07323             ast_verbose("%02X ", arr[i]);
07324          ast_verbose("\n");
07325       }
07326       break;
07327    case 5:
07328       f = ast_udptl_read(p->udptl); /* UDPTL for T.38 */
07329       break;
07330    default:
07331       f = &ast_null_frame;
07332    }
07333    /* Don't forward RFC2833 if we're not supposed to */
07334    if (f && (f->frametype == AST_FRAME_DTMF_BEGIN || f->frametype == AST_FRAME_DTMF_END) &&
07335        (ast_test_flag(&p->flags[0], SIP_DTMF) != SIP_DTMF_RFC2833)) {
07336       ast_debug(1, "Ignoring DTMF (%c) RTP frame because dtmfmode is not RFC2833\n", f->subclass.integer);
07337       return &ast_null_frame;
07338    }
07339 
07340    /* We already hold the channel lock */
07341    if (!p->owner || (f && f->frametype != AST_FRAME_VOICE))
07342       return f;
07343 
07344    if (f && f->subclass.codec != (p->owner->nativeformats & AST_FORMAT_AUDIO_MASK)) {
07345       if (!(f->subclass.codec & p->jointcapability)) {
07346          ast_debug(1, "Bogus frame of format '%s' received from '%s'!\n",
07347             ast_getformatname(f->subclass.codec), p->owner->name);
07348          return &ast_null_frame;
07349       }
07350       ast_debug(1, "Oooh, format changed to %s\n",
07351          ast_getformatname(f->subclass.codec));
07352       p->owner->nativeformats = (p->owner->nativeformats & (AST_FORMAT_VIDEO_MASK | AST_FORMAT_TEXT_MASK)) | f->subclass.codec;
07353       ast_set_read_format(p->owner, p->owner->readformat);
07354       ast_set_write_format(p->owner, p->owner->writeformat);
07355    }
07356 
07357    if (f && p->dsp) {
07358       f = ast_dsp_process(p->owner, p->dsp, f);
07359       if (f && f->frametype == AST_FRAME_DTMF) {
07360          if (f->subclass.integer == 'f') {
07361             ast_debug(1, "Fax CNG detected on %s\n", ast->name);
07362             *faxdetect = 1;
07363             /* If we only needed this DSP for fax detection purposes we can just drop it now */
07364             if (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) {
07365                ast_dsp_set_features(p->dsp, DSP_FEATURE_DIGIT_DETECT);
07366             } else {
07367                ast_dsp_free(p->dsp);
07368                p->dsp = NULL;
07369             }
07370          } else {
07371             ast_debug(1, "* Detected inband DTMF '%c'\n", f->subclass.integer);
07372          }
07373       }
07374    }
07375    
07376    return f;
07377 }
07378 
07379 /*! \brief Read SIP RTP from channel */
07380 static struct ast_frame *sip_read(struct ast_channel *ast)
07381 {
07382    struct ast_frame *fr;
07383    struct sip_pvt *p = ast->tech_pvt;
07384    int faxdetected = FALSE;
07385 
07386    sip_pvt_lock(p);
07387    fr = sip_rtp_read(ast, p, &faxdetected);
07388    p->lastrtprx = time(NULL);
07389 
07390    /* If we detect a CNG tone and fax detection is enabled then send us off to the fax extension */
07391    if (faxdetected && ast_test_flag(&p->flags[1], SIP_PAGE2_FAX_DETECT_CNG)) {
07392       if (strcmp(ast->exten, "fax")) {
07393          const char *target_context = S_OR(ast->macrocontext, ast->context);
07394          /* We need to unlock 'ast' here because
07395           * ast_exists_extension has the potential to start and
07396           * stop an autoservice on the channel. Such action is
07397           * prone to deadlock if the channel is locked.
07398           */
07399          sip_pvt_unlock(p);
07400          ast_channel_unlock(ast);
07401          if (ast_exists_extension(ast, target_context, "fax", 1,
07402             S_COR(ast->caller.id.number.valid, ast->caller.id.number.str, NULL))) {
07403             ast_channel_lock(ast);
07404             sip_pvt_lock(p);
07405             ast_verbose(VERBOSE_PREFIX_2 "Redirecting '%s' to fax extension due to CNG detection\n", ast->name);
07406             pbx_builtin_setvar_helper(ast, "FAXEXTEN", ast->exten);
07407             if (ast_async_goto(ast, target_context, "fax", 1)) {
07408                ast_log(LOG_NOTICE, "Failed to async goto '%s' into fax of '%s'\n", ast->name, target_context);
07409             }
07410             fr = &ast_null_frame;
07411          } else {
07412             ast_channel_lock(ast);
07413             sip_pvt_lock(p);
07414             ast_log(LOG_NOTICE, "FAX CNG detected but no fax extension\n");
07415          }
07416       }
07417    }
07418 
07419    /* Only allow audio through if they sent progress with SDP, or if the channel is actually answered */
07420    if (fr && fr->frametype == AST_FRAME_VOICE && p->invitestate != INV_EARLY_MEDIA && ast->_state != AST_STATE_UP) {
07421       fr = &ast_null_frame;
07422    }
07423 
07424    sip_pvt_unlock(p);
07425 
07426    return fr;
07427 }
07428 
07429 
07430 /*! \brief Generate 32 byte random string for callid's etc */
07431 static char *generate_random_string(char *buf, size_t size)
07432 {
07433    long val[4];
07434    int x;
07435 
07436    for (x=0; x<4; x++)
07437       val[x] = ast_random();
07438    snprintf(buf, size, "%08lx%08lx%08lx%08lx", val[0], val[1], val[2], val[3]);
07439 
07440    return buf;
07441 }
07442 
07443 static char *generate_uri(struct sip_pvt *pvt, char *buf, size_t size)
07444 {
07445    struct ast_str *uri = ast_str_alloca(size);
07446    ast_str_set(&uri, 0, "%s", pvt->socket.type == SIP_TRANSPORT_TLS ? "sips:" : "sip:");
07447    /* Here would be a great place to generate a UUID, but for now we'll
07448     * use the handy random string generation function we already have
07449     */
07450    ast_str_append(&uri, 0, "%s", generate_random_string(buf, size));
07451    ast_str_append(&uri, 0, "@%s", ast_sockaddr_stringify_remote(&pvt->ourip));
07452    ast_copy_string(buf, ast_str_buffer(uri), size);
07453    return buf;
07454 }
07455 
07456 /*!
07457  * \brief Build SIP Call-ID value for a non-REGISTER transaction
07458  *
07459  * \note The passed in pvt must not be in a dialogs container
07460  * since this function changes the hash key used by the
07461  * container.
07462  */
07463 static void build_callid_pvt(struct sip_pvt *pvt)
07464 {
07465    char buf[33];
07466    const char *host = S_OR(pvt->fromdomain, ast_sockaddr_stringify_remote(&pvt->ourip));
07467 
07468    ast_string_field_build(pvt, callid, "%s@%s", generate_random_string(buf, sizeof(buf)), host);
07469 }
07470 
07471 /*! \brief Unlink the given object from the container and return TRUE if it was in the container. */
07472 #define CONTAINER_UNLINK(container, obj, tag)                        \
07473    ({                                                    \
07474       int found = 0;                                        \
07475       typeof((obj)) __removed_obj;                             \
07476       __removed_obj = ao2_t_callback((container),                    \
07477          OBJ_UNLINK | OBJ_POINTER, ao2_match_by_addr, (obj), (tag));    \
07478       if (__removed_obj) {                                  \
07479          ao2_ref(__removed_obj, -1);                              \
07480          found = 1;                                         \
07481       }                                                  \
07482       found;                                                \
07483    })
07484 
07485 /*!
07486  * \internal
07487  * \brief Safely change the callid of the given SIP dialog.
07488  *
07489  * \param pvt SIP private structure to change callid
07490  * \param callid Specified new callid to use.  NULL if generate new callid.
07491  *
07492  * \return Nothing
07493  */
07494 static void change_callid_pvt(struct sip_pvt *pvt, const char *callid)
07495 {
07496    int in_dialog_container;
07497 
07498    ao2_lock(dialogs);
07499    in_dialog_container = CONTAINER_UNLINK(dialogs, pvt,
07500       "About to change the callid -- remove the old name");
07501    if (callid) {
07502       ast_string_field_set(pvt, callid, callid);
07503    } else {
07504       build_callid_pvt(pvt);
07505    }
07506    if (in_dialog_container) {
07507       ao2_t_link(dialogs, pvt, "New dialog callid -- inserted back into table");
07508    }
07509    ao2_unlock(dialogs);
07510 }
07511 
07512 /*! \brief Build SIP Call-ID value for a REGISTER transaction */
07513 static void build_callid_registry(struct sip_registry *reg, const struct ast_sockaddr *ourip, const char *fromdomain)
07514 {
07515    char buf[33];
07516 
07517    const char *host = S_OR(fromdomain, ast_sockaddr_stringify_host_remote(ourip));
07518 
07519    ast_string_field_build(reg, callid, "%s@%s", generate_random_string(buf, sizeof(buf)), host);
07520 }
07521 
07522 /*! \brief Make our SIP dialog tag */
07523 static void make_our_tag(char *tagbuf, size_t len)
07524 {
07525    snprintf(tagbuf, len, "as%08lx", ast_random());
07526 }
07527 
07528 /*! \brief Allocate Session-Timers struct w/in dialog */
07529 static struct sip_st_dlg* sip_st_alloc(struct sip_pvt *const p)
07530 {
07531    struct sip_st_dlg *stp;
07532 
07533    if (p->stimer) {
07534       ast_log(LOG_ERROR, "Session-Timer struct already allocated\n");
07535       return p->stimer;
07536    }
07537 
07538    if (!(stp = ast_calloc(1, sizeof(struct sip_st_dlg))))
07539       return NULL;
07540 
07541    p->stimer = stp;
07542 
07543    stp->st_schedid = -1;           /* Session-Timers ast_sched scheduler id */
07544 
07545    return p->stimer;
07546 }
07547 
07548 /*! \brief Allocate sip_pvt structure, set defaults and link in the container.
07549  * Returns a reference to the object so whoever uses it later must
07550  * remember to release the reference.
07551  */
07552 struct sip_pvt *sip_alloc(ast_string_field callid, struct ast_sockaddr *addr,
07553              int useglobal_nat, const int intended_method, struct sip_request *req)
07554 {
07555    struct sip_pvt *p;
07556 
07557    if (!(p = ao2_t_alloc(sizeof(*p), sip_destroy_fn, "allocate a dialog(pvt) struct")))
07558       return NULL;
07559 
07560    if (ast_string_field_init(p, 512)) {
07561       ao2_t_ref(p, -1, "failed to string_field_init, drop p");
07562       return NULL;
07563    }
07564 
07565    if (!(p->cc_params = ast_cc_config_params_init())) {
07566       ao2_t_ref(p, -1, "Yuck, couldn't allocate cc_params struct. Get rid o' p");
07567       return NULL;
07568    }
07569 
07570    /* If this dialog is created as the result of an incoming Request. Lets store
07571     * some information about that request */
07572    if (req) {
07573       struct sip_via *via;
07574       const char *cseq = get_header(req, "Cseq");
07575       unsigned int seqno;
07576 
07577       /* get branch parameter from initial Request that started this dialog */
07578       via = parse_via(get_header(req, "Via"));
07579       if (via) {
07580          /* only store the branch if it begins with the magic prefix "z9hG4bK", otherwise
07581           * it is not useful to us to have it */
07582          if (!ast_strlen_zero(via->branch) && !strncasecmp(via->branch, "z9hG4bK", 7)) {
07583             ast_string_field_set(p, initviabranch, via->branch);
07584             ast_string_field_set(p, initviasentby, via->sent_by);
07585          }
07586          free_via(via);
07587       }
07588 
07589       /* Store initial incoming cseq. An error in sscanf here is ignored.  There is no approperiate
07590        * except not storing the number.  CSeq validation must take place before dialog creation in find_call */
07591       if (!ast_strlen_zero(cseq) && (sscanf(cseq, "%30u", &seqno) == 1)) {
07592          p->init_icseq = seqno;
07593       }
07594       /* Later in ast_sip_ouraddrfor we need this to choose the right ip and port for the specific transport */
07595       set_socket_transport(&p->socket, req->socket.type);
07596    } else {
07597       set_socket_transport(&p->socket, SIP_TRANSPORT_UDP);
07598    }
07599 
07600    p->socket.fd = -1;
07601    p->method = intended_method;
07602    p->initid = -1;
07603    p->waitid = -1;
07604    p->autokillid = -1;
07605    p->request_queue_sched_id = -1;
07606    p->provisional_keepalive_sched_id = -1;
07607    p->t38id = -1;
07608    p->subscribed = NONE;
07609    p->stateid = -1;
07610    p->sessionversion_remote = -1;
07611    p->session_modify = TRUE;
07612    p->stimer = NULL;
07613    p->prefs = default_prefs;     /* Set default codecs for this call */
07614    p->maxforwards = sip_cfg.default_max_forwards;
07615 
07616    if (intended_method != SIP_OPTIONS) {  /* Peerpoke has it's own system */
07617       p->timer_t1 = global_t1;   /* Default SIP retransmission timer T1 (RFC 3261) */
07618       p->timer_b = global_timer_b;  /* Default SIP transaction timer B (RFC 3261) */
07619    }
07620 
07621    if (!addr) {
07622       p->ourip = internip;
07623    } else {
07624       ast_sockaddr_copy(&p->sa, addr);
07625       ast_sip_ouraddrfor(&p->sa, &p->ourip, p);
07626    }
07627 
07628    /* Copy global flags to this PVT at setup. */
07629    ast_copy_flags(&p->flags[0], &global_flags[0], SIP_FLAGS_TO_COPY);
07630    ast_copy_flags(&p->flags[1], &global_flags[1], SIP_PAGE2_FLAGS_TO_COPY);
07631    ast_copy_flags(&p->flags[2], &global_flags[2], SIP_PAGE3_FLAGS_TO_COPY);
07632 
07633    p->do_history = recordhistory;
07634 
07635    p->branch = ast_random();  
07636    make_our_tag(p->tag, sizeof(p->tag));
07637    p->ocseq = INITIAL_CSEQ;
07638    p->allowed_methods = UINT_MAX;
07639 
07640    if (sip_methods[intended_method].need_rtp) {
07641       if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT)) {
07642          if ((p->udptl = ast_udptl_new_with_bindaddr(sched, io, 0, &bindaddr))) {
07643             ast_udptl_setqos(p->udptl, global_tos_audio, global_cos_audio);
07644             p->t38_maxdatagram = global_t38_maxdatagram;
07645          } else {
07646             /* udptl creation failed, T38 can not be supported on this dialog */
07647             ast_log(LOG_ERROR, "UDPTL creation failed\n");
07648             ast_clear_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT);
07649          }
07650       }
07651       p->maxcallbitrate = default_maxcallbitrate;
07652       p->autoframing = global_autoframing;
07653    }
07654 
07655    if (useglobal_nat && addr) {
07656       /* Setup NAT structure according to global settings if we have an address */
07657       ast_copy_flags(&p->flags[0], &global_flags[0], SIP_NAT_FORCE_RPORT);
07658       ast_sockaddr_copy(&p->recv, addr);
07659 
07660       do_setnat(p);
07661    }
07662 
07663    if (p->method != SIP_REGISTER) {
07664       ast_string_field_set(p, fromdomain, default_fromdomain);
07665       p->fromdomainport = default_fromdomainport;
07666    }
07667    build_via(p);
07668    if (!callid)
07669       build_callid_pvt(p);
07670    else
07671       ast_string_field_set(p, callid, callid);
07672    /* Assign default music on hold class */
07673    ast_string_field_set(p, mohinterpret, default_mohinterpret);
07674    ast_string_field_set(p, mohsuggest, default_mohsuggest);
07675    p->capability = sip_cfg.capability;
07676    p->allowtransfer = sip_cfg.allowtransfer;
07677    if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
07678        (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
07679       p->noncodeccapability |= AST_RTP_DTMF;
07680    if (p->udptl) {
07681       p->t38_maxdatagram = global_t38_maxdatagram;
07682       set_t38_capabilities(p);
07683    }
07684    ast_string_field_set(p, context, sip_cfg.default_context);
07685    ast_string_field_set(p, parkinglot, default_parkinglot);
07686    ast_string_field_set(p, engine, default_engine);
07687 
07688    AST_LIST_HEAD_INIT_NOLOCK(&p->request_queue);
07689 
07690    /* Add to active dialog list */
07691 
07692    ao2_t_link(dialogs, p, "link pvt into dialogs table");
07693    
07694    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");
07695    return p;
07696 }
07697 
07698 /*!
07699  * \brief Check if an ip is an multicast IP.
07700  * \parm addr the address to check
07701  *
07702  * This function checks if an address is in the 224.0.0.0/4 network block.
07703  * \return non-zero if this is a multicast address
07704  */
07705 static int addr_is_multicast(const struct ast_sockaddr *addr)
07706 {
07707    return ((ast_sockaddr_ipv4(addr) & 0xf0000000) == 0xe0000000);
07708 }
07709 
07710 /*!
07711  * \brief Process the Via header according to RFC 3261 section 18.2.2.
07712  * \param p a sip_pvt structure that will be modified according to the received
07713  * header
07714  * \param req a sip request with a Via header to process
07715  *
07716  * This function will update the destination of the response according to the
07717  * Via header in the request and RFC 3261 section 18.2.2. We do not have a
07718  * transport layer so we ignore certain values like the 'received' param (we
07719  * set the destination address to the addres the request came from in the
07720  * respprep() function).
07721  *
07722  * \retval -1 error
07723  * \retval 0 success
07724  */
07725 static int process_via(struct sip_pvt *p, const struct sip_request *req)
07726 {
07727    struct sip_via *via = parse_via(get_header(req, "Via"));
07728 
07729    if (!via) {
07730       ast_log(LOG_ERROR, "error processing via header\n");
07731       return -1;
07732    }
07733 
07734    if (via->maddr) {
07735       if (ast_sockaddr_resolve_first(&p->sa, via->maddr, PARSE_PORT_FORBID)) {
07736          ast_log(LOG_WARNING, "Can't find address for maddr '%s'\n", via->maddr);
07737          ast_log(LOG_ERROR, "error processing via header\n");
07738          free_via(via);
07739          return -1;
07740       }
07741 
07742       if (addr_is_multicast(&p->sa)) {
07743          setsockopt(sipsock, IPPROTO_IP, IP_MULTICAST_TTL, &via->ttl, sizeof(via->ttl));
07744       }
07745    }
07746 
07747    ast_sockaddr_set_port(&p->sa, via->port ? via->port : STANDARD_SIP_PORT);
07748 
07749    free_via(via);
07750    return 0;
07751 }
07752 
07753 /* \brief arguments used for Request/Response to matching */
07754 struct match_req_args {
07755    int method;
07756    const char *callid;
07757    const char *totag;
07758    const char *fromtag;
07759    unsigned int seqno;
07760 
07761    /* Set if the method is a Request */
07762    const char *ruri;
07763    const char *viabranch;
07764    const char *viasentby;
07765 
07766    /* Set this if the Authentication header is present in the Request. */
07767    int authentication_present;
07768 };
07769 
07770 enum match_req_res {
07771    SIP_REQ_MATCH,
07772    SIP_REQ_NOT_MATCH,
07773    SIP_REQ_LOOP_DETECTED,
07774 };
07775 
07776 /*
07777  * \brief Match a incoming Request/Response to a dialog
07778  *
07779  * \retval enum match_req_res indicating if the dialog matches the arg
07780  */
07781 static enum match_req_res match_req_to_dialog(struct sip_pvt *sip_pvt_ptr, struct match_req_args *arg)
07782 {
07783    const char *init_ruri = NULL;
07784    if (sip_pvt_ptr->initreq.headers) {
07785       init_ruri = REQ_OFFSET_TO_STR(&sip_pvt_ptr->initreq, rlPart2);
07786    }
07787 
07788    /*
07789     * Match Tags and call-id to Dialog
07790     */
07791    if (!ast_strlen_zero(arg->callid) && strcmp(sip_pvt_ptr->callid, arg->callid)) {
07792       /* call-id does not match. */
07793       return SIP_REQ_NOT_MATCH;
07794    }
07795    if (arg->method == SIP_RESPONSE) {
07796       /* Verify totag if we have one stored for this dialog, but never be strict about this for
07797        * a response until the dialog is established */
07798       if (!ast_strlen_zero(sip_pvt_ptr->theirtag) && ast_test_flag(&sip_pvt_ptr->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED)) {
07799          if (ast_strlen_zero(arg->totag)) {
07800             /* missing totag when they already gave us one earlier */
07801             return SIP_REQ_NOT_MATCH;
07802          }
07803          if (strcmp(arg->totag, sip_pvt_ptr->theirtag)) {
07804             /* The totag of the response does not match the one we have stored */
07805             return SIP_REQ_NOT_MATCH;
07806          }
07807       }
07808       /* Verify fromtag of response matches the tag we gave them. */
07809       if (strcmp(arg->fromtag, sip_pvt_ptr->tag)) {
07810          /* fromtag from response does not match our tag */
07811          return SIP_REQ_NOT_MATCH;
07812       }
07813    } else {
07814       /* Verify the fromtag of Request matches the tag they provided earlier.
07815        * If this is a Request with authentication credentials, forget their old
07816        * tag as it is not valid after the 401 or 407 response. */
07817       if (!arg->authentication_present && strcmp(arg->fromtag, sip_pvt_ptr->theirtag)) {
07818          /* their tag does not match the one was have stored for them */
07819          return SIP_REQ_NOT_MATCH;
07820       }
07821       /* Verify if totag is present in Request, that it matches what we gave them as our tag earlier */
07822       if (!ast_strlen_zero(arg->totag) && (strcmp(arg->totag, sip_pvt_ptr->tag))) {
07823          /* totag from Request does not match our tag */
07824          return SIP_REQ_NOT_MATCH;
07825       }
07826    }
07827 
07828    /*
07829     * Compare incoming request against initial transaction.
07830     * 
07831     * This is a best effort attempt at distinguishing forked requests from
07832     * our initial transaction.  If all the elements are NOT in place to evaluate
07833     * this, this block is ignored and the dialog match is made regardless.
07834     * Once the totag is established after the dialog is confirmed, this is not necessary.
07835     *
07836     * CRITERIA required for initial transaction matching.
07837     * 
07838     * 1. Is a Request
07839     * 2. Callid and theirtag match (this is done in the dialog matching block)
07840     * 3. totag is NOT present
07841     * 4. CSeq matchs our initial transaction's cseq number
07842     * 5. pvt has init via branch parameter stored
07843     */
07844    if ((arg->method != SIP_RESPONSE) &&                 /* must be a Request */
07845       ast_strlen_zero(arg->totag) &&                   /* must not have a totag */
07846       (sip_pvt_ptr->init_icseq == arg->seqno) &&       /* the cseq must be the same as this dialogs initial cseq */
07847       !ast_strlen_zero(sip_pvt_ptr->initviabranch) &&  /* The dialog must have started with a RFC3261 compliant branch tag */
07848       init_ruri) {                                     /* the dialog must have an initial request uri associated with it */
07849       /* This Request matches all the criteria required for Loop/Merge detection.
07850        * Now we must go down the path of comparing VIA's and RURIs. */
07851       if (ast_strlen_zero(arg->viabranch) ||
07852          strcmp(arg->viabranch, sip_pvt_ptr->initviabranch) ||
07853          ast_strlen_zero(arg->viasentby) ||
07854          strcmp(arg->viasentby, sip_pvt_ptr->initviasentby)) {
07855          /* At this point, this request does not match this Dialog.*/
07856 
07857          /* if methods are different this is just a mismatch */
07858          if ((sip_pvt_ptr->method != arg->method)) {
07859             return SIP_REQ_NOT_MATCH;
07860          }
07861 
07862          /* If RUIs are different, this is a forked request to a separate URI.
07863           * Returning a mismatch allows this Request to be processed separately. */
07864          if (sip_uri_cmp(init_ruri, arg->ruri)) {
07865             /* not a match, request uris are different */
07866             return SIP_REQ_NOT_MATCH;
07867          }
07868 
07869          /* Loop/Merge Detected
07870           *
07871           * ---Current Matches to Initial Request---
07872           * request uri
07873           * Call-id
07874           * their-tag
07875           * no totag present
07876           * method
07877           * cseq
07878           *
07879           * --- Does not Match Initial Request ---
07880           * Top Via
07881           *
07882           * Without the same Via, this can not match our initial transaction for this dialog,
07883           * but given that this Request matches everything else associated with that initial
07884           * Request this is most certainly a Forked request in which we have already received
07885           * part of the fork.
07886           */
07887          return SIP_REQ_LOOP_DETECTED;
07888       }
07889    } /* end of Request Via check */
07890 
07891    /* Match Authentication Request.
07892     *
07893     * A Request with an Authentication header must come back with the
07894     * same Request URI.  Otherwise it is not a match.
07895     */
07896    if ((arg->method != SIP_RESPONSE) &&      /* Must be a Request type to even begin checking this */
07897       ast_strlen_zero(arg->totag) &&        /* no totag is present to match */
07898       arg->authentication_present &&        /* Authentication header is present in Request */
07899       sip_uri_cmp(init_ruri, arg->ruri)) {  /* Compare the Request URI of both the last Request and this new one */
07900 
07901       /* Authentication was provided, but the Request URI did not match the last one on this dialog. */
07902       return SIP_REQ_NOT_MATCH;
07903    }
07904 
07905    return SIP_REQ_MATCH;
07906 }
07907 
07908 /*! \internal
07909  *
07910  * \brief Locks both pvt and pvt owner if owner is present.
07911  *
07912  * \note This function gives a ref to pvt->owner if it is present and locked.
07913  *       This reference must be decremented after pvt->owner is unlocked.
07914  *
07915  * \note This function will never give you up,
07916  * \note This function will never let you down.
07917  * \note This function will run around and desert you.
07918  *
07919  * \pre pvt is not locked
07920  * \post pvt is locked
07921  * \post pvt->owner is locked and its reference count is increased (if pvt->owner is not NULL)
07922  *
07923  * \returns a pointer to the locked and reffed pvt->owner channel if it exists.
07924  */
07925 static struct ast_channel *sip_pvt_lock_full(struct sip_pvt *pvt)
07926 {
07927    struct ast_channel *chan;
07928 
07929    /* Locking is simple when it is done right.  If you see a deadlock resulting
07930     * in this function, it is not this function's fault, Your problem exists elsewhere.
07931     * This function is perfect... seriously. */
07932    for (;;) {
07933       /* First, get the channel and grab a reference to it */
07934       sip_pvt_lock(pvt);
07935       chan = pvt->owner;
07936       if (chan) {
07937          /* The channel can not go away while we hold the pvt lock.
07938           * Give the channel a ref so it will not go away after we let
07939           * the pvt lock go. */
07940          ast_channel_ref(chan);
07941       } else {
07942          /* no channel, return pvt locked */
07943          return NULL;
07944       }
07945 
07946       /* We had to hold the pvt lock while getting a ref to the owner channel
07947        * but now we have to let this lock go in order to preserve proper
07948        * locking order when grabbing the channel lock */
07949       sip_pvt_unlock(pvt);
07950 
07951       /* Look, no deadlock avoidance, hooray! */
07952       ast_channel_lock(chan);
07953       sip_pvt_lock(pvt);
07954 
07955       if (pvt->owner == chan) {
07956          /* done */
07957          break;
07958       }
07959 
07960       /* If the owner changed while everything was unlocked, no problem,
07961        * just start over and everthing will work.  This is rare, do not be
07962        * confused by this loop and think this it is an expensive operation.
07963        * The majority of the calls to this function will never involve multiple
07964        * executions of this loop. */
07965       ast_channel_unlock(chan);
07966       ast_channel_unref(chan);
07967       sip_pvt_unlock(pvt);
07968    }
07969 
07970    /* If owner exists, it is locked and reffed */
07971    return pvt->owner;
07972 }
07973 
07974 /*! \brief find or create a dialog structure for an incoming SIP message.
07975  * Connect incoming SIP message to current dialog or create new dialog structure
07976  * Returns a reference to the sip_pvt object, remember to give it back once done.
07977  *     Called by handle_request_do
07978  */
07979 static struct sip_pvt *find_call(struct sip_request *req, struct ast_sockaddr *addr, const int intended_method)
07980 {
07981    char totag[128];
07982    char fromtag[128];
07983    const char *callid = get_header(req, "Call-ID");
07984    const char *from = get_header(req, "From");
07985    const char *to = get_header(req, "To");
07986    const char *cseq = get_header(req, "Cseq");
07987    struct sip_pvt *sip_pvt_ptr;
07988    unsigned int seqno;
07989    /* Call-ID, to, from and Cseq are required by RFC 3261. (Max-forwards and via too - ignored now) */
07990    /* get_header always returns non-NULL so we must use ast_strlen_zero() */
07991    if (ast_strlen_zero(callid) || ast_strlen_zero(to) ||
07992          ast_strlen_zero(from) || ast_strlen_zero(cseq) ||
07993          (sscanf(cseq, "%30u", &seqno) != 1)) {
07994 
07995       /* RFC 3261 section 24.4.1.   Send a 400 Bad Request if the request is malformed. */
07996       if (intended_method != SIP_RESPONSE && intended_method != SIP_ACK) {
07997          transmit_response_using_temp(callid, addr, 1, intended_method,
07998                        req, "400 Bad Request");
07999       }
08000       return NULL;   /* Invalid packet */
08001    }
08002 
08003    if (sip_cfg.pedanticsipchecking) {
08004       /* In principle Call-ID's uniquely identify a call, but with a forking SIP proxy
08005          we need more to identify a branch - so we have to check branch, from
08006          and to tags to identify a call leg.
08007          For Asterisk to behave correctly, you need to turn on pedanticsipchecking
08008          in sip.conf
08009          */
08010       if (gettag(req, "To", totag, sizeof(totag)))
08011          req->has_to_tag = 1; /* Used in handle_request/response */
08012       gettag(req, "From", fromtag, sizeof(fromtag));
08013 
08014       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);
08015 
08016       /* All messages must always have From: tag */
08017       if (ast_strlen_zero(fromtag)) {
08018          ast_debug(5, "%s request has no from tag, dropping callid: %s from: %s\n", sip_methods[req->method].text , callid, from );
08019          return NULL;
08020       }
08021       /* reject requests that must always have a To: tag */
08022       if (ast_strlen_zero(totag) && (req->method == SIP_ACK || req->method == SIP_BYE || req->method == SIP_INFO )) {
08023          ast_debug(5, "%s must have a to tag. dropping callid: %s from: %s\n", sip_methods[req->method].text , callid, from );
08024          return NULL;
08025       }
08026    }
08027 
08028    if (!sip_cfg.pedanticsipchecking) {
08029       struct sip_pvt tmp_dialog = {
08030          .callid = callid,
08031       };
08032       sip_pvt_ptr = ao2_t_find(dialogs, &tmp_dialog, OBJ_POINTER, "ao2_find in dialogs");
08033       if (sip_pvt_ptr) {  /* well, if we don't find it-- what IS in there? */
08034          /* Found the call */
08035          return sip_pvt_ptr;
08036       }
08037    } else { /* in pedantic mode! -- do the fancy search */
08038       struct sip_pvt tmp_dialog = {
08039          .callid = callid,
08040       };
08041       struct match_req_args args = { 0, };
08042       int found;
08043       struct ao2_iterator *iterator = ao2_t_callback(dialogs,
08044          OBJ_POINTER | OBJ_MULTIPLE,
08045          dialog_find_multiple,
08046          &tmp_dialog,
08047          "pedantic ao2_find in dialogs");
08048       struct sip_via *via = NULL;
08049 
08050       args.method = req->method;
08051       args.callid = NULL; /* we already matched this. */
08052       args.totag = totag;
08053       args.fromtag = fromtag;
08054       args.seqno = seqno;
08055 
08056       /* If this is a Request, set the Via and Authorization header arguments */
08057       if (req->method != SIP_RESPONSE) {
08058          args.ruri = REQ_OFFSET_TO_STR(req, rlPart2);
08059          via = parse_via(get_header(req, "Via"));
08060          if (via) {
08061             args.viasentby = via->sent_by;
08062             args.viabranch = via->branch;
08063          }
08064          if (!ast_strlen_zero(get_header(req, "Authorization")) ||
08065             !ast_strlen_zero(get_header(req, "Proxy-Authorization"))) {
08066             args.authentication_present = 1;
08067          }
08068       }
08069 
08070       /* Iterate a list of dialogs already matched by Call-id */
08071       while (iterator && (sip_pvt_ptr = ao2_iterator_next(iterator))) {
08072          found = match_req_to_dialog(sip_pvt_ptr, &args);
08073 
08074          switch (found) {
08075          case SIP_REQ_MATCH:
08076             ao2_iterator_destroy(iterator);
08077             free_via(via);
08078             return sip_pvt_ptr; /* return pvt with ref */
08079          case SIP_REQ_LOOP_DETECTED:
08080             /* This is likely a forked Request that somehow resulted in us receiving multiple parts of the fork.
08081             * RFC 3261 section 8.2.2.2, Indicate that we want to merge requests by sending a 482 response. */
08082             transmit_response_using_temp(callid, addr, 1, intended_method, req, "482 (Loop Detected)");
08083             dialog_unref(sip_pvt_ptr, "pvt did not match incoming SIP msg, unref from search.");
08084             ao2_iterator_destroy(iterator);
08085             free_via(via);
08086             return NULL;
08087          case SIP_REQ_NOT_MATCH:
08088          default:
08089             dialog_unref(sip_pvt_ptr, "pvt did not match incoming SIP msg, unref from search");
08090          }
08091       }
08092       if (iterator) {
08093          ao2_iterator_destroy(iterator);
08094       }
08095 
08096       free_via(via);
08097    } /* end of pedantic mode Request/Reponse to Dialog matching */
08098 
08099    /* See if the method is capable of creating a dialog */
08100    if (sip_methods[intended_method].can_create == CAN_CREATE_DIALOG) {
08101       struct sip_pvt *p = NULL;
08102 
08103       if (intended_method == SIP_REFER) {
08104          /* We do support REFER, but not outside of a dialog yet */
08105          transmit_response_using_temp(callid, addr, 1, intended_method, req, "603 Declined (no dialog)");
08106    
08107       /* Ok, time to create a new SIP dialog object, a pvt */
08108       } else if (!(p = sip_alloc(callid, addr, 1, intended_method, req)))  {
08109          /* We have a memory or file/socket error (can't allocate RTP sockets or something) so we're not
08110             getting a dialog from sip_alloc.
08111 
08112             Without a dialog we can't retransmit and handle ACKs and all that, but at least
08113             send an error message.
08114 
08115             Sorry, we apologize for the inconvienience
08116          */
08117          transmit_response_using_temp(callid, addr, 1, intended_method, req, "500 Server internal error");
08118          ast_debug(4, "Failed allocating SIP dialog, sending 500 Server internal error and giving up\n");
08119       }
08120       return p; /* can be NULL */
08121    } else if( sip_methods[intended_method].can_create == CAN_CREATE_DIALOG_UNSUPPORTED_METHOD) {
08122       /* A method we do not support, let's take it on the volley */
08123       transmit_response_using_temp(callid, addr, 1, intended_method, req, "501 Method Not Implemented");
08124       ast_debug(2, "Got a request with unsupported SIP method.\n");
08125    } else if (intended_method != SIP_RESPONSE && intended_method != SIP_ACK) {
08126       /* This is a request outside of a dialog that we don't know about */
08127       transmit_response_using_temp(callid, addr, 1, intended_method, req, "481 Call leg/transaction does not exist");
08128       ast_debug(2, "That's odd...  Got a request in unknown dialog. Callid %s\n", callid ? callid : "<unknown>");
08129    }
08130    /* We do not respond to responses for dialogs that we don't know about, we just drop
08131       the session quickly */
08132    if (intended_method == SIP_RESPONSE)
08133       ast_debug(2, "That's odd...  Got a response on a call we don't know about. Callid %s\n", callid ? callid : "<unknown>");
08134 
08135    return NULL;
08136 }
08137 
08138 /*! \brief create sip_registry object from register=> line in sip.conf and link into reg container */
08139 static int sip_register(const char *value, int lineno)
08140 {
08141    struct sip_registry *reg;
08142 
08143    if (!(reg = ast_calloc_with_stringfields(1, struct sip_registry, 256))) {
08144       ast_log(LOG_ERROR, "Out of memory. Can't allocate SIP registry entry\n");
08145       return -1;
08146    }
08147 
08148    ast_atomic_fetchadd_int(&regobjs, 1);
08149    ASTOBJ_INIT(reg);
08150 
08151    if (sip_parse_register_line(reg, default_expiry, value, lineno)) {
08152       registry_unref(reg, "failure to parse, unref the reg pointer");
08153       return -1;
08154    }
08155 
08156    /* set default expiry if necessary */
08157    if (reg->refresh && !reg->expiry && !reg->configured_expiry) {
08158       reg->refresh = reg->expiry = reg->configured_expiry = default_expiry;
08159    }
08160 
08161    /* Add the new registry entry to the list */
08162    ASTOBJ_CONTAINER_LINK(&regl, reg);
08163 
08164    /* release the reference given by ASTOBJ_INIT. The container has another reference */
08165    registry_unref(reg, "unref the reg pointer");
08166 
08167    return 0;
08168 }
08169 
08170 /*! \brief Parse mwi=> line in sip.conf and add to list */
08171 static int sip_subscribe_mwi(const char *value, int lineno)
08172 {
08173    struct sip_subscription_mwi *mwi;
08174    int portnum = 0;
08175    enum sip_transport transport = SIP_TRANSPORT_UDP;
08176    char buf[256] = "";
08177    char *username = NULL, *hostname = NULL, *secret = NULL, *authuser = NULL, *porta = NULL, *mailbox = NULL, *at = NULL;
08178 
08179    if (!value) {
08180       return -1;
08181    }
08182 
08183    ast_copy_string(buf, value, sizeof(buf));
08184 
08185    if (!(at = strstr(buf, "@"))) {
08186       return -1;
08187    }
08188 
08189    if ((hostname = strrchr(buf, '@'))) {
08190       *hostname++ = '\0';
08191       username = buf;
08192    }
08193 
08194    if ((secret = strchr(username, ':'))) {
08195       *secret++ = '\0';
08196       if ((authuser = strchr(secret, ':'))) {
08197          *authuser++ = '\0';
08198       }
08199    }
08200 
08201    if ((mailbox = strchr(hostname, '/'))) {
08202       *mailbox++ = '\0';
08203    }
08204 
08205    if (ast_strlen_zero(username) || ast_strlen_zero(hostname) || ast_strlen_zero(mailbox)) {
08206       ast_log(LOG_WARNING, "Format for MWI subscription is user[:secret[:authuser]]@host[:port]/mailbox at line %d\n", lineno);
08207       return -1;
08208    }
08209 
08210    if ((porta = strchr(hostname, ':'))) {
08211       *porta++ = '\0';
08212       if (!(portnum = atoi(porta))) {
08213          ast_log(LOG_WARNING, "%s is not a valid port number at line %d\n", porta, lineno);
08214          return -1;
08215       }
08216    }
08217 
08218    if (!(mwi = ast_calloc_with_stringfields(1, struct sip_subscription_mwi, 256))) {
08219       return -1;
08220    }
08221 
08222    ASTOBJ_INIT(mwi);
08223    ast_string_field_set(mwi, username, username);
08224    if (secret) {
08225       ast_string_field_set(mwi, secret, secret);
08226    }
08227    if (authuser) {
08228       ast_string_field_set(mwi, authuser, authuser);
08229    }
08230    ast_string_field_set(mwi, hostname, hostname);
08231    ast_string_field_set(mwi, mailbox, mailbox);
08232    mwi->resub = -1;
08233    mwi->portno = portnum;
08234    mwi->transport = transport;
08235 
08236    ASTOBJ_CONTAINER_LINK(&submwil, mwi);
08237    ASTOBJ_UNREF(mwi, sip_subscribe_mwi_destroy);
08238 
08239    return 0;
08240 }
08241 
08242 static void mark_method_allowed(unsigned int *allowed_methods, enum sipmethod method)
08243 {
08244    (*allowed_methods) |= (1 << method);
08245 }
08246 
08247 static void mark_method_unallowed(unsigned int *allowed_methods, enum sipmethod method)
08248 {
08249    (*allowed_methods) &= ~(1 << method);
08250 }
08251 
08252 /*! \brief Check if method is allowed for a device or a dialog */
08253 static int is_method_allowed(unsigned int *allowed_methods, enum sipmethod method)
08254 {
08255    return ((*allowed_methods) >> method) & 1;
08256 }
08257 
08258 static void mark_parsed_methods(unsigned int *methods, char *methods_str)
08259 {
08260    char *method;
08261    for (method = strsep(&methods_str, ","); !ast_strlen_zero(method); method = strsep(&methods_str, ",")) {
08262       int id = find_sip_method(ast_skip_blanks(method));
08263       if (id == SIP_UNKNOWN) {
08264          continue;
08265       }
08266       mark_method_allowed(methods, id);
08267    }
08268 }
08269 /*!
08270  * \brief parse the Allow header to see what methods the endpoint we
08271  * are communicating with allows.
08272  *
08273  * We parse the allow header on incoming Registrations and save the
08274  * result to the SIP peer that is registering. When the registration
08275  * expires, we clear what we know about the peer's allowed methods.
08276  * When the peer re-registers, we once again parse to see if the
08277  * list of allowed methods has changed.
08278  *
08279  * For peers that do not register, we parse the first message we receive
08280  * during a call to see what is allowed, and save the information
08281  * for the duration of the call.
08282  * \param req The SIP request we are parsing
08283  * \retval The methods allowed
08284  */
08285 static unsigned int parse_allowed_methods(struct sip_request *req)
08286 {
08287    char *allow = ast_strdupa(get_header(req, "Allow"));
08288    unsigned int allowed_methods = SIP_UNKNOWN;
08289 
08290    if (ast_strlen_zero(allow)) {
08291       /* I have witnessed that REGISTER requests from Polycom phones do not
08292        * place the phone's allowed methods in an Allow header. Instead, they place the
08293        * allowed methods in a methods= parameter in the Contact header.
08294        */
08295       char *contact = ast_strdupa(get_header(req, "Contact"));
08296       char *methods = strstr(contact, ";methods=");
08297 
08298       if (ast_strlen_zero(methods)) {
08299          /* RFC 3261 states:
08300           *
08301           * "The absence of an Allow header field MUST NOT be
08302           * interpreted to mean that the UA sending the message supports no
08303           * methods.   Rather, it implies that the UA is not providing any
08304           * information on what methods it supports."
08305           *
08306           * For simplicity, we'll assume that the peer allows all known
08307           * SIP methods if they have no Allow header. We can then clear out the necessary
08308           * bits if the peer lets us know that we have sent an unsupported method.
08309           */
08310          return UINT_MAX;
08311       }
08312       allow = ast_strip_quoted(methods + 9, "\"", "\"");
08313    }
08314    mark_parsed_methods(&allowed_methods, allow);
08315    return allowed_methods;
08316 }
08317 
08318 /*! A wrapper for parse_allowed_methods geared toward sip_pvts
08319  *
08320  * This function, in addition to setting the allowed methods for a sip_pvt
08321  * also will take into account the setting of the SIP_PAGE2_RPID_UPDATE flag.
08322  *
08323  * \param pvt The sip_pvt we are setting the allowed_methods for
08324  * \param req The request which we are parsing
08325  * \retval The methods alloweded by the sip_pvt
08326  */
08327 static unsigned int set_pvt_allowed_methods(struct sip_pvt *pvt, struct sip_request *req)
08328 {
08329    pvt->allowed_methods = parse_allowed_methods(req);
08330    
08331    if (ast_test_flag(&pvt->flags[1], SIP_PAGE2_RPID_UPDATE)) {
08332       mark_method_allowed(&pvt->allowed_methods, SIP_UPDATE);
08333    }
08334    pvt->allowed_methods &= ~(pvt->disallowed_methods);
08335 
08336    return pvt->allowed_methods;
08337 }
08338 
08339 /*! \brief  Parse multiline SIP headers into one header
08340    This is enabled if pedanticsipchecking is enabled */
08341 static void lws2sws(struct ast_str *data)
08342 {
08343    char *msgbuf = data->str;
08344    int len = ast_str_strlen(data);
08345    int h = 0, t = 0;
08346    int lws = 0;
08347 
08348    for (; h < len;) {
08349       /* Eliminate all CRs */
08350       if (msgbuf[h] == '\r') {
08351          h++;
08352          continue;
08353       }
08354       /* Check for end-of-line */
08355       if (msgbuf[h] == '\n') {
08356          /* Check for end-of-message */
08357          if (h + 1 == len)
08358             break;
08359          /* Check for a continuation line */
08360          if (msgbuf[h + 1] == ' ' || msgbuf[h + 1] == '\t') {
08361             /* Merge continuation line */
08362             h++;
08363             continue;
08364          }
08365          /* Propagate LF and start new line */
08366          msgbuf[t++] = msgbuf[h++];
08367          lws = 0;
08368          continue;
08369       }
08370       if (msgbuf[h] == ' ' || msgbuf[h] == '\t') {
08371          if (lws) {
08372             h++;
08373             continue;
08374          }
08375          msgbuf[t++] = msgbuf[h++];
08376          lws = 1;
08377          continue;
08378       }
08379       msgbuf[t++] = msgbuf[h++];
08380       if (lws)
08381          lws = 0;
08382    }
08383    msgbuf[t] = '\0';
08384    data->used = t;
08385 }
08386 
08387 /*! \brief Parse a SIP message
08388    \note this function is used both on incoming and outgoing packets
08389 */
08390 static int parse_request(struct sip_request *req)
08391 {
08392    char *c = req->data->str;
08393    ptrdiff_t *dst = req->header;
08394    int i = 0, lim = SIP_MAX_HEADERS - 1;
08395    unsigned int skipping_headers = 0;
08396    ptrdiff_t current_header_offset = 0;
08397    char *previous_header = "";
08398 
08399    req->header[0] = 0;
08400    req->headers = -1;   /* mark that we are working on the header */
08401    for (; *c; c++) {
08402       if (*c == '\r') {    /* remove \r */
08403          *c = '\0';
08404       } else if (*c == '\n') {   /* end of this line */
08405          *c = '\0';
08406          current_header_offset = (c + 1) - req->data->str;
08407          previous_header = req->data->str + dst[i];
08408          if (skipping_headers) {
08409             /* check to see if this line is blank; if so, turn off
08410                the skipping flag, so the next line will be processed
08411                as a body line */
08412             if (ast_strlen_zero(previous_header)) {
08413                skipping_headers = 0;
08414             }
08415             dst[i] = current_header_offset; /* record start of next line */
08416             continue;
08417          }
08418          if (sipdebug) {
08419             ast_debug(4, "%7s %2d [%3d]: %s\n",
08420                  req->headers < 0 ? "Header" : "Body",
08421                  i, (int) strlen(previous_header), previous_header);
08422          }
08423          if (ast_strlen_zero(previous_header) && req->headers < 0) {
08424             req->headers = i; /* record number of header lines */
08425             dst = req->line;  /* start working on the body */
08426             i = 0;
08427             lim = SIP_MAX_LINES - 1;
08428          } else { /* move to next line, check for overflows */
08429             if (i++ == lim) {
08430                /* if we're processing headers, then skip any remaining
08431                   headers and move on to processing the body, otherwise
08432                   we're done */
08433                if (req->headers != -1) {
08434                   break;
08435                } else {
08436                   req->headers = i;
08437                   dst = req->line;
08438                   i = 0;
08439                   lim = SIP_MAX_LINES - 1;
08440                   skipping_headers = 1;
08441                }
08442             }
08443          }
08444          dst[i] = current_header_offset; /* record start of next line */
08445       }
08446    }
08447 
08448    /* Check for last header or body line without CRLF. The RFC for SDP requires CRLF,
08449       but since some devices send without, we'll be generous in what we accept. However,
08450       if we've already reached the maximum number of lines for portion of the message
08451       we were parsing, we can't accept any more, so just ignore it.
08452    */
08453    previous_header = req->data->str + dst[i];
08454    if ((i < lim) && !ast_strlen_zero(previous_header)) {
08455       if (sipdebug) {
08456          ast_debug(4, "%7s %2d [%3d]: %s\n",
08457               req->headers < 0 ? "Header" : "Body",
08458               i, (int) strlen(previous_header), previous_header );
08459       }
08460       i++;
08461    }
08462 
08463    /* update count of header or body lines */
08464    if (req->headers >= 0) {   /* we are in the body */
08465       req->lines = i;
08466    } else {       /* no body */
08467       req->headers = i;
08468       req->lines = 0;
08469       /* req->data->used will be a NULL byte */
08470       req->line[0] = ast_str_strlen(req->data);
08471    }
08472 
08473    if (*c) {
08474       ast_log(LOG_WARNING, "Too many lines, skipping <%s>\n", c);
08475    }
08476 
08477    /* Split up the first line parts */
08478    return determine_firstline_parts(req);
08479 }
08480 
08481 /*!
08482   \brief Determine whether a SIP message contains an SDP in its body
08483   \param req the SIP request to process
08484   \return 1 if SDP found, 0 if not found
08485 
08486   Also updates req->sdp_start and req->sdp_count to indicate where the SDP
08487   lives in the message body.
08488 */
08489 static int find_sdp(struct sip_request *req)
08490 {
08491    const char *content_type;
08492    const char *content_length;
08493    const char *search;
08494    char *boundary;
08495    unsigned int x;
08496    int boundaryisquoted = FALSE;
08497    int found_application_sdp = FALSE;
08498    int found_end_of_headers = FALSE;
08499 
08500    content_length = get_header(req, "Content-Length");
08501 
08502    if (!ast_strlen_zero(content_length)) {
08503       if (sscanf(content_length, "%30u", &x) != 1) {
08504          ast_log(LOG_WARNING, "Invalid Content-Length: %s\n", content_length);
08505          return 0;
08506       }
08507 
08508       /* Content-Length of zero means there can't possibly be an
08509          SDP here, even if the Content-Type says there is */
08510       if (x == 0)
08511          return 0;
08512    }
08513 
08514    content_type = get_header(req, "Content-Type");
08515 
08516    /* if the body contains only SDP, this is easy */
08517    if (!strncasecmp(content_type, "application/sdp", 15)) {
08518       req->sdp_start = 0;
08519       req->sdp_count = req->lines;
08520       return req->lines ? 1 : 0;
08521    }
08522 
08523    /* if it's not multipart/mixed, there cannot be an SDP */
08524    if (strncasecmp(content_type, "multipart/mixed", 15))
08525       return 0;
08526 
08527    /* if there is no boundary marker, it's invalid */
08528    if ((search = strcasestr(content_type, ";boundary=")))
08529       search += 10;
08530    else if ((search = strcasestr(content_type, "; boundary=")))
08531       search += 11;
08532    else
08533       return 0;
08534 
08535    if (ast_strlen_zero(search))
08536       return 0;
08537 
08538    /* If the boundary is quoted with ", remove quote */
08539    if (*search == '\"')  {
08540       search++;
08541       boundaryisquoted = TRUE;
08542    }
08543 
08544    /* make a duplicate of the string, with two extra characters
08545       at the beginning */
08546    boundary = ast_strdupa(search - 2);
08547    boundary[0] = boundary[1] = '-';
08548    /* Remove final quote */
08549    if (boundaryisquoted)
08550       boundary[strlen(boundary) - 1] = '\0';
08551 
08552    /* search for the boundary marker, the empty line delimiting headers from
08553       sdp part and the end boundry if it exists */
08554 
08555    for (x = 0; x < (req->lines); x++) {
08556       const char *line = REQ_OFFSET_TO_STR(req, line[x]);
08557       if (!strncasecmp(line, boundary, strlen(boundary))){
08558          if (found_application_sdp && found_end_of_headers) {
08559             req->sdp_count = (x - 1) - req->sdp_start;
08560             return 1;
08561          }
08562          found_application_sdp = FALSE;
08563       }
08564       if (!strcasecmp(line, "Content-Type: application/sdp"))
08565          found_application_sdp = TRUE;
08566       
08567       if (ast_strlen_zero(line)) {
08568          if (found_application_sdp && !found_end_of_headers){
08569             req->sdp_start = x;
08570             found_end_of_headers = TRUE;
08571          }
08572       }
08573    }
08574    if (found_application_sdp && found_end_of_headers) {
08575       req->sdp_count = x - req->sdp_start;
08576       return TRUE;
08577    }
08578    return FALSE;
08579 }
08580 
08581 /*! \brief Change hold state for a call */
08582 static void change_hold_state(struct sip_pvt *dialog, struct sip_request *req, int holdstate, int sendonly)
08583 {
08584    if (sip_cfg.notifyhold && (!holdstate || !ast_test_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD)))
08585       sip_peer_hold(dialog, holdstate);
08586    if (sip_cfg.callevents)
08587       manager_event(EVENT_FLAG_CALL, "Hold",
08588                "Status: %s\r\n"
08589                "Channel: %s\r\n"
08590                "Uniqueid: %s\r\n",
08591                holdstate ? "On" : "Off",
08592                dialog->owner->name,
08593                dialog->owner->uniqueid);
08594    append_history(dialog, holdstate ? "Hold" : "Unhold", "%s", req->data->str);
08595    if (!holdstate) { /* Put off remote hold */
08596       ast_clear_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD);   /* Clear both flags */
08597       return;
08598    }
08599    /* No address for RTP, we're on hold */
08600 
08601    if (sendonly == 1)   /* One directional hold (sendonly/recvonly) */
08602       ast_set_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD_ONEDIR);
08603    else if (sendonly == 2) /* Inactive stream */
08604       ast_set_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD_INACTIVE);
08605    else
08606       ast_set_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD_ACTIVE);
08607    return;
08608 }
08609 
08610 
08611 static int get_ip_and_port_from_sdp(struct sip_request *req, const enum media_type media, struct ast_sockaddr *addr)
08612 {
08613    const char *m;
08614    const char *c;
08615    int miterator = req->sdp_start;
08616    int citerator = req->sdp_start;
08617    int x = 0;
08618    int numberofports;
08619    int len;
08620    int af;
08621    char proto[4], host[258] = ""; /*Initialize to empty so we will know if we have any input */
08622 
08623    c = get_sdp_iterate(&citerator, req, "c");
08624    if (sscanf(c, "IN %3s %256s", proto, host) != 2) {
08625          ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
08626          /* Continue since there may be a valid host in a c= line specific to the audio stream */
08627    }
08628    /* We only want the m and c lines for audio */
08629    for (m = get_sdp_iterate(&miterator, req, "m"); !ast_strlen_zero(m); m = get_sdp_iterate(&miterator, req, "m")) {
08630       if ((media == SDP_AUDIO && ((sscanf(m, "audio %30u/%30u RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
08631           (sscanf(m, "audio %30u RTP/AVP %n", &x, &len) == 1 && len > 0))) ||
08632          (media == SDP_VIDEO && ((sscanf(m, "video %30u/%30u RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
08633           (sscanf(m, "video %30u RTP/AVP %n", &x, &len) == 1 && len > 0)))) {
08634          /* See if there's a c= line for this media stream.
08635           * XXX There is no guarantee that we'll be grabbing the c= line for this
08636           * particular media stream here. However, this is the same logic used in process_sdp.
08637           */
08638          c = get_sdp_iterate(&citerator, req, "c");
08639          if (!ast_strlen_zero(c)) {
08640             sscanf(c, "IN %3s %256s", proto, host);
08641          }
08642          break;
08643       }
08644    }
08645 
08646    if (!strcmp("IP4", proto)) {
08647       af = AF_INET;
08648    } else if (!strcmp("IP6", proto)) {
08649       af = AF_INET6;
08650    } else {
08651       ast_log(LOG_WARNING, "Unknown protocol '%s'.\n", proto);
08652       return -1;
08653    }
08654 
08655    if (ast_strlen_zero(host) || x == 0) {
08656       ast_log(LOG_WARNING, "Failed to read an alternate host or port in SDP. Expect %s problems\n", media == SDP_AUDIO ? "audio" : "video");
08657       return -1;
08658    }
08659 
08660    if (ast_sockaddr_resolve_first_af(addr, host, 0, af)) {
08661       ast_log(LOG_WARNING, "Could not look up IP address of alternate hostname. Expect %s problems\n", media == SDP_AUDIO? "audio" : "video");
08662       return -1;
08663    }
08664 
08665    return 0;
08666 }
08667 
08668 /*! \internal
08669  * \brief Returns whether or not the address is null or ANY / unspecified (0.0.0.0 or ::)
08670  * \retval TRUE if the address is null or any
08671  * \retval FALSE if the address it not null or any
08672  * \note In some circumstances, calls should be placed on hold if either of these conditions exist.
08673  */
08674 static int sockaddr_is_null_or_any(const struct ast_sockaddr *addr)
08675 {
08676    return ast_sockaddr_isnull(addr) || ast_sockaddr_is_any(addr);
08677 }
08678 
08679 /*! \brief Process SIP SDP offer, select formats and activate RTP channels
08680    If offer is rejected, we will not change any properties of the call
08681    Return 0 on success, a negative value on errors.
08682    Must be called after find_sdp().
08683 */
08684 static int process_sdp(struct sip_pvt *p, struct sip_request *req, int t38action)
08685 {
08686    /* Iterators for SDP parsing */
08687    int start = req->sdp_start;
08688    int next = start;
08689    int iterator = start;
08690 
08691    /* Temporary vars for SDP parsing */
08692    char type = '\0';
08693    const char *value = NULL;
08694    const char *m = NULL;           /* SDP media offer */
08695    const char *nextm = NULL;
08696    int len = -1;
08697 
08698    /* Host information */
08699    struct ast_sockaddr sessionsa;
08700    struct ast_sockaddr audiosa;
08701    struct ast_sockaddr videosa;
08702    struct ast_sockaddr textsa;
08703    struct ast_sockaddr imagesa;
08704    struct ast_sockaddr *sa = NULL;  /*!< RTP Audio host IP */
08705    struct ast_sockaddr *vsa = NULL; /*!< RTP video host IP */
08706    struct ast_sockaddr *tsa = NULL; /*!< RTP text host IP */
08707    struct ast_sockaddr *isa = NULL;     /*!< UDPTL host ip */
08708    int portno = -1;     /*!< RTP Audio port number */
08709    int vportno = -1;    /*!< RTP Video port number */
08710    int tportno = -1;    /*!< RTP Text port number */
08711    int udptlportno = -1;      /*!< UDPTL Image port number */
08712 
08713    /* Peer capability is the capability in the SDP, non codec is RFC2833 DTMF (101) */ 
08714    format_t peercapability = 0, vpeercapability = 0, tpeercapability = 0;
08715    int peernoncodeccapability = 0, vpeernoncodeccapability = 0, tpeernoncodeccapability = 0;
08716 
08717    struct ast_rtp_codecs newaudiortp, newvideortp, newtextrtp;
08718    format_t newjointcapability;           /* Negotiated capability */
08719    format_t newpeercapability;
08720    int newnoncodeccapability;
08721 
08722    const char *codecs;
08723    int codec;
08724 
08725    /* SRTP */
08726    int secure_audio = FALSE;
08727    int secure_video = FALSE;
08728 
08729    /* Others */
08730    int sendonly = -1;
08731    int vsendonly = -1;
08732    int numberofports;
08733    int numberofmediastreams = 0;
08734    int last_rtpmap_codec = 0;
08735    int red_data_pt[10];    /* For T.140 red */
08736    int red_num_gen = 0;    /* For T.140 red */
08737    char red_fmtp[100] = "empty"; /* For T.140 red */
08738    int debug = sip_debug_test_pvt(p);
08739 
08740    /* START UNKNOWN */
08741    char buf[SIPBUFSIZE];
08742    /* END UNKNOWN */
08743 
08744    /* Initial check */
08745    if (!p->rtp) {
08746       ast_log(LOG_ERROR, "Got SDP but have no RTP session allocated.\n");
08747       return -1;
08748    }
08749 
08750    /* Make sure that the codec structures are all cleared out */
08751    ast_rtp_codecs_payloads_clear(&newaudiortp, NULL);
08752    ast_rtp_codecs_payloads_clear(&newvideortp, NULL);
08753    ast_rtp_codecs_payloads_clear(&newtextrtp, NULL);
08754 
08755    /* Update our last rtprx when we receive an SDP, too */
08756    p->lastrtprx = p->lastrtptx = time(NULL); /* XXX why both ? */
08757 
08758    memset(p->offered_media, 0, sizeof(p->offered_media));
08759 
08760 
08761    /* default: novideo and notext set */
08762    p->novideo = TRUE;
08763    p->notext = TRUE;
08764 
08765    if (p->vrtp) {
08766       ast_rtp_codecs_payloads_clear(&newvideortp, NULL);
08767    }
08768 
08769    if (p->trtp) {
08770       ast_rtp_codecs_payloads_clear(&newtextrtp, NULL);
08771    }
08772 
08773    /* Scan for the first media stream (m=) line to limit scanning of globals */
08774    nextm = get_sdp_iterate(&next, req, "m");
08775    if (ast_strlen_zero(nextm)) {
08776       ast_log(LOG_WARNING, "Insufficient information for SDP (m= not found)\n");
08777       return -1;
08778    }
08779 
08780    /* Scan session level SDP parameters (lines before first media stream) */
08781    while ((type = get_sdp_line(&iterator, next - 1, req, &value)) != '\0') {
08782       int processed = FALSE;
08783       switch (type) {
08784       case 'o':
08785          /* If we end up receiving SDP that doesn't actually modify the session we don't want to treat this as a fatal
08786           * error. We just want to ignore the SDP and let the rest of the packet be handled as normal.
08787           */
08788          if (!process_sdp_o(value, p))
08789             return (p->session_modify == FALSE) ? 0 : -1;
08790          break;
08791       case 'c':
08792          if (process_sdp_c(value, &sessionsa)) {
08793             processed = TRUE;
08794             sa = &sessionsa;
08795             vsa = sa;
08796             tsa = sa;
08797             isa = sa;
08798          }
08799          break;
08800       case 'a':
08801          if (process_sdp_a_sendonly(value, &sendonly)) {
08802             processed = TRUE;
08803             vsendonly = sendonly;
08804          }
08805          else if (process_sdp_a_audio(value, p, &newaudiortp, &last_rtpmap_codec))
08806             processed = TRUE;
08807          else if (process_sdp_a_video(value, p, &newvideortp, &last_rtpmap_codec))
08808             processed = TRUE;
08809          else if (process_sdp_a_text(value, p, &newtextrtp, red_fmtp, &red_num_gen, red_data_pt, &last_rtpmap_codec))
08810             processed = TRUE;
08811          else if (process_sdp_a_image(value, p))
08812             processed = TRUE;
08813          break;
08814       }
08815 
08816       ast_debug(3, "Processing session-level SDP %c=%s... %s\n", type, value, (processed == TRUE)? "OK." : "UNSUPPORTED.");
08817    }
08818 
08819 
08820 
08821    /* Scan media stream (m=) specific parameters loop */
08822    while (!ast_strlen_zero(nextm)) {
08823       int audio = FALSE;
08824       int video = FALSE;
08825       int image = FALSE;
08826       int text = FALSE;
08827       char protocol[5] = {0,};
08828       int x;
08829 
08830       numberofports = 1;
08831       len = -1;
08832       start = next;
08833       m = nextm;
08834       iterator = next;
08835       nextm = get_sdp_iterate(&next, req, "m");
08836 
08837       /* Search for audio media definition */
08838       if ((sscanf(m, "audio %30u/%30u RTP/%4s %n", &x, &numberofports, protocol, &len) == 3 && len > 0 && x) ||
08839           (sscanf(m, "audio %30u RTP/%4s %n", &x, protocol, &len) == 2 && len > 0 && x)) {
08840          if (!strcmp(protocol, "SAVP")) {
08841             secure_audio = 1;
08842          } else if (strcmp(protocol, "AVP")) {
08843             ast_log(LOG_WARNING, "unknown SDP media protocol in offer: %s\n", protocol);
08844             continue;
08845          }
08846          if (p->offered_media[SDP_AUDIO].order_offered) {
08847             ast_log(LOG_WARNING, "Multiple audio streams are not supported\n");
08848             return -3;
08849          }
08850          audio = TRUE;
08851          p->offered_media[SDP_AUDIO].order_offered = ++numberofmediastreams;
08852          portno = x;
08853 
08854          /* Scan through the RTP payload types specified in a "m=" line: */
08855          codecs = m + len;
08856          ast_copy_string(p->offered_media[SDP_AUDIO].codecs, codecs, sizeof(p->offered_media[SDP_AUDIO].codecs));
08857          for (; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
08858             if (sscanf(codecs, "%30u%n", &codec, &len) != 1) {
08859                ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
08860                return -1;
08861             }
08862             if (debug)
08863                ast_verbose("Found RTP audio format %d\n", codec);
08864             
08865             ast_rtp_codecs_payloads_set_m_type(&newaudiortp, NULL, codec);
08866          }
08867       /* Search for video media definition */
08868       } else if ((sscanf(m, "video %30u/%30u RTP/%4s %n", &x, &numberofports, protocol, &len) == 3 && len > 0 && x) ||
08869             (sscanf(m, "video %30u RTP/%4s %n", &x, protocol, &len) == 2 && len >= 0 && x)) {
08870          if (!strcmp(protocol, "SAVP")) {
08871             secure_video = 1;
08872          } else if (strcmp(protocol, "AVP")) {
08873             ast_log(LOG_WARNING, "unknown SDP media protocol in offer: %s\n", protocol);
08874             continue;
08875          }
08876          if (p->offered_media[SDP_VIDEO].order_offered) {
08877             ast_log(LOG_WARNING, "Multiple video streams are not supported\n");
08878             return -3;
08879          }
08880          video = TRUE;
08881          p->novideo = FALSE;
08882          p->offered_media[SDP_VIDEO].order_offered = ++numberofmediastreams;
08883          vportno = x;
08884 
08885          /* Scan through the RTP payload types specified in a "m=" line: */
08886          codecs = m + len;
08887          ast_copy_string(p->offered_media[SDP_VIDEO].codecs, codecs, sizeof(p->offered_media[SDP_VIDEO].codecs));
08888          for (; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
08889             if (sscanf(codecs, "%30u%n", &codec, &len) != 1) {
08890                ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
08891                return -1;
08892             }
08893             if (debug)
08894                ast_verbose("Found RTP video format %d\n", codec);
08895             ast_rtp_codecs_payloads_set_m_type(&newvideortp, NULL, codec);
08896          }
08897       /* Search for text media definition */
08898       } else if ((sscanf(m, "text %30u/%30u RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0 && x) ||
08899             (sscanf(m, "text %30u RTP/AVP %n", &x, &len) == 1 && len > 0 && x)) {
08900          if (p->offered_media[SDP_TEXT].order_offered) {
08901             ast_log(LOG_WARNING, "Multiple text streams are not supported\n");
08902             return -3;
08903          }
08904          text = TRUE;
08905          p->notext = FALSE;
08906          p->offered_media[SDP_TEXT].order_offered = ++numberofmediastreams;
08907          tportno = x;
08908 
08909          /* Scan through the RTP payload types specified in a "m=" line: */
08910          codecs = m + len;
08911          ast_copy_string(p->offered_media[SDP_TEXT].codecs, codecs, sizeof(p->offered_media[SDP_TEXT].codecs));
08912          for (; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
08913             if (sscanf(codecs, "%30u%n", &codec, &len) != 1) {
08914                ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
08915                return -1;
08916             }
08917             if (debug)
08918                ast_verbose("Found RTP text format %d\n", codec);
08919             ast_rtp_codecs_payloads_set_m_type(&newtextrtp, NULL, codec);
08920          }
08921       /* Search for image media definition */
08922       } else if (p->udptl && ((sscanf(m, "image %30u udptl t38%n", &x, &len) == 1 && len > 0 && x) ||
08923                (sscanf(m, "image %30u UDPTL t38%n", &x, &len) == 1 && len > 0 && x) )) {
08924          if (p->offered_media[SDP_IMAGE].order_offered) {
08925             ast_log(LOG_WARNING, "Multiple T.38 streams are not supported\n");
08926             return -3;
08927          }
08928          image = TRUE;
08929          if (debug)
08930             ast_verbose("Got T.38 offer in SDP in dialog %s\n", p->callid);
08931          p->offered_media[SDP_IMAGE].order_offered = ++numberofmediastreams;
08932          udptlportno = x;
08933 
08934          if (p->t38.state != T38_ENABLED) {
08935             memset(&p->t38.their_parms, 0, sizeof(p->t38.their_parms));
08936 
08937             /* default EC to none, the remote end should
08938              * respond with the EC they want to use */
08939             ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_NONE);
08940          }
08941       } else {
08942          ast_log(LOG_WARNING, "Unsupported SDP media type in offer: %s\n", m);
08943          continue;
08944       }
08945 
08946       /* Check for number of ports */
08947       if (numberofports > 1)
08948          ast_log(LOG_WARNING, "SDP offered %d ports for media, not supported by Asterisk. Will try anyway...\n", numberofports);
08949       
08950       /* Media stream specific parameters */
08951       while ((type = get_sdp_line(&iterator, next - 1, req, &value)) != '\0') {
08952          int processed = FALSE;
08953 
08954          switch (type) {
08955          case 'c':
08956             if (audio) {
08957                if (process_sdp_c(value, &audiosa)) {
08958                   processed = TRUE;
08959                   sa = &audiosa;
08960                }
08961             } else if (video) {
08962                if (process_sdp_c(value, &videosa)) {
08963                   processed = TRUE;
08964                   vsa = &videosa;
08965                }
08966             } else if (text) {
08967                if (process_sdp_c(value, &textsa)) {
08968                   processed = TRUE;
08969                   tsa = &textsa;
08970                }
08971             } else if (image) {
08972                if (process_sdp_c(value, &imagesa)) {
08973                   processed = TRUE;
08974                   isa = &imagesa;
08975                }
08976             }
08977             break;
08978          case 'a':
08979             /* Audio specific scanning */
08980             if (audio) {
08981                if (process_sdp_a_sendonly(value, &sendonly))
08982                   processed = TRUE;
08983                else if (process_crypto(p, p->rtp, &p->srtp, value))
08984                   processed = TRUE;
08985                else if (process_sdp_a_audio(value, p, &newaudiortp, &last_rtpmap_codec))
08986                   processed = TRUE;
08987             }
08988             /* Video specific scanning */
08989             else if (video) {
08990                if (process_sdp_a_sendonly(value, &vsendonly))
08991                   processed = TRUE;
08992                else if (process_crypto(p, p->vrtp, &p->vsrtp, value))
08993                   processed = TRUE;
08994                else if (process_sdp_a_video(value, p, &newvideortp, &last_rtpmap_codec))
08995                   processed = TRUE;
08996             }
08997             /* Text (T.140) specific scanning */
08998             else if (text) {
08999                if (process_sdp_a_text(value, p, &newtextrtp, red_fmtp, &red_num_gen, red_data_pt, &last_rtpmap_codec))
09000                   processed = TRUE;
09001                else if (process_crypto(p, p->trtp, &p->tsrtp, value))
09002                   processed = TRUE;
09003             }
09004             /* Image (T.38 FAX) specific scanning */
09005             else if (image) {
09006                if (process_sdp_a_image(value, p))
09007                   processed = TRUE;
09008             }
09009             break;
09010          }
09011 
09012          ast_debug(3, "Processing media-level (%s) SDP %c=%s... %s\n",
09013                (audio == TRUE)? "audio" : (video == TRUE)? "video" : "image",
09014                type, value,
09015                (processed == TRUE)? "OK." : "UNSUPPORTED.");
09016       }
09017    }
09018 
09019 
09020    /* Sanity checks */
09021    if (!sa && !vsa && !tsa && !isa) {
09022       ast_log(LOG_WARNING, "Insufficient information in SDP (c=)...\n");
09023       return -1;
09024    }
09025 
09026    if (portno == -1 && vportno == -1 && udptlportno == -1  && tportno == -1) {
09027       /* No acceptable offer found in SDP  - we have no ports */
09028       /* Do not change RTP or VRTP if this is a re-invite */
09029       ast_log(LOG_WARNING, "Failing due to no acceptable offer found\n");
09030       return -2;
09031    }
09032 
09033    if (secure_audio && !(p->srtp && (ast_test_flag(p->srtp, SRTP_CRYPTO_OFFER_OK)))) {
09034       ast_log(LOG_WARNING, "Can't provide secure audio requested in SDP offer\n");
09035       return -4;
09036    }
09037 
09038    if (!secure_audio && p->srtp) {
09039       ast_log(LOG_WARNING, "We are requesting SRTP, but they responded without it!\n");
09040       return -4;
09041    }
09042 
09043    if (secure_video && !(p->vsrtp && (ast_test_flag(p->vsrtp, SRTP_CRYPTO_OFFER_OK)))) {
09044       ast_log(LOG_WARNING, "Can't provide secure video requested in SDP offer\n");
09045       return -4;
09046    }
09047 
09048    if (!p->novideo && !secure_video && p->vsrtp) {
09049       ast_log(LOG_WARNING, "We are requesting SRTP, but they responded without it!\n");
09050       return -4;
09051    }
09052 
09053    if (!(secure_audio || secure_video) && ast_test_flag(&p->flags[1], SIP_PAGE2_USE_SRTP)) {
09054       ast_log(LOG_WARNING, "Matched device setup to use SRTP, but request was not!\n");
09055       return -4;
09056    }
09057 
09058    if (udptlportno == -1) {
09059       change_t38_state(p, T38_DISABLED);
09060    }
09061 
09062    /* Now gather all of the codecs that we are asked for: */
09063    ast_rtp_codecs_payload_formats(&newaudiortp, &peercapability, &peernoncodeccapability);
09064    ast_rtp_codecs_payload_formats(&newvideortp, &vpeercapability, &vpeernoncodeccapability);
09065    ast_rtp_codecs_payload_formats(&newtextrtp, &tpeercapability, &tpeernoncodeccapability);
09066 
09067    newjointcapability = p->capability & (peercapability | vpeercapability | tpeercapability);
09068    newpeercapability = (peercapability | vpeercapability | tpeercapability);
09069    newnoncodeccapability = p->noncodeccapability & peernoncodeccapability;
09070 
09071    if (debug) {
09072       /* shame on whoever coded this.... */
09073       char s1[SIPBUFSIZE], s2[SIPBUFSIZE], s3[SIPBUFSIZE], s4[SIPBUFSIZE], s5[SIPBUFSIZE];
09074 
09075       ast_verbose("Capabilities: us - %s, peer - audio=%s/video=%s/text=%s, combined - %s\n",
09076              ast_getformatname_multiple(s1, SIPBUFSIZE, p->capability),
09077              ast_getformatname_multiple(s2, SIPBUFSIZE, peercapability),
09078              ast_getformatname_multiple(s3, SIPBUFSIZE, vpeercapability),
09079              ast_getformatname_multiple(s4, SIPBUFSIZE, tpeercapability),
09080              ast_getformatname_multiple(s5, SIPBUFSIZE, newjointcapability));
09081    }
09082    if (debug) {
09083       struct ast_str *s1 = ast_str_alloca(SIPBUFSIZE);
09084       struct ast_str *s2 = ast_str_alloca(SIPBUFSIZE);
09085       struct ast_str *s3 = ast_str_alloca(SIPBUFSIZE);
09086 
09087       ast_verbose("Non-codec capabilities (dtmf): us - %s, peer - %s, combined - %s\n",
09088              ast_rtp_lookup_mime_multiple2(s1, p->noncodeccapability, 0, 0),
09089              ast_rtp_lookup_mime_multiple2(s2, peernoncodeccapability, 0, 0),
09090              ast_rtp_lookup_mime_multiple2(s3, newnoncodeccapability, 0, 0));
09091    }
09092    if (!newjointcapability && udptlportno == -1) {
09093       ast_log(LOG_NOTICE, "No compatible codecs, not accepting this offer!\n");
09094       /* Do NOT Change current setting */
09095       return -1;
09096    }
09097 
09098    if (portno != -1 || vportno != -1 || tportno != -1) {
09099       /* We are now ready to change the sip session and p->rtp and p->vrtp with the offered codecs, since
09100          they are acceptable */
09101       p->jointcapability = newjointcapability;                /* Our joint codec profile for this call */
09102       p->peercapability = newpeercapability;                  /* The other sides capability in latest offer */
09103       p->jointnoncodeccapability = newnoncodeccapability;     /* DTMF capabilities */
09104    
09105       /* respond with single most preferred joint codec, limiting the other side's choice */
09106       if (ast_test_flag(&p->flags[1], SIP_PAGE2_PREFERRED_CODEC)) {
09107          p->jointcapability = ast_codec_choose(&p->prefs, p->jointcapability, 1);
09108       }
09109    }
09110 
09111    /* Setup audio address and port */
09112    if (p->rtp) {
09113       if (portno > 0) {
09114          ast_sockaddr_set_port(sa, portno);
09115          ast_rtp_instance_set_remote_address(p->rtp, sa);
09116          if (debug) {
09117             ast_verbose("Peer audio RTP is at port %s\n",
09118                    ast_sockaddr_stringify(sa));
09119          }
09120 
09121          ast_rtp_codecs_payloads_copy(&newaudiortp, ast_rtp_instance_get_codecs(p->rtp), p->rtp);
09122          /* Ensure RTCP is enabled since it may be inactive
09123             if we're coming back from a T.38 session */
09124          ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_RTCP, 1);
09125          /* Ensure audio RTCP reads are enabled */
09126          if (p->owner) {
09127             ast_channel_set_fd(p->owner, 1, ast_rtp_instance_fd(p->rtp, 1));
09128          }
09129 
09130          if (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO) {
09131             ast_clear_flag(&p->flags[0], SIP_DTMF);
09132             if (newnoncodeccapability & AST_RTP_DTMF) {
09133                /* XXX Would it be reasonable to drop the DSP at this point? XXX */
09134                ast_set_flag(&p->flags[0], SIP_DTMF_RFC2833);
09135                /* Since RFC2833 is now negotiated we need to change some properties of the RTP stream */
09136                ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_DTMF, 1);
09137                ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_DTMF_COMPENSATE, ast_test_flag(&p->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
09138             } else {
09139                ast_set_flag(&p->flags[0], SIP_DTMF_INBAND);
09140             }
09141          }
09142       } else if (udptlportno > 0) {
09143          if (debug)
09144             ast_verbose("Got T.38 Re-invite without audio. Keeping RTP active during T.38 session.\n");
09145          /* Prevent audio RTCP reads */
09146          if (p->owner) {
09147             ast_channel_set_fd(p->owner, 1, -1);
09148          }
09149          /* Silence RTCP while audio RTP is inactive */
09150          ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_RTCP, 0);
09151       } else {
09152          ast_rtp_instance_stop(p->rtp);
09153          if (debug)
09154             ast_verbose("Peer doesn't provide audio\n");
09155       }
09156    }
09157 
09158    /* Setup video address and port */
09159    if (p->vrtp) {
09160       if (vportno > 0) {
09161          ast_sockaddr_set_port(vsa, vportno);
09162          ast_rtp_instance_set_remote_address(p->vrtp, vsa);
09163          if (debug) {
09164             ast_verbose("Peer video RTP is at port %s\n",
09165                    ast_sockaddr_stringify(vsa));
09166          }
09167          ast_rtp_codecs_payloads_copy(&newvideortp, ast_rtp_instance_get_codecs(p->vrtp), p->vrtp);
09168       } else {
09169          ast_rtp_instance_stop(p->vrtp);
09170          if (debug)
09171             ast_verbose("Peer doesn't provide video\n");
09172       }
09173    }
09174 
09175    /* Setup text address and port */
09176    if (p->trtp) {
09177       if (tportno > 0) {
09178          ast_sockaddr_set_port(tsa, tportno);
09179          ast_rtp_instance_set_remote_address(p->trtp, tsa);
09180          if (debug) {
09181             ast_verbose("Peer T.140 RTP is at port %s\n",
09182                    ast_sockaddr_stringify(tsa));
09183          }
09184          if ((p->jointcapability & AST_FORMAT_T140RED)) {
09185             p->red = 1;
09186             ast_rtp_red_init(p->trtp, 300, red_data_pt, 2);
09187          } else {
09188             p->red = 0;
09189          }
09190          ast_rtp_codecs_payloads_copy(&newtextrtp, ast_rtp_instance_get_codecs(p->trtp), p->trtp);
09191       } else {
09192          ast_rtp_instance_stop(p->trtp);
09193          if (debug)
09194             ast_verbose("Peer doesn't provide T.140\n");
09195       }
09196    }
09197    /* Setup image address and port */
09198    if (p->udptl) {
09199       if (udptlportno > 0) {
09200          if (ast_test_flag(&p->flags[1], SIP_PAGE2_SYMMETRICRTP) && ast_test_flag(&p->flags[1], SIP_PAGE2_UDPTL_DESTINATION)) {
09201             ast_rtp_instance_get_remote_address(p->rtp, isa);
09202             if (!ast_sockaddr_isnull(isa) && debug) {
09203                ast_debug(1, "Peer T.38 UDPTL is set behind NAT and with destination, destination address now %s\n", ast_sockaddr_stringify(isa));
09204             }
09205          }
09206          ast_sockaddr_set_port(isa, udptlportno);
09207          ast_udptl_set_peer(p->udptl, isa);
09208          if (debug)
09209             ast_debug(1,"Peer T.38 UDPTL is at port %s\n", ast_sockaddr_stringify(isa));
09210 
09211          /* verify the far max ifp can be calculated. this requires far max datagram to be set. */
09212          if (!ast_udptl_get_far_max_datagram(p->udptl)) {
09213             /* setting to zero will force a default if none was provided by the SDP */
09214             ast_udptl_set_far_max_datagram(p->udptl, 0);
09215          }
09216 
09217          /* Remote party offers T38, we need to update state */
09218          if ((t38action == SDP_T38_ACCEPT) &&
09219              (p->t38.state == T38_LOCAL_REINVITE)) {
09220             change_t38_state(p, T38_ENABLED);
09221          } else if ((t38action == SDP_T38_INITIATE) &&
09222                p->owner && p->lastinvite) {
09223             change_t38_state(p, T38_PEER_REINVITE); /* T38 Offered in re-invite from remote party */
09224             /* If fax detection is enabled then send us off to the fax extension */
09225             if (ast_test_flag(&p->flags[1], SIP_PAGE2_FAX_DETECT_T38)) {
09226                ast_channel_lock(p->owner);
09227                if (strcmp(p->owner->exten, "fax")) {
09228                   const char *target_context = S_OR(p->owner->macrocontext, p->owner->context);
09229                   ast_channel_unlock(p->owner);
09230                   if (ast_exists_extension(p->owner, target_context, "fax", 1,
09231                      S_COR(p->owner->caller.id.number.valid, p->owner->caller.id.number.str, NULL))) {
09232                      ast_verbose(VERBOSE_PREFIX_2 "Redirecting '%s' to fax extension due to peer T.38 re-INVITE\n", p->owner->name);
09233                      pbx_builtin_setvar_helper(p->owner, "FAXEXTEN", p->owner->exten);
09234                      if (ast_async_goto(p->owner, target_context, "fax", 1)) {
09235                         ast_log(LOG_NOTICE, "Failed to async goto '%s' into fax of '%s'\n", p->owner->name, target_context);
09236                      }
09237                   } else {
09238                      ast_log(LOG_NOTICE, "T.38 re-INVITE detected but no fax extension\n");
09239                   }
09240                } else {
09241                   ast_channel_unlock(p->owner);
09242                }
09243             }
09244          }
09245       } else {
09246          change_t38_state(p, T38_DISABLED);
09247          ast_udptl_stop(p->udptl);
09248          if (debug)
09249             ast_debug(1, "Peer doesn't provide T.38 UDPTL\n");
09250       }
09251    }
09252 
09253    if ((portno == -1) && (p->t38.state != T38_DISABLED)) {
09254       ast_debug(3, "Have T.38 but no audio, accepting offer anyway\n");
09255       return 0;
09256         }
09257 
09258    /* Ok, we're going with this offer */
09259    ast_debug(2, "We're settling with these formats: %s\n", ast_getformatname_multiple(buf, SIPBUFSIZE, p->jointcapability));
09260 
09261    if (!p->owner)    /* There's no open channel owning us so we can return here. For a re-invite or so, we proceed */
09262       return 0;
09263 
09264    ast_debug(4, "We have an owner, now see if we need to change this call\n");
09265 
09266    if (!(p->owner->nativeformats & p->jointcapability) && (p->jointcapability & AST_FORMAT_AUDIO_MASK)) {
09267       if (debug) {
09268          char s1[SIPBUFSIZE], s2[SIPBUFSIZE];
09269          ast_debug(1, "Oooh, we need to change our audio formats since our peer supports only %s and not %s\n",
09270             ast_getformatname_multiple(s1, SIPBUFSIZE, p->jointcapability),
09271             ast_getformatname_multiple(s2, SIPBUFSIZE, p->owner->nativeformats));
09272       }
09273       p->owner->nativeformats = ast_codec_choose(&p->prefs, p->jointcapability, 1) | (p->capability & vpeercapability) | (p->capability & tpeercapability);
09274       ast_set_read_format(p->owner, p->owner->readformat);
09275       ast_set_write_format(p->owner, p->owner->writeformat);
09276    }
09277    
09278    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)) {
09279       ast_queue_control(p->owner, AST_CONTROL_UNHOLD);
09280       /* Activate a re-invite */
09281       ast_queue_frame(p->owner, &ast_null_frame);
09282       change_hold_state(p, req, FALSE, sendonly);
09283    } 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)) {
09284       ast_queue_control_data(p->owner, AST_CONTROL_HOLD,
09285                    S_OR(p->mohsuggest, NULL),
09286                    !ast_strlen_zero(p->mohsuggest) ? strlen(p->mohsuggest) + 1 : 0);
09287       if (sendonly)
09288          ast_rtp_instance_stop(p->rtp);
09289       /* RTCP needs to go ahead, even if we're on hold!!! */
09290       /* Activate a re-invite */
09291       ast_queue_frame(p->owner, &ast_null_frame);
09292       change_hold_state(p, req, TRUE, sendonly);
09293    }
09294    
09295    return 0;
09296 }
09297 
09298 static int process_sdp_o(const char *o, struct sip_pvt *p)
09299 {
09300    char *o_copy;
09301    char *token;
09302    int64_t rua_version;
09303 
09304    /* Store the SDP version number of remote UA. This will allow us to
09305    distinguish between session modifications and session refreshes. If
09306    the remote UA does not send an incremented SDP version number in a
09307    subsequent RE-INVITE then that means its not changing media session.
09308    The RE-INVITE may have been sent to update connected party, remote
09309    target or to refresh the session (Session-Timers).  Asterisk must not
09310    change media session and increment its own version number in answer
09311    SDP in this case. */
09312 
09313    p->session_modify = TRUE;
09314 
09315    if (ast_strlen_zero(o)) {
09316       ast_log(LOG_WARNING, "SDP syntax error. SDP without an o= line\n");
09317       return FALSE;
09318    }
09319 
09320    o_copy = ast_strdupa(o);
09321    token = strsep(&o_copy, " ");  /* Skip username   */
09322    if (!o_copy) {
09323       ast_log(LOG_WARNING, "SDP syntax error in o= line username\n");
09324       return FALSE;
09325    }
09326    token = strsep(&o_copy, " ");  /* Skip session-id */
09327    if (!o_copy) {
09328       ast_log(LOG_WARNING, "SDP syntax error in o= line session-id\n");
09329       return FALSE;
09330    }
09331    token = strsep(&o_copy, " ");  /* Version         */
09332    if (!o_copy) {
09333       ast_log(LOG_WARNING, "SDP syntax error in o= line\n");
09334       return FALSE;
09335    }
09336    if (!sscanf(token, "%30" SCNd64, &rua_version)) {
09337       ast_log(LOG_WARNING, "SDP syntax error in o= line version\n");
09338       return FALSE;
09339    }
09340 
09341    /* we need to check the SDP version number the other end sent us;
09342     * our rules for deciding what to accept are a bit complex.
09343     *
09344     * 1) if 'ignoresdpversion' has been set for this dialog, then
09345     *    we will just accept whatever they sent and assume it is
09346     *    a modification of the session, even if it is not
09347     * 2) otherwise, if this is the first SDP we've seen from them
09348     *    we accept it
09349     * 3) otherwise, if the new SDP version number is higher than the
09350     *    old one, we accept it
09351     * 4) otherwise, if this SDP is in response to us requesting a switch
09352     *    to T.38, we accept the SDP, but also generate a warning message
09353     *    that this peer should have the 'ignoresdpversion' option set,
09354     *    because it is not following the SDP offer/answer RFC; if we did
09355     *    not request a switch to T.38, then we stop parsing the SDP, as it
09356     *    has not changed from the previous version
09357     */
09358 
09359    if (ast_test_flag(&p->flags[1], SIP_PAGE2_IGNORESDPVERSION) ||
09360        (p->sessionversion_remote < 0) ||
09361        (p->sessionversion_remote < rua_version)) {
09362       p->sessionversion_remote = rua_version;
09363    } else {
09364       if (p->t38.state == T38_LOCAL_REINVITE) {
09365          p->sessionversion_remote = rua_version;
09366          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);
09367       } else {
09368          p->session_modify = FALSE;
09369          ast_debug(2, "Call %s responded to our reinvite without changing SDP version; ignoring SDP.\n", p->callid);
09370          return FALSE;
09371       }
09372    }
09373 
09374    return TRUE;
09375 }
09376 
09377 static int process_sdp_c(const char *c, struct ast_sockaddr *addr)
09378 {
09379    char proto[4], host[258];
09380    int af;
09381 
09382    /* Check for Media-description-level-address */
09383    if (sscanf(c, "IN %3s %255s", proto, host) == 2) {
09384       if (!strcmp("IP4", proto)) {
09385          af = AF_INET;
09386       } else if (!strcmp("IP6", proto)) {
09387          af = AF_INET6;
09388       } else {
09389          ast_log(LOG_WARNING, "Unknown protocol '%s'.\n", proto);
09390          return FALSE;
09391       }
09392       if (ast_sockaddr_resolve_first_af(addr, host, 0, af)) {
09393          ast_log(LOG_WARNING, "Unable to lookup RTP Audio host in c= line, '%s'\n", c);
09394          return FALSE;
09395       }
09396       return TRUE;
09397    } else {
09398       ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
09399       return FALSE;
09400    }
09401    return FALSE;
09402 }
09403 
09404 static int process_sdp_a_sendonly(const char *a, int *sendonly)
09405 {
09406    int found = FALSE;
09407 
09408    if (!strcasecmp(a, "sendonly")) {
09409       if (*sendonly == -1)
09410          *sendonly = 1;
09411       found = TRUE;
09412    } else if (!strcasecmp(a, "inactive")) {
09413       if (*sendonly == -1)
09414          *sendonly = 2;
09415       found = TRUE;
09416    }  else if (!strcasecmp(a, "sendrecv")) {
09417       if (*sendonly == -1)
09418          *sendonly = 0;
09419       found = TRUE;
09420    }
09421    return found;
09422 }
09423 
09424 static int process_sdp_a_audio(const char *a, struct sip_pvt *p, struct ast_rtp_codecs *newaudiortp, int *last_rtpmap_codec)
09425 {
09426    int found = FALSE;
09427    int codec;
09428    char mimeSubtype[128];
09429    char fmtp_string[64];
09430    unsigned int sample_rate;
09431    int debug = sip_debug_test_pvt(p);
09432 
09433    if (!strncasecmp(a, "ptime", 5)) {
09434       char *tmp = strrchr(a, ':');
09435       long int framing = 0;
09436       if (tmp) {
09437          tmp++;
09438          framing = strtol(tmp, NULL, 10);
09439          if (framing == LONG_MIN || framing == LONG_MAX) {
09440             framing = 0;
09441             ast_debug(1, "Can't read framing from SDP: %s\n", a);
09442          }
09443       }
09444       if (framing && p->autoframing) {
09445          struct ast_codec_pref *pref = &ast_rtp_instance_get_codecs(p->rtp)->pref;
09446          int codec_n;
09447          for (codec_n = 0; codec_n < AST_RTP_MAX_PT; codec_n++) {
09448             struct ast_rtp_payload_type format = ast_rtp_codecs_payload_lookup(ast_rtp_instance_get_codecs(p->rtp), codec_n);
09449             if (!format.asterisk_format || !format.code) /* non-codec or not found */
09450                continue;
09451             ast_debug(1, "Setting framing for %s to %ld\n", ast_getformatname(format.code), framing);
09452             ast_codec_pref_setsize(pref, format.code, framing);
09453          }
09454          ast_rtp_codecs_packetization_set(ast_rtp_instance_get_codecs(p->rtp), p->rtp, pref);
09455       }
09456       found = TRUE;
09457    } else if (sscanf(a, "rtpmap: %30u %127[^/]/%30u", &codec, mimeSubtype, &sample_rate) == 3) {
09458       /* We have a rtpmap to handle */
09459       if (*last_rtpmap_codec < SDP_MAX_RTPMAP_CODECS) {
09460          if (!(ast_rtp_codecs_payloads_set_rtpmap_type_rate(newaudiortp, NULL, codec, "audio", mimeSubtype,
09461              ast_test_flag(&p->flags[0], SIP_G726_NONSTANDARD) ? AST_RTP_OPT_G726_NONSTANDARD : 0, sample_rate))) {
09462             if (debug)
09463                ast_verbose("Found audio description format %s for ID %d\n", mimeSubtype, codec);
09464             //found_rtpmap_codecs[last_rtpmap_codec] = codec;
09465             (*last_rtpmap_codec)++;
09466             found = TRUE;
09467          } else {
09468             ast_rtp_codecs_payloads_unset(newaudiortp, NULL, codec);
09469             if (debug)
09470                ast_verbose("Found unknown media description format %s for ID %d\n", mimeSubtype, codec);
09471          }
09472       } else {
09473          if (debug)
09474             ast_verbose("Discarded description format %s for ID %d\n", mimeSubtype, codec);
09475       }
09476    } else if (sscanf(a, "fmtp: %30u %63s", &codec, fmtp_string) == 2) {
09477       struct ast_rtp_payload_type payload;
09478 
09479       payload = ast_rtp_codecs_payload_lookup(newaudiortp, codec);
09480       if (payload.code && payload.asterisk_format) {
09481          unsigned int bit_rate;
09482 
09483          switch (payload.code) {
09484          case AST_FORMAT_SIREN7:
09485             if (sscanf(fmtp_string, "bitrate=%30u", &bit_rate) == 1) {
09486                if (bit_rate != 32000) {
09487                   ast_log(LOG_WARNING, "Got Siren7 offer at %d bps, but only 32000 bps supported; ignoring.\n", bit_rate);
09488                   ast_rtp_codecs_payloads_unset(newaudiortp, NULL, codec);
09489                } else {
09490                   found = TRUE;
09491                }
09492             }
09493             break;
09494          case AST_FORMAT_SIREN14:
09495             if (sscanf(fmtp_string, "bitrate=%30u", &bit_rate) == 1) {
09496                if (bit_rate != 48000) {
09497                   ast_log(LOG_WARNING, "Got Siren14 offer at %d bps, but only 48000 bps supported; ignoring.\n", bit_rate);
09498                   ast_rtp_codecs_payloads_unset(newaudiortp, NULL, codec);
09499                } else {
09500                   found = TRUE;
09501                }
09502             }
09503             break;
09504          case AST_FORMAT_G719:
09505             if (sscanf(fmtp_string, "bitrate=%30u", &bit_rate) == 1) {
09506                if (bit_rate != 64000) {
09507                   ast_log(LOG_WARNING, "Got G.719 offer at %d bps, but only 64000 bps supported; ignoring.\n", bit_rate);
09508                   ast_rtp_codecs_payloads_unset(newaudiortp, NULL, codec);
09509                } else {
09510                   found = TRUE;
09511                }
09512             }
09513          }
09514       }
09515    }
09516 
09517    return found;
09518 }
09519 
09520 static int process_sdp_a_video(const char *a, struct sip_pvt *p, struct ast_rtp_codecs *newvideortp, int *last_rtpmap_codec)
09521 {
09522    int found = FALSE;
09523    int codec;
09524    char mimeSubtype[128];
09525    unsigned int sample_rate;
09526    int debug = sip_debug_test_pvt(p);
09527 
09528    if (sscanf(a, "rtpmap: %30u %127[^/]/%30u", &codec, mimeSubtype, &sample_rate) == 3) {
09529       /* We have a rtpmap to handle */
09530       if (*last_rtpmap_codec < SDP_MAX_RTPMAP_CODECS) {
09531          /* Note: should really look at the '#chans' params too */
09532          if (!strncasecmp(mimeSubtype, "H26", 3) || !strncasecmp(mimeSubtype, "MP4", 3)) {
09533             if (!(ast_rtp_codecs_payloads_set_rtpmap_type_rate(newvideortp, NULL, codec, "video", mimeSubtype, 0, sample_rate))) {
09534                if (debug)
09535                   ast_verbose("Found video description format %s for ID %d\n", mimeSubtype, codec);
09536                //found_rtpmap_codecs[last_rtpmap_codec] = codec;
09537                (*last_rtpmap_codec)++;
09538                found = TRUE;
09539             } else {
09540                ast_rtp_codecs_payloads_unset(newvideortp, NULL, codec);
09541                if (debug)
09542                   ast_verbose("Found unknown media description format %s for ID %d\n", mimeSubtype, codec);
09543             }
09544          }
09545       } else {
09546          if (debug)
09547             ast_verbose("Discarded description format %s for ID %d\n", mimeSubtype, codec);
09548       }
09549    }
09550 
09551    return found;
09552 }
09553 
09554 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)
09555 {
09556    int found = FALSE;
09557    int codec;
09558    char mimeSubtype[128];
09559    unsigned int sample_rate;
09560    char *red_cp;
09561    int debug = sip_debug_test_pvt(p);
09562 
09563    if (sscanf(a, "rtpmap: %30u %127[^/]/%30u", &codec, mimeSubtype, &sample_rate) == 3) {
09564       /* We have a rtpmap to handle */
09565       if (*last_rtpmap_codec < SDP_MAX_RTPMAP_CODECS) {
09566          if (!strncasecmp(mimeSubtype, "T140", 4)) { /* Text */
09567             if (p->trtp) {
09568                /* ast_verbose("Adding t140 mimeSubtype to textrtp struct\n"); */
09569                ast_rtp_codecs_payloads_set_rtpmap_type_rate(newtextrtp, NULL, codec, "text", mimeSubtype, 0, sample_rate);
09570                found = TRUE;
09571             }
09572          } else if (!strncasecmp(mimeSubtype, "RED", 3)) { /* Text with Redudancy */
09573             if (p->trtp) {
09574                ast_rtp_codecs_payloads_set_rtpmap_type_rate(newtextrtp, NULL, codec, "text", mimeSubtype, 0, sample_rate);
09575                sprintf(red_fmtp, "fmtp:%d ", codec);
09576                if (debug)
09577                   ast_verbose("RED submimetype has payload type: %d\n", codec);
09578                found = TRUE;
09579             }
09580          }
09581       } else {
09582          if (debug)
09583             ast_verbose("Discarded description format %s for ID %d\n", mimeSubtype, codec);
09584       }
09585    } else if (!strncmp(a, red_fmtp, strlen(red_fmtp))) {
09586       /* count numbers of generations in fmtp */
09587       red_cp = &red_fmtp[strlen(red_fmtp)];
09588       strncpy(red_fmtp, a, 100);
09589 
09590       sscanf(red_cp, "%30u", &red_data_pt[*red_num_gen]);
09591       red_cp = strtok(red_cp, "/");
09592       while (red_cp && (*red_num_gen)++ < AST_RED_MAX_GENERATION) {
09593          sscanf(red_cp, "%30u", &red_data_pt[*red_num_gen]);
09594          red_cp = strtok(NULL, "/");
09595       }
09596       red_cp = red_fmtp;
09597       found = TRUE;
09598    }
09599 
09600    return found;
09601 }
09602 
09603 static int process_sdp_a_image(const char *a, struct sip_pvt *p)
09604 {
09605    int found = FALSE;
09606    char s[256];
09607    unsigned int x;
09608 
09609    if ((sscanf(a, "T38FaxMaxBuffer:%30u", &x) == 1)) {
09610       ast_debug(3, "MaxBufferSize:%d\n", x);
09611       found = TRUE;
09612    } else if ((sscanf(a, "T38MaxBitRate:%30u", &x) == 1) || (sscanf(a, "T38FaxMaxRate:%30u", &x) == 1)) {
09613       ast_debug(3, "T38MaxBitRate: %d\n", x);
09614       switch (x) {
09615       case 14400:
09616          p->t38.their_parms.rate = AST_T38_RATE_14400;
09617          break;
09618       case 12000:
09619          p->t38.their_parms.rate = AST_T38_RATE_12000;
09620          break;
09621       case 9600:
09622          p->t38.their_parms.rate = AST_T38_RATE_9600;
09623          break;
09624       case 7200:
09625          p->t38.their_parms.rate = AST_T38_RATE_7200;
09626          break;
09627       case 4800:
09628          p->t38.their_parms.rate = AST_T38_RATE_4800;
09629          break;
09630       case 2400:
09631          p->t38.their_parms.rate = AST_T38_RATE_2400;
09632          break;
09633       }
09634       found = TRUE;
09635    } else if ((sscanf(a, "T38FaxVersion:%30u", &x) == 1)) {
09636       ast_debug(3, "FaxVersion: %u\n", x);
09637       p->t38.their_parms.version = x;
09638       found = TRUE;
09639    } else if ((sscanf(a, "T38FaxMaxDatagram:%30u", &x) == 1) || (sscanf(a, "T38MaxDatagram:%30u", &x) == 1)) {
09640       /* override the supplied value if the configuration requests it */
09641       if (((signed int) p->t38_maxdatagram >= 0) && ((unsigned int) p->t38_maxdatagram > x)) {
09642          ast_debug(1, "Overriding T38FaxMaxDatagram '%d' with '%d'\n", x, p->t38_maxdatagram);
09643          x = p->t38_maxdatagram;
09644       }
09645       ast_debug(3, "FaxMaxDatagram: %u\n", x);
09646       ast_udptl_set_far_max_datagram(p->udptl, x);
09647       found = TRUE;
09648    } else if ((strncmp(a, "T38FaxFillBitRemoval", 20) == 0)) {
09649       if (sscanf(a, "T38FaxFillBitRemoval:%30u", &x) == 1) {
09650          ast_debug(3, "FillBitRemoval: %d\n", x);
09651          if (x == 1) {
09652             p->t38.their_parms.fill_bit_removal = TRUE;
09653          }
09654       } else {
09655          ast_debug(3, "FillBitRemoval\n");
09656          p->t38.their_parms.fill_bit_removal = TRUE;
09657       }
09658       found = TRUE;
09659    } else if ((strncmp(a, "T38FaxTranscodingMMR", 20) == 0)) {
09660       if (sscanf(a, "T38FaxTranscodingMMR:%30u", &x) == 1) {
09661          ast_debug(3, "Transcoding MMR: %d\n", x);
09662          if (x == 1) {
09663             p->t38.their_parms.transcoding_mmr = TRUE;
09664          }
09665       } else {
09666          ast_debug(3, "Transcoding MMR\n");
09667          p->t38.their_parms.transcoding_mmr = TRUE;
09668       }
09669       found = TRUE;
09670    } else if ((strncmp(a, "T38FaxTranscodingJBIG", 21) == 0)) {
09671       if (sscanf(a, "T38FaxTranscodingJBIG:%30u", &x) == 1) {
09672          ast_debug(3, "Transcoding JBIG: %d\n", x);
09673          if (x == 1) {
09674             p->t38.their_parms.transcoding_jbig = TRUE;
09675          }
09676       } else {
09677          ast_debug(3, "Transcoding JBIG\n");
09678          p->t38.their_parms.transcoding_jbig = TRUE;
09679       }
09680       found = TRUE;
09681    } else if ((sscanf(a, "T38FaxRateManagement:%255s", s) == 1)) {
09682       ast_debug(3, "RateManagement: %s\n", s);
09683       if (!strcasecmp(s, "localTCF"))
09684          p->t38.their_parms.rate_management = AST_T38_RATE_MANAGEMENT_LOCAL_TCF;
09685       else if (!strcasecmp(s, "transferredTCF"))
09686          p->t38.their_parms.rate_management = AST_T38_RATE_MANAGEMENT_TRANSFERRED_TCF;
09687       found = TRUE;
09688    } else if ((sscanf(a, "T38FaxUdpEC:%255s", s) == 1)) {
09689       ast_debug(3, "UDP EC: %s\n", s);
09690       if (!strcasecmp(s, "t38UDPRedundancy")) {
09691          ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_REDUNDANCY);
09692       } else if (!strcasecmp(s, "t38UDPFEC")) {
09693          ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_FEC);
09694       } else {
09695          ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_NONE);
09696       }
09697       found = TRUE;
09698    }
09699 
09700    return found;
09701 }
09702 
09703 /*! \brief Add "Supported" header to sip message.  Since some options may
09704  *  be disabled in the config, the sip_pvt must be inspected to determine what
09705  *  is supported for this dialog. */
09706 static int add_supported_header(struct sip_pvt *pvt, struct sip_request *req)
09707 {
09708    int res;
09709    if (st_get_mode(pvt, 0) != SESSION_TIMER_MODE_REFUSE) {
09710       res = add_header(req, "Supported", "replaces, timer");
09711    } else {
09712       res = add_header(req, "Supported", "replaces");
09713    }
09714    return res;
09715 }
09716 
09717 /*! \brief Add header to SIP message */
09718 static int add_header(struct sip_request *req, const char *var, const char *value)
09719 {
09720    if (req->headers == SIP_MAX_HEADERS) {
09721       ast_log(LOG_WARNING, "Out of SIP header space\n");
09722       return -1;
09723    }
09724 
09725    if (req->lines) {
09726       ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
09727       return -1;
09728    }
09729 
09730    if (sip_cfg.compactheaders) {
09731       var = find_alias(var, var);
09732    }
09733 
09734    ast_str_append(&req->data, 0, "%s: %s\r\n", var, value);
09735    req->header[req->headers] = ast_str_strlen(req->data);
09736 
09737    req->headers++;
09738 
09739    return 0;   
09740 }
09741 
09742 /*! 
09743  * \pre dialog is assumed to be locked while calling this function
09744  * \brief Add 'Max-Forwards' header to SIP message 
09745  */
09746 static int add_header_max_forwards(struct sip_pvt *dialog, struct sip_request *req)
09747 {
09748    char clen[10];
09749 
09750    snprintf(clen, sizeof(clen), "%d", dialog->maxforwards);
09751 
09752    return add_header(req, "Max-Forwards", clen);
09753 }
09754 
09755 /*! \brief Add 'Content-Length' header and content to SIP message */
09756 static int finalize_content(struct sip_request *req)
09757 {
09758    char clen[10];
09759 
09760    if (req->lines) {
09761       ast_log(LOG_WARNING, "finalize_content() called on a message that has already been finalized\n");
09762       return -1;
09763    }
09764 
09765    snprintf(clen, sizeof(clen), "%zd", ast_str_strlen(req->content));
09766    add_header(req, "Content-Length", clen);
09767 
09768    if (ast_str_strlen(req->content)) {
09769       ast_str_append(&req->data, 0, "\r\n%s", ast_str_buffer(req->content));
09770    }
09771    req->lines = ast_str_strlen(req->content) ? 1 : 0;
09772    return 0;
09773 }
09774 
09775 /*! \brief Add content (not header) to SIP message */
09776 static int add_content(struct sip_request *req, const char *line)
09777 {
09778    if (req->lines) {
09779       ast_log(LOG_WARNING, "Can't add more content when the content has been finalized\n");
09780       return -1;
09781    }
09782 
09783    ast_str_append(&req->content, 0, "%s", line);
09784    return 0;
09785 }
09786 
09787 /*! \brief Copy one header field from one request to another */
09788 static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field)
09789 {
09790    const char *tmp = get_header(orig, field);
09791 
09792    if (!ast_strlen_zero(tmp)) /* Add what we're responding to */
09793       return add_header(req, field, tmp);
09794    ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
09795    return -1;
09796 }
09797 
09798 /*! \brief Copy all headers from one request to another */
09799 static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field)
09800 {
09801    int start = 0;
09802    int copied = 0;
09803    for (;;) {
09804       const char *tmp = __get_header(orig, field, &start);
09805 
09806       if (ast_strlen_zero(tmp))
09807          break;
09808       /* Add what we're responding to */
09809       add_header(req, field, tmp);
09810       copied++;
09811    }
09812    return copied ? 0 : -1;
09813 }
09814 
09815 /*! \brief Copy SIP VIA Headers from the request to the response
09816 \note If the client indicates that it wishes to know the port we received from,
09817    it adds ;rport without an argument to the topmost via header. We need to
09818    add the port number (from our point of view) to that parameter.
09819 \verbatim
09820    We always add ;received=<ip address> to the topmost via header.
09821 \endverbatim
09822    Received: RFC 3261, rport RFC 3581 */
09823 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field)
09824 {
09825    int copied = 0;
09826    int start = 0;
09827 
09828    for (;;) {
09829       char new[512];
09830       const char *oh = __get_header(orig, field, &start);
09831 
09832       if (ast_strlen_zero(oh))
09833          break;
09834 
09835       if (!copied) { /* Only check for empty rport in topmost via header */
09836          char leftmost[512], *others, *rport;
09837 
09838          /* Only work on leftmost value */
09839          ast_copy_string(leftmost, oh, sizeof(leftmost));
09840          others = strchr(leftmost, ',');
09841          if (others)
09842              *others++ = '\0';
09843 
09844          /* Find ;rport;  (empty request) */
09845          rport = strstr(leftmost, ";rport");
09846          if (rport && *(rport+6) == '=')
09847             rport = NULL;     /* We already have a parameter to rport */
09848 
09849          if (((ast_test_flag(&p->flags[0], SIP_NAT_FORCE_RPORT)) || (rport && ast_test_flag(&p->flags[0], SIP_NAT_RPORT_PRESENT)))) {
09850             /* We need to add received port - rport */
09851             char *end;
09852 
09853             rport = strstr(leftmost, ";rport");
09854 
09855             if (rport) {
09856                end = strchr(rport + 1, ';');
09857                if (end)
09858                   memmove(rport, end, strlen(end) + 1);
09859                else
09860                   *rport = '\0';
09861             }
09862 
09863             /* Add rport to first VIA header if requested */
09864             snprintf(new, sizeof(new), "%s;received=%s;rport=%d%s%s",
09865                leftmost, ast_sockaddr_stringify_addr_remote(&p->recv),
09866                ast_sockaddr_port(&p->recv),
09867                others ? "," : "", others ? others : "");
09868          } else {
09869             /* We should *always* add a received to the topmost via */
09870             snprintf(new, sizeof(new), "%s;received=%s%s%s",
09871                leftmost, ast_sockaddr_stringify_addr_remote(&p->recv),
09872                others ? "," : "", others ? others : "");
09873          }
09874          oh = new;   /* the header to copy */
09875       }  /* else add the following via headers untouched */
09876       add_header(req, field, oh);
09877       copied++;
09878    }
09879    if (!copied) {
09880       ast_log(LOG_NOTICE, "No header field '%s' present to copy\n", field);
09881       return -1;
09882    }
09883    return 0;
09884 }
09885 
09886 /*! \brief Add route header into request per learned route */
09887 static void add_route(struct sip_request *req, struct sip_route *route)
09888 {
09889    char r[SIPBUFSIZE*2], *p;
09890    int n, rem = sizeof(r);
09891 
09892    if (!route)
09893       return;
09894 
09895    p = r;
09896    for (;route ; route = route->next) {
09897       n = strlen(route->hop);
09898       if (rem < n+3) /* we need room for ",<route>" */
09899          break;
09900       if (p != r) {  /* add a separator after fist route */
09901          *p++ = ',';
09902          --rem;
09903       }
09904       *p++ = '<';
09905       ast_copy_string(p, route->hop, rem); /* cannot fail */
09906       p += n;
09907       *p++ = '>';
09908       rem -= (n+2);
09909    }
09910    *p = '\0';
09911    add_header(req, "Route", r);
09912 }
09913 
09914 /*! \brief Set destination from SIP URI
09915  *
09916  * Parse uri to h (host) and port - uri is already just the part inside the <>
09917  * general form we are expecting is sip[s]:username[:password][;parameter]@host[:port][;...]
09918  * If there's a port given, turn NAPTR/SRV off. NAPTR might indicate SIPS preference even
09919  * for SIP: uri's
09920  *
09921  * If there's a sips: uri scheme, TLS will be required.
09922  */
09923 static void set_destination(struct sip_pvt *p, char *uri)
09924 {
09925    char *h, *maddr, hostname[256];
09926    int hn;
09927    int debug=sip_debug_test_pvt(p);
09928    int tls_on = FALSE;
09929 
09930    if (debug)
09931       ast_verbose("set_destination: Parsing <%s> for address/port to send to\n", uri);
09932 
09933    /* Find and parse hostname */
09934    h = strchr(uri, '@');
09935    if (h)
09936       ++h;
09937    else {
09938       h = uri;
09939       if (!strncasecmp(h, "sip:", 4)) {
09940          h += 4;
09941       } else if (!strncasecmp(h, "sips:", 5)) {
09942          h += 5;
09943          tls_on = TRUE;
09944       }
09945    }
09946    hn = strcspn(h, ";>") + 1;
09947    if (hn > sizeof(hostname))
09948       hn = sizeof(hostname);
09949    ast_copy_string(hostname, h, hn);
09950    /* XXX bug here if string has been trimmed to sizeof(hostname) */
09951    h += hn - 1;
09952 
09953    /*! \todo XXX If we have sip_cfg.srvlookup on, then look for NAPTR/SRV,
09954     * otherwise, just look for A records */
09955    if (ast_sockaddr_resolve_first(&p->sa, hostname, 0)) {
09956       ast_log(LOG_WARNING, "Can't find address for host '%s'\n", hostname);
09957       return;
09958    }
09959 
09960    /* Got the hostname - but maybe there's a "maddr=" to override address? */
09961    maddr = strstr(h, "maddr=");
09962    if (maddr) {
09963       int port;
09964 
09965       maddr += 6;
09966       hn = strspn(maddr, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
09967                     "0123456789-.:[]") + 1;
09968       if (hn > sizeof(hostname))
09969          hn = sizeof(hostname);
09970       ast_copy_string(hostname, maddr, hn);
09971 
09972       port = ast_sockaddr_port(&p->sa);
09973 
09974       /*! \todo XXX If we have sip_cfg.srvlookup on, then look for
09975        * NAPTR/SRV, otherwise, just look for A records */
09976       if (ast_sockaddr_resolve_first(&p->sa, hostname, PARSE_PORT_FORBID)) {
09977          ast_log(LOG_WARNING, "Can't find address for host '%s'\n", hostname);
09978          return;
09979       }
09980 
09981       ast_sockaddr_set_port(&p->sa, port);
09982    }
09983 
09984    if (!ast_sockaddr_port(&p->sa)) {
09985       ast_sockaddr_set_port(&p->sa, tls_on ?
09986                   STANDARD_TLS_PORT : STANDARD_SIP_PORT);
09987    }
09988 
09989    if (debug) {
09990       ast_verbose("set_destination: set destination to %s\n",
09991              ast_sockaddr_stringify(&p->sa));
09992    }
09993 }
09994 
09995 /*! \brief Initialize SIP response, based on SIP request */
09996 static int init_resp(struct sip_request *resp, const char *msg)
09997 {
09998    /* Initialize a response */
09999    memset(resp, 0, sizeof(*resp));
10000    resp->method = SIP_RESPONSE;
10001    if (!(resp->data = ast_str_create(SIP_MIN_PACKET)))
10002       goto e_return;
10003    if (!(resp->content = ast_str_create(SIP_MIN_PACKET)))
10004       goto e_free_data;
10005    resp->header[0] = 0;
10006    ast_str_set(&resp->data, 0, "SIP/2.0 %s\r\n", msg);
10007    resp->headers++;
10008    return 0;
10009 
10010 e_free_data:
10011    ast_free(resp->data);
10012    resp->data = NULL;
10013 e_return:
10014    return -1;
10015 }
10016 
10017 /*! \brief Initialize SIP request */
10018 static int init_req(struct sip_request *req, int sipmethod, const char *recip)
10019 {
10020    /* Initialize a request */
10021    memset(req, 0, sizeof(*req));
10022    if (!(req->data = ast_str_create(SIP_MIN_PACKET)))
10023       goto e_return;
10024    if (!(req->content = ast_str_create(SIP_MIN_PACKET)))
10025       goto e_free_data;
10026    req->method = sipmethod;
10027    req->header[0] = 0;
10028    ast_str_set(&req->data, 0, "%s %s SIP/2.0\r\n", sip_methods[sipmethod].text, recip);
10029    req->headers++;
10030    return 0;
10031 
10032 e_free_data:
10033    ast_free(req->data);
10034    req->data = NULL;
10035 e_return:
10036    return -1;
10037 }
10038 
10039 /*! \brief Deinitialize SIP response/request */
10040 static void deinit_req(struct sip_request *req)
10041 {
10042    if (req->data) {
10043       ast_free(req->data);
10044       req->data = NULL;
10045    }
10046    if (req->content) {
10047       ast_free(req->content);
10048       req->content = NULL;
10049    }
10050 }
10051 
10052 
10053 /*! \brief Test if this response needs a contact header */
10054 static inline int resp_needs_contact(const char *msg, enum sipmethod method) {
10055    /* Requirements for Contact header inclusion in responses generated
10056     * from the header tables found in the following RFCs.  Where the
10057     * Contact header was marked mandatory (m) or optional (o) this
10058     * function returns 1.
10059     *
10060     * - RFC 3261 (ACK, BYE, CANCEL, INVITE, OPTIONS, REGISTER)
10061     * - RFC 2976 (INFO)
10062     * - RFC 3262 (PRACK)
10063     * - RFC 3265 (SUBSCRIBE, NOTIFY)
10064     * - RFC 3311 (UPDATE)
10065     * - RFC 3428 (MESSAGE)
10066     * - RFC 3515 (REFER)
10067     * - RFC 3903 (PUBLISH)
10068     */
10069 
10070    switch (method) {
10071       /* 1xx, 2xx, 3xx, 485 */
10072       case SIP_INVITE:
10073       case SIP_UPDATE:
10074       case SIP_SUBSCRIBE:
10075       case SIP_NOTIFY:
10076          if ((msg[0] >= '1' && msg[0] <= '3') || !strncmp(msg, "485", 3))
10077             return 1;
10078          break;
10079 
10080       /* 2xx, 3xx, 485 */
10081       case SIP_REGISTER:
10082       case SIP_OPTIONS:
10083          if (msg[0] == '2' || msg[0] == '3' || !strncmp(msg, "485", 3))
10084             return 1;
10085          break;
10086 
10087       /* 3xx, 485 */
10088       case SIP_BYE:
10089       case SIP_PRACK:
10090       case SIP_MESSAGE:
10091       case SIP_PUBLISH:
10092          if (msg[0] == '3' || !strncmp(msg, "485", 3))
10093             return 1;
10094          break;
10095 
10096       /* 2xx, 3xx, 4xx, 5xx, 6xx */
10097       case SIP_REFER:
10098          if (msg[0] >= '2' && msg[0] <= '6')
10099             return 1;
10100          break;
10101 
10102       /* contact will not be included for everything else */
10103       case SIP_ACK:
10104       case SIP_CANCEL:
10105       case SIP_INFO:
10106       case SIP_PING:
10107       default:
10108          return 0;
10109    }
10110    return 0;
10111 }
10112 
10113 /*! \brief Prepare SIP response packet */
10114 static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req)
10115 {
10116    char newto[256];
10117    const char *ot;
10118 
10119    init_resp(resp, msg);
10120    copy_via_headers(p, resp, req, "Via");
10121    if (msg[0] == '1' || msg[0] == '2')
10122       copy_all_header(resp, req, "Record-Route");
10123    copy_header(resp, req, "From");
10124    ot = get_header(req, "To");
10125    if (!strcasestr(ot, "tag=") && strncmp(msg, "100", 3)) {
10126       /* Add the proper tag if we don't have it already.  If they have specified
10127          their tag, use it.  Otherwise, use our own tag */
10128       if (!ast_strlen_zero(p->theirtag) && ast_test_flag(&p->flags[0], SIP_OUTGOING))
10129          snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
10130       else if (p->tag && !ast_test_flag(&p->flags[0], SIP_OUTGOING))
10131          snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->tag);
10132       else
10133          ast_copy_string(newto, ot, sizeof(newto));
10134       ot = newto;
10135    }
10136    add_header(resp, "To", ot);
10137    copy_header(resp, req, "Call-ID");
10138    copy_header(resp, req, "CSeq");
10139    if (!ast_strlen_zero(global_useragent))
10140       add_header(resp, "Server", global_useragent);
10141    add_header(resp, "Allow", ALLOWED_METHODS);
10142    add_supported_header(p, resp);
10143 
10144    /* If this is an invite, add Session-Timers related headers if the feature is active for this session */
10145    if (p->method == SIP_INVITE && p->stimer && p->stimer->st_active == TRUE && p->stimer->st_active_peer_ua == TRUE) {
10146       char se_hdr[256];
10147       snprintf(se_hdr, sizeof(se_hdr), "%d;refresher=%s", p->stimer->st_interval,
10148          strefresher2str(p->stimer->st_ref));
10149       add_header(resp, "Session-Expires", se_hdr);
10150    }
10151 
10152    if (msg[0] == '2' && (p->method == SIP_SUBSCRIBE || p->method == SIP_REGISTER)) {
10153       /* For registration responses, we also need expiry and
10154          contact info */
10155       char tmp[256];
10156 
10157       snprintf(tmp, sizeof(tmp), "%d", p->expiry);
10158       add_header(resp, "Expires", tmp);
10159       if (p->expiry) {  /* Only add contact if we have an expiry time */
10160          char contact[SIPBUFSIZE];
10161          const char *contact_uri = p->method == SIP_SUBSCRIBE ? p->our_contact : p->fullcontact;
10162          char *brackets = strchr(contact_uri, '<');
10163          snprintf(contact, sizeof(contact), "%s%s%s;expires=%d", brackets ? "" : "<", contact_uri, brackets ? "" : ">", p->expiry);
10164          add_header(resp, "Contact", contact);  /* Not when we unregister */
10165       }
10166    } else if (!ast_strlen_zero(p->our_contact) && resp_needs_contact(msg, p->method)) {
10167       add_header(resp, "Contact", p->our_contact);
10168    }
10169 
10170    if (!ast_strlen_zero(p->url)) {
10171       add_header(resp, "Access-URL", p->url);
10172       ast_string_field_set(p, url, NULL);
10173    }
10174 
10175    /* default to routing the response to the address where the request
10176     * came from.  Since we don't have a transport layer, we do this here.
10177     * The process_via() function will update the port to either the port
10178     * specified in the via header or the default port later on (per RFC
10179     * 3261 section 18.2.2).
10180     */
10181    p->sa = p->recv;
10182 
10183    if (process_via(p, req)) {
10184       ast_log(LOG_WARNING, "error processing via header, will send response to originating address\n");
10185    }
10186 
10187    return 0;
10188 }
10189 
10190 /*! \brief Initialize a SIP request message (not the initial one in a dialog) */
10191 static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, int seqno, int newbranch)
10192 {
10193    struct sip_request *orig = &p->initreq;
10194    char stripped[80];
10195    char tmp[80];
10196    char newto[256];
10197    const char *c;
10198    const char *ot, *of;
10199    int is_strict = FALSE;     /*!< Strict routing flag */
10200    int is_outbound = ast_test_flag(&p->flags[0], SIP_OUTGOING);   /* Session direction */
10201 
10202    memset(req, 0, sizeof(struct sip_request));
10203    
10204    snprintf(p->lastmsg, sizeof(p->lastmsg), "Tx: %s", sip_methods[sipmethod].text);
10205    
10206    if (!seqno) {
10207       p->ocseq++;
10208       seqno = p->ocseq;
10209    }
10210    
10211    /* A CANCEL must have the same branch as the INVITE that it is canceling. */
10212    if (sipmethod == SIP_CANCEL) {
10213       p->branch = p->invite_branch;
10214       build_via(p);
10215    } else if (newbranch && (sipmethod == SIP_INVITE)) {
10216       p->branch ^= ast_random();
10217       p->invite_branch = p->branch;
10218       build_via(p);
10219    } else if (newbranch) {
10220       p->branch ^= ast_random();
10221       build_via(p);
10222    }
10223 
10224    /* Check for strict or loose router */
10225    if (p->route && !ast_strlen_zero(p->route->hop) && strstr(p->route->hop, ";lr") == NULL) {
10226       is_strict = TRUE;
10227       if (sipdebug)
10228          ast_debug(1, "Strict routing enforced for session %s\n", p->callid);
10229    }
10230    
10231    if (sipmethod == SIP_CANCEL)
10232       c = REQ_OFFSET_TO_STR(&p->initreq, rlPart2); /* Use original URI */
10233    else if (sipmethod == SIP_ACK) {
10234       /* Use URI from Contact: in 200 OK (if INVITE)
10235       (we only have the contacturi on INVITEs) */
10236       if (!ast_strlen_zero(p->okcontacturi))
10237          c = is_strict ? p->route->hop : p->okcontacturi;
10238       else
10239          c = REQ_OFFSET_TO_STR(&p->initreq, rlPart2);
10240    } else if (!ast_strlen_zero(p->okcontacturi))
10241       c = is_strict ? p->route->hop : p->okcontacturi; /* Use for BYE or REINVITE */
10242    else if (!ast_strlen_zero(p->uri))
10243       c = p->uri;
10244    else {
10245       char *n;
10246       /* We have no URI, use To: or From:  header as URI (depending on direction) */
10247       ast_copy_string(stripped, get_header(orig, is_outbound ? "To" : "From"),
10248             sizeof(stripped));
10249       n = get_in_brackets(stripped);
10250       c = remove_uri_parameters(n);
10251    }  
10252    init_req(req, sipmethod, c);
10253 
10254    snprintf(tmp, sizeof(tmp), "%d %s", seqno, sip_methods[sipmethod].text);
10255 
10256    add_header(req, "Via", p->via);
10257    if (p->route) {
10258       set_destination(p, p->route->hop);
10259       add_route(req, is_strict ? p->route->next : p->route);
10260    }
10261    add_header_max_forwards(p, req);
10262 
10263    ot = get_header(orig, "To");
10264    of = get_header(orig, "From");
10265 
10266    /* Add tag *unless* this is a CANCEL, in which case we need to send it exactly
10267       as our original request, including tag (or presumably lack thereof) */
10268    if (!strcasestr(ot, "tag=") && sipmethod != SIP_CANCEL) {
10269       /* Add the proper tag if we don't have it already.  If they have specified
10270          their tag, use it.  Otherwise, use our own tag */
10271       if (is_outbound && !ast_strlen_zero(p->theirtag))
10272          snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
10273       else if (!is_outbound)
10274          snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->tag);
10275       else
10276          snprintf(newto, sizeof(newto), "%s", ot);
10277       ot = newto;
10278    }
10279 
10280    if (is_outbound) {
10281       add_header(req, "From", of);
10282       add_header(req, "To", ot);
10283    } else {
10284       add_header(req, "From", ot);
10285       add_header(req, "To", of);
10286    }
10287    /* Do not add Contact for MESSAGE, BYE and Cancel requests */
10288    if (sipmethod != SIP_BYE && sipmethod != SIP_CANCEL && sipmethod != SIP_MESSAGE)
10289       add_header(req, "Contact", p->our_contact);
10290 
10291    copy_header(req, orig, "Call-ID");
10292    add_header(req, "CSeq", tmp);
10293 
10294    if (!ast_strlen_zero(global_useragent))
10295       add_header(req, "User-Agent", global_useragent);
10296 
10297    if (!ast_strlen_zero(p->url)) {
10298       add_header(req, "Access-URL", p->url);
10299       ast_string_field_set(p, url, NULL);
10300    }
10301 
10302    /* Add Session-Timers related headers if the feature is active for this session.
10303       An exception to this behavior is the ACK request. Since Asterisk never requires
10304       session-timers support from a remote end-point (UAS) in an INVITE, it must
10305       not send 'Require: timer' header in the ACK request.
10306       This should only be added in the INVITE transactions, not MESSAGE or REFER or other
10307       in-dialog messages.
10308    */
10309    if (p->stimer && p->stimer->st_active == TRUE && p->stimer->st_active_peer_ua == TRUE
10310        && sipmethod == SIP_INVITE) {
10311       char se_hdr[256];
10312       snprintf(se_hdr, sizeof(se_hdr), "%d;refresher=%s", p->stimer->st_interval,
10313          strefresher2str(p->stimer->st_ref));
10314       add_header(req, "Session-Expires", se_hdr);
10315       snprintf(se_hdr, sizeof(se_hdr), "%d", st_get_se(p, FALSE));
10316       add_header(req, "Min-SE", se_hdr);
10317    }
10318 
10319    return 0;
10320 }
10321 
10322 /*! \brief Base transmit response function */
10323 static int __transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable)
10324 {
10325    struct sip_request resp;
10326    int seqno = 0;
10327 
10328    if (reliable && (sscanf(get_header(req, "CSeq"), "%30d ", &seqno) != 1)) {
10329       ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
10330       return -1;
10331    }
10332    respprep(&resp, p, msg, req);
10333 
10334    if (ast_test_flag(&p->flags[0], SIP_SENDRPID)
10335          && ast_test_flag(&p->flags[1], SIP_PAGE2_CONNECTLINEUPDATE_PEND)
10336          && (!strncmp(msg, "180", 3) || !strncmp(msg, "183", 3))) {
10337       ast_clear_flag(&p->flags[1], SIP_PAGE2_CONNECTLINEUPDATE_PEND);
10338       add_rpid(&resp, p);
10339    }
10340    if (ast_test_flag(&p->flags[0], SIP_OFFER_CC)) {
10341       add_cc_call_info_to_response(p, &resp);
10342    }
10343 
10344    /* If we are sending a 302 Redirect we can add a diversion header if the redirect information is set */
10345    if (!strncmp(msg, "302", 3)) {
10346       add_diversion_header(&resp, p);
10347    }
10348 
10349    /* If we are cancelling an incoming invite for some reason, add information
10350       about the reason why we are doing this in clear text */
10351    if (p->method == SIP_INVITE && msg[0] != '1') {
10352       char buf[20];
10353 
10354       if (ast_test_flag(&p->flags[1], SIP_PAGE2_Q850_REASON)) {
10355          int hangupcause = 0;
10356 
10357          if (p->owner && p->owner->hangupcause) {
10358             hangupcause = p->owner->hangupcause;
10359          } else if (p->hangupcause) {
10360             hangupcause = p->hangupcause;
10361          } else {
10362             int respcode;
10363             if (sscanf(msg, "%30d ", &respcode))
10364                hangupcause = hangup_sip2cause(respcode);
10365          }
10366 
10367          if (hangupcause) {
10368             sprintf(buf, "Q.850;cause=%i", hangupcause & 0x7f);
10369             add_header(&resp, "Reason", buf);
10370          }
10371       }
10372 
10373       if (p->owner && p->owner->hangupcause) {
10374          add_header(&resp, "X-Asterisk-HangupCause", ast_cause2str(p->owner->hangupcause));
10375          snprintf(buf, sizeof(buf), "%d", p->owner->hangupcause);
10376          add_header(&resp, "X-Asterisk-HangupCauseCode", buf);
10377       }
10378    }
10379    return send_response(p, &resp, reliable, seqno);
10380 }
10381 
10382 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)
10383 {
10384    struct sip_request resp;
10385 
10386    if (need_new_etag) {
10387       create_new_sip_etag(esc_entry, 1);
10388    }
10389    respprep(&resp, p, msg, req);
10390    add_header(&resp, "SIP-ETag", esc_entry->entity_tag);
10391 
10392    return send_response(p, &resp, 0, 0);
10393 }
10394 
10395 static int temp_pvt_init(void *data)
10396 {
10397    struct sip_pvt *p = data;
10398 
10399    p->do_history = 0;   /* XXX do we need it ? isn't already all 0 ? */
10400    return ast_string_field_init(p, 512);
10401 }
10402 
10403 static void temp_pvt_cleanup(void *data)
10404 {
10405    struct sip_pvt *p = data;
10406 
10407    ast_string_field_free_memory(p);
10408 
10409    ast_free(data);
10410 }
10411 
10412 /*! \brief Transmit response, no retransmits, using a temporary pvt structure */
10413 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)
10414 {
10415    struct sip_pvt *p = NULL;
10416 
10417    if (!(p = ast_threadstorage_get(&ts_temp_pvt, sizeof(*p)))) {
10418       ast_log(LOG_ERROR, "Failed to get temporary pvt\n");
10419       return -1;
10420    }
10421 
10422    /* XXX the structure may be dirty from previous usage.
10423     * Here we should state clearly how we should reinitialize it
10424     * before using it.
10425     * E.g. certainly the threadstorage should be left alone,
10426     * but other thihngs such as flags etc. maybe need cleanup ?
10427     */
10428 
10429    /* Initialize the bare minimum */
10430    p->method = intended_method;
10431 
10432    if (!addr) {
10433       ast_sockaddr_copy(&p->ourip, &internip);
10434    } else {
10435       ast_sockaddr_copy(&p->sa, addr);
10436       ast_sip_ouraddrfor(&p->sa, &p->ourip, p);
10437    }
10438 
10439    p->branch = ast_random();
10440    make_our_tag(p->tag, sizeof(p->tag));
10441    p->ocseq = INITIAL_CSEQ;
10442 
10443    if (useglobal_nat && addr) {
10444       ast_copy_flags(&p->flags[0], &global_flags[0], SIP_NAT_FORCE_RPORT);
10445       ast_sockaddr_copy(&p->recv, addr);
10446       do_setnat(p);
10447    }
10448 
10449    ast_string_field_set(p, fromdomain, default_fromdomain);
10450    p->fromdomainport = default_fromdomainport;
10451    build_via(p);
10452    ast_string_field_set(p, callid, callid);
10453 
10454    copy_socket_data(&p->socket, &req->socket);
10455 
10456    /* Use this temporary pvt structure to send the message */
10457    __transmit_response(p, msg, req, XMIT_UNRELIABLE);
10458 
10459    /* Free the string fields, but not the pool space */
10460    ast_string_field_init(p, 0);
10461 
10462    return 0;
10463 }
10464 
10465 /*! \brief Transmit response, no retransmits */
10466 static int transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req)
10467 {
10468    return __transmit_response(p, msg, req, XMIT_UNRELIABLE);
10469 }
10470 
10471 /*! \brief Transmit response, no retransmits */
10472 static int transmit_response_with_unsupported(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *unsupported)
10473 {
10474    struct sip_request resp;
10475    respprep(&resp, p, msg, req);
10476    append_date(&resp);
10477    add_header(&resp, "Unsupported", unsupported);
10478    return send_response(p, &resp, XMIT_UNRELIABLE, 0);
10479 }
10480 
10481 /*! \brief Transmit 422 response with Min-SE header (Session-Timers)  */
10482 static int transmit_response_with_minse(struct sip_pvt *p, const char *msg, const struct sip_request *req, int minse_int)
10483 {
10484    struct sip_request resp;
10485    char minse_str[20];
10486 
10487    respprep(&resp, p, msg, req);
10488    append_date(&resp);
10489 
10490    snprintf(minse_str, sizeof(minse_str), "%d", minse_int);
10491    add_header(&resp, "Min-SE", minse_str);
10492    return send_response(p, &resp, XMIT_UNRELIABLE, 0);
10493 }
10494 
10495 
10496 /*! \brief Transmit response, Make sure you get an ACK
10497    This is only used for responses to INVITEs, where we need to make sure we get an ACK
10498 */
10499 static int transmit_response_reliable(struct sip_pvt *p, const char *msg, const struct sip_request *req)
10500 {
10501    return __transmit_response(p, msg, req, req->ignore ? XMIT_UNRELIABLE : XMIT_CRITICAL);
10502 }
10503 
10504 /*! \brief Append date to SIP message */
10505 static void append_date(struct sip_request *req)
10506 {
10507    char tmpdat[256];
10508    struct tm tm;
10509    time_t t = time(NULL);
10510 
10511    gmtime_r(&t, &tm);
10512    strftime(tmpdat, sizeof(tmpdat), "%a, %d %b %Y %T GMT", &tm);
10513    add_header(req, "Date", tmpdat);
10514 }
10515 
10516 /*! \brief Append Retry-After header field when transmitting response */
10517 static int transmit_response_with_retry_after(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *seconds)
10518 {
10519    struct sip_request resp;
10520    respprep(&resp, p, msg, req);
10521    add_header(&resp, "Retry-After", seconds);
10522    return send_response(p, &resp, XMIT_UNRELIABLE, 0);
10523 }
10524 
10525 /*! \brief Append date and content length before transmitting response */
10526 static int transmit_response_with_date(struct sip_pvt *p, const char *msg, const struct sip_request *req)
10527 {
10528    struct sip_request resp;
10529    respprep(&resp, p, msg, req);
10530    append_date(&resp);
10531    return send_response(p, &resp, XMIT_UNRELIABLE, 0);
10532 }
10533 
10534 /*! \brief Append Accept header, content length before transmitting response */
10535 static int transmit_response_with_allow(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable)
10536 {
10537    struct sip_request resp;
10538    respprep(&resp, p, msg, req);
10539    add_header(&resp, "Accept", "application/sdp");
10540    return send_response(p, &resp, reliable, 0);
10541 }
10542 
10543 /*! \brief Append Min-Expires header, content length before transmitting response */
10544 static int transmit_response_with_minexpires(struct sip_pvt *p, const char *msg, const struct sip_request *req)
10545 {
10546    struct sip_request resp;
10547    char tmp[32];
10548 
10549    snprintf(tmp, sizeof(tmp), "%d", min_expiry);
10550    respprep(&resp, p, msg, req);
10551    add_header(&resp, "Min-Expires", tmp);
10552    return send_response(p, &resp, XMIT_UNRELIABLE, 0);
10553 }
10554 
10555 /*! \brief Respond with authorization request */
10556 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)
10557 {
10558    struct sip_request resp;
10559    char tmp[512];
10560    int seqno = 0;
10561 
10562    if (reliable && (sscanf(get_header(req, "CSeq"), "%30d ", &seqno) != 1)) {
10563       ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
10564       return -1;
10565    }
10566    /* Choose Realm */
10567    get_realm(p, req);
10568 
10569    /* Stale means that they sent us correct authentication, but
10570       based it on an old challenge (nonce) */
10571    snprintf(tmp, sizeof(tmp), "Digest algorithm=MD5, realm=\"%s\", nonce=\"%s\"%s", p->realm, randdata, stale ? ", stale=true" : "");
10572    respprep(&resp, p, msg, req);
10573    add_header(&resp, header, tmp);
10574    append_history(p, "AuthChal", "Auth challenge sent for %s - nc %d", p->username, p->noncecount);
10575    return send_response(p, &resp, reliable, seqno);
10576 }
10577 
10578 /*!
10579  \brief Extract domain from SIP To/From header
10580  \return -1 on error, 1 if domain string is empty, 0 if domain was properly extracted
10581  \note TODO: Such code is all over SIP channel, there is a sense to organize
10582       this patern in one function
10583 */
10584 static int get_domain(const char *str, char *domain, int len)
10585 {
10586    char tmpf[256];
10587    char *a, *from;
10588 
10589    *domain = '\0';
10590    ast_copy_string(tmpf, str, sizeof(tmpf));
10591    from = get_in_brackets(tmpf);
10592    if (!ast_strlen_zero(from)) {
10593       if (strncasecmp(from, "sip:", 4)) {
10594          ast_log(LOG_WARNING, "Huh?  Not a SIP header (%s)?\n", from);
10595          return -1;
10596       }
10597       from += 4;
10598    } else
10599       from = NULL;
10600 
10601    if (from) {
10602       int bracket = 0;
10603 
10604       /* Strip any params or options from user */
10605       if ((a = strchr(from, ';')))
10606          *a = '\0';
10607       /* Strip port from domain if present */
10608       for (a = from; *a != '\0'; ++a) {
10609          if (*a == ':' && bracket == 0) {
10610             *a = '\0';
10611             break;
10612          } else if (*a == '[') {
10613             ++bracket;
10614          } else if (*a == ']') {
10615             --bracket;
10616          }
10617       }
10618       if ((a = strchr(from, '@'))) {
10619          *a = '\0';
10620          ast_copy_string(domain, a + 1, len);
10621       } else
10622          ast_copy_string(domain, from, len);
10623    }
10624 
10625    return ast_strlen_zero(domain);
10626 }
10627 
10628 /*!
10629   \brief Choose realm based on From header and then To header or use globaly configured realm.
10630   Realm from From/To header should be listed among served domains in config file: domain=...
10631 */
10632 static void get_realm(struct sip_pvt *p, const struct sip_request *req)
10633 {
10634    char domain[MAXHOSTNAMELEN];
10635 
10636    if (!ast_strlen_zero(p->realm))
10637       return;
10638 
10639    if (sip_cfg.domainsasrealm &&
10640        !AST_LIST_EMPTY(&domain_list))
10641    {
10642       /* Check From header first */
10643       if (!get_domain(get_header(req, "From"), domain, sizeof(domain))) {
10644          if (check_sip_domain(domain, NULL, 0)) {
10645             ast_string_field_set(p, realm, domain);
10646             return;
10647          }
10648       }
10649       /* Check To header */
10650       if (!get_domain(get_header(req, "To"), domain, sizeof(domain))) {
10651          if (check_sip_domain(domain, NULL, 0)) {
10652             ast_string_field_set(p, realm, domain);
10653             return;
10654          }
10655       }
10656    }
10657    
10658    /* Use default realm from config file */
10659    ast_string_field_set(p, realm, sip_cfg.realm);
10660 }
10661 
10662 /* Only use a static string for the msg, here! */
10663 static int transmit_provisional_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, int with_sdp)
10664 {
10665    int res;
10666 
10667    if (!(res = with_sdp ? transmit_response_with_sdp(p, msg, req, XMIT_UNRELIABLE, FALSE, FALSE) : transmit_response(p, msg, req))) {
10668       p->last_provisional = msg;
10669       update_provisional_keepalive(p, with_sdp);
10670    }
10671 
10672    return res;
10673 }
10674 
10675 /*! \brief Add text body to SIP message */
10676 static int add_text(struct sip_request *req, const char *text)
10677 {
10678    /* XXX Convert \n's to \r\n's XXX */
10679    add_header(req, "Content-Type", "text/plain;charset=UTF-8");
10680    add_content(req, text);
10681    return 0;
10682 }
10683 
10684 /*! \brief Add DTMF INFO tone to sip message
10685    Mode =   0 for application/dtmf-relay (Cisco)
10686       1 for application/dtmf
10687 */
10688 static int add_digit(struct sip_request *req, char digit, unsigned int duration, int mode)
10689 {
10690    char tmp[256];
10691    int event;
10692    if (mode) {
10693       /* Application/dtmf short version used by some implementations */
10694       if ('0' <= digit && digit <= '9') {
10695          event = digit - '0';
10696       } else if (digit == '*') {
10697          event = 10;
10698       } else if (digit == '#') {
10699          event = 11;
10700       } else if ('A' <= digit && digit <= 'D') {
10701          event = 12 + digit - 'A';
10702       } else if ('a' <= digit && digit <= 'd') {
10703          event = 12 + digit - 'a';
10704       } else {
10705          /* Unknown digit */
10706          event = 0;
10707       }
10708       snprintf(tmp, sizeof(tmp), "%d\r\n", event);
10709       add_header(req, "Content-Type", "application/dtmf");
10710       add_content(req, tmp);
10711    } else {
10712       /* Application/dtmf-relay as documented by Cisco */
10713       snprintf(tmp, sizeof(tmp), "Signal=%c\r\nDuration=%u\r\n", digit, duration);
10714       add_header(req, "Content-Type", "application/dtmf-relay");
10715       add_content(req, tmp);
10716    }
10717    return 0;
10718 }
10719 
10720 /*!
10721  * \pre if p->owner exists, it must be locked
10722  * \brief Add Remote-Party-ID header to SIP message
10723  */
10724 static int add_rpid(struct sip_request *req, struct sip_pvt *p)
10725 {
10726    struct ast_str *tmp = ast_str_alloca(256);
10727    char tmp2[256];
10728    char *lid_num = NULL;
10729    char *lid_name = NULL;
10730    int lid_pres;
10731    const char *fromdomain;
10732    const char *privacy = NULL;
10733    const char *screen = NULL;
10734    const char *anonymous_string = "\"Anonymous\" <sip:anonymous@anonymous.invalid>";
10735 
10736    if (!ast_test_flag(&p->flags[0], SIP_SENDRPID)) {
10737       return 0;
10738    }
10739 
10740    if (p->owner && p->owner->connected.id.number.valid
10741       && p->owner->connected.id.number.str) {
10742       lid_num = p->owner->connected.id.number.str;
10743    }
10744    if (p->owner && p->owner->connected.id.name.valid
10745       && p->owner->connected.id.name.str) {
10746       lid_name = p->owner->connected.id.name.str;
10747    }
10748    lid_pres = (p->owner) ? ast_party_id_presentation(&p->owner->connected.id) : AST_PRES_NUMBER_NOT_AVAILABLE;
10749 
10750    if (ast_strlen_zero(lid_num))
10751       return 0;
10752    if (ast_strlen_zero(lid_name))
10753       lid_name = lid_num;
10754    fromdomain = S_OR(p->fromdomain, ast_sockaddr_stringify_host_remote(&p->ourip));
10755 
10756    lid_num = ast_uri_encode(lid_num, tmp2, sizeof(tmp2), 0);
10757 
10758    if (ast_test_flag(&p->flags[0], SIP_SENDRPID_PAI)) {
10759       if ((lid_pres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED) {
10760          ast_str_set(&tmp, -1, "%s", anonymous_string);
10761       } else {
10762          ast_str_set(&tmp, -1, "\"%s\" <sip:%s@%s>", lid_name, lid_num, fromdomain);
10763       }
10764       add_header(req, "P-Asserted-Identity", ast_str_buffer(tmp));
10765    } else {
10766       ast_str_set(&tmp, -1, "\"%s\" <sip:%s@%s>;party=%s", lid_name, lid_num, fromdomain, ast_test_flag(&p->flags[0], SIP_OUTGOING) ? "calling" : "called");
10767 
10768       switch (lid_pres) {
10769       case AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED:
10770       case AST_PRES_ALLOWED_USER_NUMBER_FAILED_SCREEN:
10771          privacy = "off";
10772          screen = "no";
10773          break;
10774       case AST_PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN:
10775       case AST_PRES_ALLOWED_NETWORK_NUMBER:
10776          privacy = "off";
10777          screen = "yes";
10778          break;
10779       case AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED:
10780       case AST_PRES_PROHIB_USER_NUMBER_FAILED_SCREEN:
10781          privacy = "full";
10782          screen = "no";
10783          break;
10784       case AST_PRES_PROHIB_USER_NUMBER_PASSED_SCREEN:
10785       case AST_PRES_PROHIB_NETWORK_NUMBER:
10786          privacy = "full";
10787          screen = "yes";
10788          break;
10789       case AST_PRES_NUMBER_NOT_AVAILABLE:
10790          break;
10791       default:
10792          if ((lid_pres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED) {
10793             privacy = "full";
10794          }
10795          else
10796             privacy = "off";
10797          screen = "no";
10798          break;
10799       }
10800 
10801       if (!ast_strlen_zero(privacy) && !ast_strlen_zero(screen)) {
10802          ast_str_append(&tmp, -1, ";privacy=%s;screen=%s", privacy, screen);
10803       }
10804 
10805       add_header(req, "Remote-Party-ID", ast_str_buffer(tmp));
10806    }
10807    return 0;
10808 }
10809 
10810 /*! \brief add XML encoded media control with update
10811    \note XML: The only way to turn 0 bits of information into a few hundred. (markster) */
10812 static int add_vidupdate(struct sip_request *req)
10813 {
10814    const char *xml_is_a_huge_waste_of_space =
10815       "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\r\n"
10816       " <media_control>\r\n"
10817       "  <vc_primitive>\r\n"
10818       "   <to_encoder>\r\n"
10819       "    <picture_fast_update>\r\n"
10820       "    </picture_fast_update>\r\n"
10821       "   </to_encoder>\r\n"
10822       "  </vc_primitive>\r\n"
10823       " </media_control>\r\n";
10824    add_header(req, "Content-Type", "application/media_control+xml");
10825    add_content(req, xml_is_a_huge_waste_of_space);
10826    return 0;
10827 }
10828 
10829 /*! \brief Add codec offer to SDP offer/answer body in INVITE or 200 OK */
10830 static void add_codec_to_sdp(const struct sip_pvt *p, format_t codec,
10831               struct ast_str **m_buf, struct ast_str **a_buf,
10832               int debug, int *min_packet_size)
10833 {
10834    int rtp_code;
10835    struct ast_format_list fmt;
10836 
10837 
10838    if (debug)
10839       ast_verbose("Adding codec 0x%" PRIx64 " (%s) to SDP\n", codec, ast_getformatname(codec));
10840    if ((rtp_code = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(p->rtp), 1, codec)) == -1)
10841       return;
10842 
10843    if (p->rtp) {
10844       struct ast_codec_pref *pref = &ast_rtp_instance_get_codecs(p->rtp)->pref;
10845       fmt = ast_codec_pref_getsize(pref, codec);
10846    } 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 */
10847       return;
10848    ast_str_append(m_buf, 0, " %d", rtp_code);
10849    ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%d\r\n", rtp_code,
10850              ast_rtp_lookup_mime_subtype2(1, codec,
10851                      ast_test_flag(&p->flags[0], SIP_G726_NONSTANDARD) ? AST_RTP_OPT_G726_NONSTANDARD : 0),
10852              ast_rtp_lookup_sample_rate2(1, codec));
10853 
10854    switch (codec) {
10855    case AST_FORMAT_G729A:
10856       /* Indicate that we don't support VAD (G.729 annex B) */
10857       ast_str_append(a_buf, 0, "a=fmtp:%d annexb=no\r\n", rtp_code);
10858       break;
10859    case AST_FORMAT_G723_1:
10860       /* Indicate that we don't support VAD (G.723.1 annex A) */
10861       ast_str_append(a_buf, 0, "a=fmtp:%d annexa=no\r\n", rtp_code);
10862       break;
10863    case AST_FORMAT_ILBC:
10864       /* Add information about us using only 20/30 ms packetization */
10865       ast_str_append(a_buf, 0, "a=fmtp:%d mode=%d\r\n", rtp_code, fmt.cur_ms);
10866       break;
10867    case AST_FORMAT_SIREN7:
10868       /* Indicate that we only expect 32Kbps */
10869       ast_str_append(a_buf, 0, "a=fmtp:%d bitrate=32000\r\n", rtp_code);
10870       break;
10871    case AST_FORMAT_SIREN14:
10872       /* Indicate that we only expect 48Kbps */
10873       ast_str_append(a_buf, 0, "a=fmtp:%d bitrate=48000\r\n", rtp_code);
10874       break;
10875    case AST_FORMAT_G719:
10876       /* Indicate that we only expect 64Kbps */
10877       ast_str_append(a_buf, 0, "a=fmtp:%d bitrate=64000\r\n", rtp_code);
10878       break;
10879    }
10880 
10881    if (fmt.cur_ms && (fmt.cur_ms < *min_packet_size))
10882       *min_packet_size = fmt.cur_ms;
10883 
10884    /* Our first codec packetization processed cannot be zero */
10885    if ((*min_packet_size)==0 && fmt.cur_ms)
10886       *min_packet_size = fmt.cur_ms;
10887 }
10888 
10889 /*! \brief Add video codec offer to SDP offer/answer body in INVITE or 200 OK */
10890 /* This is different to the audio one now so we can add more caps later */
10891 static void add_vcodec_to_sdp(const struct sip_pvt *p, format_t codec,
10892               struct ast_str **m_buf, struct ast_str **a_buf,
10893               int debug, int *min_packet_size)
10894 {
10895    int rtp_code;
10896 
10897    if (!p->vrtp)
10898       return;
10899 
10900    if (debug)
10901       ast_verbose("Adding video codec 0x%" PRIx64 " (%s) to SDP\n", codec, ast_getformatname(codec));
10902 
10903    if ((rtp_code = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(p->vrtp), 1, codec)) == -1)
10904       return;
10905 
10906    ast_str_append(m_buf, 0, " %d", rtp_code);
10907    ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%d\r\n", rtp_code,
10908              ast_rtp_lookup_mime_subtype2(1, codec, 0),
10909              ast_rtp_lookup_sample_rate2(1, codec));
10910    /* Add fmtp code here */
10911 }
10912 
10913 /*! \brief Add text codec offer to SDP offer/answer body in INVITE or 200 OK */
10914 static void add_tcodec_to_sdp(const struct sip_pvt *p, int codec,
10915               struct ast_str **m_buf, struct ast_str **a_buf,
10916               int debug, int *min_packet_size)
10917 {
10918    int rtp_code;
10919 
10920    if (!p->trtp)
10921       return;
10922 
10923    if (debug)
10924       ast_verbose("Adding text codec 0x%x (%s) to SDP\n", codec, ast_getformatname(codec));
10925 
10926    if ((rtp_code = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(p->trtp), 1, codec)) == -1)
10927       return;
10928 
10929    ast_str_append(m_buf, 0, " %d", rtp_code);
10930    ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%d\r\n", rtp_code,
10931              ast_rtp_lookup_mime_subtype2(1, codec, 0),
10932              ast_rtp_lookup_sample_rate2(1, codec));
10933    /* Add fmtp code here */
10934 
10935    if (codec == AST_FORMAT_T140RED) {
10936       int t140code = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(p->trtp), 1, AST_FORMAT_T140);
10937       ast_str_append(a_buf, 0, "a=fmtp:%d %d/%d/%d\r\n", rtp_code,
10938           t140code,
10939           t140code,
10940           t140code);
10941 
10942    }
10943 }
10944 
10945 
10946 /*! \brief Get Max T.38 Transmission rate from T38 capabilities */
10947 static unsigned int t38_get_rate(enum ast_control_t38_rate rate)
10948 {
10949    switch (rate) {
10950    case AST_T38_RATE_2400:
10951       return 2400;
10952    case AST_T38_RATE_4800:
10953       return 4800;
10954    case AST_T38_RATE_7200:
10955       return 7200;
10956    case AST_T38_RATE_9600:
10957       return 9600;
10958    case AST_T38_RATE_12000:
10959       return 12000;
10960    case AST_T38_RATE_14400:
10961       return 14400;
10962    default:
10963       return 0;
10964    }
10965 }
10966 
10967 /*! \brief Add RFC 2833 DTMF offer to SDP */
10968 static void add_noncodec_to_sdp(const struct sip_pvt *p, int format,
10969             struct ast_str **m_buf, struct ast_str **a_buf,
10970             int debug)
10971 {
10972    int rtp_code;
10973 
10974    if (debug)
10975       ast_verbose("Adding non-codec 0x%x (%s) to SDP\n", format, ast_rtp_lookup_mime_subtype2(0, format, 0));
10976    if ((rtp_code = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(p->rtp), 0, format)) == -1)
10977       return;
10978 
10979    ast_str_append(m_buf, 0, " %d", rtp_code);
10980    ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%d\r\n", rtp_code,
10981              ast_rtp_lookup_mime_subtype2(0, format, 0),
10982              ast_rtp_lookup_sample_rate2(0, format));
10983    if (format == AST_RTP_DTMF)   /* Indicate we support DTMF and FLASH... */
10984       ast_str_append(a_buf, 0, "a=fmtp:%d 0-16\r\n", rtp_code);
10985 }
10986 
10987 /*! \brief Set all IP media addresses for this call
10988    \note called from add_sdp()
10989 */
10990 static void get_our_media_address(struct sip_pvt *p, int needvideo, int needtext,
10991               struct ast_sockaddr *addr, struct ast_sockaddr *vaddr,
10992               struct ast_sockaddr *taddr, struct ast_sockaddr *dest,
10993               struct ast_sockaddr *vdest, struct ast_sockaddr *tdest)
10994 {
10995    int use_externip = 0;
10996 
10997    /* First, get our address */
10998    ast_rtp_instance_get_local_address(p->rtp, addr);
10999    if (p->vrtp) {
11000       ast_rtp_instance_get_local_address(p->vrtp, vaddr);
11001    }
11002    if (p->trtp) {
11003       ast_rtp_instance_get_local_address(p->trtp, taddr);
11004    }
11005 
11006    /* If our real IP differs from the local address returned by the RTP engine, use it. */
11007    /* The premise is that if we are already using that IP to communicate with the client, */
11008    /* we should be using it for RTP too. */
11009         use_externip = ast_sockaddr_cmp_addr(&p->ourip, addr);
11010 
11011    /* Now, try to figure out where we want them to send data */
11012    /* Is this a re-invite to move the media out, then use the original offer from caller  */
11013    if (!ast_sockaddr_isnull(&p->redirip)) {  /* If we have a redirection IP, use it */
11014       ast_sockaddr_copy(dest, &p->redirip);
11015    } else {
11016       /*
11017        * Audio Destination IP:
11018        *
11019        * 1. Specifically configured media address.
11020        * 2. Local address as specified by the RTP engine.
11021        * 3. The local IP as defined by chan_sip.
11022        *
11023        * Audio Destination Port:
11024        *
11025        * 1. Provided by the RTP engine.
11026        */
11027       ast_sockaddr_copy(dest,
11028               !ast_sockaddr_isnull(&media_address) ? &media_address :
11029               !ast_sockaddr_is_any(addr) && !use_externip ? addr    :
11030               &p->ourip);
11031       ast_sockaddr_set_port(dest, ast_sockaddr_port(addr));
11032    }
11033 
11034    if (needvideo) {
11035       /* Determine video destination */
11036       if (!ast_sockaddr_isnull(&p->vredirip)) {
11037          ast_sockaddr_copy(vdest, &p->vredirip);
11038       } else {
11039          /*
11040           * Video Destination IP:
11041           *
11042           * 1. Specifically configured media address.
11043           * 2. Local address as specified by the RTP engine.
11044           * 3. The local IP as defined by chan_sip.
11045           *
11046           * Video Destination Port:
11047           *
11048           * 1. Provided by the RTP engine.
11049           */
11050          ast_sockaddr_copy(vdest,
11051                  !ast_sockaddr_isnull(&media_address) ? &media_address :
11052                  !ast_sockaddr_is_any(vaddr) && !use_externip ? vaddr  :
11053                  &p->ourip);
11054          ast_sockaddr_set_port(vdest, ast_sockaddr_port(vaddr));
11055       }
11056    }
11057 
11058    if (needtext) {
11059       /* Determine text destination */
11060       if (!ast_sockaddr_isnull(&p->tredirip)) {
11061          ast_sockaddr_copy(tdest, &p->tredirip);
11062       } else {
11063          /*
11064           * Text Destination IP:
11065           *
11066           * 1. Specifically configured media address.
11067           * 2. Local address as specified by the RTP engine.
11068           * 3. The local IP as defined by chan_sip.
11069           *
11070           * Text Destination Port:
11071           *
11072           * 1. Provided by the RTP engine.
11073           */
11074          ast_sockaddr_copy(tdest,
11075                  !ast_sockaddr_isnull(&media_address) ? &media_address  :
11076                  !ast_sockaddr_is_any(taddr) && !use_externip ? taddr   :
11077                  &p->ourip);
11078          ast_sockaddr_set_port(tdest, ast_sockaddr_port(taddr));
11079       }
11080    }
11081 }
11082 
11083 static void get_crypto_attrib(struct sip_srtp *srtp, const char **a_crypto)
11084 {
11085    /* Set encryption properties */
11086    if (srtp) {
11087       if (!srtp->crypto) {
11088          srtp->crypto = sdp_crypto_setup();
11089       }
11090       if (srtp->crypto && (sdp_crypto_offer(srtp->crypto) >= 0)) {
11091          *a_crypto = sdp_crypto_attrib(srtp->crypto);
11092       }
11093 
11094       if (!*a_crypto) {
11095          ast_log(LOG_WARNING, "No SRTP key management enabled\n");
11096       }
11097    }
11098 }
11099 
11100 /*! \brief Add Session Description Protocol message
11101 
11102     If oldsdp is TRUE, then the SDP version number is not incremented. This mechanism
11103     is used in Session-Timers where RE-INVITEs are used for refreshing SIP sessions
11104     without modifying the media session in any way.
11105 */
11106 static enum sip_result add_sdp(struct sip_request *resp, struct sip_pvt *p, int oldsdp, int add_audio, int add_t38)
11107 {
11108    format_t alreadysent = 0;
11109    int doing_directmedia = FALSE;
11110 
11111    struct ast_sockaddr addr = { {0,} };
11112    struct ast_sockaddr vaddr = { {0,} };
11113    struct ast_sockaddr taddr = { {0,} };
11114    struct ast_sockaddr udptladdr = { {0,} };
11115    struct ast_sockaddr dest = { {0,} };
11116    struct ast_sockaddr vdest = { {0,} };
11117    struct ast_sockaddr tdest = { {0,} };
11118    struct ast_sockaddr udptldest = { {0,} };
11119 
11120    /* SDP fields */
11121    char *version =   "v=0\r\n";     /* Protocol version */
11122    char subject[256];            /* Subject of the session */
11123    char owner[256];           /* Session owner/creator */
11124    char connection[256];            /* Connection data */
11125    char *session_time = "t=0 0\r\n";         /* Time the session is active */
11126    char bandwidth[256] = "";        /* Max bitrate */
11127    char *hold = "";
11128    struct ast_str *m_audio = ast_str_alloca(256);  /* Media declaration line for audio */
11129    struct ast_str *m_video = ast_str_alloca(256);  /* Media declaration line for video */
11130    struct ast_str *m_text = ast_str_alloca(256);   /* Media declaration line for text */
11131    struct ast_str *m_modem = ast_str_alloca(256);  /* Media declaration line for modem */
11132    struct ast_str *a_audio = ast_str_alloca(1024); /* Attributes for audio */
11133    struct ast_str *a_video = ast_str_alloca(1024); /* Attributes for video */
11134    struct ast_str *a_text = ast_str_alloca(1024);  /* Attributes for text */
11135    struct ast_str *a_modem = ast_str_alloca(1024); /* Attributes for modem */
11136    const char *a_crypto = NULL;
11137    const char *v_a_crypto = NULL;
11138    const char *t_a_crypto = NULL;
11139 
11140    format_t x;
11141    format_t capability = 0;
11142    int needaudio = FALSE;
11143    int needvideo = FALSE;
11144    int needtext = FALSE;
11145    int debug = sip_debug_test_pvt(p);
11146    int min_audio_packet_size = 0;
11147    int min_video_packet_size = 0;
11148    int min_text_packet_size = 0;
11149 
11150    char codecbuf[SIPBUFSIZE];
11151    char buf[SIPBUFSIZE];
11152    char dummy_answer[256];
11153 
11154    /* Set the SDP session name */
11155    snprintf(subject, sizeof(subject), "s=%s\r\n", ast_strlen_zero(global_sdpsession) ? "-" : global_sdpsession);
11156 
11157    if (!p->rtp) {
11158       ast_log(LOG_WARNING, "No way to add SDP without an RTP structure\n");
11159       return AST_FAILURE;
11160    }
11161    /* XXX We should not change properties in the SIP dialog until
11162       we have acceptance of the offer if this is a re-invite */
11163 
11164    /* Set RTP Session ID and version */
11165    if (!p->sessionid) {
11166       p->sessionid = (int)ast_random();
11167       p->sessionversion = p->sessionid;
11168    } else {
11169       if (oldsdp == FALSE)
11170          p->sessionversion++;
11171    }
11172 
11173    if (add_audio) {
11174       doing_directmedia = (!ast_sockaddr_isnull(&p->redirip) && p->redircodecs) ? TRUE : FALSE;
11175       /* Check if we need video in this call */
11176       if ((p->jointcapability & AST_FORMAT_VIDEO_MASK) && !p->novideo) {
11177          if (doing_directmedia && !(p->jointcapability & AST_FORMAT_VIDEO_MASK & p->redircodecs)) {
11178             ast_debug(2, "This call needs video offers, but caller probably did not offer it!\n");
11179          } else if (p->vrtp) {
11180             needvideo = TRUE;
11181             ast_debug(2, "This call needs video offers!\n");
11182          } else {
11183             ast_debug(2, "This call needs video offers, but there's no video support enabled!\n");
11184          }
11185       }
11186       /* Check if we need text in this call */
11187       if ((p->jointcapability & AST_FORMAT_TEXT_MASK) && !p->notext) {
11188          if (sipdebug_text)
11189             ast_verbose("We think we can do text\n");
11190          if (p->trtp) {
11191             if (sipdebug_text) {
11192                ast_verbose("And we have a text rtp object\n");
11193             }
11194             needtext = TRUE;
11195             ast_debug(2, "This call needs text offers! \n");
11196          } else {
11197             ast_debug(2, "This call needs text offers, but there's no text support enabled ! \n");
11198          }
11199       }
11200    }
11201 
11202    get_our_media_address(p, needvideo, needtext, &addr, &vaddr, &taddr, &dest, &vdest, &tdest);
11203 
11204    snprintf(owner, sizeof(owner), "o=%s %d %d IN %s %s\r\n",
11205        ast_strlen_zero(global_sdpowner) ? "-" : global_sdpowner,
11206        p->sessionid, p->sessionversion,
11207        (ast_sockaddr_is_ipv6(&dest) && !ast_sockaddr_is_ipv4_mapped(&dest)) ?
11208          "IP6" : "IP4",
11209        ast_sockaddr_stringify_addr_remote(&dest));
11210 
11211    snprintf(connection, sizeof(connection), "c=IN %s %s\r\n",
11212        (ast_sockaddr_is_ipv6(&dest) && !ast_sockaddr_is_ipv4_mapped(&dest)) ?
11213          "IP6" : "IP4",
11214        ast_sockaddr_stringify_addr_remote(&dest));
11215 
11216    if (add_audio) {
11217       if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD) == SIP_PAGE2_CALL_ONHOLD_ONEDIR) {
11218          hold = "a=recvonly\r\n";
11219          doing_directmedia = FALSE;
11220       } else if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD) == SIP_PAGE2_CALL_ONHOLD_INACTIVE) {
11221          hold = "a=inactive\r\n";
11222          doing_directmedia = FALSE;
11223       } else {
11224          hold = "a=sendrecv\r\n";
11225       }
11226 
11227       capability = p->jointcapability;
11228 
11229       /* XXX note, Video and Text are negated - 'true' means 'no' */
11230       ast_debug(1, "** Our capability: %s Video flag: %s Text flag: %s\n", ast_getformatname_multiple(codecbuf, sizeof(codecbuf), capability),
11231            p->novideo ? "True" : "False", p->notext ? "True" : "False");
11232       ast_debug(1, "** Our prefcodec: %s \n", ast_getformatname_multiple(codecbuf, sizeof(codecbuf), p->prefcodec));
11233 
11234       if (doing_directmedia) {
11235          capability &= p->redircodecs;
11236          ast_debug(1, "** Our native-bridge filtered capablity: %s\n", ast_getformatname_multiple(codecbuf, sizeof(codecbuf), capability));
11237       }
11238 
11239       /* Check if we need audio */
11240       if (capability & AST_FORMAT_AUDIO_MASK)
11241          needaudio = TRUE;
11242 
11243       if (debug) {
11244          ast_verbose("Audio is at %s\n", ast_sockaddr_stringify_port(&addr));
11245       }
11246 
11247       /* Ok, we need video. Let's add what we need for video and set codecs.
11248          Video is handled differently than audio since we can not transcode. */
11249       if (needvideo) {
11250          get_crypto_attrib(p->vsrtp, &v_a_crypto);
11251          ast_str_append(&m_video, 0, "m=video %d RTP/%s", ast_sockaddr_port(&vdest),
11252             v_a_crypto ? "SAVP" : "AVP");
11253 
11254          /* Build max bitrate string */
11255          if (p->maxcallbitrate)
11256             snprintf(bandwidth, sizeof(bandwidth), "b=CT:%d\r\n", p->maxcallbitrate);
11257          if (debug) {
11258             ast_verbose("Video is at %s\n", ast_sockaddr_stringify(&vdest));
11259          }
11260       }
11261 
11262       /* Ok, we need text. Let's add what we need for text and set codecs.
11263          Text is handled differently than audio since we can not transcode. */
11264       if (needtext) {
11265          if (sipdebug_text)
11266             ast_verbose("Lets set up the text sdp\n");
11267          get_crypto_attrib(p->tsrtp, &t_a_crypto);
11268          ast_str_append(&m_text, 0, "m=text %d RTP/%s", ast_sockaddr_port(&tdest),
11269             t_a_crypto ? "SAVP" : "AVP");
11270          if (debug) {  /* XXX should I use tdest below ? */
11271             ast_verbose("Text is at %s\n", ast_sockaddr_stringify(&taddr));
11272          }
11273       }
11274 
11275       /* Start building generic SDP headers */
11276 
11277       /* We break with the "recommendation" and send our IP, in order that our
11278          peer doesn't have to ast_gethostbyname() us */
11279 
11280       get_crypto_attrib(p->srtp, &a_crypto);
11281       ast_str_append(&m_audio, 0, "m=audio %d RTP/%s", ast_sockaddr_port(&dest),
11282          a_crypto ? "SAVP" : "AVP");
11283 
11284       /* Now, start adding audio codecs. These are added in this order:
11285          - First what was requested by the calling channel
11286          - Then preferences in order from sip.conf device config for this peer/user
11287          - Then other codecs in capabilities, including video
11288       */
11289 
11290       /* Prefer the audio codec we were requested to use, first, no matter what
11291          Note that p->prefcodec can include video codecs, so mask them out
11292       */
11293       if (capability & p->prefcodec) {
11294          format_t codec = p->prefcodec & AST_FORMAT_AUDIO_MASK;
11295 
11296          add_codec_to_sdp(p, codec, &m_audio, &a_audio, debug, &min_audio_packet_size);
11297          alreadysent |= codec;
11298       }
11299 
11300       /* Start by sending our preferred audio/video codecs */
11301       for (x = 0; x < 64; x++) {
11302          format_t codec;
11303 
11304          if (!(codec = ast_codec_pref_index(&p->prefs, x)))
11305             break;
11306 
11307          if (!(capability & codec))
11308             continue;
11309 
11310          if (alreadysent & codec)
11311             continue;
11312 
11313          add_codec_to_sdp(p, codec, &m_audio, &a_audio, debug, &min_audio_packet_size);
11314          alreadysent |= codec;
11315       }
11316 
11317       /* Now send any other common audio and video codecs, and non-codec formats: */
11318       for (x = 1ULL; x <= (needtext ? AST_FORMAT_TEXT_MASK : (needvideo ? AST_FORMAT_VIDEO_MASK : AST_FORMAT_AUDIO_MASK)); x <<= 1) {
11319          if (!(capability & x))  /* Codec not requested */
11320             continue;
11321 
11322          if (alreadysent & x) /* Already added to SDP */
11323             continue;
11324 
11325          if (x & AST_FORMAT_AUDIO_MASK)
11326             add_codec_to_sdp(p, x, &m_audio, &a_audio, debug, &min_audio_packet_size);
11327          else if (x & AST_FORMAT_VIDEO_MASK)
11328             add_vcodec_to_sdp(p, x, &m_video, &a_video, debug, &min_video_packet_size);
11329          else if (x & AST_FORMAT_TEXT_MASK)
11330             add_tcodec_to_sdp(p, x, &m_text, &a_text, debug, &min_text_packet_size);
11331       }
11332 
11333       /* Now add DTMF RFC2833 telephony-event as a codec */
11334       for (x = 1LL; x <= AST_RTP_MAX; x <<= 1) {
11335          if (!(p->jointnoncodeccapability & x))
11336             continue;
11337 
11338          add_noncodec_to_sdp(p, x, &m_audio, &a_audio, debug);
11339       }
11340 
11341       ast_debug(3, "-- Done with adding codecs to SDP\n");
11342 
11343       if (!p->owner || !ast_internal_timing_enabled(p->owner))
11344          ast_str_append(&a_audio, 0, "a=silenceSupp:off - - - -\r\n");
11345 
11346       if (min_audio_packet_size)
11347          ast_str_append(&a_audio, 0, "a=ptime:%d\r\n", min_audio_packet_size);
11348 
11349       /* XXX don't think you can have ptime for video */
11350       if (min_video_packet_size)
11351          ast_str_append(&a_video, 0, "a=ptime:%d\r\n", min_video_packet_size);
11352 
11353       /* XXX don't think you can have ptime for text */
11354       if (min_text_packet_size)
11355          ast_str_append(&a_text, 0, "a=ptime:%d\r\n", min_text_packet_size);
11356 
11357       if (m_audio->len - m_audio->used < 2 || m_video->len - m_video->used < 2 ||
11358           m_text->len - m_text->used < 2 || a_text->len - a_text->used < 2 ||
11359           a_audio->len - a_audio->used < 2 || a_video->len - a_video->used < 2)
11360          ast_log(LOG_WARNING, "SIP SDP may be truncated due to undersized buffer!!\n");
11361    }
11362 
11363    if (add_t38) {
11364       /* Our T.38 end is */
11365       ast_udptl_get_us(p->udptl, &udptladdr);
11366 
11367       /* Determine T.38 UDPTL destination */
11368       if (!ast_sockaddr_isnull(&p->udptlredirip)) {
11369          ast_sockaddr_copy(&udptldest, &p->udptlredirip);
11370       } else {
11371          ast_sockaddr_copy(&udptldest, &p->ourip);
11372          ast_sockaddr_set_port(&udptldest, ast_sockaddr_port(&udptladdr));
11373       }
11374 
11375       if (debug) {
11376          ast_debug(1, "T.38 UDPTL is at %s port %d\n", ast_sockaddr_stringify_addr(&p->ourip), ast_sockaddr_port(&udptladdr));
11377       }
11378 
11379       /* We break with the "recommendation" and send our IP, in order that our
11380          peer doesn't have to ast_gethostbyname() us */
11381 
11382       ast_str_append(&m_modem, 0, "m=image %d udptl t38\r\n", ast_sockaddr_port(&udptldest));
11383 
11384       if (!ast_sockaddr_cmp(&udptldest, &dest)) {
11385          ast_str_append(&m_modem, 0, "c=IN %s %s\r\n",
11386                (ast_sockaddr_is_ipv6(&dest) && !ast_sockaddr_is_ipv4_mapped(&dest)) ?
11387                "IP6" : "IP4", ast_sockaddr_stringify_addr_remote(&udptldest));
11388       }
11389 
11390       ast_str_append(&a_modem, 0, "a=T38FaxVersion:%d\r\n", p->t38.our_parms.version);
11391       ast_str_append(&a_modem, 0, "a=T38MaxBitRate:%d\r\n", t38_get_rate(p->t38.our_parms.rate));
11392       if (p->t38.our_parms.fill_bit_removal) {
11393          ast_str_append(&a_modem, 0, "a=T38FaxFillBitRemoval\r\n");
11394       }
11395       if (p->t38.our_parms.transcoding_mmr) {
11396          ast_str_append(&a_modem, 0, "a=T38FaxTranscodingMMR\r\n");
11397       }
11398       if (p->t38.our_parms.transcoding_jbig) {
11399          ast_str_append(&a_modem, 0, "a=T38FaxTranscodingJBIG\r\n");
11400       }
11401       switch (p->t38.our_parms.rate_management) {
11402       case AST_T38_RATE_MANAGEMENT_TRANSFERRED_TCF:
11403          ast_str_append(&a_modem, 0, "a=T38FaxRateManagement:transferredTCF\r\n");
11404          break;
11405       case AST_T38_RATE_MANAGEMENT_LOCAL_TCF:
11406          ast_str_append(&a_modem, 0, "a=T38FaxRateManagement:localTCF\r\n");
11407          break;
11408       }
11409       ast_str_append(&a_modem, 0, "a=T38FaxMaxDatagram:%u\r\n", ast_udptl_get_local_max_datagram(p->udptl));
11410       switch (ast_udptl_get_error_correction_scheme(p->udptl)) {
11411       case UDPTL_ERROR_CORRECTION_NONE:
11412          break;
11413       case UDPTL_ERROR_CORRECTION_FEC:
11414          ast_str_append(&a_modem, 0, "a=T38FaxUdpEC:t38UDPFEC\r\n");
11415          break;
11416       case UDPTL_ERROR_CORRECTION_REDUNDANCY:
11417          ast_str_append(&a_modem, 0, "a=T38FaxUdpEC:t38UDPRedundancy\r\n");
11418          break;
11419       }
11420    }
11421 
11422    if (needaudio)
11423       ast_str_append(&m_audio, 0, "\r\n");
11424    if (needvideo)
11425       ast_str_append(&m_video, 0, "\r\n");
11426    if (needtext)
11427       ast_str_append(&m_text, 0, "\r\n");
11428 
11429    add_header(resp, "Content-Type", "application/sdp");
11430    add_content(resp, version);
11431    add_content(resp, owner);
11432    add_content(resp, subject);
11433    add_content(resp, connection);
11434    /* only if video response is appropriate */
11435    if (needvideo) {
11436       add_content(resp, bandwidth);
11437    }
11438    add_content(resp, session_time);
11439    /* if this is a response to an invite, order our offers properly */
11440    if (p->offered_media[SDP_AUDIO].order_offered ||
11441       p->offered_media[SDP_VIDEO].order_offered ||
11442       p->offered_media[SDP_TEXT].order_offered ||
11443       p->offered_media[SDP_IMAGE].order_offered) {
11444       int i;
11445       /* we have up to 3 streams as limited by process_sdp */
11446       for (i = 1; i <= 3; i++) {
11447          if (p->offered_media[SDP_AUDIO].order_offered == i) {
11448             if (needaudio) {
11449                add_content(resp, m_audio->str);
11450                add_content(resp, a_audio->str);
11451                add_content(resp, hold);
11452                if (a_crypto) {
11453                   add_content(resp, a_crypto);
11454                }
11455             } else {
11456                snprintf(dummy_answer, sizeof(dummy_answer), "m=audio 0 RTP/AVP %s\r\n", p->offered_media[SDP_AUDIO].codecs);
11457                add_content(resp, dummy_answer);
11458             }
11459          } else if (p->offered_media[SDP_VIDEO].order_offered == i) {
11460             if (needvideo) { /* only if video response is appropriate */
11461                add_content(resp, m_video->str);
11462                add_content(resp, a_video->str);
11463                add_content(resp, hold);   /* Repeat hold for the video stream */
11464                if (v_a_crypto) {
11465                   add_content(resp, v_a_crypto);
11466                }
11467             } else {
11468                snprintf(dummy_answer, sizeof(dummy_answer), "m=video 0 RTP/AVP %s\r\n", p->offered_media[SDP_VIDEO].codecs);
11469                add_content(resp, dummy_answer);
11470             }
11471          } else if (p->offered_media[SDP_TEXT].order_offered == i) {
11472             if (needtext) { /* only if text response is appropriate */
11473                add_content(resp, m_text->str);
11474                add_content(resp, a_text->str);
11475                add_content(resp, hold);   /* Repeat hold for the text stream */
11476                if (t_a_crypto) {
11477                   add_content(resp, t_a_crypto);
11478                }
11479             } else {
11480                snprintf(dummy_answer, sizeof(dummy_answer), "m=text 0 RTP/AVP %s\r\n", p->offered_media[SDP_TEXT].codecs);
11481                add_content(resp, dummy_answer);
11482             }
11483          } else if (p->offered_media[SDP_IMAGE].order_offered == i) {
11484             if (add_t38) {
11485                add_content(resp, m_modem->str);
11486                add_content(resp, a_modem->str);
11487             } else {
11488                add_content(resp, "m=image 0 udptl t38\r\n");
11489             }
11490          }
11491       }
11492    } else {
11493       /* generate new SDP from scratch, no offers */
11494       if (needaudio) {
11495          add_content(resp, m_audio->str);
11496          add_content(resp, a_audio->str);
11497          add_content(resp, hold);
11498          if (a_crypto) {
11499             add_content(resp, a_crypto);
11500          }
11501       }
11502       if (needvideo) { /* only if video response is appropriate */
11503          add_content(resp, m_video->str);
11504          add_content(resp, a_video->str);
11505          add_content(resp, hold);   /* Repeat hold for the video stream */
11506          if (v_a_crypto) {
11507             add_content(resp, v_a_crypto);
11508          }
11509       }
11510       if (needtext) { /* only if text response is appropriate */
11511          add_content(resp, m_text->str);
11512          add_content(resp, a_text->str);
11513          add_content(resp, hold);   /* Repeat hold for the text stream */
11514          if (t_a_crypto) {
11515             add_content(resp, t_a_crypto);
11516          }
11517       }
11518       if (add_t38) {
11519          add_content(resp, m_modem->str);
11520          add_content(resp, a_modem->str);
11521       }
11522    }
11523 
11524    /* Update lastrtprx when we send our SDP */
11525    p->lastrtprx = p->lastrtptx = time(NULL); /* XXX why both ? */
11526 
11527    ast_debug(3, "Done building SDP. Settling with this capability: %s\n", ast_getformatname_multiple(buf, SIPBUFSIZE, capability));
11528 
11529    return AST_SUCCESS;
11530 }
11531 
11532 /*! \brief Used for 200 OK and 183 early media */
11533 static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans)
11534 {
11535    struct sip_request resp;
11536    int seqno;
11537    
11538    if (sscanf(get_header(req, "CSeq"), "%30d ", &seqno) != 1) {
11539       ast_log(LOG_WARNING, "Unable to get seqno from '%s'\n", get_header(req, "CSeq"));
11540       return -1;
11541    }
11542    respprep(&resp, p, msg, req);
11543    if (p->udptl) {
11544       add_sdp(&resp, p, 0, 0, 1);
11545    } else
11546       ast_log(LOG_ERROR, "Can't add SDP to response, since we have no UDPTL session allocated. Call-ID %s\n", p->callid);
11547    if (retrans && !p->pendinginvite)
11548       p->pendinginvite = seqno;     /* Buggy clients sends ACK on RINGING too */
11549    return send_response(p, &resp, retrans, seqno);
11550 }
11551 
11552 /*! \brief copy SIP request (mostly used to save request for responses) */
11553 static void copy_request(struct sip_request *dst, const struct sip_request *src)
11554 {
11555    /* XXX this function can encounter memory allocation errors, perhaps it
11556     * should return a value */
11557 
11558    struct ast_str *duplicate = dst->data;
11559    struct ast_str *duplicate_content = dst->content;
11560 
11561    /* copy the entire request then restore the original data and content
11562     * members from the dst request */
11563    memcpy(dst, src, sizeof(*dst));
11564    dst->data = duplicate;
11565    dst->content = duplicate_content;
11566 
11567    /* copy the data into the dst request */
11568    if (!dst->data && !(dst->data = ast_str_create(ast_str_strlen(src->data) + 1)))
11569       return;
11570    ast_str_copy_string(&dst->data, src->data);
11571 
11572    /* copy the content into the dst request (if it exists) */
11573    if (src->content) {
11574       if (!dst->content && !(dst->content = ast_str_create(ast_str_strlen(src->content) + 1)))
11575          return;
11576       ast_str_copy_string(&dst->content, src->content);
11577    }
11578 }
11579 
11580 static void add_cc_call_info_to_response(struct sip_pvt *p, struct sip_request *resp)
11581 {
11582    char uri[SIPBUFSIZE];
11583    struct ast_str *header = ast_str_alloca(SIPBUFSIZE);
11584    struct ast_cc_agent *agent = find_sip_cc_agent_by_original_callid(p);
11585    struct sip_cc_agent_pvt *agent_pvt;
11586 
11587    if (!agent) {
11588       /* Um, what? How could the SIP_OFFER_CC flag be set but there not be an
11589        * agent? Oh well, we'll just warn and return without adding the header.
11590        */
11591       ast_log(LOG_WARNING, "Can't find SIP CC agent for call '%s' even though OFFER_CC flag was set?\n", p->callid);
11592       return;
11593    }
11594 
11595    agent_pvt = agent->private_data;
11596 
11597    if (!ast_strlen_zero(agent_pvt->subscribe_uri)) {
11598       ast_copy_string(uri, agent_pvt->subscribe_uri, sizeof(uri));
11599    } else {
11600       generate_uri(p, uri, sizeof(uri));
11601       ast_copy_string(agent_pvt->subscribe_uri, uri, sizeof(agent_pvt->subscribe_uri));
11602    }
11603    /* XXX Hardcode "NR" as the m reason for now. This should perhaps be changed
11604     * to be more accurate. This parameter has no bearing on the actual operation
11605     * of the feature; it's just there for informational purposes.
11606     */
11607    ast_str_set(&header, 0, "<%s>;purpose=call-completion;m=%s", uri, "NR");
11608    add_header(resp, "Call-Info", ast_str_buffer(header));
11609    ao2_ref(agent, -1);
11610 }
11611 
11612 /*! \brief Used for 200 OK and 183 early media
11613    \return Will return XMIT_ERROR for network errors.
11614 */
11615 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)
11616 {
11617    struct sip_request resp;
11618    int seqno;
11619    if (sscanf(get_header(req, "CSeq"), "%30d ", &seqno) != 1) {
11620       ast_log(LOG_WARNING, "Unable to get seqno from '%s'\n", get_header(req, "CSeq"));
11621       return -1;
11622    }
11623    respprep(&resp, p, msg, req);
11624    if (rpid == TRUE) {
11625       add_rpid(&resp, p);
11626    }
11627    if (ast_test_flag(&p->flags[0], SIP_OFFER_CC)) {
11628       add_cc_call_info_to_response(p, &resp);
11629    }
11630    if (p->rtp) {
11631       if (!p->autoframing && !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
11632          ast_debug(1, "Setting framing from config on incoming call\n");
11633          ast_rtp_codecs_packetization_set(ast_rtp_instance_get_codecs(p->rtp), p->rtp, &p->prefs);
11634       }
11635       ast_rtp_instance_activate(p->rtp);
11636       try_suggested_sip_codec(p);
11637       if (p->t38.state == T38_ENABLED) {
11638          add_sdp(&resp, p, oldsdp, TRUE, TRUE);
11639       } else {
11640          add_sdp(&resp, p, oldsdp, TRUE, FALSE);
11641       }
11642    } else
11643       ast_log(LOG_ERROR, "Can't add SDP to response, since we have no RTP session allocated. Call-ID %s\n", p->callid);
11644    if (reliable && !p->pendinginvite)
11645       p->pendinginvite = seqno;     /* Buggy clients sends ACK on RINGING too */
11646    return send_response(p, &resp, reliable, seqno);
11647 }
11648 
11649 /*! \brief Parse first line of incoming SIP request */
11650 static int determine_firstline_parts(struct sip_request *req)
11651 {
11652    char *e = ast_skip_blanks(req->data->str);   /* there shouldn't be any */
11653    char *local_rlPart1;
11654 
11655    if (!*e)
11656       return -1;
11657    req->rlPart1 = e - req->data->str;  /* method or protocol */
11658    local_rlPart1 = e;
11659    e = ast_skip_nonblanks(e);
11660    if (*e)
11661       *e++ = '\0';
11662    /* Get URI or status code */
11663    e = ast_skip_blanks(e);
11664    if ( !*e )
11665       return -1;
11666    ast_trim_blanks(e);
11667 
11668    if (!strcasecmp(local_rlPart1, "SIP/2.0") ) { /* We have a response */
11669       if (strlen(e) < 3)   /* status code is 3 digits */
11670          return -1;
11671       req->rlPart2 = e - req->data->str;
11672    } else { /* We have a request */
11673       if ( *e == '<' ) { /* XXX the spec says it must not be in <> ! */
11674          ast_debug(3, "Oops. Bogus uri in <> %s\n", e);
11675          e++;
11676          if (!*e)
11677             return -1;
11678       }
11679       req->rlPart2 = e - req->data->str;  /* URI */
11680       e = ast_skip_nonblanks(e);
11681       if (*e)
11682          *e++ = '\0';
11683       e = ast_skip_blanks(e);
11684       if (strcasecmp(e, "SIP/2.0") ) {
11685          ast_debug(3, "Skipping packet - Bad request protocol %s\n", e);
11686          return -1;
11687       }
11688    }
11689    return 1;
11690 }
11691 
11692 /*! \brief Transmit reinvite with SDP
11693 \note    A re-invite is basically a new INVITE with the same CALL-ID and TAG as the
11694    INVITE that opened the SIP dialogue
11695    We reinvite so that the audio stream (RTP) go directly between
11696    the SIP UAs. SIP Signalling stays with * in the path.
11697    
11698    If t38version is TRUE, we send T38 SDP for re-invite from audio/video to
11699    T38 UDPTL transmission on the channel
11700 
11701     If oldsdp is TRUE then the SDP version number is not incremented. This
11702     is needed for Session-Timers so we can send a re-invite to refresh the
11703     SIP session without modifying the media session.
11704 */
11705 static int transmit_reinvite_with_sdp(struct sip_pvt *p, int t38version, int oldsdp)
11706 {
11707    struct sip_request req;
11708    
11709    reqprep(&req, p, ast_test_flag(&p->flags[0], SIP_REINVITE_UPDATE) ?  SIP_UPDATE : SIP_INVITE, 0, 1);
11710 
11711    add_header(&req, "Allow", ALLOWED_METHODS);
11712    add_supported_header(p, &req);
11713    if (sipdebug) {
11714       if (oldsdp == TRUE)
11715          add_header(&req, "X-asterisk-Info", "SIP re-invite (Session-Timers)");
11716       else
11717          add_header(&req, "X-asterisk-Info", "SIP re-invite (External RTP bridge)");
11718    }
11719 
11720    if (ast_test_flag(&p->flags[0], SIP_SENDRPID))
11721       add_rpid(&req, p);
11722 
11723    if (p->do_history) {
11724       append_history(p, "ReInv", "Re-invite sent");
11725    }
11726    memset(p->offered_media, 0, sizeof(p->offered_media));
11727 
11728    try_suggested_sip_codec(p);
11729    if (t38version) {
11730       add_sdp(&req, p, oldsdp, FALSE, TRUE);
11731    } else {
11732       add_sdp(&req, p, oldsdp, TRUE, FALSE);
11733    }
11734 
11735    /* Use this as the basis */
11736    initialize_initreq(p, &req);
11737    p->lastinvite = p->ocseq;
11738    ast_set_flag(&p->flags[0], SIP_OUTGOING);       /* Change direction of this dialog */
11739 
11740    return send_request(p, &req, XMIT_CRITICAL, p->ocseq);
11741 }
11742 
11743 /* \brief Remove URI parameters at end of URI, not in username part though */
11744 static char *remove_uri_parameters(char *uri)
11745 {
11746    char *atsign;
11747    atsign = strchr(uri, '@'); /* First, locate the at sign */
11748    if (!atsign) {
11749       atsign = uri;  /* Ok hostname only, let's stick with the rest */
11750    }
11751    atsign = strchr(atsign, ';'); /* Locate semi colon */
11752    if (atsign)
11753       *atsign = '\0';   /* Kill at the semi colon */
11754    return uri;
11755 }
11756 
11757 /*! \brief Check Contact: URI of SIP message */
11758 static void extract_uri(struct sip_pvt *p, struct sip_request *req)
11759 {
11760    char stripped[SIPBUFSIZE];
11761    char *c;
11762 
11763    ast_copy_string(stripped, get_header(req, "Contact"), sizeof(stripped));
11764    c = get_in_brackets(stripped);
11765    /* Cut the URI at the at sign after the @, not in the username part */
11766    c = remove_uri_parameters(c);
11767    if (!ast_strlen_zero(c)) {
11768       ast_string_field_set(p, uri, c);
11769    }
11770 
11771 }
11772 
11773 /*! \brief Build contact header - the contact header we send out */
11774 static void build_contact(struct sip_pvt *p)
11775 {
11776    char tmp[SIPBUFSIZE];
11777    char *user = ast_uri_encode(p->exten, tmp, sizeof(tmp), 0);
11778 
11779    if (p->socket.type == SIP_TRANSPORT_UDP) {
11780       ast_string_field_build(p, our_contact, "<sip:%s%s%s>", user,
11781          ast_strlen_zero(user) ? "" : "@", ast_sockaddr_stringify_remote(&p->ourip));
11782    } else {
11783       ast_string_field_build(p, our_contact, "<sip:%s%s%s;transport=%s>", user,
11784          ast_strlen_zero(user) ? "" : "@", ast_sockaddr_stringify_remote(&p->ourip),
11785          get_transport(p->socket.type));
11786    }
11787 }
11788 
11789 /*! \brief Initiate new SIP request to peer/user */
11790 static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, const char * const explicit_uri)
11791 {
11792    struct ast_str *invite = ast_str_alloca(256);
11793    char from[256];
11794    char to[256];
11795    char tmp_n[SIPBUFSIZE/2];  /* build a local copy of 'n' if needed */
11796    char tmp_l[SIPBUFSIZE/2];  /* build a local copy of 'l' if needed */
11797    const char *l = NULL;   /* XXX what is this, exactly ? */
11798    const char *n = NULL;   /* XXX what is this, exactly ? */
11799    const char *d = NULL;   /* domain in from header */
11800    const char *urioptions = "";
11801    int ourport;
11802 
11803    if (ast_test_flag(&p->flags[0], SIP_USEREQPHONE)) {
11804       const char *s = p->username;  /* being a string field, cannot be NULL */
11805 
11806       /* Test p->username against allowed characters in AST_DIGIT_ANY
11807          If it matches the allowed characters list, then sipuser = ";user=phone"
11808          If not, then sipuser = ""
11809       */
11810       /* + is allowed in first position in a tel: uri */
11811       if (*s == '+')
11812          s++;
11813       for (; *s; s++) {
11814          if (!strchr(AST_DIGIT_ANYNUM, *s) )
11815             break;
11816       }
11817       /* If we have only digits, add ;user=phone to the uri */
11818       if (!*s)
11819          urioptions = ";user=phone";
11820    }
11821 
11822 
11823    snprintf(p->lastmsg, sizeof(p->lastmsg), "Init: %s", sip_methods[sipmethod].text);
11824 
11825    d = S_OR(p->fromdomain, ast_sockaddr_stringify_host_remote(&p->ourip));
11826    if (p->owner) {
11827       if ((ast_party_id_presentation(&p->owner->connected.id) & AST_PRES_RESTRICTION) == AST_PRES_ALLOWED) {
11828          l = p->owner->connected.id.number.valid ? p->owner->connected.id.number.str : NULL;
11829          n = p->owner->connected.id.name.valid ? p->owner->connected.id.name.str : NULL;
11830       } else if (!ast_test_flag(&p->flags[0], SIP_SENDRPID)) {
11831          /* if we are not sending RPID and user wants his callerid restricted */    
11832          l = CALLERID_UNKNOWN;
11833          n = l;
11834          d = FROMDOMAIN_INVALID;
11835       }
11836    }
11837 
11838    /* Hey, it's a NOTIFY! See if they've configured a mwi_from.
11839     * XXX Right now, this logic works because the only place that mwi_from
11840     * is set on the sip_pvt is in sip_send_mwi_to_peer. If things changed, then
11841     * we might end up putting the mwi_from setting into other types of NOTIFY
11842     * messages as well.
11843     */
11844    if (sipmethod == SIP_NOTIFY && !ast_strlen_zero(p->mwi_from)) {
11845       l = p->mwi_from;
11846    }
11847 
11848    if (ast_strlen_zero(l))
11849       l = default_callerid;
11850    if (ast_strlen_zero(n))
11851       n = l;
11852    /* Allow user to be overridden */
11853    if (!ast_strlen_zero(p->fromuser))
11854       l = p->fromuser;
11855    else /* Save for any further attempts */
11856       ast_string_field_set(p, fromuser, l);
11857 
11858    /* Allow user to be overridden */
11859    if (!ast_strlen_zero(p->fromname))
11860       n = p->fromname;
11861    else /* Save for any further attempts */
11862       ast_string_field_set(p, fromname, n);
11863 
11864    if (sip_cfg.pedanticsipchecking) {
11865       ast_escape_quoted(n, tmp_n, sizeof(tmp_n));
11866       n = tmp_n;
11867       ast_uri_encode(l, tmp_l, sizeof(tmp_l), 0);
11868       l = tmp_l;
11869    }
11870 
11871    ourport = (p->fromdomainport) ? p->fromdomainport : ast_sockaddr_port(&p->ourip);
11872    if (!sip_standard_port(p->socket.type, ourport)) {
11873       snprintf(from, sizeof(from), "\"%s\" <sip:%s@%s:%d>;tag=%s", n, l, d, ourport, p->tag);
11874    } else {
11875       snprintf(from, sizeof(from), "\"%s\" <sip:%s@%s>;tag=%s", n, l, d, p->tag);
11876    }
11877 
11878    if (!ast_strlen_zero(explicit_uri)) {
11879       ast_str_set(&invite, 0, "%s", explicit_uri);
11880    } else {
11881       /* If we're calling a registered SIP peer, use the fullcontact to dial to the peer */
11882       if (!ast_strlen_zero(p->fullcontact)) {
11883          /* If we have full contact, trust it */
11884          ast_str_append(&invite, 0, "%s", p->fullcontact);
11885       } else {
11886          /* Otherwise, use the username while waiting for registration */
11887          ast_str_append(&invite, 0, "sip:");
11888          if (!ast_strlen_zero(p->username)) {
11889             n = p->username;
11890             if (sip_cfg.pedanticsipchecking) {
11891                ast_uri_encode(n, tmp_n, sizeof(tmp_n), 0);
11892                n = tmp_n;
11893             }
11894             ast_str_append(&invite, 0, "%s@", n);
11895          }
11896          ast_str_append(&invite, 0, "%s", p->tohost);
11897          if (p->portinuri) {
11898             ast_str_append(&invite, 0, ":%d", ast_sockaddr_port(&p->sa));
11899          }
11900          ast_str_append(&invite, 0, "%s", urioptions);
11901       }
11902    }
11903 
11904    /* If custom URI options have been provided, append them */
11905    if (p->options && !ast_strlen_zero(p->options->uri_options))
11906       ast_str_append(&invite, 0, ";%s", p->options->uri_options);
11907    
11908    /* This is the request URI, which is the next hop of the call
11909       which may or may not be the destination of the call
11910    */
11911    ast_string_field_set(p, uri, invite->str);
11912 
11913    if (!ast_strlen_zero(p->todnid)) {
11914       /*! \todo Need to add back the VXML URL here at some point, possibly use build_string for all this junk */
11915       if (!strchr(p->todnid, '@')) {
11916          /* We have no domain in the dnid */
11917          snprintf(to, sizeof(to), "<sip:%s@%s>%s%s", p->todnid, p->tohost, ast_strlen_zero(p->theirtag) ? "" : ";tag=", p->theirtag);
11918       } else {
11919          snprintf(to, sizeof(to), "<sip:%s>%s%s", p->todnid, ast_strlen_zero(p->theirtag) ? "" : ";tag=", p->theirtag);
11920       }
11921    } else {
11922       if (sipmethod == SIP_NOTIFY && !ast_strlen_zero(p->theirtag)) {
11923          /* If this is a NOTIFY, use the From: tag in the subscribe (RFC 3265) */
11924          snprintf(to, sizeof(to), "<%s%s>;tag=%s", (strncasecmp(p->uri, "sip:", 4) ? "sip:" : ""), p->uri, p->theirtag);
11925       } else if (p->options && p->options->vxml_url) {
11926          /* If there is a VXML URL append it to the SIP URL */
11927          snprintf(to, sizeof(to), "<%s>;%s", p->uri, p->options->vxml_url);
11928       } else {
11929          snprintf(to, sizeof(to), "<%s>", p->uri);
11930       }
11931    }
11932 
11933    init_req(req, sipmethod, p->uri);
11934    /* now tmp_n is available so reuse it to build the CSeq */
11935    snprintf(tmp_n, sizeof(tmp_n), "%d %s", ++p->ocseq, sip_methods[sipmethod].text);
11936 
11937    add_header(req, "Via", p->via);
11938    add_header_max_forwards(p, req);
11939    /* This will be a no-op most of the time. However, under certain circumstances,
11940     * NOTIFY messages will use this function for preparing the request and should
11941     * have Route headers present.
11942     */
11943    add_route(req, p->route);
11944 
11945    add_header(req, "From", from);
11946    add_header(req, "To", to);
11947    ast_string_field_set(p, exten, l);
11948    build_contact(p);
11949    add_header(req, "Contact", p->our_contact);
11950    add_header(req, "Call-ID", p->callid);
11951    add_header(req, "CSeq", tmp_n);
11952    if (!ast_strlen_zero(global_useragent)) {
11953       add_header(req, "User-Agent", global_useragent);
11954    }
11955 }
11956 
11957 /*! \brief Add "Diversion" header to outgoing message
11958  *
11959  * We need to add a Diversion header if the owner channel of
11960  * this dialog has redirecting information associated with it.
11961  *
11962  * \param req The request/response to which we will add the header
11963  * \param pvt The sip_pvt which represents the call-leg
11964  */
11965 static void add_diversion_header(struct sip_request *req, struct sip_pvt *pvt)
11966 {
11967    const char *diverting_number;
11968    const char *diverting_name;
11969    const char *reason;
11970    char header_text[256];
11971 
11972    if (!pvt->owner) {
11973       return;
11974    }
11975 
11976    diverting_number = pvt->owner->redirecting.from.number.str;
11977    if (!pvt->owner->redirecting.from.number.valid
11978       || ast_strlen_zero(diverting_number)) {
11979       return;
11980    }
11981 
11982    reason = sip_reason_code_to_str(pvt->owner->redirecting.reason);
11983 
11984    /* We at least have a number to place in the Diversion header, which is enough */
11985    diverting_name = pvt->owner->redirecting.from.name.str;
11986    if (!pvt->owner->redirecting.from.name.valid
11987       || ast_strlen_zero(diverting_name)) {
11988       snprintf(header_text, sizeof(header_text), "<sip:%s@%s>;reason=%s", diverting_number,
11989             ast_sockaddr_stringify_host_remote(&pvt->ourip), reason);
11990    } else {
11991       snprintf(header_text, sizeof(header_text), "\"%s\" <sip:%s@%s>;reason=%s",
11992             diverting_name, diverting_number,
11993             ast_sockaddr_stringify_host_remote(&pvt->ourip), reason);
11994    }
11995 
11996    add_header(req, "Diversion", header_text);
11997 }
11998 
11999 static int transmit_publish(struct sip_epa_entry *epa_entry, enum sip_publish_type publish_type, const char * const explicit_uri)
12000 {
12001    struct sip_pvt *pvt;
12002    int expires;
12003 
12004    epa_entry->publish_type = publish_type;
12005 
12006    if (!(pvt = sip_alloc(NULL, NULL, 0, SIP_PUBLISH, NULL))) {
12007       return -1;
12008    }
12009 
12010    sip_pvt_lock(pvt);
12011 
12012    if (create_addr(pvt, epa_entry->destination, NULL, TRUE, NULL)) {
12013       sip_pvt_unlock(pvt);
12014       dialog_unlink_all(pvt);
12015       dialog_unref(pvt, "create_addr failed in transmit_publish. Unref dialog");
12016       return -1;
12017    }
12018    ast_sip_ouraddrfor(&pvt->sa, &pvt->ourip, pvt);
12019    ast_set_flag(&pvt->flags[0], SIP_OUTGOING);
12020    expires = (publish_type == SIP_PUBLISH_REMOVE) ? 0 : DEFAULT_PUBLISH_EXPIRES;
12021    pvt->expiry = expires;
12022 
12023    /* Bump refcount for sip_pvt's reference */
12024    ao2_ref(epa_entry, +1);
12025    pvt->epa_entry = epa_entry;
12026 
12027    transmit_invite(pvt, SIP_PUBLISH, FALSE, 2, explicit_uri);
12028    sip_pvt_unlock(pvt);
12029    sip_scheddestroy(pvt, DEFAULT_TRANS_TIMEOUT);
12030    dialog_unref(pvt, "Done with the sip_pvt allocated for transmitting PUBLISH");
12031    return 0;
12032 }
12033 
12034 /*! 
12035  * \brief Build REFER/INVITE/OPTIONS/SUBSCRIBE message and transmit it
12036  * \param p sip_pvt structure
12037  * \param sipmethod
12038  * \param sdp unknown
12039  * \param init 0 = Prepare request within dialog, 1= prepare request, new branch,
12040  *  2= prepare new request and new dialog. do_proxy_auth calls this with init!=2
12041  * \param explicit_uri
12042 */
12043 static int transmit_invite(struct sip_pvt *p, int sipmethod, int sdp, int init, const char * const explicit_uri)
12044 {
12045    struct sip_request req;
12046    struct ast_variable *var;
12047    
12048    req.method = sipmethod;
12049    if (init) {/* Bump branch even on initial requests */
12050       p->branch ^= ast_random();
12051       p->invite_branch = p->branch;
12052       build_via(p);
12053    }
12054    if (init > 1) {
12055       initreqprep(&req, p, sipmethod, explicit_uri);
12056    } else {
12057       /* If init=1, we should not generate a new branch. If it's 0, we need a new branch. */
12058       reqprep(&req, p, sipmethod, 0, init ? 0 : 1);
12059    }
12060       
12061    if (p->options && p->options->auth) {
12062       add_header(&req, p->options->authheader, p->options->auth);
12063    }
12064    append_date(&req);
12065    if (sipmethod == SIP_REFER) { /* Call transfer */
12066       if (p->refer) {
12067          char buf[SIPBUFSIZE];
12068          if (!ast_strlen_zero(p->refer->refer_to)) {
12069             add_header(&req, "Refer-To", p->refer->refer_to);
12070          }
12071          if (!ast_strlen_zero(p->refer->referred_by)) {
12072             snprintf(buf, sizeof(buf), "%s <%s>", p->refer->referred_by_name, p->refer->referred_by);
12073             add_header(&req, "Referred-By", buf);
12074          }
12075       }
12076    } else if (sipmethod == SIP_SUBSCRIBE) {
12077       char buf[SIPBUFSIZE];
12078       if (p->subscribed == MWI_NOTIFICATION) {
12079          add_header(&req, "Event", "message-summary");
12080          add_header(&req, "Accept", "application/simple-message-summary");
12081       } else if (p->subscribed == CALL_COMPLETION) {
12082          add_header(&req, "Event", "call-completion");
12083          add_header(&req, "Accept", "application/call-completion");
12084       }
12085       snprintf(buf, sizeof(buf), "%d", p->expiry);
12086       add_header(&req, "Expires", buf);
12087    }
12088 
12089    /* This new INVITE is part of an attended transfer. Make sure that the
12090    other end knows and replace the current call with this new call */
12091    if (p->options && !ast_strlen_zero(p->options->replaces)) {
12092       add_header(&req, "Replaces", p->options->replaces);
12093       add_header(&req, "Require", "replaces");
12094    }
12095 
12096    /* Add Session-Timers related headers */
12097    if (st_get_mode(p, 0) == SESSION_TIMER_MODE_ORIGINATE) {
12098       char i2astr[10];
12099 
12100       if (!p->stimer->st_interval) {
12101          p->stimer->st_interval = st_get_se(p, TRUE);
12102       }
12103 
12104       p->stimer->st_active = TRUE;
12105       
12106       snprintf(i2astr, sizeof(i2astr), "%d", p->stimer->st_interval);
12107       add_header(&req, "Session-Expires", i2astr);
12108       snprintf(i2astr, sizeof(i2astr), "%d", st_get_se(p, FALSE));
12109       add_header(&req, "Min-SE", i2astr);
12110    }
12111 
12112    add_header(&req, "Allow", ALLOWED_METHODS);
12113    add_supported_header(p, &req);
12114 
12115    if (p->options && p->options->addsipheaders && p->owner) {
12116       struct ast_channel *chan = p->owner; /* The owner channel */
12117       struct varshead *headp;
12118    
12119       ast_channel_lock(chan);
12120 
12121       headp = &chan->varshead;
12122 
12123       if (!headp) {
12124          ast_log(LOG_WARNING, "No Headp for the channel...ooops!\n");
12125       } else {
12126          const struct ast_var_t *current;
12127          AST_LIST_TRAVERSE(headp, current, entries) {
12128             /* SIPADDHEADER: Add SIP header to outgoing call */
12129             if (!strncasecmp(ast_var_name(current), "SIPADDHEADER", strlen("SIPADDHEADER"))) {
12130                char *content, *end;
12131                const char *header = ast_var_value(current);
12132                char *headdup = ast_strdupa(header);
12133 
12134                /* Strip of the starting " (if it's there) */
12135                if (*headdup == '"') {
12136                   headdup++;
12137                }
12138                if ((content = strchr(headdup, ':'))) {
12139                   *content++ = '\0';
12140                   content = ast_skip_blanks(content); /* Skip white space */
12141                   /* Strip the ending " (if it's there) */
12142                   end = content + strlen(content) -1; 
12143                   if (*end == '"') {
12144                      *end = '\0';
12145                   }
12146                
12147                   add_header(&req, headdup, content);
12148                   if (sipdebug) {
12149                      ast_debug(1, "Adding SIP Header \"%s\" with content :%s: \n", headdup, content);
12150                   }
12151                }
12152             }
12153          }
12154       }
12155 
12156       ast_channel_unlock(chan);
12157    }
12158    if ((sipmethod == SIP_INVITE || sipmethod == SIP_UPDATE) && ast_test_flag(&p->flags[0], SIP_SENDRPID))
12159       add_rpid(&req, p);
12160    if (sipmethod == SIP_INVITE) {
12161       add_diversion_header(&req, p);
12162    }
12163    if (sdp) {
12164       memset(p->offered_media, 0, sizeof(p->offered_media));
12165       if (p->udptl && p->t38.state == T38_LOCAL_REINVITE) {
12166          ast_debug(1, "T38 is in state %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
12167          add_sdp(&req, p, FALSE, FALSE, TRUE);
12168       } else if (p->rtp) {
12169          try_suggested_sip_codec(p);
12170          add_sdp(&req, p, FALSE, TRUE, FALSE);
12171       }
12172    } else if (p->notify) {
12173       for (var = p->notify->headers; var; var = var->next) {
12174          add_header(&req, var->name, var->value);
12175       }
12176       if (ast_str_strlen(p->notify->content)) {
12177          add_content(&req, ast_str_buffer(p->notify->content));
12178       }
12179    } else if (sipmethod == SIP_PUBLISH) {
12180       char expires[SIPBUFSIZE];
12181 
12182       switch (p->epa_entry->static_data->event) {
12183       case CALL_COMPLETION:
12184          snprintf(expires, sizeof(expires), "%d", p->expiry);
12185          add_header(&req, "Event", "call-completion");
12186          add_header(&req, "Expires", expires);
12187          if (p->epa_entry->publish_type != SIP_PUBLISH_INITIAL) {
12188             add_header(&req, "SIP-If-Match", p->epa_entry->entity_tag);
12189          }
12190 
12191          if (!ast_strlen_zero(p->epa_entry->body)) {
12192             add_header(&req, "Content-Type", "application/pidf+xml");
12193             add_content(&req, p->epa_entry->body);
12194          }
12195       default:
12196          break;
12197       }
12198    }
12199 
12200    if (!p->initreq.headers || init > 2) {
12201       initialize_initreq(p, &req);
12202    }
12203    if (sipmethod == SIP_INVITE || sipmethod == SIP_SUBSCRIBE) {
12204       p->lastinvite = p->ocseq;
12205    }
12206    return send_request(p, &req, init ? XMIT_CRITICAL : XMIT_RELIABLE, p->ocseq);
12207 }
12208 
12209 /*! \brief Send a subscription or resubscription for MWI */
12210 static int sip_subscribe_mwi_do(const void *data)
12211 {
12212    struct sip_subscription_mwi *mwi = (struct sip_subscription_mwi*)data;
12213    
12214    if (!mwi) {
12215       return -1;
12216    }
12217    
12218    mwi->resub = -1;
12219    __sip_subscribe_mwi_do(mwi);
12220    ASTOBJ_UNREF(mwi, sip_subscribe_mwi_destroy);
12221    
12222    return 0;
12223 }
12224 
12225 /*! \brief Actually setup an MWI subscription or resubscribe */
12226 static int __sip_subscribe_mwi_do(struct sip_subscription_mwi *mwi)
12227 {
12228    /* If we have no DNS manager let's do a lookup */
12229    if (!mwi->dnsmgr) {
12230       char transport[MAXHOSTNAMELEN];
12231       snprintf(transport, sizeof(transport), "_%s._%s", get_srv_service(mwi->transport), get_srv_protocol(mwi->transport));
12232 
12233       mwi->us.ss.ss_family = get_address_family_filter(&bindaddr); /* Filter address family */
12234       ast_dnsmgr_lookup(mwi->hostname, &mwi->us, &mwi->dnsmgr, sip_cfg.srvlookup ? transport : NULL);
12235    }
12236 
12237    /* If we already have a subscription up simply send a resubscription */
12238    if (mwi->call) {
12239       transmit_invite(mwi->call, SIP_SUBSCRIBE, 0, 0, NULL);
12240       return 0;
12241    }
12242    
12243    /* Create a dialog that we will use for the subscription */
12244    if (!(mwi->call = sip_alloc(NULL, NULL, 0, SIP_SUBSCRIBE, NULL))) {
12245       return -1;
12246    }
12247 
12248    ref_proxy(mwi->call, obproxy_get(mwi->call, NULL));
12249 
12250    if (!ast_sockaddr_port(&mwi->us) && mwi->portno) {
12251       ast_sockaddr_set_port(&mwi->us, mwi->portno);
12252    }
12253    
12254    /* Setup the destination of our subscription */
12255    if (create_addr(mwi->call, mwi->hostname, &mwi->us, 0, NULL)) {
12256       dialog_unlink_all(mwi->call);
12257       mwi->call = dialog_unref(mwi->call, "unref dialog after unlink_all");
12258       return 0;
12259    }
12260 
12261    mwi->call->expiry = mwi_expiry;
12262    
12263    if (!mwi->dnsmgr && mwi->portno) {
12264       ast_sockaddr_set_port(&mwi->call->sa, mwi->portno);
12265       ast_sockaddr_set_port(&mwi->call->recv, mwi->portno);
12266    } else {
12267       mwi->portno = ast_sockaddr_port(&mwi->call->sa);
12268    }
12269    
12270    /* Set various other information */
12271    if (!ast_strlen_zero(mwi->authuser)) {
12272       ast_string_field_set(mwi->call, peername, mwi->authuser);
12273       ast_string_field_set(mwi->call, authname, mwi->authuser);
12274       ast_string_field_set(mwi->call, fromuser, mwi->authuser);
12275    } else {
12276       ast_string_field_set(mwi->call, peername, mwi->username);
12277       ast_string_field_set(mwi->call, authname, mwi->username);
12278       ast_string_field_set(mwi->call, fromuser, mwi->username);
12279    }
12280    ast_string_field_set(mwi->call, username, mwi->username);
12281    if (!ast_strlen_zero(mwi->secret)) {
12282       ast_string_field_set(mwi->call, peersecret, mwi->secret);
12283    }
12284    set_socket_transport(&mwi->call->socket, mwi->transport);
12285    mwi->call->socket.port = htons(mwi->portno);
12286    ast_sip_ouraddrfor(&mwi->call->sa, &mwi->call->ourip, mwi->call);
12287    build_contact(mwi->call);
12288    build_via(mwi->call);
12289 
12290    /* Change the dialog callid. */
12291    change_callid_pvt(mwi->call, NULL);
12292 
12293    ast_set_flag(&mwi->call->flags[0], SIP_OUTGOING);
12294    
12295    /* Associate the call with us */
12296    mwi->call->mwi = ASTOBJ_REF(mwi);
12297 
12298    mwi->call->subscribed = MWI_NOTIFICATION;
12299 
12300    /* Actually send the packet */
12301    transmit_invite(mwi->call, SIP_SUBSCRIBE, 0, 2, NULL);
12302 
12303    return 0;
12304 }
12305 
12306 /*! \brief Find the channel that is causing the RINGING update */
12307 static int find_calling_channel(void *obj, void *arg, void *data, int flags)
12308 {
12309    struct ast_channel *c = obj;
12310    struct sip_pvt *p = data;
12311    int res;
12312 
12313    ast_channel_lock(c);
12314 
12315    res = (c->pbx &&
12316          (!strcasecmp(c->macroexten, p->exten) || !strcasecmp(c->exten, p->exten)) &&
12317          (sip_cfg.notifycid == IGNORE_CONTEXT || !strcasecmp(c->context, p->context)));
12318 
12319    ast_channel_unlock(c);
12320 
12321    return res ? CMP_MATCH | CMP_STOP : 0;
12322 }
12323 
12324 /*! \brief Builds XML portion of NOTIFY messages for presence or dialog updates */
12325 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)
12326 {
12327    enum state { NOTIFY_OPEN, NOTIFY_INUSE, NOTIFY_CLOSED } local_state = NOTIFY_OPEN;
12328    const char *statestring = "terminated";
12329    const char *pidfstate = "--";
12330    const char *pidfnote= "Ready";
12331    char hint[AST_MAX_EXTENSION];
12332 
12333    switch (state) {
12334    case (AST_EXTENSION_RINGING | AST_EXTENSION_INUSE):
12335       statestring = (sip_cfg.notifyringing) ? "early" : "confirmed";
12336       local_state = NOTIFY_INUSE;
12337       pidfstate = "busy";
12338       pidfnote = "Ringing";
12339       break;
12340    case AST_EXTENSION_RINGING:
12341       statestring = "early";
12342       local_state = NOTIFY_INUSE;
12343       pidfstate = "busy";
12344       pidfnote = "Ringing";
12345       break;
12346    case AST_EXTENSION_INUSE:
12347       statestring = "confirmed";
12348       local_state = NOTIFY_INUSE;
12349       pidfstate = "busy";
12350       pidfnote = "On the phone";
12351       break;
12352    case AST_EXTENSION_BUSY:
12353       statestring = "confirmed";
12354       local_state = NOTIFY_CLOSED;
12355       pidfstate = "busy";
12356       pidfnote = "On the phone";
12357       break;
12358    case AST_EXTENSION_UNAVAILABLE:
12359       statestring = "terminated";
12360       local_state = NOTIFY_CLOSED;
12361       pidfstate = "away";
12362       pidfnote = "Unavailable";
12363       break;
12364    case AST_EXTENSION_ONHOLD:
12365       statestring = "confirmed";
12366       local_state = NOTIFY_CLOSED;
12367       pidfstate = "busy";
12368       pidfnote = "On hold";
12369       break;
12370    case AST_EXTENSION_NOT_INUSE:
12371    default:
12372       /* Default setting */
12373       break;
12374    }
12375 
12376    /* Check which device/devices we are watching  and if they are registered */
12377    if (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, context, exten)) {
12378       char *hint2 = hint, *individual_hint = NULL;
12379       int hint_count = 0, unavailable_count = 0;
12380 
12381       while ((individual_hint = strsep(&hint2, "&"))) {
12382          hint_count++;
12383 
12384          if (ast_device_state(individual_hint) == AST_DEVICE_UNAVAILABLE)
12385             unavailable_count++;
12386       }
12387 
12388       /* If none of the hinted devices are registered, we will
12389        * override notification and show no availability.
12390        */
12391       if (hint_count > 0 && hint_count == unavailable_count) {
12392          local_state = NOTIFY_CLOSED;
12393          pidfstate = "away";
12394          pidfnote = "Not online";
12395       }
12396    }
12397 
12398    switch (subscribed) {
12399    case XPIDF_XML:
12400    case CPIM_PIDF_XML:
12401       ast_str_append(tmp, 0,
12402          "<?xml version=\"1.0\"?>\n"
12403          "<!DOCTYPE presence PUBLIC \"-//IETF//DTD RFCxxxx XPIDF 1.0//EN\" \"xpidf.dtd\">\n"
12404          "<presence>\n");
12405       ast_str_append(tmp, 0, "<presentity uri=\"%s;method=SUBSCRIBE\" />\n", mfrom);
12406       ast_str_append(tmp, 0, "<atom id=\"%s\">\n", exten);
12407       ast_str_append(tmp, 0, "<address uri=\"%s;user=ip\" priority=\"0.800000\">\n", mto);
12408       ast_str_append(tmp, 0, "<status status=\"%s\" />\n", (local_state ==  NOTIFY_OPEN) ? "open" : (local_state == NOTIFY_INUSE) ? "inuse" : "closed");
12409       ast_str_append(tmp, 0, "<msnsubstatus substatus=\"%s\" />\n", (local_state == NOTIFY_OPEN) ? "online" : (local_state == NOTIFY_INUSE) ? "onthephone" : "offline");
12410       ast_str_append(tmp, 0, "</address>\n</atom>\n</presence>\n");
12411       break;
12412    case PIDF_XML: /* Eyebeam supports this format */
12413       ast_str_append(tmp, 0,
12414          "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n"
12415          "<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);
12416       ast_str_append(tmp, 0, "<pp:person><status>\n");
12417       if (pidfstate[0] != '-') {
12418          ast_str_append(tmp, 0, "<ep:activities><ep:%s/></ep:activities>\n", pidfstate);
12419       }
12420       ast_str_append(tmp, 0, "</status></pp:person>\n");
12421       ast_str_append(tmp, 0, "<note>%s</note>\n", pidfnote); /* Note */
12422       ast_str_append(tmp, 0, "<tuple id=\"%s\">\n", exten); /* Tuple start */
12423       ast_str_append(tmp, 0, "<contact priority=\"1\">%s</contact>\n", mto);
12424       if (pidfstate[0] == 'b') /* Busy? Still open ... */
12425          ast_str_append(tmp, 0, "<status><basic>open</basic></status>\n");
12426       else
12427          ast_str_append(tmp, 0, "<status><basic>%s</basic></status>\n", (local_state != NOTIFY_CLOSED) ? "open" : "closed");
12428       ast_str_append(tmp, 0, "</tuple>\n</presence>\n");
12429       break;
12430    case DIALOG_INFO_XML: /* SNOM subscribes in this format */
12431       ast_str_append(tmp, 0, "<?xml version=\"1.0\"?>");
12432       ast_str_append(tmp, 0, "<dialog-info xmlns=\"urn:ietf:params:xml:ns:dialog-info\" version=\"%d\" state=\"%s\" entity=\"%s\">", p->dialogver, full ? "full" : "partial", mto);
12433       if ((state & AST_EXTENSION_RINGING) && sip_cfg.notifyringing) {
12434          const char *local_display = exten;
12435          char *local_target = ast_strdupa(mto);
12436 
12437          /* There are some limitations to how this works.  The primary one is that the
12438             callee must be dialing the same extension that is being monitored.  Simply dialing
12439             the hint'd device is not sufficient. */
12440          if (sip_cfg.notifycid) {
12441             struct ast_channel *caller;
12442 
12443             if ((caller = ast_channel_callback(find_calling_channel, NULL, p, 0))) {
12444                char *cid_num;
12445                int need;
12446 
12447                ast_channel_lock(caller);
12448                cid_num = S_COR(caller->caller.id.number.valid,
12449                   caller->caller.id.number.str, "");
12450                need = strlen(cid_num) + strlen(p->fromdomain) + sizeof("sip:@");
12451                local_target = alloca(need);
12452                snprintf(local_target, need, "sip:%s@%s", cid_num, p->fromdomain);
12453                local_display = ast_strdupa(S_COR(caller->caller.id.name.valid,
12454                   caller->caller.id.name.str, ""));
12455                ast_channel_unlock(caller);
12456                caller = ast_channel_unref(caller);
12457             }
12458 
12459             /* We create a fake call-id which the phone will send back in an INVITE
12460                Replaces header which we can grab and do some magic with. */
12461             if (sip_cfg.pedanticsipchecking) {
12462                ast_str_append(tmp, 0, "<dialog id=\"%s\" call-id=\"pickup-%s\" local-tag=\"%s\" remote-tag=\"%s\" direction=\"recipient\">\n",
12463                   exten, p->callid, p->theirtag, p->tag);
12464             } else {
12465                ast_str_append(tmp, 0, "<dialog id=\"%s\" call-id=\"pickup-%s\" direction=\"recipient\">\n",
12466                   exten, p->callid);
12467             }
12468             ast_str_append(tmp, 0,
12469                   "<remote>\n"
12470                   /* See the limitations of this above.  Luckily the phone seems to still be
12471                      happy when these values are not correct. */
12472                   "<identity display=\"%s\">%s</identity>\n"
12473                   "<target uri=\"%s\"/>\n"
12474                   "</remote>\n"
12475                   "<local>\n"
12476                   "<identity>%s</identity>\n"
12477                   "<target uri=\"%s\"/>\n"
12478                   "</local>\n",
12479                   local_display, local_target, local_target, mto, mto);
12480          } else {
12481             ast_str_append(tmp, 0, "<dialog id=\"%s\" direction=\"recipient\">\n", exten);
12482          }
12483 
12484       } else {
12485          ast_str_append(tmp, 0, "<dialog id=\"%s\">", exten);
12486       }
12487       ast_str_append(tmp, 0, "<state>%s</state>\n", statestring);
12488       if (state == AST_EXTENSION_ONHOLD) {
12489             ast_str_append(tmp, 0, "<local>\n<target uri=\"%s\">\n"
12490                                              "<param pname=\"+sip.rendering\" pvalue=\"no\"/>\n"
12491                                              "</target>\n</local>\n", mto);
12492       }
12493       ast_str_append(tmp, 0, "</dialog>\n</dialog-info>\n");
12494       break;
12495    case NONE:
12496    default:
12497       break;
12498    }
12499 }
12500 
12501 static int transmit_cc_notify(struct ast_cc_agent *agent, struct sip_pvt *subscription, enum sip_cc_notify_state state)
12502 {
12503    struct sip_request req;
12504    struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
12505    char uri[SIPBUFSIZE];
12506    char state_str[64];
12507 
12508    if (state < CC_QUEUED || state > CC_READY) {
12509       ast_log(LOG_WARNING, "Invalid state provided for transmit_cc_notify (%d)\n", state);
12510       return -1;
12511    }
12512 
12513    reqprep(&req, subscription, SIP_NOTIFY, 0, TRUE);
12514    snprintf(state_str, sizeof(state_str), "%s\r\n", sip_cc_notify_state_map[state].state_string);
12515    add_header(&req, "Event", "call-completion");
12516    add_header(&req, "Content-Type", "application/call-completion");
12517    if (state == CC_READY) {
12518       generate_uri(subscription, agent_pvt->notify_uri, sizeof(agent_pvt->notify_uri));
12519       snprintf(uri, sizeof(uri) - 1, "cc-URI: %s\r\n", agent_pvt->notify_uri);
12520    }
12521    add_content(&req, state_str);
12522    if (state == CC_READY) {
12523       add_content(&req, uri);
12524    }
12525    return send_request(subscription, &req, XMIT_RELIABLE, subscription->ocseq);
12526 }
12527 
12528 /*! \brief Used in the SUBSCRIBE notification subsystem (RFC3265) */
12529 static int transmit_state_notify(struct sip_pvt *p, int state, int full, int timeout)
12530 {
12531    struct ast_str *tmp = ast_str_alloca(4000);
12532    char from[256], to[256];
12533    char *c, *mfrom, *mto;
12534    struct sip_request req;
12535    const struct cfsubscription_types *subscriptiontype;
12536 
12537    memset(from, 0, sizeof(from));
12538    memset(to, 0, sizeof(to));
12539 
12540    subscriptiontype = find_subscription_type(p->subscribed);
12541 
12542    ast_copy_string(from, get_header(&p->initreq, "From"), sizeof(from));
12543    c = get_in_brackets(from);
12544    if (strncasecmp(c, "sip:", 4) && strncasecmp(c, "sips:", 5)) {
12545       ast_log(LOG_WARNING, "Huh?  Not a SIP header (%s)?\n", c);
12546       return -1;
12547    }
12548 
12549    mfrom = remove_uri_parameters(c);
12550 
12551    ast_copy_string(to, get_header(&p->initreq, "To"), sizeof(to));
12552    c = get_in_brackets(to);
12553    if (strncasecmp(c, "sip:", 4) && strncasecmp(c, "sips:", 5)) {
12554       ast_log(LOG_WARNING, "Huh?  Not a SIP header (%s)?\n", c);
12555       return -1;
12556    }
12557    mto = remove_uri_parameters(c);
12558 
12559    reqprep(&req, p, SIP_NOTIFY, 0, 1);
12560 
12561    switch(state) {
12562    case AST_EXTENSION_DEACTIVATED:
12563       if (timeout)
12564          add_header(&req, "Subscription-State", "terminated;reason=timeout");
12565       else {
12566          add_header(&req, "Subscription-State", "terminated;reason=probation");
12567          add_header(&req, "Retry-After", "60");
12568       }
12569       break;
12570    case AST_EXTENSION_REMOVED:
12571       add_header(&req, "Subscription-State", "terminated;reason=noresource");
12572       break;
12573    default:
12574       if (p->expiry)
12575          add_header(&req, "Subscription-State", "active");
12576       else  /* Expired */
12577          add_header(&req, "Subscription-State", "terminated;reason=timeout");
12578    }
12579 
12580    switch (p->subscribed) {
12581    case XPIDF_XML:
12582    case CPIM_PIDF_XML:
12583       add_header(&req, "Event", subscriptiontype->event);
12584       state_notify_build_xml(state, full, p->exten, p->context, &tmp, p, p->subscribed, mfrom, mto);
12585       add_header(&req, "Content-Type", subscriptiontype->mediatype);
12586       p->dialogver++;
12587       break;
12588    case PIDF_XML: /* Eyebeam supports this format */
12589       add_header(&req, "Event", subscriptiontype->event);
12590       state_notify_build_xml(state, full, p->exten, p->context, &tmp, p, p->subscribed, mfrom, mto);
12591       add_header(&req, "Content-Type", subscriptiontype->mediatype);
12592       p->dialogver++;
12593       break;
12594    case DIALOG_INFO_XML: /* SNOM subscribes in this format */
12595       add_header(&req, "Event", subscriptiontype->event);
12596       state_notify_build_xml(state, full, p->exten, p->context, &tmp, p, p->subscribed, mfrom, mto);
12597       add_header(&req, "Content-Type", subscriptiontype->mediatype);
12598       p->dialogver++;
12599       break;
12600    case NONE:
12601    default:
12602       break;
12603    }
12604 
12605    add_content(&req, tmp->str);
12606 
12607    p->pendinginvite = p->ocseq;  /* Remember that we have a pending NOTIFY in order not to confuse the NOTIFY subsystem */
12608 
12609    return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
12610 }
12611 
12612 /*! \brief Notify user of messages waiting in voicemail (RFC3842)
12613 \note - Notification only works for registered peers with mailbox= definitions
12614    in sip.conf
12615    - We use the SIP Event package message-summary
12616     MIME type defaults to  "application/simple-message-summary";
12617  */
12618 static int transmit_notify_with_mwi(struct sip_pvt *p, int newmsgs, int oldmsgs, const char *vmexten)
12619 {
12620    struct sip_request req;
12621    struct ast_str *out = ast_str_alloca(500);
12622    int ourport = (p->fromdomainport) ? p->fromdomainport : ast_sockaddr_port(&p->ourip);
12623    const char *domain = S_OR(p->fromdomain, ast_sockaddr_stringify_host_remote(&p->ourip));
12624    const char *exten = S_OR(vmexten, default_vmexten);
12625 
12626    initreqprep(&req, p, SIP_NOTIFY, NULL);
12627    add_header(&req, "Event", "message-summary");
12628    add_header(&req, "Content-Type", default_notifymime);
12629    ast_str_append(&out, 0, "Messages-Waiting: %s\r\n", newmsgs ? "yes" : "no");
12630 
12631 
12632    if (!sip_standard_port(p->socket.type, ourport)) {
12633       if (p->socket.type == SIP_TRANSPORT_UDP) {
12634          ast_str_append(&out, 0, "Message-Account: sip:%s@%s:%d\r\n", exten, domain, ourport);
12635       } else {
12636          ast_str_append(&out, 0, "Message-Account: sip:%s@%s:%d;transport=%s\r\n", exten, domain, ourport, get_transport(p->socket.type));
12637       }
12638    } else {
12639       if (p->socket.type == SIP_TRANSPORT_UDP) {
12640          ast_str_append(&out, 0, "Message-Account: sip:%s@%s\r\n", exten, domain);
12641       } else {
12642          ast_str_append(&out, 0, "Message-Account: sip:%s@%s;transport=%s\r\n", exten, domain, get_transport(p->socket.type));
12643       }
12644    }
12645    /* Cisco has a bug in the SIP stack where it can't accept the
12646       (0/0) notification. This can temporarily be disabled in
12647       sip.conf with the "buggymwi" option */
12648    ast_str_append(&out, 0, "Voice-Message: %d/%d%s\r\n",
12649       newmsgs, oldmsgs, (ast_test_flag(&p->flags[1], SIP_PAGE2_BUGGY_MWI) ? "" : " (0/0)"));
12650 
12651    if (p->subscribed) {
12652       if (p->expiry) {
12653          add_header(&req, "Subscription-State", "active");
12654       } else { /* Expired */
12655          add_header(&req, "Subscription-State", "terminated;reason=timeout");
12656       }
12657    }
12658 
12659    add_content(&req, out->str);
12660 
12661    if (!p->initreq.headers) {
12662       initialize_initreq(p, &req);
12663    }
12664    return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
12665 }
12666 
12667 /*! \brief Notify a transferring party of the status of transfer (RFC3515) */
12668 static int transmit_notify_with_sipfrag(struct sip_pvt *p, int cseq, char *message, int terminate)
12669 {
12670    struct sip_request req;
12671    char tmp[SIPBUFSIZE/2];
12672    
12673    reqprep(&req, p, SIP_NOTIFY, 0, 1);
12674    snprintf(tmp, sizeof(tmp), "refer;id=%d", cseq);
12675    add_header(&req, "Event", tmp);
12676    add_header(&req, "Subscription-state", terminate ? "terminated;reason=noresource" : "active");
12677    add_header(&req, "Content-Type", "message/sipfrag;version=2.0");
12678    add_header(&req, "Allow", ALLOWED_METHODS);
12679    add_supported_header(p, &req);
12680 
12681    snprintf(tmp, sizeof(tmp), "SIP/2.0 %s\r\n", message);
12682    add_content(&req, tmp);
12683 
12684    if (!p->initreq.headers) {
12685       initialize_initreq(p, &req);
12686    }
12687 
12688    return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
12689 }
12690 
12691 static int manager_sipnotify(struct mansession *s, const struct message *m)
12692 {
12693    const char *channame = astman_get_header(m, "Channel");
12694    struct ast_variable *vars = astman_get_variables(m);
12695    struct sip_pvt *p;
12696    struct ast_variable *header, *var;
12697 
12698    if (ast_strlen_zero(channame)) {
12699       astman_send_error(s, m, "SIPNotify requires a channel name");
12700       return 0;
12701    }
12702 
12703    if (!strncasecmp(channame, "sip/", 4)) {
12704       channame += 4;
12705    }
12706 
12707    if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY, NULL))) {
12708       astman_send_error(s, m, "Unable to build sip pvt data for notify (memory/socket error)");
12709       return 0;
12710    }
12711 
12712    if (create_addr(p, channame, NULL, 0, NULL)) {
12713       /* Maybe they're not registered, etc. */
12714       dialog_unlink_all(p);
12715       dialog_unref(p, "unref dialog inside for loop" );
12716       /* sip_destroy(p); */
12717       astman_send_error(s, m, "Could not create address");
12718       return 0;
12719    }
12720 
12721    /* Notify is outgoing call */
12722    ast_set_flag(&p->flags[0], SIP_OUTGOING);
12723    sip_notify_allocate(p);
12724 
12725    p->notify->headers = header = ast_variable_new("Subscription-State", "terminated", "");
12726 
12727    for (var = vars; var; var = var->next) {
12728       if (!strcasecmp(var->name, "Content")) {
12729          if (ast_str_strlen(p->notify->content))
12730             ast_str_append(&p->notify->content, 0, "\r\n");
12731          ast_str_append(&p->notify->content, 0, "%s", var->value);
12732       } else if (!strcasecmp(var->name, "Content-Length")) {
12733          ast_log(LOG_WARNING, "it is not necessary to specify Content-Length, ignoring");
12734       } else {
12735          header->next = ast_variable_new(var->name, var->value, "");
12736          header = header->next;
12737       }
12738    }
12739 
12740    sip_scheddestroy(p, SIP_TRANS_TIMEOUT);
12741    transmit_invite(p, SIP_NOTIFY, 0, 2, NULL);
12742    dialog_unref(p, "bump down the count of p since we're done with it.");
12743 
12744    astman_send_ack(s, m, "Notify Sent");
12745    ast_variables_destroy(vars);
12746    return 0;
12747 }
12748 
12749 /*! \brief Send a provisional response indicating that a call was redirected
12750  */
12751 static void update_redirecting(struct sip_pvt *p, const void *data, size_t datalen)
12752 {
12753    struct sip_request resp;
12754 
12755    if (p->owner->_state == AST_STATE_UP || ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
12756       return;
12757    }
12758 
12759    respprep(&resp, p, "181 Call is being forwarded", &p->initreq);
12760    add_diversion_header(&resp, p);
12761    send_response(p, &resp, XMIT_UNRELIABLE, 0);
12762 }
12763 
12764 /*! \brief Notify peer that the connected line has changed */
12765 static void update_connectedline(struct sip_pvt *p, const void *data, size_t datalen)
12766 {
12767 
12768    if (!ast_test_flag(&p->flags[0], SIP_SENDRPID)) {
12769       return;
12770    }
12771    if (!p->owner->connected.id.number.valid
12772       || ast_strlen_zero(p->owner->connected.id.number.str)) {
12773       return;
12774    }
12775 
12776    append_history(p, "ConnectedLine", "%s party is now %s <%s>",
12777       ast_test_flag(&p->flags[0], SIP_OUTGOING) ? "Calling" : "Called",
12778       S_COR(p->owner->connected.id.name.valid, p->owner->connected.id.name.str, ""),
12779       S_COR(p->owner->connected.id.number.valid, p->owner->connected.id.number.str, ""));
12780 
12781    if (p->owner->_state == AST_STATE_UP || ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
12782       struct sip_request req;
12783 
12784       if (p->invitestate == INV_CONFIRMED || p->invitestate == INV_TERMINATED) {
12785          reqprep(&req, p, ast_test_flag(&p->flags[0], SIP_REINVITE_UPDATE) ? SIP_UPDATE : SIP_INVITE, 0, 1);
12786 
12787          add_header(&req, "Allow", ALLOWED_METHODS);
12788          add_supported_header(p, &req);
12789          add_rpid(&req, p);
12790          add_sdp(&req, p, FALSE, TRUE, FALSE);
12791 
12792          initialize_initreq(p, &req);
12793          p->lastinvite = p->ocseq;
12794          ast_set_flag(&p->flags[0], SIP_OUTGOING);
12795          p->invitestate = INV_CALLING;
12796          send_request(p, &req, XMIT_CRITICAL, p->ocseq);
12797       } else if ((is_method_allowed(&p->allowed_methods, SIP_UPDATE)) && (!ast_strlen_zero(p->okcontacturi))) { 
12798          reqprep(&req, p, SIP_UPDATE, 0, 1);
12799          add_rpid(&req, p);
12800          add_header(&req, "X-Asterisk-rpid-update", "Yes");
12801          send_request(p, &req, XMIT_CRITICAL, p->ocseq);
12802       } else {
12803          /* We cannot send the update yet, so we have to wait until we can */
12804          ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
12805       }
12806    } else {
12807       ast_set_flag(&p->flags[1], SIP_PAGE2_CONNECTLINEUPDATE_PEND);
12808       if (ast_test_flag(&p->flags[1], SIP_PAGE2_RPID_IMMEDIATE)) {
12809          struct sip_request resp;
12810 
12811          if ((p->owner->_state == AST_STATE_RING) && !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT)) {
12812             ast_clear_flag(&p->flags[1], SIP_PAGE2_CONNECTLINEUPDATE_PEND);
12813             respprep(&resp, p, "180 Ringing", &p->initreq);
12814             add_rpid(&resp, p);
12815             send_response(p, &resp, XMIT_UNRELIABLE, 0);
12816             ast_set_flag(&p->flags[0], SIP_RINGING);
12817          } else if (p->owner->_state == AST_STATE_RINGING) {
12818             ast_clear_flag(&p->flags[1], SIP_PAGE2_CONNECTLINEUPDATE_PEND);
12819             respprep(&resp, p, "183 Session Progress", &p->initreq);
12820             add_rpid(&resp, p);
12821             send_response(p, &resp, XMIT_UNRELIABLE, 0);
12822             ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
12823          } else {
12824             ast_debug(1, "Unable able to send update to '%s' in state '%s'\n", p->owner->name, ast_state2str(p->owner->_state));
12825          }
12826       }
12827    }
12828 }
12829 
12830 static const struct _map_x_s regstatestrings[] = {
12831    { REG_STATE_FAILED,     "Failed" },
12832    { REG_STATE_UNREGISTERED, "Unregistered"},
12833    { REG_STATE_REGSENT, "Request Sent"},
12834    { REG_STATE_AUTHSENT, "Auth. Sent"},
12835    { REG_STATE_REGISTERED, "Registered"},
12836    { REG_STATE_REJECTED, "Rejected"},
12837    { REG_STATE_TIMEOUT, "Timeout"},
12838    { REG_STATE_NOAUTH, "No Authentication"},
12839    { -1, NULL } /* terminator */
12840 };
12841 
12842 /*! \brief Convert registration state status to string */
12843 static const char *regstate2str(enum sipregistrystate regstate)
12844 {
12845    return map_x_s(regstatestrings, regstate, "Unknown");
12846 }
12847 
12848 /*! \brief Update registration with SIP Proxy.
12849  * Called from the scheduler when the previous registration expires,
12850  * so we don't have to cancel the pending event.
12851  * We assume the reference so the sip_registry is valid, since it
12852  * is stored in the scheduled event anyways.
12853  */
12854 static int sip_reregister(const void *data)
12855 {
12856    /* if we are here, we know that we need to reregister. */
12857    struct sip_registry *r = (struct sip_registry *) data;
12858 
12859    /* if we couldn't get a reference to the registry object, punt */
12860    if (!r) {
12861       return 0;
12862    }
12863 
12864    if (r->call && r->call->do_history) {
12865       append_history(r->call, "RegistryRenew", "Account: %s@%s", r->username, r->hostname);
12866    }
12867    /* Since registry's are only added/removed by the the monitor thread, this
12868       may be overkill to reference/dereference at all here */
12869    if (sipdebug) {
12870       ast_log(LOG_NOTICE, "   -- Re-registration for  %s@%s\n", r->username, r->hostname);
12871    }
12872 
12873    r->expire = -1;
12874    r->expiry = r->configured_expiry;
12875    __sip_do_register(r);
12876    registry_unref(r, "unref the re-register scheduled event");
12877    return 0;
12878 }
12879 
12880 /*! \brief Register with SIP proxy 
12881    \return see \ref __sip_xmit 
12882 */
12883 static int __sip_do_register(struct sip_registry *r)
12884 {
12885    int res;
12886 
12887    res = transmit_register(r, SIP_REGISTER, NULL, NULL);
12888    return res;
12889 }
12890 
12891 /*! \brief Registration timeout, register again
12892  * Registered as a timeout handler during transmit_register(),
12893  * to retransmit the packet if a reply does not come back.
12894  * This is called by the scheduler so the event is not pending anymore when
12895  * we are called.
12896  */
12897 static int sip_reg_timeout(const void *data)
12898 {
12899 
12900    /* if we are here, our registration timed out, so we'll just do it over */
12901    struct sip_registry *r = (struct sip_registry *)data; /* the ref count should have been bumped when the sched item was added */
12902    struct sip_pvt *p;
12903 
12904    /* if we couldn't get a reference to the registry object, punt */
12905    if (!r) {
12906       return 0;
12907    }
12908 
12909    if (r->dnsmgr) {
12910       struct sip_peer *peer;
12911       /* If the registration has timed out, maybe the IP changed.  Force a refresh. */
12912       ast_dnsmgr_refresh(r->dnsmgr);
12913       /* If we are resolving a peer, we have to make sure the refreshed address gets copied */
12914       if ((peer = find_peer(r->hostname, NULL, TRUE, FINDPEERS, FALSE, 0))) {
12915          ast_sockaddr_copy(&peer->addr, &r->us);
12916          if (r->portno) {
12917             ast_sockaddr_set_port(&peer->addr, r->portno);
12918          }
12919          peer = unref_peer(peer, "unref after find_peer");
12920       }
12921    }
12922 
12923    /* If the initial tranmission failed, we may not have an existing dialog,
12924     * so it is possible that r->call == NULL.
12925     * Otherwise destroy it, as we have a timeout so we don't want it.
12926     */
12927    if (r->call) {
12928       /* Unlink us, destroy old call.  Locking is not relevant here because all this happens
12929          in the single SIP manager thread. */
12930       p = r->call;
12931       sip_pvt_lock(p);
12932       pvt_set_needdestroy(p, "registration timeout");
12933       /* Pretend to ACK anything just in case */
12934       __sip_pretend_ack(p);
12935       sip_pvt_unlock(p);
12936 
12937       /* decouple the two objects */
12938       /* p->registry == r, so r has 2 refs, and the unref won't take the object away */
12939       if (p->registry) {
12940          p->registry = registry_unref(p->registry, "p->registry unreffed");
12941       }
12942       r->call = dialog_unref(r->call, "unrefing r->call");
12943    }
12944    /* If we have a limit, stop registration and give up */
12945    r->timeout = -1;
12946    if (global_regattempts_max && r->regattempts >= global_regattempts_max) {
12947       /* Ok, enough is enough. Don't try any more */
12948       /* We could add an external notification here...
12949          steal it from app_voicemail :-) */
12950       ast_log(LOG_NOTICE, "   -- Last Registration Attempt #%d failed, Giving up forever trying to register '%s@%s'\n", r->regattempts, r->username, r->hostname);
12951       r->regstate = REG_STATE_FAILED;
12952    } else {
12953       r->regstate = REG_STATE_UNREGISTERED;
12954       transmit_register(r, SIP_REGISTER, NULL, NULL);
12955       ast_log(LOG_NOTICE, "   -- Registration for '%s@%s' timed out, trying again (Attempt #%d)\n", r->username, r->hostname, r->regattempts);
12956    }
12957    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));
12958    registry_unref(r, "unreffing registry_unref r");
12959    return 0;
12960 }
12961 
12962 static const char *sip_sanitized_host(const char *host)
12963 {
12964    struct ast_sockaddr addr = { { 0, 0, }, };
12965 
12966    /* peer/sip_pvt->tohost and sip_registry->hostname should never have a port
12967     * in them, so we use PARSE_PORT_FORBID here. If this lookup fails, we return
12968     * the original host which is most likely a host name and not an IP. */
12969    if (!ast_sockaddr_parse(&addr, host, PARSE_PORT_FORBID)) {
12970       return host;
12971    }
12972    return ast_sockaddr_stringify_host_remote(&addr);
12973 }
12974 
12975 /*! \brief Transmit register to SIP proxy or UA
12976  * auth = NULL on the initial registration (from sip_reregister())
12977  */
12978 static int transmit_register(struct sip_registry *r, int sipmethod, const char *auth, const char *authheader)
12979 {
12980    struct sip_request req;
12981    char from[256];
12982    char to[256];
12983    char tmp[80];
12984    char addr[80];
12985    struct sip_pvt *p;
12986    struct sip_peer *peer = NULL;
12987    int res;
12988    int portno = 0;
12989 
12990    /* exit if we are already in process with this registrar ?*/
12991    if (r == NULL || ((auth == NULL) && (r->regstate == REG_STATE_REGSENT || r->regstate == REG_STATE_AUTHSENT))) {
12992       if (r) {
12993          ast_log(LOG_NOTICE, "Strange, trying to register %s@%s when registration already pending\n", r->username, r->hostname);
12994       }
12995       return 0;
12996    }
12997 
12998    if (r->dnsmgr == NULL) {
12999       char transport[MAXHOSTNAMELEN];
13000       peer = find_peer(r->hostname, NULL, TRUE, FINDPEERS, FALSE, 0);
13001       snprintf(transport, sizeof(transport), "_%s._%s",get_srv_service(r->transport), get_srv_protocol(r->transport)); /* have to use static get_transport function */
13002       r->us.ss.ss_family = get_address_family_filter(&bindaddr); /* Filter address family */
13003       ast_dnsmgr_lookup(peer ? peer->tohost : r->hostname, &r->us, &r->dnsmgr, sip_cfg.srvlookup ? transport : NULL);
13004       if (peer) {
13005          peer = unref_peer(peer, "removing peer ref for dnsmgr_lookup");
13006       }
13007    }
13008 
13009    if (r->call) { /* We have a registration */
13010       if (!auth) {
13011          ast_log(LOG_WARNING, "Already have a REGISTER going on to %s@%s?? \n", r->username, r->hostname);
13012          return 0;
13013       } else {
13014          p = dialog_ref(r->call, "getting a copy of the r->call dialog in transmit_register");
13015          make_our_tag(p->tag, sizeof(p->tag));  /* create a new local tag for every register attempt */
13016          ast_string_field_set(p, theirtag, NULL);  /* forget their old tag, so we don't match tags when getting response */
13017       }
13018    } else {
13019       /* Build callid for registration if we haven't registered before */
13020       if (!r->callid_valid) {
13021          build_callid_registry(r, &internip, default_fromdomain);
13022          r->callid_valid = TRUE;
13023       }
13024       /* Allocate SIP dialog for registration */
13025       if (!(p = sip_alloc( r->callid, NULL, 0, SIP_REGISTER, NULL))) {
13026          ast_log(LOG_WARNING, "Unable to allocate registration transaction (memory or socket error)\n");
13027          return 0;
13028       }
13029       
13030       if (p->do_history) {
13031          append_history(p, "RegistryInit", "Account: %s@%s", r->username, r->hostname);
13032       }
13033 
13034       /* Use port number specified if no SRV record was found */
13035       if (!ast_sockaddr_port(&r->us) && r->portno) {
13036          ast_sockaddr_set_port(&r->us, r->portno);
13037       }
13038 
13039       /* It is possible that DNS is unavailable at the time the peer is created. Here, if
13040        * we've updated the address in the registry, we copy it to the peer so that
13041        * create_addr() can copy it to the dialog via create_addr_from_peer */
13042       if ((peer = find_peer(r->hostname, NULL, TRUE, FINDPEERS, FALSE, 0))) {
13043          if (ast_sockaddr_isnull(&peer->addr) && !(ast_sockaddr_isnull(&r->us))) {
13044             ast_sockaddr_copy(&peer->addr, &r->us);
13045          }
13046          peer = unref_peer(peer, "unref after find_peer");
13047       }
13048 
13049       /* Find address to hostname */
13050       if (create_addr(p, S_OR(r->peername, r->hostname), &r->us, 0, NULL)) {
13051          /* we have what we hope is a temporary network error,
13052           * probably DNS.  We need to reschedule a registration try */
13053          dialog_unlink_all(p);
13054          p = dialog_unref(p, "unref dialog after unlink_all");
13055          if (r->timeout > -1) {
13056             AST_SCHED_REPLACE_UNREF(r->timeout, sched, global_reg_timeout * 1000, sip_reg_timeout, r,
13057                               registry_unref(_data, "del for REPLACE of registry ptr"),
13058                               registry_unref(r, "object ptr dec when SCHED_REPLACE add failed"),
13059                               registry_addref(r,"add for REPLACE registry ptr"));
13060             ast_log(LOG_WARNING, "Still have a registration timeout for %s@%s (create_addr() error), %d\n", r->username, r->hostname, r->timeout);
13061          } else {
13062             r->timeout = ast_sched_add(sched, global_reg_timeout * 1000, sip_reg_timeout, registry_addref(r, "add for REPLACE registry ptr"));
13063             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);
13064          }
13065          r->regattempts++;
13066          return 0;
13067       }
13068 
13069       /* Copy back Call-ID in case create_addr changed it */
13070       ast_string_field_set(r, callid, p->callid);
13071 
13072       if (!r->dnsmgr && r->portno) {
13073          ast_sockaddr_set_port(&p->sa, r->portno);
13074          ast_sockaddr_set_port(&p->recv, r->portno);
13075       }
13076       if (!ast_strlen_zero(p->fromdomain)) {
13077          portno = (p->fromdomainport) ? p->fromdomainport : STANDARD_SIP_PORT;
13078       } else if (!ast_strlen_zero(r->regdomain)) {
13079          portno = (r->regdomainport) ? r->regdomainport : STANDARD_SIP_PORT;
13080       } else {
13081          portno = ast_sockaddr_port(&p->sa);
13082       }
13083 
13084       ast_set_flag(&p->flags[0], SIP_OUTGOING); /* Registration is outgoing call */
13085       r->call = dialog_ref(p, "copying dialog into registry r->call");     /* Save pointer to SIP dialog */
13086       p->registry = registry_addref(r, "transmit_register: addref to p->registry in transmit_register"); /* Add pointer to registry in packet */
13087       if (!ast_strlen_zero(r->secret)) {  /* Secret (password) */
13088          ast_string_field_set(p, peersecret, r->secret);
13089       }
13090       if (!ast_strlen_zero(r->md5secret))
13091          ast_string_field_set(p, peermd5secret, r->md5secret);
13092       /* User name in this realm
13093       - if authuser is set, use that, otherwise use username */
13094       if (!ast_strlen_zero(r->authuser)) {
13095          ast_string_field_set(p, peername, r->authuser);
13096          ast_string_field_set(p, authname, r->authuser);
13097       } else if (!ast_strlen_zero(r->username)) {
13098          ast_string_field_set(p, peername, r->username);
13099          ast_string_field_set(p, authname, r->username);
13100          ast_string_field_set(p, fromuser, r->username);
13101       }
13102       if (!ast_strlen_zero(r->username)) {
13103          ast_string_field_set(p, username, r->username);
13104       }
13105       /* Save extension in packet */
13106       if (!ast_strlen_zero(r->callback)) {
13107          ast_string_field_set(p, exten, r->callback);
13108       }
13109 
13110       /* Set transport and port so the correct contact is built */
13111       set_socket_transport(&p->socket, r->transport);
13112       if (r->transport == SIP_TRANSPORT_TLS || r->transport == SIP_TRANSPORT_TCP) {
13113          p->socket.port =
13114              htons(ast_sockaddr_port(&sip_tcp_desc.local_address));
13115       }
13116 
13117       /*
13118         check which address we should use in our contact header
13119         based on whether the remote host is on the external or
13120         internal network so we can register through nat
13121        */
13122       ast_sip_ouraddrfor(&p->sa, &p->ourip, p);
13123       build_contact(p);
13124    }
13125 
13126    /* set up a timeout */
13127    if (auth == NULL)  {
13128       if (r->timeout > -1) {
13129          ast_log(LOG_WARNING, "Still have a registration timeout, #%d - deleting it\n", r->timeout);
13130       }
13131       AST_SCHED_REPLACE_UNREF(r->timeout, sched, global_reg_timeout * 1000, sip_reg_timeout, r,
13132                         registry_unref(_data,"reg ptr unrefed from del in SCHED_REPLACE"),
13133                         registry_unref(r,"reg ptr unrefed from add failure in SCHED_REPLACE"),
13134                         registry_addref(r,"reg ptr reffed from add in SCHED_REPLACE"));
13135       ast_debug(1, "Scheduled a registration timeout for %s id  #%d \n", r->hostname, r->timeout);
13136    }
13137 
13138    snprintf(from, sizeof(from), "<sip:%s@%s>;tag=%s", r->username, S_OR(r->regdomain, sip_sanitized_host(p->tohost)), p->tag);
13139    if (!ast_strlen_zero(p->theirtag)) {
13140       snprintf(to, sizeof(to), "<sip:%s@%s>;tag=%s", r->username, S_OR(r->regdomain, sip_sanitized_host(p->tohost)), p->theirtag);
13141    } else {
13142       snprintf(to, sizeof(to), "<sip:%s@%s>", r->username, S_OR(r->regdomain, sip_sanitized_host(p->tohost)));
13143    }
13144 
13145    /* Fromdomain is what we are registering to, regardless of actual
13146       host name from SRV */
13147    if (portno && portno != STANDARD_SIP_PORT) {
13148       snprintf(addr, sizeof(addr), "sip:%s:%d", S_OR(p->fromdomain,S_OR(r->regdomain, sip_sanitized_host(r->hostname))), portno);
13149    } else {
13150       snprintf(addr, sizeof(addr), "sip:%s", S_OR(p->fromdomain,S_OR(r->regdomain, sip_sanitized_host(r->hostname))));
13151    }
13152 
13153    ast_string_field_set(p, uri, addr);
13154 
13155    p->branch ^= ast_random();
13156 
13157    init_req(&req, sipmethod, addr);
13158 
13159    /* Add to CSEQ */
13160    snprintf(tmp, sizeof(tmp), "%u %s", ++r->ocseq, sip_methods[sipmethod].text);
13161    p->ocseq = r->ocseq;
13162 
13163    build_via(p);
13164    add_header(&req, "Via", p->via);
13165    add_header_max_forwards(p, &req);
13166    add_header(&req, "From", from);
13167    add_header(&req, "To", to);
13168    add_header(&req, "Call-ID", p->callid);
13169    add_header(&req, "CSeq", tmp);
13170    if (!ast_strlen_zero(global_useragent))
13171       add_header(&req, "User-Agent", global_useragent);
13172 
13173    if (auth) {    /* Add auth header */
13174       add_header(&req, authheader, auth);
13175    } else if (!ast_strlen_zero(r->nonce)) {
13176       char digest[1024];
13177 
13178       /* We have auth data to reuse, build a digest header.
13179        * Note, this is not always useful because some parties do not
13180        * like nonces to be reused (for good reasons!) so they will
13181        * challenge us anyways.
13182        */
13183       if (sipdebug) {
13184          ast_debug(1, "   >>> Re-using Auth data for %s@%s\n", r->username, r->hostname);
13185       }
13186       ast_string_field_set(p, realm, r->realm);
13187       ast_string_field_set(p, nonce, r->nonce);
13188       ast_string_field_set(p, domain, r->authdomain);
13189       ast_string_field_set(p, opaque, r->opaque);
13190       ast_string_field_set(p, qop, r->qop);
13191       p->noncecount = ++r->noncecount;
13192 
13193       memset(digest, 0, sizeof(digest));
13194       if(!build_reply_digest(p, sipmethod, digest, sizeof(digest))) {
13195          add_header(&req, "Authorization", digest);
13196       } else {
13197          ast_log(LOG_NOTICE, "No authorization available for authentication of registration to %s@%s\n", r->username, r->hostname);
13198       }
13199    }
13200 
13201    snprintf(tmp, sizeof(tmp), "%d", r->expiry);
13202    add_header(&req, "Expires", tmp);
13203    add_header(&req, "Contact", p->our_contact);
13204 
13205    initialize_initreq(p, &req);
13206    if (sip_debug_test_pvt(p)) {
13207       ast_verbose("REGISTER %d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
13208    }
13209    r->regstate = auth ? REG_STATE_AUTHSENT : REG_STATE_REGSENT;
13210    r->regattempts++; /* Another attempt */
13211    ast_debug(4, "REGISTER attempt %d to %s@%s\n", r->regattempts, r->username, r->hostname);
13212    res = send_request(p, &req, XMIT_CRITICAL, p->ocseq);
13213    dialog_unref(p, "p is finished here at the end of transmit_register");
13214    return res;
13215 }
13216 
13217 /*! \brief Transmit text with SIP MESSAGE method */
13218 static int transmit_message_with_text(struct sip_pvt *p, const char *text)
13219 {
13220    struct sip_request req;
13221    
13222    reqprep(&req, p, SIP_MESSAGE, 0, 1);
13223    add_text(&req, text);
13224    return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
13225 }
13226 
13227 /*! \brief Allocate SIP refer structure */
13228 static int sip_refer_allocate(struct sip_pvt *p)
13229 {
13230    p->refer = ast_calloc(1, sizeof(struct sip_refer));
13231    return p->refer ? 1 : 0;
13232 }
13233 
13234 /*! \brief Allocate SIP refer structure */
13235 static int sip_notify_allocate(struct sip_pvt *p)
13236 {
13237    p->notify = ast_calloc(1, sizeof(struct sip_notify));
13238    if (p->notify) {
13239       p->notify->content = ast_str_create(128);
13240    }
13241    return p->notify ? 1 : 0;
13242 }
13243 
13244 /*! \brief Transmit SIP REFER message (initiated by the transfer() dialplan application
13245    \note this is currently broken as we have no way of telling the dialplan
13246    engine whether a transfer succeeds or fails.
13247    \todo Fix the transfer() dialplan function so that a transfer may fail
13248 */
13249 static int transmit_refer(struct sip_pvt *p, const char *dest)
13250 {
13251    struct sip_request req = {
13252       .headers = 0,  
13253    };
13254    char from[256];
13255    const char *of;
13256    char *c;
13257    char referto[256];
13258    int   use_tls=FALSE;
13259 
13260    if (sipdebug) {
13261       ast_debug(1, "SIP transfer of %s to %s\n", p->callid, dest);
13262    }
13263 
13264    /* Are we transfering an inbound or outbound call ? */
13265    if (ast_test_flag(&p->flags[0], SIP_OUTGOING))  {
13266       of = get_header(&p->initreq, "To");
13267    } else {
13268       of = get_header(&p->initreq, "From");
13269    }
13270 
13271    ast_copy_string(from, of, sizeof(from));
13272    of = get_in_brackets(from);
13273    ast_string_field_set(p, from, of);
13274    if (!strncasecmp(of, "sip:", 4)) {
13275       of += 4;
13276    } else if (!strncasecmp(of, "sips:", 5)) {
13277       of += 5;
13278       use_tls = TRUE;
13279    } else {
13280       ast_log(LOG_NOTICE, "From address missing 'sip(s):', assuming sip:\n");
13281    }
13282    /* Get just the username part */
13283    if ((c = strchr(dest, '@'))) {
13284       c = NULL;
13285    } else if ((c = strchr(of, '@'))) {
13286       *c++ = '\0';
13287    }
13288    if (c) {
13289       snprintf(referto, sizeof(referto), "<sip%s:%s@%s>", use_tls ? "s" : "", dest, c);
13290    } else {
13291       snprintf(referto, sizeof(referto), "<sip%s:%s>", use_tls ? "s" : "", dest);
13292    }
13293 
13294    /* save in case we get 407 challenge */
13295    sip_refer_allocate(p);
13296    ast_copy_string(p->refer->refer_to, referto, sizeof(p->refer->refer_to));
13297    ast_copy_string(p->refer->referred_by, p->our_contact, sizeof(p->refer->referred_by));
13298    p->refer->status = REFER_SENT;   /* Set refer status */
13299 
13300    reqprep(&req, p, SIP_REFER, 0, 1);
13301 
13302    add_header(&req, "Refer-To", referto);
13303    add_header(&req, "Allow", ALLOWED_METHODS);
13304    add_supported_header(p, &req);
13305    if (!ast_strlen_zero(p->our_contact)) {
13306       add_header(&req, "Referred-By", p->our_contact);
13307    }
13308 
13309    return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
13310 
13311    /* We should propably wait for a NOTIFY here until we ack the transfer */
13312    /* Maybe fork a new thread and wait for a STATUS of REFER_200OK on the refer status before returning to app_transfer */
13313 
13314    /*! \todo In theory, we should hang around and wait for a reply, before
13315    returning to the dial plan here. Don't know really how that would
13316    affect the transfer() app or the pbx, but, well, to make this
13317    useful we should have a STATUS code on transfer().
13318    */
13319 }
13320 
13321 /*! \brief Send SIP INFO advice of charge message */
13322 static int transmit_info_with_aoc(struct sip_pvt *p, struct ast_aoc_decoded *decoded)
13323 {
13324    struct sip_request req;
13325    struct ast_str *str = ast_str_alloca(512);
13326    const struct ast_aoc_unit_entry *unit_entry = ast_aoc_get_unit_info(decoded, 0);
13327    enum ast_aoc_charge_type charging = ast_aoc_get_charge_type(decoded);
13328 
13329    reqprep(&req, p, SIP_INFO, 0, 1);
13330 
13331    if (ast_aoc_get_msg_type(decoded) == AST_AOC_D) {
13332       ast_str_append(&str, 0, "type=active;");
13333    } else if (ast_aoc_get_msg_type(decoded) == AST_AOC_E) {
13334       ast_str_append(&str, 0, "type=terminated;");
13335    } else {
13336       /* unsupported message type */
13337       return -1;
13338    }
13339 
13340    switch (charging) {
13341    case AST_AOC_CHARGE_FREE:
13342       ast_str_append(&str, 0, "free-of-charge;");
13343       break;
13344    case AST_AOC_CHARGE_CURRENCY:
13345       ast_str_append(&str, 0, "charging;");
13346       ast_str_append(&str, 0, "charging-info=currency;");
13347       ast_str_append(&str, 0, "amount=%u;", ast_aoc_get_currency_amount(decoded));
13348       ast_str_append(&str, 0, "multiplier=%s;", ast_aoc_get_currency_multiplier_decimal(decoded));
13349       if (!ast_strlen_zero(ast_aoc_get_currency_name(decoded))) {
13350          ast_str_append(&str, 0, "currency=%s;", ast_aoc_get_currency_name(decoded));
13351       }
13352       break;
13353    case AST_AOC_CHARGE_UNIT:
13354       ast_str_append(&str, 0, "charging;");
13355       ast_str_append(&str, 0, "charging-info=pulse;");
13356       if (unit_entry) {
13357          ast_str_append(&str, 0, "recorded-units=%u;", unit_entry->amount);
13358       }
13359       break;
13360    default:
13361       ast_str_append(&str, 0, "not-available;");
13362    };
13363 
13364    add_header(&req, "AOC", ast_str_buffer(str));
13365 
13366    return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
13367 }
13368 
13369 /*! \brief Send SIP INFO dtmf message, see Cisco documentation on cisco.com */
13370 static int transmit_info_with_digit(struct sip_pvt *p, const char digit, unsigned int duration)
13371 {
13372    struct sip_request req;
13373    
13374    reqprep(&req, p, SIP_INFO, 0, 1);
13375    add_digit(&req, digit, duration, (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_SHORTINFO));
13376    return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
13377 }
13378 
13379 /*! \brief Send SIP INFO with video update request */
13380 static int transmit_info_with_vidupdate(struct sip_pvt *p)
13381 {
13382    struct sip_request req;
13383    
13384    reqprep(&req, p, SIP_INFO, 0, 1);
13385    add_vidupdate(&req);
13386    return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
13387 }
13388 
13389 /*! \brief Transmit generic SIP request
13390    returns XMIT_ERROR if transmit failed with a critical error (don't retry)
13391 */
13392 static int transmit_request(struct sip_pvt *p, int sipmethod, int seqno, enum xmittype reliable, int newbranch)
13393 {
13394    struct sip_request resp;
13395    
13396    if (sipmethod == SIP_ACK) {
13397       p->invitestate = INV_CONFIRMED;
13398    }
13399 
13400    reqprep(&resp, p, sipmethod, seqno, newbranch);
13401    if (sipmethod == SIP_CANCEL && p->answered_elsewhere) {
13402       add_header(&resp, "Reason", "SIP;cause=200;text=\"Call completed elsewhere\"");
13403    }
13404 
13405    return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);
13406 }
13407 
13408 /*! \brief return the request and response header for a 401 or 407 code */
13409 static void auth_headers(enum sip_auth_type code, char **header, char **respheader)
13410 {
13411    if (code == WWW_AUTH) {       /* 401 */
13412       *header = "WWW-Authenticate";
13413       *respheader = "Authorization";
13414    } else if (code == PROXY_AUTH) { /* 407 */
13415       *header = "Proxy-Authenticate";
13416       *respheader = "Proxy-Authorization";
13417    } else {
13418       ast_verbose("-- wrong response code %d\n", code);
13419       *header = *respheader = "Invalid";
13420    }
13421 }
13422 
13423 /*! \brief Transmit SIP request, auth added */
13424 static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, int seqno, enum xmittype reliable, int newbranch)
13425 {
13426    struct sip_request resp;
13427    
13428    reqprep(&resp, p, sipmethod, seqno, newbranch);
13429    if (!ast_strlen_zero(p->realm)) {
13430       char digest[1024];
13431 
13432       memset(digest, 0, sizeof(digest));
13433       if(!build_reply_digest(p, sipmethod, digest, sizeof(digest))) {
13434          char *dummy, *response;
13435          enum sip_auth_type code = p->options ? p->options->auth_type : PROXY_AUTH; /* XXX force 407 if unknown */
13436          auth_headers(code, &dummy, &response);
13437          add_header(&resp, response, digest);
13438       } else {
13439          ast_log(LOG_WARNING, "No authentication available for call %s\n", p->callid);
13440       }
13441    }
13442    /* If we are hanging up and know a cause for that, send it in clear text to make
13443       debugging easier. */
13444    if (sipmethod == SIP_BYE)  {
13445       char buf[20];
13446 
13447       if (ast_test_flag(&p->flags[1], SIP_PAGE2_Q850_REASON) && p->hangupcause) {
13448          sprintf(buf, "Q.850;cause=%i", p->hangupcause & 0x7f);
13449          add_header(&resp, "Reason", buf);
13450       }
13451 
13452       add_header(&resp, "X-Asterisk-HangupCause", ast_cause2str(p->hangupcause));
13453       snprintf(buf, sizeof(buf), "%d", p->hangupcause);
13454       add_header(&resp, "X-Asterisk-HangupCauseCode", buf);
13455    }
13456 
13457    return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);   
13458 }
13459 
13460 /*! \brief Remove registration data from realtime database or AST/DB when registration expires */
13461 static void destroy_association(struct sip_peer *peer)
13462 {
13463    int realtimeregs = ast_check_realtime("sipregs");
13464    char *tablename = (realtimeregs) ? "sipregs" : "sippeers";
13465 
13466    if (!sip_cfg.ignore_regexpire) {
13467       if (peer->rt_fromcontact && sip_cfg.peer_rtupdate) {
13468          ast_update_realtime(tablename, "name", peer->name, "fullcontact", "", "ipaddr", "", "port", "", "regseconds", "0", "regserver", "", "useragent", "", "lastms", "", SENTINEL);
13469       } else {
13470          ast_db_del("SIP/Registry", peer->name);
13471          ast_db_del("SIP/PeerMethods", peer->name);
13472       }
13473    }
13474 }
13475 
13476 static void set_socket_transport(struct sip_socket *socket, int transport)
13477 {
13478    /* if the transport type changes, clear all socket data */
13479    if (socket->type != transport) {
13480       socket->fd = -1;
13481       socket->type = transport;
13482       if (socket->tcptls_session) {
13483          ao2_ref(socket->tcptls_session, -1);
13484          socket->tcptls_session = NULL;
13485       }
13486    }
13487 }
13488 
13489 /*! \brief Expire registration of SIP peer */
13490 static int expire_register(const void *data)
13491 {
13492    struct sip_peer *peer = (struct sip_peer *)data;
13493 
13494    if (!peer) {      /* Hmmm. We have no peer. Weird. */
13495       return 0;
13496    }
13497 
13498    peer->expire = -1;
13499    peer->portinuri = 0;
13500 
13501    destroy_association(peer); /* remove registration data from storage */
13502    set_socket_transport(&peer->socket, peer->default_outbound_transport);
13503 
13504    if (peer->socket.tcptls_session) {
13505       ao2_ref(peer->socket.tcptls_session, -1);
13506       peer->socket.tcptls_session = NULL;
13507    }
13508 
13509    manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: Unregistered\r\nCause: Expired\r\n", peer->name);
13510    register_peer_exten(peer, FALSE);   /* Remove regexten */
13511    ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", peer->name);
13512 
13513    /* Do we need to release this peer from memory?
13514       Only for realtime peers and autocreated peers
13515    */
13516    if (peer->is_realtime) {
13517       ast_debug(3, "-REALTIME- peer expired registration. Name: %s. Realtime peer objects now %d\n", peer->name, rpeerobjs);
13518    }
13519 
13520    if (peer->selfdestruct ||
13521        ast_test_flag(&peer->flags[1], SIP_PAGE2_RTAUTOCLEAR)) {
13522       unlink_peer_from_tables(peer);
13523    } else if (!ast_sockaddr_isnull(&peer->addr)) {
13524       /* If we aren't self-destructing a temp_peer, we still need to unlink the peer
13525        * from the peers_by_ip table, otherwise we end up with multiple copies hanging
13526        * around each time a registration expires and the peer re-registers. */
13527       ao2_t_unlink(peers_by_ip, peer, "ao2_unlink of peer from peers_by_ip table");
13528    }
13529 
13530    /* Only clear the addr after we check for destruction.  The addr must remain
13531     * in order to unlink from the peers_by_ip container correctly */
13532    memset(&peer->addr, 0, sizeof(peer->addr));
13533 
13534    unref_peer(peer, "removing peer ref for expire_register");
13535 
13536    return 0;
13537 }
13538 
13539 /*! \brief Poke peer (send qualify to check if peer is alive and well) */
13540 static int sip_poke_peer_s(const void *data)
13541 {
13542    struct sip_peer *peer = (struct sip_peer *)data;
13543    struct sip_peer *foundpeer;
13544 
13545    peer->pokeexpire = -1;
13546 
13547    foundpeer = ao2_find(peers, peer, OBJ_POINTER);
13548    if (!foundpeer) {
13549       unref_peer(peer, "removing poke peer ref");
13550       return 0;
13551    } else if (foundpeer->name != peer->name) {
13552       unref_peer(foundpeer, "removing above peer ref");
13553       unref_peer(peer, "removing poke peer ref");
13554       return 0;
13555    }
13556 
13557    unref_peer(foundpeer, "removing above peer ref");
13558    sip_poke_peer(peer, 0);
13559    unref_peer(peer, "removing poke peer ref");
13560 
13561    return 0;
13562 }
13563 
13564 /*! \brief Get registration details from Asterisk DB */
13565 static void reg_source_db(struct sip_peer *peer)
13566 {
13567    char data[256];
13568    struct ast_sockaddr sa;
13569    int expire;
13570    char full_addr[128];
13571    AST_DECLARE_APP_ARGS(args,
13572       AST_APP_ARG(addr);
13573       AST_APP_ARG(port);
13574       AST_APP_ARG(expiry_str);
13575       AST_APP_ARG(username);
13576       AST_APP_ARG(contact);
13577    );
13578 
13579    /* If read-only RT backend, then refresh from local DB cache */
13580    if (peer->rt_fromcontact && sip_cfg.peer_rtupdate) {
13581       return;
13582    }
13583    if (ast_db_get("SIP/Registry", peer->name, data, sizeof(data))) {
13584       return;
13585    }
13586 
13587    AST_NONSTANDARD_RAW_ARGS(args, data, ':');
13588 
13589    snprintf(full_addr, sizeof(full_addr), "%s:%s", args.addr, args.port);
13590 
13591    if (!ast_sockaddr_parse(&sa, full_addr, 0)) {
13592       return;
13593    }
13594 
13595    if (args.expiry_str) {
13596       expire = atoi(args.expiry_str);
13597    } else {
13598       return;
13599    }
13600 
13601    if (args.username) {
13602       ast_string_field_set(peer, username, args.username);
13603    }
13604    if (args.contact) {
13605       ast_string_field_set(peer, fullcontact, args.contact);
13606    }
13607 
13608    ast_debug(2, "SIP Seeding peer from astdb: '%s' at %s@%s for %d\n",
13609        peer->name, peer->username, ast_sockaddr_stringify_host(&sa), expire);
13610 
13611    ast_sockaddr_copy(&peer->addr, &sa);
13612    if (sipsock < 0) {
13613       /* SIP isn't up yet, so schedule a poke only, pretty soon */
13614       AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched, ast_random() % 5000 + 1, sip_poke_peer_s, peer,
13615             unref_peer(_data, "removing poke peer ref"),
13616             unref_peer(peer, "removing poke peer ref"),
13617             ref_peer(peer, "adding poke peer ref"));
13618    } else {
13619       sip_poke_peer(peer, 0);
13620    }
13621    AST_SCHED_REPLACE_UNREF(peer->expire, sched, (expire + 10) * 1000, expire_register, peer,
13622          unref_peer(_data, "remove registration ref"),
13623          unref_peer(peer, "remove registration ref"),
13624          ref_peer(peer, "add registration ref"));
13625    register_peer_exten(peer, TRUE);
13626 }
13627 
13628 /*! \brief Save contact header for 200 OK on INVITE */
13629 static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req)
13630 {
13631    char contact[SIPBUFSIZE];
13632    char *c;
13633 
13634    /* Look for brackets */
13635    ast_copy_string(contact, get_header(req, "Contact"), sizeof(contact));
13636    c = get_in_brackets(contact);
13637 
13638    /* Save full contact to call pvt for later bye or re-invite */
13639    ast_string_field_set(pvt, fullcontact, c);
13640 
13641    /* Save URI for later ACKs, BYE or RE-invites */
13642    ast_string_field_set(pvt, okcontacturi, c);
13643 
13644    /* We should return false for URI:s we can't handle,
13645       like tel:, mailto:,ldap: etc */
13646    return TRUE;      
13647 }
13648 
13649 /*! \brief parse uri in a way that allows semicolon stripping if legacy mode is enabled
13650  *
13651  * \note This calls parse_uri which has the unexpected property that passing more
13652  *       arguments results in more splitting. Most common is to leave out the pass
13653  *       argument, causing user to contain user:pass if available.
13654  */
13655 static int parse_uri_legacy_check(char *uri, const char *scheme, char **user, char **pass, char **hostport, char **transport)
13656 {
13657    int ret = parse_uri(uri, scheme, user, pass, hostport, transport);
13658    if (sip_cfg.legacy_useroption_parsing) { /* if legacy mode is active, strip semis from the user field */
13659       char *p;
13660       if ((p = strchr(uri, (int)';'))) {
13661          *p = '\0';
13662       }
13663    }
13664    return ret;
13665 }
13666 
13667 static int __set_address_from_contact(const char *fullcontact, struct ast_sockaddr *addr, int tcp)
13668 {
13669    char *hostport, *transport;
13670    char contact_buf[256];
13671    char *contact;
13672 
13673    /* Work on a copy */
13674    ast_copy_string(contact_buf, fullcontact, sizeof(contact_buf));
13675    contact = contact_buf;
13676 
13677    /* 
13678     * We have only the part in <brackets> here so we just need to parse a SIP URI.
13679     *
13680     * Note: The outbound proxy could be using UDP between the proxy and Asterisk.
13681     * We still need to be able to send to the remote agent through the proxy.
13682     */
13683 
13684    if (parse_uri_legacy_check(contact, "sip:,sips:", &contact, NULL, &hostport,
13685             &transport)) {
13686       ast_log(LOG_WARNING, "Invalid contact uri %s (missing sip: or sips:), attempting to use anyway\n", fullcontact);
13687    }
13688 
13689    /* XXX This could block for a long time XXX */
13690    /* We should only do this if it's a name, not an IP */
13691    /* \todo - if there's no PORT number in contact - we are required to check NAPTR/SRV records
13692       to find transport, port address and hostname. If there's a port number, we have to
13693       assume that the hostport part is a host name and only look for an A/AAAA record in DNS.
13694    */
13695 
13696    /* If we took in an invalid URI, hostport may not have been initialized */
13697    /* ast_sockaddr_resolve requires an initialized hostport string. */
13698    if (ast_strlen_zero(hostport)) {
13699       ast_log(LOG_WARNING, "Invalid URI: parse_uri failed to acquire hostport\n");
13700       return -1;
13701    }
13702 
13703    if (ast_sockaddr_resolve_first(addr, hostport, 0)) {
13704       ast_log(LOG_WARNING, "Invalid host name in Contact: (can't "
13705          "resolve in DNS) : '%s'\n", hostport);
13706       return -1;
13707    }
13708 
13709    /* set port */
13710    if (!ast_sockaddr_port(addr)) {
13711       ast_sockaddr_set_port(addr,
13712                   (get_transport_str2enum(transport) ==
13713                    SIP_TRANSPORT_TLS ||
13714                    !strncasecmp(fullcontact, "sips", 4)) ?
13715                   STANDARD_TLS_PORT : STANDARD_SIP_PORT);
13716    }
13717 
13718    return 0;
13719 }
13720 
13721 /*! \brief Change the other partys IP address based on given contact */
13722 static int set_address_from_contact(struct sip_pvt *pvt)
13723 {
13724    if (ast_test_flag(&pvt->flags[0], SIP_NAT_FORCE_RPORT)) {
13725       /* NAT: Don't trust the contact field.  Just use what they came to us
13726          with. */
13727       /*! \todo We need to save the TRANSPORT here too */
13728       pvt->sa = pvt->recv;
13729       return 0;
13730    }
13731 
13732    return __set_address_from_contact(pvt->fullcontact, &pvt->sa, pvt->socket.type == SIP_TRANSPORT_TLS ? 1 : 0);
13733 }
13734 
13735 /*! \brief Parse contact header and save registration (peer registration) */
13736 static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *peer, struct sip_request *req)
13737 {
13738    char contact[SIPBUFSIZE];
13739    char data[SIPBUFSIZE];
13740    const char *expires = get_header(req, "Expires");
13741    int expire = atoi(expires);
13742    char *curi = NULL, *hostport = NULL, *transport = NULL;
13743    int transport_type;
13744    const char *useragent;
13745    struct ast_sockaddr oldsin, testsa;
13746    char *firstcuri = NULL;
13747    int start = 0;
13748    int wildcard_found = 0;
13749    int single_binding_found = 0;
13750 
13751    ast_copy_string(contact, __get_header(req, "Contact", &start), sizeof(contact));
13752 
13753    if (ast_strlen_zero(expires)) {  /* No expires header, try look in Contact: */
13754       char *s = strcasestr(contact, ";expires=");
13755       if (s) {
13756          expires = strsep(&s, ";"); /* trim ; and beyond */
13757          if (sscanf(expires + 9, "%30d", &expire) != 1) {
13758             expire = default_expiry;
13759          }
13760       } else {
13761          /* Nothing has been specified */
13762          expire = default_expiry;
13763       }
13764    }
13765 
13766    copy_socket_data(&pvt->socket, &req->socket);
13767 
13768    do {
13769       /* Look for brackets */
13770       curi = contact;
13771       if (strchr(contact, '<') == NULL)   /* No <, check for ; and strip it */
13772          strsep(&curi, ";");  /* This is Header options, not URI options */
13773       curi = get_in_brackets(contact);
13774       if (!firstcuri) {
13775          firstcuri = ast_strdupa(curi);
13776       }
13777 
13778       if (!strcasecmp(curi, "*")) {
13779          wildcard_found = 1;
13780       } else {
13781          single_binding_found = 1;
13782       }
13783 
13784       if (wildcard_found && (ast_strlen_zero(expires) || expire != 0 || single_binding_found)) {
13785          /* Contact header parameter "*" detected, so punt if: Expires header is missing,
13786           * Expires value is not zero, or another Contact header is present. */
13787          return PARSE_REGISTER_FAILED;
13788       }
13789 
13790       ast_copy_string(contact, __get_header(req, "Contact", &start), sizeof(contact));
13791    } while (!ast_strlen_zero(contact));
13792    curi = firstcuri;
13793 
13794    /* if they did not specify Contact: or Expires:, they are querying
13795       what we currently have stored as their contact address, so return
13796       it
13797    */
13798    if (ast_strlen_zero(curi) && ast_strlen_zero(expires)) {
13799       /* If we have an active registration, tell them when the registration is going to expire */
13800       if (peer->expire > -1 && !ast_strlen_zero(peer->fullcontact)) {
13801          pvt->expiry = ast_sched_when(sched, peer->expire);
13802       }
13803       return PARSE_REGISTER_QUERY;
13804    } else if (!strcasecmp(curi, "*") || !expire) { /* Unregister this peer */
13805       /* This means remove all registrations and return OK */
13806       AST_SCHED_DEL_UNREF(sched, peer->expire,
13807             unref_peer(peer, "remove register expire ref"));
13808       ast_verb(3, "Unregistered SIP '%s'\n", peer->name);
13809       expire_register(ref_peer(peer,"add ref for explicit expire_register"));
13810       return PARSE_REGISTER_UPDATE;
13811    }
13812 
13813    /* Store whatever we got as a contact from the client */
13814    ast_string_field_set(peer, fullcontact, curi);
13815 
13816    /* For the 200 OK, we should use the received contact */
13817    ast_string_field_build(pvt, our_contact, "<%s>", curi);
13818 
13819    /* Make sure it's a SIP URL */
13820    if (ast_strlen_zero(curi) || parse_uri_legacy_check(curi, "sip:,sips:", &curi, NULL, &hostport, &transport)) {
13821       ast_log(LOG_NOTICE, "Not a valid SIP contact (missing sip:/sips:) trying to use anyway\n");
13822    }
13823 
13824    /* handle the transport type specified in Contact header. */
13825    if (!(transport_type = get_transport_str2enum(transport))) {
13826       transport_type = pvt->socket.type;
13827    }
13828 
13829    /* if the peer's socket type is different than the Registration
13830     * transport type, change it.  If it got this far, it is a
13831     * supported type, but check just in case */
13832    if ((peer->socket.type != transport_type) && (peer->transports & transport_type)) {
13833       set_socket_transport(&peer->socket, transport_type);
13834    }
13835 
13836    oldsin = peer->addr;
13837 
13838    /* If we were already linked into the peers_by_ip container unlink ourselves so nobody can find us */
13839    if (!ast_sockaddr_isnull(&peer->addr) && (!peer->is_realtime || ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS))) {
13840       ao2_t_unlink(peers_by_ip, peer, "ao2_unlink of peer from peers_by_ip table");
13841    }
13842 
13843    if (!ast_test_flag(&peer->flags[0], SIP_NAT_FORCE_RPORT) && !ast_test_flag(&peer->flags[0], SIP_NAT_RPORT_PRESENT)) {
13844        /* use the data provided in the Contact header for call routing */
13845       ast_debug(1, "Store REGISTER's Contact header for call routing.\n");
13846       /* XXX This could block for a long time XXX */
13847       /*! \todo Check NAPTR/SRV if we have not got a port in the URI */
13848       if (ast_sockaddr_resolve_first(&testsa, hostport, 0)) {
13849          ast_log(LOG_WARNING, "Invalid hostport '%s'\n", hostport);
13850          ast_string_field_set(peer, fullcontact, "");
13851          ast_string_field_set(pvt, our_contact, "");
13852          return PARSE_REGISTER_FAILED;
13853       }
13854 
13855       /* If we have a port number in the given URI, make sure we do remember to not check for NAPTR/SRV records.
13856          The hostport part is actually a host. */
13857       peer->portinuri = ast_sockaddr_port(&testsa) ? TRUE : FALSE;
13858 
13859       if (!ast_sockaddr_port(&testsa)) {
13860          ast_sockaddr_set_port(&testsa,
13861                     transport_type == SIP_TRANSPORT_TLS ?
13862                     STANDARD_TLS_PORT : STANDARD_SIP_PORT);
13863       }
13864 
13865       ast_sockaddr_copy(&peer->addr, &testsa);
13866    } else {
13867       /* Don't trust the contact field.  Just use what they came to us
13868          with */
13869       ast_debug(1, "Store REGISTER's src-IP:port for call routing.\n");
13870       peer->addr = pvt->recv;
13871    }
13872 
13873    /* Check that they're allowed to register at this IP */
13874    if (ast_apply_ha(sip_cfg.contact_ha, &peer->addr) != AST_SENSE_ALLOW ||
13875          ast_apply_ha(peer->contactha, &peer->addr) != AST_SENSE_ALLOW) {
13876       ast_log(LOG_WARNING, "Domain '%s' disallowed by contact ACL (violating IP %s)\n", hostport,
13877          ast_sockaddr_stringify_addr(&testsa));
13878       ast_string_field_set(peer, fullcontact, "");
13879       ast_string_field_set(pvt, our_contact, "");
13880       return PARSE_REGISTER_DENIED;
13881    }
13882 
13883    /* if the Contact header information copied into peer->addr matches the
13884     * received address, and the transport types are the same, then copy socket
13885     * data into the peer struct */
13886    if ((peer->socket.type == pvt->socket.type) &&
13887       !ast_sockaddr_cmp(&peer->addr, &pvt->recv)) {
13888       copy_socket_data(&peer->socket, &pvt->socket);
13889    }
13890 
13891    /* Now that our address has been updated put ourselves back into the container for lookups */
13892    if (!peer->is_realtime || ast_test_flag(&peer->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
13893       ao2_t_link(peers_by_ip, peer, "ao2_link into peers_by_ip table");
13894    }
13895 
13896    /* Save SIP options profile */
13897    peer->sipoptions = pvt->sipoptions;
13898 
13899    if (!ast_strlen_zero(curi) && ast_strlen_zero(peer->username)) {
13900       ast_string_field_set(peer, username, curi);
13901    }
13902 
13903    AST_SCHED_DEL_UNREF(sched, peer->expire,
13904          unref_peer(peer, "remove register expire ref"));
13905 
13906    if (expire > max_expiry) {
13907       expire = max_expiry;
13908    }
13909    if (expire < min_expiry) {
13910       expire = min_expiry;
13911    }
13912    if (peer->is_realtime && !ast_test_flag(&peer->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
13913       peer->expire = -1;
13914    } else {
13915       peer->expire = ast_sched_add(sched, (expire + 10) * 1000, expire_register,
13916             ref_peer(peer, "add registration ref"));
13917       if (peer->expire == -1) {
13918          unref_peer(peer, "remote registration ref");
13919       }
13920    }
13921    pvt->expiry = expire;
13922    snprintf(data, sizeof(data), "%s:%d:%s:%s", ast_sockaddr_stringify(&peer->addr),
13923        expire, peer->username, peer->fullcontact);
13924    /* We might not immediately be able to reconnect via TCP, but try caching it anyhow */
13925    if (!peer->rt_fromcontact || !sip_cfg.peer_rtupdate)
13926       ast_db_put("SIP/Registry", peer->name, data);
13927    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));
13928 
13929    /* Is this a new IP address for us? */
13930    if (VERBOSITY_ATLEAST(2) && ast_sockaddr_cmp(&peer->addr, &oldsin)) {
13931       ast_verbose(VERBOSE_PREFIX_3 "Registered SIP '%s' at %s\n", peer->name,
13932             ast_sockaddr_stringify(&peer->addr));
13933    }
13934    sip_poke_peer(peer, 0);
13935    register_peer_exten(peer, 1);
13936    
13937    /* Save User agent */
13938    useragent = get_header(req, "User-Agent");
13939    if (strcasecmp(useragent, peer->useragent)) {
13940       ast_string_field_set(peer, useragent, useragent);
13941       ast_verb(4, "Saved useragent \"%s\" for peer %s\n", peer->useragent, peer->name);
13942    }
13943    return PARSE_REGISTER_UPDATE;
13944 }
13945 
13946 /*! \brief Remove route from route list */
13947 static void free_old_route(struct sip_route *route)
13948 {
13949    struct sip_route *next;
13950 
13951    while (route) {
13952       next = route->next;
13953       ast_free(route);
13954       route = next;
13955    }
13956 }
13957 
13958 /*! \brief List all routes - mostly for debugging */
13959 static void list_route(struct sip_route *route)
13960 {
13961    if (!route) {
13962       ast_verbose("list_route: no route\n");
13963    } else {
13964       for (;route; route = route->next)
13965          ast_verbose("list_route: hop: <%s>\n", route->hop);
13966    }
13967 }
13968 
13969 /*! \brief Build route list from Record-Route header */
13970 static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards)
13971 {
13972    struct sip_route *thishop, *head, *tail;
13973    int start = 0;
13974    int len;
13975    const char *rr, *contact, *c;
13976 
13977    /* Once a persistent route is set, don't fool with it */
13978    if (p->route && p->route_persistent) {
13979       ast_debug(1, "build_route: Retaining previous route: <%s>\n", p->route->hop);
13980       return;
13981    }
13982 
13983    if (p->route) {
13984       free_old_route(p->route);
13985       p->route = NULL;
13986    }
13987 
13988    /* We only want to create the route set the first time this is called */
13989    p->route_persistent = 1;
13990    
13991    /* Build a tailq, then assign it to p->route when done.
13992     * If backwards, we add entries from the head so they end up
13993     * in reverse order. However, we do need to maintain a correct
13994     * tail pointer because the contact is always at the end.
13995     */
13996    head = NULL;
13997    tail = head;
13998    /* 1st we pass through all the hops in any Record-Route headers */
13999    for (;;) {
14000       /* Each Record-Route header */
14001       rr = __get_header(req, "Record-Route", &start);
14002       if (*rr == '\0') {
14003          break;
14004       }
14005       for (; (rr = strchr(rr, '<')) ; rr += len) { /* Each route entry */
14006          ++rr;
14007          len = strcspn(rr, ">") + 1;
14008          /* Make a struct route */
14009          if ((thishop = ast_malloc(sizeof(*thishop) + len))) {
14010             /* ast_calloc is not needed because all fields are initialized in this block */
14011             ast_copy_string(thishop->hop, rr, len);
14012             ast_debug(2, "build_route: Record-Route hop: <%s>\n", thishop->hop);
14013             /* Link in */
14014             if (backwards) {
14015                /* Link in at head so they end up in reverse order */
14016                thishop->next = head;
14017                head = thishop;
14018                /* If this was the first then it'll be the tail */
14019                if (!tail) {
14020                   tail = thishop;
14021                }
14022             } else {
14023                thishop->next = NULL;
14024                /* Link in at the end */
14025                if (tail) {
14026                   tail->next = thishop;
14027                } else {
14028                   head = thishop;
14029                }
14030                tail = thishop;
14031             }
14032          }
14033       }
14034    }
14035 
14036    /* Only append the contact if we are dealing with a strict router */
14037    if (!head || (!ast_strlen_zero(head->hop) && strstr(head->hop, ";lr") == NULL) ) {
14038       /* 2nd append the Contact: if there is one */
14039       /* Can be multiple Contact headers, comma separated values - we just take the first */
14040       contact = get_header(req, "Contact");
14041       if (!ast_strlen_zero(contact)) {
14042          ast_debug(2, "build_route: Contact hop: %s\n", contact);
14043          /* Look for <: delimited address */
14044          c = strchr(contact, '<');
14045          if (c) {
14046             /* Take to > */
14047             ++c;
14048             len = strcspn(c, ">") + 1;
14049          } else {
14050             /* No <> - just take the lot */
14051             c = contact;
14052             len = strlen(contact) + 1;
14053          }
14054          if ((thishop = ast_malloc(sizeof(*thishop) + len))) {
14055             /* ast_calloc is not needed because all fields are initialized in this block */
14056             ast_copy_string(thishop->hop, c, len);
14057             thishop->next = NULL;
14058             /* Goes at the end */
14059             if (tail) {
14060                tail->next = thishop;
14061             } else {
14062                head = thishop;
14063             }
14064          }
14065       }
14066    }
14067 
14068    /* Store as new route */
14069    p->route = head;
14070 
14071    /* For debugging dump what we ended up with */
14072    if (sip_debug_test_pvt(p)) {
14073       list_route(p->route);
14074    }
14075 }
14076 
14077 /*! \brief builds the sip_pvt's randdata field which is used for the nonce
14078  *  challenge.  When forceupdate is not set, the nonce is only updated if
14079  *  the current one is stale.  In this case, a stalenonce is one which
14080  *  has already received a response, if a nonce has not received a response
14081  *  it is not always necessary or beneficial to create a new one. */
14082 
14083 static void set_nonce_randdata(struct sip_pvt *p, int forceupdate)
14084 {
14085    if (p->stalenonce || forceupdate || ast_strlen_zero(p->randdata)) {
14086       ast_string_field_build(p, randdata, "%08lx", ast_random()); /* Create nonce for challenge */
14087       p->stalenonce = 0;
14088    }
14089 }
14090 
14091 AST_THREADSTORAGE(check_auth_buf);
14092 #define CHECK_AUTH_BUF_INITLEN   256
14093 
14094 /*! \brief  Check user authorization from peer definition
14095    Some actions, like REGISTER and INVITEs from peers require
14096    authentication (if peer have secret set)
14097     \return 0 on success, non-zero on error
14098 */
14099 static enum check_auth_result check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
14100                 const char *secret, const char *md5secret, int sipmethod,
14101                 const char *uri, enum xmittype reliable, int ignore)
14102 {
14103    const char *response;
14104    char *reqheader, *respheader;
14105    const char *authtoken;
14106    char a1_hash[256];
14107    char resp_hash[256]="";
14108    char *c;
14109    int  wrongnonce = FALSE;
14110    int  good_response;
14111    const char *usednonce = p->randdata;
14112    struct ast_str *buf;
14113    int res;
14114 
14115    /* table of recognised keywords, and their value in the digest */
14116    enum keys { K_RESP, K_URI, K_USER, K_NONCE, K_LAST };
14117    struct x {
14118       const char *key;
14119       const char *s;
14120    } *i, keys[] = {
14121       [K_RESP] = { "response=", "" },
14122       [K_URI] = { "uri=", "" },
14123       [K_USER] = { "username=", "" },
14124       [K_NONCE] = { "nonce=", "" },
14125       [K_LAST] = { NULL, NULL}
14126    };
14127 
14128    /* Always OK if no secret */
14129    if (ast_strlen_zero(secret) && ast_strlen_zero(md5secret))
14130       return AUTH_SUCCESSFUL;
14131 
14132    /* Always auth with WWW-auth since we're NOT a proxy */
14133    /* Using proxy-auth in a B2BUA may block proxy authorization in the same transaction */
14134    response = "401 Unauthorized";
14135 
14136    /*
14137     * Note the apparent swap of arguments below, compared to other
14138     * usages of auth_headers().
14139     */
14140    auth_headers(WWW_AUTH, &respheader, &reqheader);
14141 
14142    authtoken =  get_header(req, reqheader);  
14143    if (ignore && !ast_strlen_zero(p->randdata) && ast_strlen_zero(authtoken)) {
14144       /* This is a retransmitted invite/register/etc, don't reconstruct authentication
14145          information */
14146       if (!reliable) {
14147          /* Resend message if this was NOT a reliable delivery.   Otherwise the
14148             retransmission should get it */
14149          transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, 0);
14150          /* Schedule auto destroy in 32 seconds (according to RFC 3261) */
14151          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14152       }
14153       return AUTH_CHALLENGE_SENT;
14154    } else if (ast_strlen_zero(p->randdata) || ast_strlen_zero(authtoken)) {
14155       /* We have no auth, so issue challenge and request authentication */
14156       set_nonce_randdata(p, 1); /* Create nonce for challenge */
14157       transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, 0);
14158       /* Schedule auto destroy in 32 seconds */
14159       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14160       return AUTH_CHALLENGE_SENT;
14161    }
14162 
14163    /* --- We have auth, so check it */
14164 
14165    /* Whoever came up with the authentication section of SIP can suck my %&#$&* for not putting
14166       an example in the spec of just what it is you're doing a hash on. */
14167 
14168    if (!(buf = ast_str_thread_get(&check_auth_buf, CHECK_AUTH_BUF_INITLEN))) {
14169       return AUTH_SECRET_FAILED; /*! XXX \todo need a better return code here */
14170    }
14171 
14172    /* Make a copy of the response and parse it */
14173    res = ast_str_set(&buf, 0, "%s", authtoken);
14174 
14175    if (res == AST_DYNSTR_BUILD_FAILED) {
14176       return AUTH_SECRET_FAILED; /*! XXX \todo need a better return code here */
14177    }
14178 
14179    c = buf->str;
14180 
14181    while(c && *(c = ast_skip_blanks(c)) ) { /* lookup for keys */
14182       for (i = keys; i->key != NULL; i++) {
14183          const char *separator = ",";  /* default */
14184 
14185          if (strncasecmp(c, i->key, strlen(i->key)) != 0) {
14186             continue;
14187          }
14188          /* Found. Skip keyword, take text in quotes or up to the separator. */
14189          c += strlen(i->key);
14190          if (*c == '"') { /* in quotes. Skip first and look for last */
14191             c++;
14192             separator = "\"";
14193          }
14194          i->s = c;
14195          strsep(&c, separator);
14196          break;
14197       }
14198       if (i->key == NULL) { /* not found, jump after space or comma */
14199          strsep(&c, " ,");
14200       }
14201    }
14202 
14203    /* Verify that digest username matches  the username we auth as */
14204    if (strcmp(username, keys[K_USER].s)) {
14205       ast_log(LOG_WARNING, "username mismatch, have <%s>, digest has <%s>\n",
14206          username, keys[K_USER].s);
14207       /* Oops, we're trying something here */
14208       return AUTH_USERNAME_MISMATCH;
14209    }
14210 
14211    /* Verify nonce from request matches our nonce, and the nonce has not already been responded to.
14212     * If this check fails, send 401 with new nonce */
14213    if (strcasecmp(p->randdata, keys[K_NONCE].s) || p->stalenonce) { /* XXX it was 'n'casecmp ? */
14214       wrongnonce = TRUE;
14215       usednonce = keys[K_NONCE].s;
14216    } else {
14217       p->stalenonce = 1; /* now, since the nonce has a response, mark it as stale so it can't be sent or responded to again */
14218    }
14219 
14220    if (!ast_strlen_zero(md5secret)) {
14221       ast_copy_string(a1_hash, md5secret, sizeof(a1_hash));
14222    } else {
14223       char a1[256];
14224 
14225       snprintf(a1, sizeof(a1), "%s:%s:%s", username, p->realm, secret);
14226       ast_md5_hash(a1_hash, a1);
14227    }
14228 
14229    /* compute the expected response to compare with what we received */
14230    {
14231       char a2[256];
14232       char a2_hash[256];
14233       char resp[256];
14234 
14235       snprintf(a2, sizeof(a2), "%s:%s", sip_methods[sipmethod].text,
14236             S_OR(keys[K_URI].s, uri));
14237       ast_md5_hash(a2_hash, a2);
14238       snprintf(resp, sizeof(resp), "%s:%s:%s", a1_hash, usednonce, a2_hash);
14239       ast_md5_hash(resp_hash, resp);
14240    }
14241 
14242    good_response = keys[K_RESP].s &&
14243          !strncasecmp(keys[K_RESP].s, resp_hash, strlen(resp_hash));
14244    if (wrongnonce) {
14245       if (good_response) {
14246          if (sipdebug)
14247             ast_log(LOG_NOTICE, "Correct auth, but based on stale nonce received from '%s'\n", get_header(req, "From"));
14248          /* We got working auth token, based on stale nonce . */
14249          set_nonce_randdata(p, 0);
14250          transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, TRUE);
14251       } else {
14252          /* Everything was wrong, so give the device one more try with a new challenge */
14253          if (!req->ignore) {
14254             if (sipdebug) {
14255                ast_log(LOG_NOTICE, "Bad authentication received from '%s'\n", get_header(req, "To"));
14256             }
14257             set_nonce_randdata(p, 1);
14258          } else {
14259             if (sipdebug) {
14260                ast_log(LOG_NOTICE, "Duplicate authentication received from '%s'\n", get_header(req, "To"));
14261             }
14262          }
14263          transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, FALSE);
14264       }
14265 
14266       /* Schedule auto destroy in 32 seconds */
14267       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14268       return AUTH_CHALLENGE_SENT;
14269    }
14270    if (good_response) {
14271       append_history(p, "AuthOK", "Auth challenge successful for %s", username);
14272       return AUTH_SUCCESSFUL;
14273    }
14274 
14275    /* Ok, we have a bad username/secret pair */
14276    /* Tell the UAS not to re-send this authentication data, because
14277       it will continue to fail
14278    */
14279 
14280    return AUTH_SECRET_FAILED;
14281 }
14282 
14283 /*! \brief Change onhold state of a peer using a pvt structure */
14284 static void sip_peer_hold(struct sip_pvt *p, int hold)
14285 {
14286    if (!p->relatedpeer) {
14287       return;
14288    }
14289 
14290    /* If they put someone on hold, increment the value... otherwise decrement it */
14291    ast_atomic_fetchadd_int(&p->relatedpeer->onHold, (hold ? +1 : -1));
14292 
14293    /* Request device state update */
14294    ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", p->relatedpeer->name);
14295    
14296    return;
14297 }
14298 
14299 /*! \brief Receive MWI events that we have subscribed to */
14300 static void mwi_event_cb(const struct ast_event *event, void *userdata)
14301 {
14302    struct sip_peer *peer = userdata;
14303 
14304    sip_send_mwi_to_peer(peer, 0);
14305 }
14306 
14307 static void network_change_event_subscribe(void)
14308 {
14309    if (!network_change_event_subscription) {
14310       network_change_event_subscription = ast_event_subscribe(AST_EVENT_NETWORK_CHANGE,
14311          network_change_event_cb, "SIP Network Change", NULL, AST_EVENT_IE_END);
14312    }
14313 }
14314 
14315 static void network_change_event_unsubscribe(void)
14316 {
14317    if (network_change_event_subscription) {
14318       network_change_event_subscription = ast_event_unsubscribe(network_change_event_subscription);
14319    }
14320 }
14321 
14322 static int network_change_event_sched_cb(const void *data)
14323 {
14324    network_change_event_sched_id = -1;
14325    sip_send_all_registers();
14326    sip_send_all_mwi_subscriptions();
14327    return 0;
14328 }
14329 
14330 static void network_change_event_cb(const struct ast_event *event, void *userdata)
14331 {
14332    ast_debug(1, "SIP, got a network change event, renewing all SIP registrations.\n");
14333    if (network_change_event_sched_id == -1) {
14334       network_change_event_sched_id = ast_sched_add(sched, 1000, network_change_event_sched_cb, NULL);
14335    }
14336 }
14337 
14338 static void cb_extensionstate_destroy(int id, void *data)
14339 {
14340    struct sip_pvt *p = data;
14341 
14342    dialog_unref(p, "the extensionstate containing this dialog ptr was destroyed");
14343 }
14344 
14345 /*! \brief Callback for the devicestate notification (SUBSCRIBE) support subsystem
14346 \note If you add an "hint" priority to the extension in the dial plan,
14347    you will get notifications on device state changes */
14348 static int cb_extensionstate(char *context, char* exten, int state, void *data)
14349 {
14350    struct sip_pvt *p = data;
14351 
14352    sip_pvt_lock(p);
14353 
14354    switch(state) {
14355    case AST_EXTENSION_DEACTIVATED:  /* Retry after a while */
14356    case AST_EXTENSION_REMOVED:   /* Extension is gone */
14357       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);  /* Delete subscription in 32 secs */
14358       ast_verb(2, "Extension state: Watcher for hint %s %s. Notify User %s\n", exten, state == AST_EXTENSION_DEACTIVATED ? "deactivated" : "removed", p->username);
14359       p->subscribed = NONE;
14360       append_history(p, "Subscribestatus", "%s", state == AST_EXTENSION_REMOVED ? "HintRemoved" : "Deactivated");
14361       break;
14362    default: /* Tell user */
14363       p->laststate = state;
14364       break;
14365    }
14366    if (p->subscribed != NONE) {  /* Only send state NOTIFY if we know the format */
14367       if (!p->pendinginvite) {
14368          transmit_state_notify(p, state, 1, FALSE);
14369       } else {
14370          /* We already have a NOTIFY sent that is not answered. Queue the state up.
14371             if many state changes happen meanwhile, we will only send a notification of the last one */
14372          ast_set_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE);
14373       }
14374    }
14375    ast_verb(2, "Extension Changed %s[%s] new state %s for Notify User %s %s\n", exten, context, ast_extension_state2str(state), p->username,
14376          ast_test_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE) ? "(queued)" : "");
14377 
14378    sip_pvt_unlock(p);
14379 
14380    return 0;
14381 }
14382 
14383 /*! \brief Send a fake 401 Unauthorized response when the administrator
14384   wants to hide the names of local devices  from fishers
14385  */
14386 static void transmit_fake_auth_response(struct sip_pvt *p, int sipmethod, struct sip_request *req, enum xmittype reliable)
14387 {
14388    /* We have to emulate EXACTLY what we'd get with a good peer
14389     * and a bad password, or else we leak information. */
14390    const char *response = "401 Unauthorized";
14391    const char *reqheader = "Authorization";
14392    const char *respheader = "WWW-Authenticate";
14393    const char *authtoken;
14394    struct ast_str *buf;
14395    char *c;
14396 
14397    /* table of recognised keywords, and their value in the digest */
14398    enum keys { K_NONCE, K_LAST };
14399    struct x {
14400       const char *key;
14401       const char *s;
14402    } *i, keys[] = {
14403       [K_NONCE] = { "nonce=", "" },
14404       [K_LAST] = { NULL, NULL}
14405    };
14406 
14407    authtoken = get_header(req, reqheader);
14408    if (req->ignore && !ast_strlen_zero(p->randdata) && ast_strlen_zero(authtoken)) {
14409       /* This is a retransmitted invite/register/etc, don't reconstruct authentication
14410        * information */
14411       transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, 0);
14412       /* Schedule auto destroy in 32 seconds (according to RFC 3261) */
14413       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14414       return;
14415    } else if (ast_strlen_zero(p->randdata) || ast_strlen_zero(authtoken)) {
14416       /* We have no auth, so issue challenge and request authentication */
14417       set_nonce_randdata(p, 1);
14418       transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, 0);
14419       /* Schedule auto destroy in 32 seconds */
14420       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14421       return;
14422    }
14423 
14424    if (!(buf = ast_str_thread_get(&check_auth_buf, CHECK_AUTH_BUF_INITLEN))) {
14425       transmit_response(p, "403 Forbidden (Bad auth)", &p->initreq);
14426       return;
14427    }
14428 
14429    /* Make a copy of the response and parse it */
14430    if (ast_str_set(&buf, 0, "%s", authtoken) == AST_DYNSTR_BUILD_FAILED) {
14431       transmit_response(p, "403 Forbidden (Bad auth)", &p->initreq);
14432       return;
14433    }
14434 
14435    c = buf->str;
14436 
14437    while (c && *(c = ast_skip_blanks(c))) { /* lookup for keys */
14438       for (i = keys; i->key != NULL; i++) {
14439          const char *separator = ",";  /* default */
14440 
14441          if (strncasecmp(c, i->key, strlen(i->key)) != 0) {
14442             continue;
14443          }
14444          /* Found. Skip keyword, take text in quotes or up to the separator. */
14445          c += strlen(i->key);
14446          if (*c == '"') { /* in quotes. Skip first and look for last */
14447             c++;
14448             separator = "\"";
14449          }
14450          i->s = c;
14451          strsep(&c, separator);
14452          break;
14453       }
14454       if (i->key == NULL) { /* not found, jump after space or comma */
14455          strsep(&c, " ,");
14456       }
14457    }
14458 
14459    /* Verify nonce from request matches our nonce.  If not, send 401 with new nonce */
14460    if (strcasecmp(p->randdata, keys[K_NONCE].s)) {
14461       if (!req->ignore) {
14462          set_nonce_randdata(p, 1);
14463       }
14464       transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, FALSE);
14465 
14466       /* Schedule auto destroy in 32 seconds */
14467       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14468    } else {
14469       transmit_response(p, "403 Forbidden (Bad auth)", &p->initreq);
14470    }
14471 }
14472 
14473 /*!
14474  * Terminate the uri at the first ';' or space.
14475  * Technically we should ignore escaped space per RFC3261 (19.1.1 etc)
14476  * but don't do it for the time being. Remember the uri format is:
14477  * (User-parameters was added after RFC 3261)
14478  *\verbatim
14479  *
14480  * sip:user:password;user-parameters@host:port;uri-parameters?headers
14481  * sips:user:password;user-parameters@host:port;uri-parameters?headers
14482  *
14483  *\endverbatim
14484  * \todo As this function does not support user-parameters, it's considered broken
14485  * and needs fixing.
14486  */
14487 static char *terminate_uri(char *uri)
14488 {
14489    char *t = uri;
14490    while (*t && *t > ' ' && *t != ';') {
14491       t++;
14492    }
14493    *t = '\0';
14494    return uri;
14495 }
14496 
14497 /*! \brief Terminate a host:port at the ':'
14498  * \param hostport The address of the hostport string
14499  *
14500  * \note In the case of a bracket-enclosed IPv6 address, the hostport variable
14501  * will contain the non-bracketed host as a result of calling this function.
14502  */
14503 static void extract_host_from_hostport(char **hostport)
14504 {
14505    char *dont_care;
14506    ast_sockaddr_split_hostport(*hostport, hostport, &dont_care, PARSE_PORT_IGNORE);
14507 }
14508 
14509 /*! \brief Verify registration of user
14510    - Registration is done in several steps, first a REGISTER without auth
14511      to get a challenge (nonce) then a second one with auth
14512    - Registration requests are only matched with peers that are marked as "dynamic"
14513  */
14514 static enum check_auth_result register_verify(struct sip_pvt *p, struct ast_sockaddr *addr,
14515                      struct sip_request *req, const char *uri)
14516 {
14517    enum check_auth_result res = AUTH_NOT_FOUND;
14518    struct sip_peer *peer;
14519    char tmp[256];
14520    char *c, *name, *unused_password, *domain;
14521    char *uri2 = ast_strdupa(uri);
14522 
14523    terminate_uri(uri2);
14524 
14525    ast_copy_string(tmp, get_header(req, "To"), sizeof(tmp));
14526 
14527    c = get_in_brackets(tmp);
14528    c = remove_uri_parameters(c);
14529 
14530    if (parse_uri_legacy_check(c, "sip:,sips:", &name, &unused_password, &domain, NULL)) {
14531       ast_log(LOG_NOTICE, "Invalid to address: '%s' from %s (missing sip:) trying to use anyway...\n", c, ast_sockaddr_stringify_addr(addr));
14532       return -1;
14533    }
14534 
14535    SIP_PEDANTIC_DECODE(name);
14536    SIP_PEDANTIC_DECODE(domain);
14537 
14538    extract_host_from_hostport(&domain);
14539 
14540    if (ast_strlen_zero(domain)) {
14541       /* <sip:name@[EMPTY]>, never good */
14542       transmit_response(p, "404 Not found", &p->initreq);
14543       return AUTH_UNKNOWN_DOMAIN;
14544    }
14545 
14546    if (ast_strlen_zero(name)) {
14547       /* <sip:[EMPTY][@]hostport>, unsure whether valid for
14548        * registration. RFC 3261, 10.2 states:
14549        * "The To header field and the Request-URI field typically
14550        * differ, as the former contains a user name."
14551        * But, Asterisk has always treated the domain-only uri as a
14552        * username: we allow admins to create accounts described by
14553        * domain name. */
14554       name = domain;
14555    }
14556 
14557    /* This here differs from 1.4 and 1.6: the domain matching ACLs were
14558     * skipped if it was a domain-only URI (used as username). Here we treat
14559     * <sip:hostport> as <sip:host@hostport> and won't forget to test the
14560     * domain ACLs against host. */
14561    if (!AST_LIST_EMPTY(&domain_list)) {
14562       if (!check_sip_domain(domain, NULL, 0)) {
14563          if (sip_cfg.alwaysauthreject) {
14564             transmit_fake_auth_response(p, SIP_REGISTER, &p->initreq, XMIT_UNRELIABLE);
14565          } else {
14566             transmit_response(p, "404 Not found (unknown domain)", &p->initreq);
14567          }
14568          return AUTH_UNKNOWN_DOMAIN;
14569       }
14570    }
14571 
14572    ast_string_field_set(p, exten, name);
14573    build_contact(p);
14574    if (req->ignore) {
14575       /* Expires is a special case, where we only want to load the peer if this isn't a deregistration attempt */
14576       const char *expires = get_header(req, "Expires");
14577       int expire = atoi(expires);
14578 
14579       if (ast_strlen_zero(expires)) { /* No expires header; look in Contact */
14580          if ((expires = strcasestr(get_header(req, "Contact"), ";expires="))) {
14581             expire = atoi(expires + 9);
14582          }
14583       }
14584       if (!ast_strlen_zero(expires) && expire == 0) {
14585          transmit_response_with_date(p, "200 OK", req);
14586          return 0;
14587       }
14588    }
14589    peer = find_peer(name, NULL, TRUE, FINDPEERS, FALSE, 0);
14590 
14591    if (!(peer && ast_apply_ha(peer->ha, addr))) {
14592       /* Peer fails ACL check */
14593       if (peer) {
14594          unref_peer(peer, "register_verify: unref_peer: from find_peer operation");
14595          peer = NULL;
14596          res = AUTH_ACL_FAILED;
14597       } else {
14598          res = AUTH_NOT_FOUND;
14599       }
14600    }
14601 
14602    if (peer) {
14603       ao2_lock(peer);
14604       if (!peer->host_dynamic) {
14605          ast_log(LOG_ERROR, "Peer '%s' is trying to register, but not configured as host=dynamic\n", peer->name);
14606          res = AUTH_PEER_NOT_DYNAMIC;
14607       } else {
14608          ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_NAT_FORCE_RPORT);
14609          if (!(res = check_auth(p, req, peer->name, peer->secret, peer->md5secret, SIP_REGISTER, uri2, XMIT_UNRELIABLE, req->ignore))) {
14610             if (sip_cancel_destroy(p))
14611                ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
14612 
14613             if (check_request_transport(peer, req)) {
14614                ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
14615                transmit_response_with_date(p, "403 Forbidden", req);
14616                res = AUTH_BAD_TRANSPORT;
14617             } else {
14618 
14619                /* We have a successful registration attempt with proper authentication,
14620                   now, update the peer */
14621                switch (parse_register_contact(p, peer, req)) {
14622                case PARSE_REGISTER_DENIED:
14623                   ast_log(LOG_WARNING, "Registration denied because of contact ACL\n");
14624                   transmit_response_with_date(p, "603 Denied", req);
14625                   peer->lastmsgssent = -1;
14626                   res = 0;
14627                   break;
14628                case PARSE_REGISTER_FAILED:
14629                   ast_log(LOG_WARNING, "Failed to parse contact info\n");
14630                   transmit_response_with_date(p, "400 Bad Request", req);
14631                   peer->lastmsgssent = -1;
14632                   res = 0;
14633                   break;
14634                case PARSE_REGISTER_QUERY:
14635                   ast_string_field_set(p, fullcontact, peer->fullcontact);
14636                   transmit_response_with_date(p, "200 OK", req);
14637                   peer->lastmsgssent = -1;
14638                   res = 0;
14639                   break;
14640                case PARSE_REGISTER_UPDATE:
14641                   ast_string_field_set(p, fullcontact, peer->fullcontact);
14642                   update_peer(peer, p->expiry);
14643                   /* Say OK and ask subsystem to retransmit msg counter */
14644                   transmit_response_with_date(p, "200 OK", req);
14645                   if (!ast_test_flag((&peer->flags[1]), SIP_PAGE2_SUBSCRIBEMWIONLY))
14646                      peer->lastmsgssent = -1;
14647                   res = 0;
14648                   break;
14649                }
14650             }
14651 
14652          }
14653       }
14654       ao2_unlock(peer);
14655    }
14656    if (!peer && sip_cfg.autocreatepeer) {
14657       /* Create peer if we have autocreate mode enabled */
14658       peer = temp_peer(name);
14659       if (peer) {
14660          ao2_t_link(peers, peer, "link peer into peer table");
14661          if (!ast_sockaddr_isnull(&peer->addr)) {
14662             ao2_t_link(peers_by_ip, peer, "link peer into peers-by-ip table");
14663          }
14664          ao2_lock(peer);
14665          if (sip_cancel_destroy(p))
14666             ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
14667          switch (parse_register_contact(p, peer, req)) {
14668          case PARSE_REGISTER_DENIED:
14669             ast_log(LOG_WARNING, "Registration denied because of contact ACL\n");
14670             transmit_response_with_date(p, "403 Forbidden (ACL)", req);
14671             peer->lastmsgssent = -1;
14672             res = 0;
14673             break;
14674          case PARSE_REGISTER_FAILED:
14675             ast_log(LOG_WARNING, "Failed to parse contact info\n");
14676             transmit_response_with_date(p, "400 Bad Request", req);
14677             peer->lastmsgssent = -1;
14678             res = 0;
14679             break;
14680          case PARSE_REGISTER_QUERY:
14681             ast_string_field_set(p, fullcontact, peer->fullcontact);
14682             transmit_response_with_date(p, "200 OK", req);
14683             peer->lastmsgssent = -1;
14684             res = 0;
14685             break;
14686          case PARSE_REGISTER_UPDATE:
14687             ast_string_field_set(p, fullcontact, peer->fullcontact);
14688             /* Say OK and ask subsystem to retransmit msg counter */
14689             transmit_response_with_date(p, "200 OK", req);
14690             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));
14691             peer->lastmsgssent = -1;
14692             res = 0;
14693             break;
14694          }
14695          ao2_unlock(peer);
14696       }
14697    }
14698    if (!res) {
14699       ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", peer->name);
14700    }
14701    if (res < 0) {
14702       switch (res) {
14703       case AUTH_SECRET_FAILED:
14704          /* Wrong password in authentication. Go away, don't try again until you fixed it */
14705          transmit_response(p, "403 Forbidden (Bad auth)", &p->initreq);
14706          if (global_authfailureevents) {
14707             const char *peer_addr = ast_strdupa(ast_sockaddr_stringify_addr(addr));
14708             const char *peer_port = ast_strdupa(ast_sockaddr_stringify_port(addr));
14709             manager_event(EVENT_FLAG_SYSTEM, "PeerStatus",
14710                      "ChannelType: SIP\r\n"
14711                      "Peer: SIP/%s\r\n"
14712                      "PeerStatus: Rejected\r\n"
14713                      "Cause: AUTH_SECRET_FAILED\r\n"
14714                      "Address: %s\r\n"
14715                      "Port: %s\r\n",
14716                      name, peer_addr, peer_port);
14717          }
14718          break;
14719       case AUTH_USERNAME_MISMATCH:
14720          /* Username and digest username does not match.
14721             Asterisk uses the From: username for authentication. We need the
14722             devices to use the same authentication user name until we support
14723             proper authentication by digest auth name */
14724       case AUTH_NOT_FOUND:
14725       case AUTH_PEER_NOT_DYNAMIC:
14726       case AUTH_ACL_FAILED:
14727          if (sip_cfg.alwaysauthreject) {
14728             transmit_fake_auth_response(p, SIP_REGISTER, &p->initreq, XMIT_UNRELIABLE);
14729             if (global_authfailureevents) {
14730                const char *peer_addr = ast_strdupa(ast_sockaddr_stringify_addr(addr));
14731                const char *peer_port = ast_strdupa(ast_sockaddr_stringify_port(addr));
14732                manager_event(EVENT_FLAG_SYSTEM, "PeerStatus",
14733                         "ChannelType: SIP\r\n"
14734                         "Peer: SIP/%s\r\n"
14735                         "PeerStatus: Rejected\r\n"
14736                         "Cause: %s\r\n"
14737                         "Address: %s\r\n"
14738                         "Port: %s\r\n",
14739                         name,
14740                         res == AUTH_PEER_NOT_DYNAMIC ? "AUTH_PEER_NOT_DYNAMIC" : "URI_NOT_FOUND",
14741                         peer_addr, peer_port);
14742             }
14743          } else {
14744             /* URI not found */
14745             if (res == AUTH_PEER_NOT_DYNAMIC) {
14746                transmit_response(p, "403 Forbidden", &p->initreq);
14747                if (global_authfailureevents) {
14748                   const char *peer_addr = ast_strdupa(ast_sockaddr_stringify_addr(addr));
14749                   const char *peer_port = ast_strdupa(ast_sockaddr_stringify_port(addr));
14750                   manager_event(EVENT_FLAG_SYSTEM, "PeerStatus",
14751                      "ChannelType: SIP\r\n"
14752                      "Peer: SIP/%s\r\n"
14753                      "PeerStatus: Rejected\r\n"
14754                      "Cause: AUTH_PEER_NOT_DYNAMIC\r\n"
14755                      "Address: %s\r\n"
14756                      "Port: %s\r\n",
14757                      name, peer_addr, peer_port);
14758                }
14759             } else {
14760                transmit_response(p, "404 Not found", &p->initreq);
14761                if (global_authfailureevents) {
14762                   const char *peer_addr = ast_strdupa(ast_sockaddr_stringify_addr(addr));
14763                   const char *peer_port = ast_strdupa(ast_sockaddr_stringify_port(addr));
14764                   manager_event(EVENT_FLAG_SYSTEM, "PeerStatus",
14765                      "ChannelType: SIP\r\n"
14766                      "Peer: SIP/%s\r\n"
14767                      "PeerStatus: Rejected\r\n"
14768                      "Cause: %s\r\n"
14769                      "Address: %s\r\n"
14770                      "Port: %s\r\n",
14771                      name,
14772                      (res == AUTH_USERNAME_MISMATCH) ? "AUTH_USERNAME_MISMATCH" : "URI_NOT_FOUND",
14773                      peer_addr, peer_port);
14774                }
14775             }
14776          }
14777          break;
14778       case AUTH_BAD_TRANSPORT:
14779       default:
14780          break;
14781       }
14782    }
14783    if (peer) {
14784       unref_peer(peer, "register_verify: unref_peer: tossing stack peer pointer at end of func");
14785    }
14786 
14787    return res;
14788 }
14789 
14790 /*! \brief Translate referring cause */
14791 static void sip_set_redirstr(struct sip_pvt *p, char *reason) {
14792 
14793    if (!strcmp(reason, "unknown")) {
14794       ast_string_field_set(p, redircause, "UNKNOWN");
14795    } else if (!strcmp(reason, "user-busy")) {
14796       ast_string_field_set(p, redircause, "BUSY");
14797    } else if (!strcmp(reason, "no-answer")) {
14798       ast_string_field_set(p, redircause, "NOANSWER");
14799    } else if (!strcmp(reason, "unavailable")) {
14800       ast_string_field_set(p, redircause, "UNREACHABLE");
14801    } else if (!strcmp(reason, "unconditional")) {
14802       ast_string_field_set(p, redircause, "UNCONDITIONAL");
14803    } else if (!strcmp(reason, "time-of-day")) {
14804       ast_string_field_set(p, redircause, "UNKNOWN");
14805    } else if (!strcmp(reason, "do-not-disturb")) {
14806       ast_string_field_set(p, redircause, "UNKNOWN");
14807    } else if (!strcmp(reason, "deflection")) {
14808       ast_string_field_set(p, redircause, "UNKNOWN");
14809    } else if (!strcmp(reason, "follow-me")) {
14810       ast_string_field_set(p, redircause, "UNKNOWN");
14811    } else if (!strcmp(reason, "out-of-service")) {
14812       ast_string_field_set(p, redircause, "UNREACHABLE");
14813    } else if (!strcmp(reason, "away")) {
14814       ast_string_field_set(p, redircause, "UNREACHABLE");
14815    } else {
14816       ast_string_field_set(p, redircause, "UNKNOWN");
14817    }
14818 }
14819 
14820 /*! \brief Parse the parts of the P-Asserted-Identity header
14821  * on an incoming packet. Returns 1 if a valid header is found
14822  * and it is different from the current caller id.
14823  */
14824 static int get_pai(struct sip_pvt *p, struct sip_request *req)
14825 {
14826    char pai[256];
14827    char privacy[64];
14828    char *cid_num = "";
14829    char *cid_name = "";
14830    int callingpres = AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
14831    char *start = NULL, *end = NULL, *uri = NULL;
14832 
14833    ast_copy_string(pai, get_header(req, "P-Asserted-Identity"), sizeof(pai));
14834 
14835    if (ast_strlen_zero(pai)) {
14836       return 0;
14837    }
14838 
14839    start = pai;
14840    if (*start == '"') {
14841       *start++ = '\0';
14842       end = strchr(start, '"');
14843       if (!end) {
14844          return 0;
14845       }
14846       *end++ = '\0';
14847       cid_name = start;
14848       start = ast_skip_blanks(end);
14849    }
14850 
14851    if (*start != '<')
14852       return 0;
14853    /* At this point, 'start' points to the URI in brackets.
14854     * We need a copy so that our comparison to the anonymous
14855     * URI is valid.
14856     */
14857    uri = ast_strdupa(start);
14858    *start++ = '\0';
14859    end = strchr(start, '@');
14860    if (!end) {
14861       return 0;
14862    }
14863    *end++ = '\0';
14864    if (!strncasecmp(uri, "sip:anonymous@anonymous.invalid", 31)) {
14865       callingpres = AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED;
14866       /*XXX Assume no change in cid_num. Perhaps it should be
14867        * blanked?
14868        */
14869       cid_num = (char *)p->cid_num;
14870    } else if (!strncasecmp(start, "sip:", 4)) {
14871       cid_num = start + 4;
14872       if (global_shrinkcallerid && ast_is_shrinkable_phonenumber(cid_num))
14873          ast_shrink_phone_number(cid_num);
14874       start = end;
14875 
14876       end = strchr(start, '>');
14877       if (!end) {
14878          return 0;
14879       }
14880       *end = '\0';
14881    } else {
14882       return 0;
14883    }
14884 
14885    ast_copy_string(privacy, get_header(req, "Privacy"), sizeof(privacy));
14886    if (!ast_strlen_zero(privacy) && strncmp(privacy, "id", 2)) {
14887       callingpres = AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED;
14888    }
14889 
14890    /* Only return true if the supplied caller id is different */
14891    if (!strcasecmp(p->cid_num, cid_num) && !strcasecmp(p->cid_name, cid_name) && p->callingpres == callingpres) {
14892       return 0;
14893    }
14894 
14895    ast_string_field_set(p, cid_num, cid_num);
14896    ast_string_field_set(p, cid_name, cid_name);
14897    p->callingpres = callingpres;
14898 
14899    if (p->owner) {
14900       ast_set_callerid(p->owner, cid_num, cid_name, NULL);
14901       p->owner->caller.id.name.presentation = callingpres;
14902       p->owner->caller.id.number.presentation = callingpres;
14903    }
14904 
14905    return 1;
14906 }
14907 
14908 /*! \brief Get name, number and presentation from remote party id header,
14909  *  returns true if a valid header was found and it was different from the
14910  *  current caller id.
14911  */
14912 static int get_rpid(struct sip_pvt *p, struct sip_request *oreq)
14913 {
14914    char tmp[256];
14915    struct sip_request *req;
14916    char *cid_num = "";
14917    char *cid_name = "";
14918    int callingpres = AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
14919    char *privacy = "";
14920    char *screen = "";
14921    char *start, *end;
14922 
14923    if (!ast_test_flag(&p->flags[0], SIP_TRUSTRPID))
14924       return 0;
14925    req = oreq;
14926    if (!req)
14927       req = &p->initreq;
14928    ast_copy_string(tmp, get_header(req, "Remote-Party-ID"), sizeof(tmp));
14929    if (ast_strlen_zero(tmp)) {
14930       return get_pai(p, req);
14931    }
14932 
14933    start = tmp;
14934    if (*start == '"') {
14935       *start++ = '\0';
14936       end = strchr(start, '"');
14937       if (!end)
14938          return 0;
14939       *end++ = '\0';
14940       cid_name = start;
14941       start = ast_skip_blanks(end);
14942    }
14943 
14944    if (*start != '<')
14945       return 0;
14946    *start++ = '\0';
14947    end = strchr(start, '@');
14948    if (!end)
14949       return 0;
14950    *end++ = '\0';
14951    if (strncasecmp(start, "sip:", 4))
14952       return 0;
14953    cid_num = start + 4;
14954    if (global_shrinkcallerid && ast_is_shrinkable_phonenumber(cid_num))
14955       ast_shrink_phone_number(cid_num);
14956    start = end;
14957 
14958    end = strchr(start, '>');
14959    if (!end)
14960       return 0;
14961    *end++ = '\0';
14962    if (*end) {
14963       start = end;
14964       if (*start != ';')
14965          return 0;
14966       *start++ = '\0';
14967       while (!ast_strlen_zero(start)) {
14968          end = strchr(start, ';');
14969          if (end)
14970             *end++ = '\0';
14971          if (!strncasecmp(start, "privacy=", 8))
14972             privacy = start + 8;
14973          else if (!strncasecmp(start, "screen=", 7))
14974             screen = start + 7;
14975          start = end;
14976       }
14977 
14978       if (!strcasecmp(privacy, "full")) {
14979          if (!strcasecmp(screen, "yes"))
14980             callingpres = AST_PRES_PROHIB_USER_NUMBER_PASSED_SCREEN;
14981          else if (!strcasecmp(screen, "no"))
14982             callingpres = AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED;
14983       } else {
14984          if (!strcasecmp(screen, "yes"))
14985             callingpres = AST_PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN;
14986          else if (!strcasecmp(screen, "no"))
14987             callingpres = AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
14988       }
14989    }
14990 
14991    /* Only return true if the supplied caller id is different */
14992    if (!strcasecmp(p->cid_num, cid_num) && !strcasecmp(p->cid_name, cid_name) && p->callingpres == callingpres)
14993       return 0;
14994 
14995    ast_string_field_set(p, cid_num, cid_num);
14996    ast_string_field_set(p, cid_name, cid_name);
14997    p->callingpres = callingpres;
14998 
14999    if (p->owner) {
15000       ast_set_callerid(p->owner, cid_num, cid_name, NULL);
15001       p->owner->caller.id.name.presentation = callingpres;
15002       p->owner->caller.id.number.presentation = callingpres;
15003    }
15004 
15005    return 1;
15006 }
15007 
15008 /*! \brief Get referring dnis */
15009 static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq, char **name, char **number, int *reason)
15010 {
15011    char tmp[256], *exten, *rexten, *rdomain, *rname = NULL;
15012    char *params, *reason_param = NULL;
15013    struct sip_request *req;
15014 
15015    req = oreq ? oreq : &p->initreq;
15016 
15017    ast_copy_string(tmp, get_header(req, "Diversion"), sizeof(tmp));
15018    if (ast_strlen_zero(tmp))
15019       return -1;
15020 
15021    if ((params = strchr(tmp, '>'))) {
15022       params = strchr(params, ';');
15023    }
15024 
15025    exten = get_in_brackets(tmp);
15026    if (!strncasecmp(exten, "sip:", 4)) {
15027       exten += 4;
15028    } else if (!strncasecmp(exten, "sips:", 5)) {
15029       exten += 5;
15030    } else {
15031       ast_log(LOG_WARNING, "Huh?  Not an RDNIS SIP header (%s)?\n", exten);
15032       return -1;
15033    }
15034 
15035    /* Get diversion-reason param if present */
15036    if (params) {
15037       *params = '\0';   /* Cut off parameters  */
15038       params++;
15039       while (*params == ';' || *params == ' ')
15040          params++;
15041       /* Check if we have a reason parameter */
15042       if ((reason_param = strcasestr(params, "reason="))) {
15043          char *end;
15044          reason_param+=7;
15045          if ((end = strchr(reason_param, ';'))) {
15046             *end = '\0';
15047          }
15048          /* Remove enclosing double-quotes */
15049          if (*reason_param == '"')
15050             ast_strip_quoted(reason_param, "\"", "\"");
15051          if (!ast_strlen_zero(reason_param)) {
15052             sip_set_redirstr(p, reason_param);
15053             if (p->owner) {
15054                pbx_builtin_setvar_helper(p->owner, "__PRIREDIRECTREASON", p->redircause);
15055                pbx_builtin_setvar_helper(p->owner, "__SIPREDIRECTREASON", reason_param);
15056             }
15057          }
15058       }
15059    }
15060 
15061    rdomain = exten;
15062    rexten = strsep(&rdomain, "@");  /* trim anything after @ */
15063    if (p->owner)
15064       pbx_builtin_setvar_helper(p->owner, "__SIPRDNISDOMAIN", rdomain);
15065 
15066    if (sip_debug_test_pvt(p))
15067       ast_verbose("RDNIS for this call is %s (reason %s)\n", exten, reason ? reason_param : "");
15068 
15069    /*ast_string_field_set(p, rdnis, rexten);*/
15070 
15071    if (*tmp == '\"') {
15072       char *end_quote;
15073       rname = tmp + 1;
15074       end_quote = strchr(rname, '\"');
15075       *end_quote = '\0';
15076    }
15077 
15078    if (number) {
15079       *number = ast_strdup(rexten);
15080    }
15081 
15082    if (name && rname) {
15083       *name = ast_strdup(rname);
15084    }
15085 
15086    if (reason && !ast_strlen_zero(reason_param)) {
15087       *reason = sip_reason_str_to_code(reason_param);
15088    }
15089 
15090    return 0;
15091 }
15092 
15093 /*!
15094  * \brief Find out who the call is for.
15095  *
15096  * \details
15097  * We use the request uri as a destination.
15098  * This code assumes authentication has been done, so that the
15099  * device (peer/user) context is already set.
15100  *
15101  * \return 0 on success (found a matching extension), non-zero on failure
15102  *
15103  * \note If the incoming uri is a SIPS: uri, we are required to carry this across
15104  * the dialplan, so that the outbound call also is a sips: call or encrypted
15105  * IAX2 call. If that's not available, the call should FAIL.
15106  */
15107 static enum sip_get_dest_result get_destination(struct sip_pvt *p, struct sip_request *oreq, int *cc_recall_core_id)
15108 {
15109    char tmp[256] = "", *uri, *unused_password, *domain;
15110    char tmpf[256] = "", *from = NULL;
15111    struct sip_request *req;
15112    char *decoded_uri;
15113 
15114    req = oreq;
15115    if (!req) {
15116       req = &p->initreq;
15117    }
15118 
15119    /* Find the request URI */
15120    if (req->rlPart2)
15121       ast_copy_string(tmp, REQ_OFFSET_TO_STR(req, rlPart2), sizeof(tmp));
15122    
15123    uri = ast_strdupa(get_in_brackets(tmp));
15124 
15125    if (parse_uri_legacy_check(uri, "sip:,sips:", &uri, &unused_password, &domain, NULL)) {
15126       ast_log(LOG_WARNING, "Not a SIP header (%s)?\n", uri);
15127       return SIP_GET_DEST_INVALID_URI;
15128    }
15129 
15130    SIP_PEDANTIC_DECODE(domain);
15131    SIP_PEDANTIC_DECODE(uri);
15132 
15133    extract_host_from_hostport(&domain);
15134 
15135    if (ast_strlen_zero(uri)) {
15136       /*
15137        * Either there really was no extension found or the request
15138        * URI had encoded nulls that made the string "empty".  Use "s"
15139        * as the extension.
15140        */
15141       uri = "s";
15142    }
15143 
15144    ast_string_field_set(p, domain, domain);
15145 
15146    /* Now find the From: caller ID and name */
15147    /* XXX Why is this done in get_destination? Isn't it already done?
15148       Needs to be checked
15149         */
15150    ast_copy_string(tmpf, get_header(req, "From"), sizeof(tmpf));
15151    if (!ast_strlen_zero(tmpf)) {
15152       from = get_in_brackets(tmpf);
15153       if (parse_uri_legacy_check(from, "sip:,sips:", &from, NULL, &domain, NULL)) {
15154          ast_log(LOG_WARNING, "Not a SIP header (%s)?\n", from);
15155          return SIP_GET_DEST_INVALID_URI;
15156       }
15157 
15158       SIP_PEDANTIC_DECODE(from);
15159       SIP_PEDANTIC_DECODE(domain);
15160 
15161       extract_host_from_hostport(&domain);
15162 
15163       ast_string_field_set(p, fromdomain, domain);
15164    }
15165 
15166    if (!AST_LIST_EMPTY(&domain_list)) {
15167       char domain_context[AST_MAX_EXTENSION];
15168 
15169       domain_context[0] = '\0';
15170       if (!check_sip_domain(p->domain, domain_context, sizeof(domain_context))) {
15171          if (!sip_cfg.allow_external_domains && (req->method == SIP_INVITE || req->method == SIP_REFER)) {
15172             ast_debug(1, "Got SIP %s to non-local domain '%s'; refusing request.\n", sip_methods[req->method].text, p->domain);
15173             return SIP_GET_DEST_REFUSED;
15174          }
15175       }
15176       /* If we don't have a peer (i.e. we're a guest call),
15177        * overwrite the original context */
15178       if (!ast_test_flag(&p->flags[1], SIP_PAGE2_HAVEPEERCONTEXT) && !ast_strlen_zero(domain_context)) {
15179          ast_string_field_set(p, context, domain_context);
15180       }
15181    }
15182 
15183    /* If the request coming in is a subscription and subscribecontext has been specified use it */
15184    if (req->method == SIP_SUBSCRIBE && !ast_strlen_zero(p->subscribecontext)) {
15185       ast_string_field_set(p, context, p->subscribecontext);
15186    }
15187 
15188    if (sip_debug_test_pvt(p)) {
15189       ast_verbose("Looking for %s in %s (domain %s)\n", uri, p->context, p->domain);
15190    }
15191 
15192    /* Since extensions.conf can have unescaped characters, try matching a
15193     * decoded uri in addition to the non-decoded uri. */
15194    decoded_uri = ast_strdupa(uri);
15195    ast_uri_decode(decoded_uri);
15196 
15197    /* If this is a subscription we actually just need to see if a hint exists for the extension */
15198    if (req->method == SIP_SUBSCRIBE) {
15199       char hint[AST_MAX_EXTENSION];
15200       int which = 0;
15201       if (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, p->context, uri) ||
15202           (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, p->context, decoded_uri) && (which = 1))) {
15203          if (!oreq) {
15204             ast_string_field_set(p, exten, which ? decoded_uri : uri);
15205          }
15206          return SIP_GET_DEST_EXTEN_FOUND;
15207       } else {
15208          return SIP_GET_DEST_EXTEN_NOT_FOUND;
15209       }
15210    } else {
15211       struct ast_cc_agent *agent;
15212       /* Check the dialplan for the username part of the request URI,
15213          the domain will be stored in the SIPDOMAIN variable
15214          Return 0 if we have a matching extension */
15215       if (ast_exists_extension(NULL, p->context, uri, 1, S_OR(p->cid_num, from))) {
15216          if (!oreq) {
15217             ast_string_field_set(p, exten, uri);
15218          }
15219          return SIP_GET_DEST_EXTEN_FOUND;
15220       }
15221       if (ast_exists_extension(NULL, p->context, decoded_uri, 1, S_OR(p->cid_num, from))
15222          || !strcmp(decoded_uri, ast_pickup_ext())) {
15223          if (!oreq) {
15224             ast_string_field_set(p, exten, decoded_uri);
15225          }
15226          return SIP_GET_DEST_EXTEN_FOUND;
15227       }
15228       if ((agent = find_sip_cc_agent_by_notify_uri(tmp))) {
15229          struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
15230          /* This is a CC recall. We can set p's extension to the exten from
15231           * the original INVITE
15232           */
15233          ast_string_field_set(p, exten, agent_pvt->original_exten);
15234          /* And we need to let the CC core know that the caller is attempting
15235           * his recall
15236           */
15237          ast_cc_agent_recalling(agent->core_id, "SIP caller %s is attempting recall",
15238                agent->device_name);
15239          if (cc_recall_core_id) {
15240             *cc_recall_core_id = agent->core_id;
15241          }
15242          ao2_ref(agent, -1);
15243          return SIP_GET_DEST_EXTEN_FOUND;
15244       }
15245    }
15246 
15247    if (ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP)
15248       && (ast_canmatch_extension(NULL, p->context, uri, 1, S_OR(p->cid_num, from))
15249          || ast_canmatch_extension(NULL, p->context, decoded_uri, 1, S_OR(p->cid_num, from))
15250          || !strncmp(decoded_uri, ast_pickup_ext(), strlen(decoded_uri)))) {
15251       /* Overlap dialing is enabled and we need more digits to match an extension. */
15252       return SIP_GET_DEST_EXTEN_MATCHMORE;
15253    }
15254 
15255    return SIP_GET_DEST_EXTEN_NOT_FOUND;
15256 }
15257 
15258 /*! \brief Lock dialog lock and find matching pvt lock
15259    \return a reference, remember to release it when done
15260 */
15261 static struct sip_pvt *get_sip_pvt_byid_locked(const char *callid, const char *totag, const char *fromtag)
15262 {
15263    struct sip_pvt *sip_pvt_ptr;
15264    struct sip_pvt tmp_dialog = {
15265       .callid = callid,
15266    };
15267 
15268    if (totag) {
15269       ast_debug(4, "Looking for callid %s (fromtag %s totag %s)\n", callid, fromtag ? fromtag : "<no fromtag>", totag ? totag : "<no totag>");
15270    }
15271 
15272    /* Search dialogs and find the match */
15273    
15274    sip_pvt_ptr = ao2_t_find(dialogs, &tmp_dialog, OBJ_POINTER, "ao2_find of dialog in dialogs table");
15275    if (sip_pvt_ptr) {
15276       /* Go ahead and lock it (and its owner) before returning */
15277       sip_pvt_lock(sip_pvt_ptr);
15278       if (sip_cfg.pedanticsipchecking) {
15279          unsigned char frommismatch = 0, tomismatch = 0;
15280 
15281          if (ast_strlen_zero(fromtag)) {
15282             sip_pvt_unlock(sip_pvt_ptr);
15283             ast_debug(4, "Matched %s call for callid=%s - no from tag specified, pedantic check fails\n",
15284                  sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid);
15285             return NULL;
15286          }
15287 
15288          if (ast_strlen_zero(totag)) {
15289             sip_pvt_unlock(sip_pvt_ptr);
15290             ast_debug(4, "Matched %s call for callid=%s - no to tag specified, pedantic check fails\n",
15291                  sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid);
15292             return NULL;
15293          }
15294          /* RFC 3891
15295           * > 3.  User Agent Server Behavior: Receiving a Replaces Header
15296           * > The Replaces header contains information used to match an existing
15297           * > SIP dialog (call-id, to-tag, and from-tag).  Upon receiving an INVITE
15298           * > with a Replaces header, the User Agent (UA) attempts to match this
15299           * > information with a confirmed or early dialog.  The User Agent Server
15300           * > (UAS) matches the to-tag and from-tag parameters as if they were tags
15301           * > present in an incoming request.  In other words, the to-tag parameter
15302           * > is compared to the local tag, and the from-tag parameter is compared
15303           * > to the remote tag.
15304           *
15305           * Thus, the totag is always compared to the local tag, regardless if
15306           * this our call is an incoming or outgoing call.
15307           */
15308          frommismatch = !!strcmp(fromtag, sip_pvt_ptr->theirtag);
15309          tomismatch = !!strcmp(totag, sip_pvt_ptr->tag);
15310 
15311          if (frommismatch || tomismatch) {
15312             sip_pvt_unlock(sip_pvt_ptr);
15313             if (frommismatch) {
15314                ast_debug(4, "Matched %s call for callid=%s - pedantic from tag check fails; their tag is %s our tag is %s\n",
15315                     sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid,
15316                     fromtag, sip_pvt_ptr->theirtag);
15317             }
15318             if (tomismatch) {
15319                ast_debug(4, "Matched %s call for callid=%s - pedantic to tag check fails; their tag is %s our tag is %s\n",
15320                     sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid,
15321                     totag, sip_pvt_ptr->tag);
15322             }
15323             return NULL;
15324          }
15325       }
15326       
15327       if (totag)
15328          ast_debug(4, "Matched %s call - their tag is %s Our tag is %s\n",
15329                  sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING",
15330                  sip_pvt_ptr->theirtag, sip_pvt_ptr->tag);
15331 
15332       /* deadlock avoidance... */
15333       while (sip_pvt_ptr->owner && ast_channel_trylock(sip_pvt_ptr->owner)) {
15334          sip_pvt_unlock(sip_pvt_ptr);
15335          usleep(1);
15336          sip_pvt_lock(sip_pvt_ptr);
15337       }
15338    }
15339    
15340    return sip_pvt_ptr;
15341 }
15342 
15343 /*! \brief Call transfer support (the REFER method)
15344  *    Extracts Refer headers into pvt dialog structure
15345  *
15346  * \note If we get a SIPS uri in the refer-to header, we're required to set up a secure signalling path
15347  * to that extension. As a minimum, this needs to be added to a channel variable, if not a channel
15348  * flag.
15349  */
15350 static int get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req)
15351 {
15352 
15353    const char *p_referred_by = NULL;
15354    char *h_refer_to = NULL;
15355    char *h_referred_by = NULL;
15356    char *refer_to;
15357    const char *p_refer_to;
15358    char *referred_by_uri = NULL;
15359    char *ptr;
15360    struct sip_request *req = NULL;
15361    const char *transfer_context = NULL;
15362    struct sip_refer *referdata;
15363 
15364 
15365    req = outgoing_req;
15366    referdata = transferer->refer;
15367 
15368    if (!req) {
15369       req = &transferer->initreq;
15370    }
15371 
15372    p_refer_to = get_header(req, "Refer-To");
15373    if (ast_strlen_zero(p_refer_to)) {
15374       ast_log(LOG_WARNING, "Refer-To Header missing. Skipping transfer.\n");
15375       return -2;  /* Syntax error */
15376    }
15377    h_refer_to = ast_strdupa(p_refer_to);
15378    refer_to = get_in_brackets(h_refer_to);
15379    if (!strncasecmp(refer_to, "sip:", 4)) {
15380       refer_to += 4;       /* Skip sip: */
15381    } else if (!strncasecmp(refer_to, "sips:", 5)) {
15382       refer_to += 5;
15383    } else {
15384       ast_log(LOG_WARNING, "Can't transfer to non-sip: URI.  (Refer-to: %s)?\n", refer_to);
15385       return -3;
15386    }
15387 
15388    /* Get referred by header if it exists */
15389    p_referred_by = get_header(req, "Referred-By");
15390 
15391    /* Give useful transfer information to the dialplan */
15392    if (transferer->owner) {
15393       struct ast_channel *peer = ast_bridged_channel(transferer->owner);
15394       if (peer) {
15395          pbx_builtin_setvar_helper(peer, "SIPREFERRINGCONTEXT", transferer->context);
15396          pbx_builtin_setvar_helper(peer, "SIPREFERREDBYHDR", p_referred_by);
15397       }
15398    }
15399 
15400    if (!ast_strlen_zero(p_referred_by)) {
15401       char *lessthan;
15402       h_referred_by = ast_strdupa(p_referred_by);
15403 
15404       /* Store referrer's caller ID name */
15405       ast_copy_string(referdata->referred_by_name, h_referred_by, sizeof(referdata->referred_by_name));
15406       if ((lessthan = strchr(referdata->referred_by_name, '<'))) {
15407          *(lessthan - 1) = '\0'; /* Space */
15408       }
15409 
15410       referred_by_uri = get_in_brackets(h_referred_by);
15411 
15412       if (!strncasecmp(referred_by_uri, "sip:", 4)) {
15413          referred_by_uri += 4;      /* Skip sip: */
15414       } else if (!strncasecmp(referred_by_uri, "sips:", 5)) {
15415          referred_by_uri += 5;      /* Skip sips: */
15416       } else {
15417          ast_log(LOG_WARNING, "Huh?  Not a sip: header (Referred-by: %s). Skipping.\n", referred_by_uri);
15418          referred_by_uri = NULL;
15419       }
15420    }
15421 
15422    /* Check for arguments in the refer_to header */
15423    if ((ptr = strcasestr(refer_to, "replaces="))) {
15424       char *to = NULL, *from = NULL;
15425       
15426       /* This is an attended transfer */
15427       referdata->attendedtransfer = 1;
15428       ast_copy_string(referdata->replaces_callid, ptr+9, sizeof(referdata->replaces_callid));
15429       ast_uri_decode(referdata->replaces_callid);
15430       if ((ptr = strchr(referdata->replaces_callid, ';')))  /* Find options */ {
15431          *ptr++ = '\0';
15432       }
15433       
15434       if (ptr) {
15435          /* Find the different tags before we destroy the string */
15436          to = strcasestr(ptr, "to-tag=");
15437          from = strcasestr(ptr, "from-tag=");
15438       }
15439       
15440       /* Grab the to header */
15441       if (to) {
15442          ptr = to + 7;
15443          if ((to = strchr(ptr, '&'))) {
15444             *to = '\0';
15445          }
15446          if ((to = strchr(ptr, ';'))) {
15447             *to = '\0';
15448          }
15449          ast_copy_string(referdata->replaces_callid_totag, ptr, sizeof(referdata->replaces_callid_totag));
15450       }
15451       
15452       if (from) {
15453          ptr = from + 9;
15454          if ((to = strchr(ptr, '&'))) {
15455             *to = '\0';
15456          }
15457          if ((to = strchr(ptr, ';'))) {
15458             *to = '\0';
15459          }
15460          ast_copy_string(referdata->replaces_callid_fromtag, ptr, sizeof(referdata->replaces_callid_fromtag));
15461       }
15462 
15463       if (!strcmp(referdata->replaces_callid, transferer->callid) &&
15464          (!sip_cfg.pedanticsipchecking ||
15465          (!strcmp(referdata->replaces_callid_fromtag, transferer->theirtag) &&
15466          !strcmp(referdata->replaces_callid_totag, transferer->tag)))) {
15467             ast_log(LOG_WARNING, "Got an attempt to replace own Call-ID on %s\n", transferer->callid);
15468             return -4;
15469       }
15470 
15471       if (!sip_cfg.pedanticsipchecking) {
15472          ast_debug(2, "Attended transfer: Will use Replace-Call-ID : %s (No check of from/to tags)\n", referdata->replaces_callid );
15473       } else {
15474          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>" );
15475       }
15476    }
15477    
15478    if ((ptr = strchr(refer_to, '@'))) {   /* Separate domain */
15479       char *urioption = NULL, *domain;
15480       int bracket = 0;
15481       *ptr++ = '\0';
15482 
15483       if ((urioption = strchr(ptr, ';'))) { /* Separate urioptions */
15484          *urioption++ = '\0';
15485       }
15486 
15487       domain = ptr;
15488 
15489       /* Remove :port */
15490       for (; *ptr != '\0'; ++ptr) {
15491          if (*ptr == ':' && bracket == 0) {
15492             *ptr = '\0';
15493             break;
15494          } else if (*ptr == '[') {
15495             ++bracket;
15496          } else if (*ptr == ']') {
15497             --bracket;
15498          }
15499       }
15500 
15501       SIP_PEDANTIC_DECODE(domain);
15502       SIP_PEDANTIC_DECODE(urioption);
15503 
15504       /* Save the domain for the dial plan */
15505       ast_copy_string(referdata->refer_to_domain, domain, sizeof(referdata->refer_to_domain));
15506       if (urioption) {
15507          ast_copy_string(referdata->refer_to_urioption, urioption, sizeof(referdata->refer_to_urioption));
15508       }
15509    }
15510 
15511    if ((ptr = strchr(refer_to, ';')))  /* Remove options */
15512       *ptr = '\0';
15513 
15514    SIP_PEDANTIC_DECODE(refer_to);
15515    ast_copy_string(referdata->refer_to, refer_to, sizeof(referdata->refer_to));
15516    
15517    if (referred_by_uri) {
15518       if ((ptr = strchr(referred_by_uri, ';')))    /* Remove options */
15519          *ptr = '\0';
15520       SIP_PEDANTIC_DECODE(referred_by_uri);
15521       ast_copy_string(referdata->referred_by, referred_by_uri, sizeof(referdata->referred_by));
15522    } else {
15523       referdata->referred_by[0] = '\0';
15524    }
15525 
15526    /* Determine transfer context */
15527    if (transferer->owner)  /* Mimic behaviour in res_features.c */
15528       transfer_context = pbx_builtin_getvar_helper(transferer->owner, "TRANSFER_CONTEXT");
15529 
15530    /* By default, use the context in the channel sending the REFER */
15531    if (ast_strlen_zero(transfer_context)) {
15532       transfer_context = S_OR(transferer->owner->macrocontext,
15533                S_OR(transferer->context, sip_cfg.default_context));
15534    }
15535 
15536    ast_copy_string(referdata->refer_to_context, transfer_context, sizeof(referdata->refer_to_context));
15537    
15538    /* Either an existing extension or the parking extension */
15539    if (referdata->attendedtransfer || ast_exists_extension(NULL, transfer_context, refer_to, 1, NULL) ) {
15540       if (sip_debug_test_pvt(transferer)) {
15541          ast_verbose("SIP transfer to extension %s@%s by %s\n", refer_to, transfer_context, referred_by_uri);
15542       }
15543       /* We are ready to transfer to the extension */
15544       return 0;
15545    }
15546    if (sip_debug_test_pvt(transferer))
15547       ast_verbose("Failed SIP Transfer to non-existing extension %s in context %s\n n", refer_to, transfer_context);
15548 
15549    /* Failure, we can't find this extension */
15550    return -1;
15551 }
15552 
15553 
15554 /*! \brief Call transfer support (old way, deprecated by the IETF)
15555  * \note does not account for SIPS: uri requirements, nor check transport
15556  */
15557 static int get_also_info(struct sip_pvt *p, struct sip_request *oreq)
15558 {
15559    char tmp[256] = "", *c, *a;
15560    struct sip_request *req = oreq ? oreq : &p->initreq;
15561    struct sip_refer *referdata = NULL;
15562    const char *transfer_context = NULL;
15563    
15564    if (!p->refer && !sip_refer_allocate(p))
15565       return -1;
15566 
15567    referdata = p->refer;
15568 
15569    ast_copy_string(tmp, get_header(req, "Also"), sizeof(tmp));
15570    c = get_in_brackets(tmp);
15571 
15572    if (parse_uri_legacy_check(c, "sip:,sips:", &c, NULL, &a, NULL)) {
15573       ast_log(LOG_WARNING, "Huh?  Not a SIP header in Also: transfer (%s)?\n", c);
15574       return -1;
15575    }
15576    
15577    SIP_PEDANTIC_DECODE(c);
15578    SIP_PEDANTIC_DECODE(a);
15579 
15580    if (!ast_strlen_zero(a)) {
15581       ast_copy_string(referdata->refer_to_domain, a, sizeof(referdata->refer_to_domain));
15582    }
15583 
15584    if (sip_debug_test_pvt(p))
15585       ast_verbose("Looking for %s in %s\n", c, p->context);
15586 
15587    if (p->owner)  /* Mimic behaviour in res_features.c */
15588       transfer_context = pbx_builtin_getvar_helper(p->owner, "TRANSFER_CONTEXT");
15589 
15590    /* By default, use the context in the channel sending the REFER */
15591    if (ast_strlen_zero(transfer_context)) {
15592       transfer_context = S_OR(p->owner->macrocontext,
15593                S_OR(p->context, sip_cfg.default_context));
15594    }
15595    if (ast_exists_extension(NULL, transfer_context, c, 1, NULL)) {
15596       /* This is a blind transfer */
15597       ast_debug(1, "SIP Bye-also transfer to Extension %s@%s \n", c, transfer_context);
15598       ast_copy_string(referdata->refer_to, c, sizeof(referdata->refer_to));
15599       ast_copy_string(referdata->referred_by, "", sizeof(referdata->referred_by));
15600       ast_copy_string(referdata->refer_contact, "", sizeof(referdata->refer_contact));
15601       referdata->refer_call = dialog_unref(referdata->refer_call, "unreffing referdata->refer_call");
15602       /* Set new context */
15603       ast_string_field_set(p, context, transfer_context);
15604       return 0;
15605    } else if (ast_canmatch_extension(NULL, p->context, c, 1, NULL)) {
15606       return 1;
15607    }
15608 
15609    return -1;
15610 }
15611 
15612 /*! \brief check received= and rport= in a SIP response.
15613  * If we get a response with received= and/or rport= in the Via:
15614  * line, use them as 'p->ourip' (see RFC 3581 for rport,
15615  * and RFC 3261 for received).
15616  * Using these two fields SIP can produce the correct
15617  * address and port in the SIP headers without the need for STUN.
15618  * The address part is also reused for the media sessions.
15619  * Note that ast_sip_ouraddrfor() still rewrites p->ourip
15620  * if you specify externaddr/seternaddr/.
15621  */
15622 static attribute_unused void check_via_response(struct sip_pvt *p, struct sip_request *req)
15623 {
15624    char via[256];
15625    char *cur, *opts;
15626 
15627    ast_copy_string(via, get_header(req, "Via"), sizeof(via));
15628 
15629    /* Work on the leftmost value of the topmost Via header */
15630    opts = strchr(via, ',');
15631    if (opts)
15632       *opts = '\0';
15633 
15634    /* parse all relevant options */
15635    opts = strchr(via, ';');
15636    if (!opts)
15637       return;  /* no options to parse */
15638    *opts++ = '\0';
15639    while ( (cur = strsep(&opts, ";")) ) {
15640       if (!strncmp(cur, "rport=", 6)) {
15641          int port = strtol(cur+6, NULL, 10);
15642          /* XXX add error checking */
15643          ast_sockaddr_set_port(&p->ourip, port);
15644       } else if (!strncmp(cur, "received=", 9)) {
15645          if (ast_parse_arg(cur + 9, PARSE_ADDR, &p->ourip))
15646             ;  /* XXX add error checking */
15647       }
15648    }
15649 }
15650 
15651 /*! \brief check Via: header for hostname, port and rport request/answer */
15652 static void check_via(struct sip_pvt *p, struct sip_request *req)
15653 {
15654    char via[512];
15655    char *c, *maddr;
15656    struct ast_sockaddr tmp = { { 0, } };
15657    uint16_t port;
15658 
15659    ast_copy_string(via, get_header(req, "Via"), sizeof(via));
15660 
15661    /* Work on the leftmost value of the topmost Via header */
15662    c = strchr(via, ',');
15663    if (c)
15664       *c = '\0';
15665 
15666    /* Check for rport */
15667    c = strstr(via, ";rport");
15668    if (c && (c[6] != '=')) { /* rport query, not answer */
15669       ast_set_flag(&p->flags[1], SIP_PAGE2_RPORT_PRESENT);
15670       ast_set_flag(&p->flags[0], SIP_NAT_RPORT_PRESENT);
15671    }
15672 
15673    /* Check for maddr */
15674    maddr = strstr(via, "maddr=");
15675    if (maddr) {
15676       maddr += 6;
15677       c = maddr + strspn(maddr, "abcdefghijklmnopqrstuvwxyz"
15678                       "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-.:[]");
15679       *c = '\0';
15680    }
15681 
15682    c = strchr(via, ';');
15683    if (c)
15684       *c = '\0';
15685 
15686    c = strchr(via, ' ');
15687    if (c) {
15688       *c = '\0';
15689       c = ast_skip_blanks(c+1);
15690       if (strcasecmp(via, "SIP/2.0/UDP") && strcasecmp(via, "SIP/2.0/TCP") && strcasecmp(via, "SIP/2.0/TLS")) {
15691          ast_log(LOG_WARNING, "Don't know how to respond via '%s'\n", via);
15692          return;
15693       }
15694 
15695       if (maddr && ast_sockaddr_resolve_first(&p->sa, maddr, 0)) {
15696          p->sa = p->recv;
15697       }
15698 
15699       ast_sockaddr_resolve_first(&tmp, c, 0);
15700       port = ast_sockaddr_port(&tmp);
15701       ast_sockaddr_set_port(&p->sa,
15702                   port != 0 ? port : STANDARD_SIP_PORT);
15703 
15704       if (sip_debug_test_pvt(p)) {
15705          ast_verbose("Sending to %s (%s)\n",
15706                 ast_sockaddr_stringify(sip_real_dst(p)),
15707                 sip_nat_mode(p));
15708       }
15709    }
15710 }
15711 
15712 /*! \brief Validate device authentication */
15713 static enum check_auth_result check_peer_ok(struct sip_pvt *p, char *of,
15714    struct sip_request *req, int sipmethod, struct ast_sockaddr *addr,
15715    struct sip_peer **authpeer,
15716    enum xmittype reliable, char *calleridname, char *uri2)
15717 {
15718    enum check_auth_result res;
15719    int debug = sip_debug_test_addr(addr);
15720    struct sip_peer *peer;
15721 
15722    if (sipmethod == SIP_SUBSCRIBE) {
15723       /* For subscribes, match on device name only; for other methods,
15724       * match on IP address-port of the incoming request.
15725       */
15726       peer = find_peer(of, NULL, TRUE, FINDALLDEVICES, FALSE, 0);
15727    } else {
15728       /* First find devices based on username (avoid all type=peer's) */
15729       peer = find_peer(of, NULL, TRUE, FINDUSERS, FALSE, 0);
15730 
15731       /* Then find devices based on IP */
15732       if (!peer) {
15733          peer = find_peer(NULL, &p->recv, TRUE, FINDPEERS, FALSE, p->socket.type);
15734       }
15735    }
15736 
15737    if (!peer) {
15738       if (debug) {
15739          ast_verbose("No matching peer for '%s' from '%s'\n",
15740             of, ast_sockaddr_stringify(&p->recv));
15741       }
15742       return AUTH_DONT_KNOW;
15743    }
15744 
15745    if (!ast_apply_ha(peer->ha, addr)) {
15746       ast_debug(2, "Found peer '%s' for '%s', but fails host access\n", peer->name, of);
15747       unref_peer(peer, "unref_peer: check_peer_ok: from find_peer call, early return of AUTH_ACL_FAILED");
15748       return AUTH_ACL_FAILED;
15749    }
15750    if (debug)
15751       ast_verbose("Found peer '%s' for '%s' from %s\n",
15752          peer->name, of, ast_sockaddr_stringify(&p->recv));
15753 
15754    /* XXX what about p->prefs = peer->prefs; ? */
15755    /* Set Frame packetization */
15756    if (p->rtp) {
15757       ast_rtp_codecs_packetization_set(ast_rtp_instance_get_codecs(p->rtp), p->rtp, &peer->prefs);
15758       p->autoframing = peer->autoframing;
15759    }
15760 
15761    /* Take the peer */
15762    ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
15763    ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
15764    ast_copy_flags(&p->flags[2], &peer->flags[2], SIP_PAGE3_FLAGS_TO_COPY);
15765 
15766    if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) && p->udptl) {
15767       p->t38_maxdatagram = peer->t38_maxdatagram;
15768       set_t38_capabilities(p);
15769    }
15770 
15771    /* Copy SIP extensions profile to peer */
15772    /* XXX is this correct before a successful auth ? */
15773    if (p->sipoptions)
15774       peer->sipoptions = p->sipoptions;
15775 
15776    do_setnat(p);
15777 
15778    ast_string_field_set(p, peersecret, peer->secret);
15779    ast_string_field_set(p, peermd5secret, peer->md5secret);
15780    ast_string_field_set(p, subscribecontext, peer->subscribecontext);
15781    ast_string_field_set(p, mohinterpret, peer->mohinterpret);
15782    ast_string_field_set(p, mohsuggest, peer->mohsuggest);
15783    if (!ast_strlen_zero(peer->parkinglot)) {
15784       ast_string_field_set(p, parkinglot, peer->parkinglot);
15785    }
15786    ast_string_field_set(p, engine, peer->engine);
15787    p->disallowed_methods = peer->disallowed_methods;
15788    set_pvt_allowed_methods(p, req);
15789    ast_cc_copy_config_params(p->cc_params, peer->cc_params);
15790    if (peer->callingpres)  /* Peer calling pres setting will override RPID */
15791       p->callingpres = peer->callingpres;
15792    if (peer->maxms && peer->lastms)
15793       p->timer_t1 = peer->lastms < global_t1min ? global_t1min : peer->lastms;
15794    else
15795       p->timer_t1 = peer->timer_t1;
15796 
15797    /* Set timer B to control transaction timeouts */
15798    if (peer->timer_b)
15799       p->timer_b = peer->timer_b;
15800    else
15801       p->timer_b = 64 * p->timer_t1;
15802 
15803    if (ast_test_flag(&peer->flags[0], SIP_INSECURE_INVITE)) {
15804       /* Pretend there is no required authentication */
15805       ast_string_field_set(p, peersecret, NULL);
15806       ast_string_field_set(p, peermd5secret, NULL);
15807    }
15808    if (!(res = check_auth(p, req, peer->name, p->peersecret, p->peermd5secret, sipmethod, uri2, reliable, req->ignore))) {
15809       ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
15810       ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
15811       ast_copy_flags(&p->flags[2], &peer->flags[2], SIP_PAGE3_FLAGS_TO_COPY);
15812       /* If we have a call limit, set flag */
15813       if (peer->call_limit)
15814          ast_set_flag(&p->flags[0], SIP_CALL_LIMIT);
15815       ast_string_field_set(p, peername, peer->name);
15816       ast_string_field_set(p, authname, peer->name);
15817 
15818       if (sipmethod == SIP_INVITE) {
15819          /* destroy old channel vars and copy in new ones. */
15820          ast_variables_destroy(p->chanvars);
15821          p->chanvars = copy_vars(peer->chanvars);
15822       }
15823 
15824       if (authpeer) {
15825          ao2_t_ref(peer, 1, "copy pointer into (*authpeer)");
15826          (*authpeer) = peer;  /* Add a ref to the object here, to keep it in memory a bit longer if it is realtime */
15827       }
15828 
15829       if (!ast_strlen_zero(peer->username)) {
15830          ast_string_field_set(p, username, peer->username);
15831          /* Use the default username for authentication on outbound calls */
15832          /* XXX this takes the name from the caller... can we override ? */
15833          ast_string_field_set(p, authname, peer->username);
15834       }
15835       if (!get_rpid(p, req)) {
15836          if (!ast_strlen_zero(peer->cid_num)) {
15837             char *tmp = ast_strdupa(peer->cid_num);
15838             if (global_shrinkcallerid && ast_is_shrinkable_phonenumber(tmp))
15839                ast_shrink_phone_number(tmp);
15840             ast_string_field_set(p, cid_num, tmp);
15841          }
15842          if (!ast_strlen_zero(peer->cid_name))
15843             ast_string_field_set(p, cid_name, peer->cid_name);
15844          if (!ast_strlen_zero(peer->cid_tag))
15845             ast_string_field_set(p, cid_tag, peer->cid_tag);
15846          if (peer->callingpres)
15847             p->callingpres = peer->callingpres;
15848       }
15849       ast_string_field_set(p, fullcontact, peer->fullcontact);
15850       if (!ast_strlen_zero(peer->context))
15851          ast_string_field_set(p, context, peer->context);
15852       ast_string_field_set(p, peersecret, peer->secret);
15853       ast_string_field_set(p, peermd5secret, peer->md5secret);
15854       ast_string_field_set(p, language, peer->language);
15855       ast_string_field_set(p, accountcode, peer->accountcode);
15856       p->amaflags = peer->amaflags;
15857       p->callgroup = peer->callgroup;
15858       p->pickupgroup = peer->pickupgroup;
15859       p->capability = peer->capability;
15860       p->prefs = peer->prefs;
15861       p->jointcapability = peer->capability;
15862       if (peer->maxforwards > 0) {
15863          p->maxforwards = peer->maxforwards;
15864       }
15865       if (p->peercapability)
15866          p->jointcapability &= p->peercapability;
15867       p->maxcallbitrate = peer->maxcallbitrate;
15868       if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
15869           (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
15870          p->noncodeccapability |= AST_RTP_DTMF;
15871       else
15872          p->noncodeccapability &= ~AST_RTP_DTMF;
15873       p->jointnoncodeccapability = p->noncodeccapability;
15874       p->rtptimeout = peer->rtptimeout;
15875       p->rtpholdtimeout = peer->rtpholdtimeout;
15876       p->rtpkeepalive = peer->rtpkeepalive;
15877       if (!dialog_initialize_rtp(p)) {
15878          if (p->rtp) {
15879             ast_rtp_codecs_packetization_set(ast_rtp_instance_get_codecs(p->rtp), p->rtp, &peer->prefs);
15880             p->autoframing = peer->autoframing;
15881          }
15882       } else {
15883          res = AUTH_RTP_FAILED;
15884       }
15885    }
15886    unref_peer(peer, "check_peer_ok: unref_peer: tossing temp ptr to peer from find_peer");
15887    return res;
15888 }
15889 
15890 
15891 /*! \brief  Check if matching user or peer is defined
15892    Match user on From: user name and peer on IP/port
15893    This is used on first invite (not re-invites) and subscribe requests
15894     \return 0 on success, non-zero on failure
15895 */
15896 static enum check_auth_result check_user_full(struct sip_pvt *p, struct sip_request *req,
15897                      int sipmethod, const char *uri, enum xmittype reliable,
15898                      struct ast_sockaddr *addr, struct sip_peer **authpeer)
15899 {
15900    char from[256] = "", *of, *name, *unused_password, *domain;
15901    enum check_auth_result res = AUTH_DONT_KNOW;
15902    char calleridname[50];
15903    char *uri2 = ast_strdupa(uri);
15904 
15905    terminate_uri(uri2); /* trim extra stuff */
15906 
15907    ast_copy_string(from, get_header(req, "From"), sizeof(from));
15908    /* XXX here tries to map the username for invite things */
15909    memset(calleridname, 0, sizeof(calleridname));
15910 
15911    /* strip the display-name portion off the beginning of the FROM header. */
15912    if (!(of = (char *) get_calleridname(from, calleridname, sizeof(calleridname)))) {
15913       ast_log(LOG_ERROR, "FROM header can not be parsed \n");
15914       return res;
15915    }
15916 
15917    if (calleridname[0]) {
15918       ast_string_field_set(p, cid_name, calleridname);
15919    }
15920 
15921    if (ast_strlen_zero(p->exten)) {
15922       char *t = uri2;
15923       if (!strncasecmp(t, "sip:", 4))
15924          t+= 4;
15925       else if (!strncasecmp(t, "sips:", 5))
15926          t += 5;
15927       ast_string_field_set(p, exten, t);
15928       t = strchr(p->exten, '@');
15929       if (t)
15930          *t = '\0';
15931 
15932       if (ast_strlen_zero(p->our_contact))
15933          build_contact(p);
15934    }
15935 
15936    of = get_in_brackets(of);
15937 
15938    /* save the URI part of the From header */
15939    ast_string_field_set(p, from, of);
15940 
15941    if (parse_uri_legacy_check(of, "sip:,sips:", &name, &unused_password, &domain, NULL)) {
15942       ast_log(LOG_NOTICE, "From address missing 'sip:', using it anyway\n");
15943    }
15944 
15945    SIP_PEDANTIC_DECODE(name);
15946    SIP_PEDANTIC_DECODE(domain);
15947 
15948    extract_host_from_hostport(&domain);
15949 
15950    if (ast_strlen_zero(domain)) {
15951       /* <sip:name@[EMPTY]>, never good */
15952       ast_log(LOG_ERROR, "Empty domain name in FROM header\n");
15953       return res;
15954    }
15955 
15956    if (ast_strlen_zero(name)) {
15957       /* <sip:[EMPTY][@]hostport>. Asterisk 1.4 and 1.6 have always
15958        * treated that as a username, so we continue the tradition:
15959        * uri is now <sip:host@hostport>. */
15960       name = domain;
15961    } else {
15962       /* Non-empty name, try to get caller id from it */
15963       char *tmp = ast_strdupa(name);
15964       /* We need to be able to handle from-headers looking like
15965          <sip:8164444422;phone-context=+1@1.2.3.4:5060;user=phone;tag=SDadkoa01-gK0c3bdb43>
15966       */
15967       tmp = strsep(&tmp, ";");
15968       if (global_shrinkcallerid && ast_is_shrinkable_phonenumber(tmp)) {
15969          ast_shrink_phone_number(tmp);
15970       }
15971       ast_string_field_set(p, cid_num, tmp);
15972    }
15973 
15974    if (global_match_auth_username) {
15975       /*
15976        * XXX This is experimental code to grab the search key from the
15977        * Auth header's username instead of the 'From' name, if available.
15978        * Do not enable this block unless you understand the side effects (if any!)
15979        * Note, the search for "username" should be done in a more robust way.
15980        * Note2, at the moment we check both fields, though maybe we should
15981        * pick one or another depending on the request ? XXX
15982        */
15983       const char *hdr = get_header(req, "Authorization");
15984       if (ast_strlen_zero(hdr)) {
15985          hdr = get_header(req, "Proxy-Authorization");
15986       }
15987 
15988       if (!ast_strlen_zero(hdr) && (hdr = strstr(hdr, "username=\""))) {
15989          ast_copy_string(from, hdr + strlen("username=\""), sizeof(from));
15990          name = from;
15991          name = strsep(&name, "\"");
15992       }
15993    }
15994 
15995    res = check_peer_ok(p, name, req, sipmethod, addr,
15996          authpeer, reliable, calleridname, uri2);
15997    if (res != AUTH_DONT_KNOW) {
15998       return res;
15999    }
16000 
16001    /* Finally, apply the guest policy */
16002    if (sip_cfg.allowguest) {
16003       get_rpid(p, req);
16004       p->rtptimeout = global_rtptimeout;
16005       p->rtpholdtimeout = global_rtpholdtimeout;
16006       p->rtpkeepalive = global_rtpkeepalive;
16007       if (!dialog_initialize_rtp(p)) {
16008          res = AUTH_SUCCESSFUL;
16009       } else {
16010          res = AUTH_RTP_FAILED;
16011       }
16012    } else if (sip_cfg.alwaysauthreject) {
16013       res = AUTH_FAKE_AUTH; /* reject with fake authorization request */
16014    } else {
16015       res = AUTH_SECRET_FAILED; /* we don't want any guests, authentication will fail */
16016    }
16017 
16018    if (ast_test_flag(&p->flags[1], SIP_PAGE2_RPORT_PRESENT)) {
16019       ast_set_flag(&p->flags[0], SIP_NAT_RPORT_PRESENT);
16020    }
16021 
16022    return res;
16023 }
16024 
16025 /*! \brief  Find user
16026    If we get a match, this will add a reference pointer to the user object in ASTOBJ, that needs to be unreferenced
16027 */
16028 static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, const char *uri, enum xmittype reliable, struct ast_sockaddr *addr)
16029 {
16030    return check_user_full(p, req, sipmethod, uri, reliable, addr, NULL);
16031 }
16032 
16033 /*! \brief Get message body from a SIP request
16034  * \param buf Destination buffer
16035  * \param len Destination buffer size
16036  * \param req The SIP request
16037  *
16038  * When parsing the request originally, the lines are split by LF or CRLF.
16039  * This function adds a single LF after every line.
16040  */
16041 static int get_msg_text(char *buf, int len, struct sip_request *req)
16042 {
16043    int x;
16044    int linelen;
16045 
16046    buf[0] = '\0';
16047    --len; /* reserve strncat null */
16048    for (x = 0; len && x < req->lines; ++x) {
16049       const char *line = REQ_OFFSET_TO_STR(req, line[x]);
16050       strncat(buf, line, len); /* safe */
16051       linelen = strlen(buf);
16052       buf += linelen;
16053       len -= linelen;
16054       if (len) {
16055          strcat(buf, "\n"); /* safe */
16056          ++buf;
16057          --len;
16058       }
16059    }
16060    return 0;
16061 }
16062 
16063 
16064 /*! \brief  Receive SIP MESSAGE method messages
16065 \note We only handle messages within current calls currently
16066    Reference: RFC 3428 */
16067 static void receive_message(struct sip_pvt *p, struct sip_request *req)
16068 {
16069    char buf[1400];   
16070    char *bufp;
16071    struct ast_frame f;
16072    const char *content_type = get_header(req, "Content-Type");
16073 
16074    if (strncmp(content_type, "text/plain", strlen("text/plain"))) { /* No text/plain attachment */
16075       transmit_response(p, "415 Unsupported Media Type", req); /* Good enough, or? */
16076       if (!p->owner)
16077          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
16078       return;
16079    }
16080 
16081    if (get_msg_text(buf, sizeof(buf), req)) {
16082       ast_log(LOG_WARNING, "Unable to retrieve text from %s\n", p->callid);
16083       transmit_response(p, "202 Accepted", req);
16084       if (!p->owner)
16085          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
16086       return;
16087    }
16088 
16089    /* Strip trailing line feeds from message body. (get_msg_text may add
16090     * a trailing linefeed and we don't need any at the end) */
16091    bufp = buf + strlen(buf);
16092    while (--bufp >= buf && *bufp == '\n') {
16093       *bufp = '\0';
16094    }
16095 
16096    if (p->owner) {
16097       if (sip_debug_test_pvt(p))
16098          ast_verbose("SIP Text message received: '%s'\n", buf);
16099       memset(&f, 0, sizeof(f));
16100       f.frametype = AST_FRAME_TEXT;
16101       f.subclass.integer = 0;
16102       f.offset = 0;
16103       f.data.ptr = buf;
16104       f.datalen = strlen(buf) + 1;
16105       ast_queue_frame(p->owner, &f);
16106       transmit_response(p, "202 Accepted", req); /* We respond 202 accepted, since we relay the message */
16107       return;
16108    }
16109 
16110    /* Message outside of a call, we do not support that */
16111    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);
16112    transmit_response(p, "405 Method Not Allowed", req);
16113    sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
16114    return;
16115 }
16116 
16117 /*! \brief  CLI Command to show calls within limits set by call_limit */
16118 static char *sip_show_inuse(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16119 {
16120 #define FORMAT "%-25.25s %-15.15s %-15.15s \n"
16121 #define FORMAT2 "%-25.25s %-15.15s %-15.15s \n"
16122    char ilimits[40];
16123    char iused[40];
16124    int showall = FALSE;
16125    struct ao2_iterator i;
16126    struct sip_peer *peer;
16127    
16128    switch (cmd) {
16129    case CLI_INIT:
16130       e->command = "sip show inuse";
16131       e->usage =
16132          "Usage: sip show inuse [all]\n"
16133          "       List all SIP devices usage counters and limits.\n"
16134          "       Add option \"all\" to show all devices, not only those with a limit.\n";
16135       return NULL;
16136    case CLI_GENERATE:
16137       return NULL;
16138    }
16139 
16140    if (a->argc < 3)
16141       return CLI_SHOWUSAGE;
16142 
16143    if (a->argc == 4 && !strcmp(a->argv[3], "all"))
16144       showall = TRUE;
16145    
16146    ast_cli(a->fd, FORMAT, "* Peer name", "In use", "Limit");
16147 
16148    i = ao2_iterator_init(peers, 0);
16149    while ((peer = ao2_t_iterator_next(&i, "iterate thru peer table"))) {
16150       ao2_lock(peer);
16151       if (peer->call_limit)
16152          snprintf(ilimits, sizeof(ilimits), "%d", peer->call_limit);
16153       else
16154          ast_copy_string(ilimits, "N/A", sizeof(ilimits));
16155       snprintf(iused, sizeof(iused), "%d/%d/%d", peer->inUse, peer->inRinging, peer->onHold);
16156       if (showall || peer->call_limit)
16157          ast_cli(a->fd, FORMAT2, peer->name, iused, ilimits);
16158       ao2_unlock(peer);
16159       unref_peer(peer, "toss iterator pointer");
16160    }
16161    ao2_iterator_destroy(&i);
16162 
16163    return CLI_SUCCESS;
16164 #undef FORMAT
16165 #undef FORMAT2
16166 }
16167 
16168 
16169 /*! \brief Convert transfer mode to text string */
16170 static char *transfermode2str(enum transfermodes mode)
16171 {
16172    if (mode == TRANSFER_OPENFORALL)
16173       return "open";
16174    else if (mode == TRANSFER_CLOSED)
16175       return "closed";
16176    return "strict";
16177 }
16178 
16179 /*! \brief  Report Peer status in character string
16180  *  \return 0 if peer is unreachable, 1 if peer is online, -1 if unmonitored
16181  */
16182 
16183 
16184 /* Session-Timer Modes */
16185 static const struct _map_x_s stmodes[] = {
16186         { SESSION_TIMER_MODE_ACCEPT,    "Accept"},
16187         { SESSION_TIMER_MODE_ORIGINATE, "Originate"},
16188         { SESSION_TIMER_MODE_REFUSE,    "Refuse"},
16189         { -1,                           NULL},
16190 };
16191 
16192 static const char *stmode2str(enum st_mode m)
16193 {
16194    return map_x_s(stmodes, m, "Unknown");
16195 }
16196 
16197 static enum st_mode str2stmode(const char *s)
16198 {
16199    return map_s_x(stmodes, s, -1);
16200 }
16201 
16202 /* Session-Timer Refreshers */
16203 static const struct _map_x_s strefreshers[] = {
16204         { SESSION_TIMER_REFRESHER_AUTO,     "auto"},
16205         { SESSION_TIMER_REFRESHER_UAC,      "uac"},
16206         { SESSION_TIMER_REFRESHER_UAS,      "uas"},
16207         { -1,                               NULL},
16208 };
16209 
16210 static const char *strefresher2str(enum st_refresher r)
16211 {
16212    return map_x_s(strefreshers, r, "Unknown");
16213 }
16214 
16215 static enum st_refresher str2strefresher(const char *s)
16216 {
16217    return map_s_x(strefreshers, s, -1);
16218 }
16219 
16220 
16221 static int peer_status(struct sip_peer *peer, char *status, int statuslen)
16222 {
16223    int res = 0;
16224    if (peer->maxms) {
16225       if (peer->lastms < 0) {
16226          ast_copy_string(status, "UNREACHABLE", statuslen);
16227       } else if (peer->lastms > peer->maxms) {
16228          snprintf(status, statuslen, "LAGGED (%d ms)", peer->lastms);
16229          res = 1;
16230       } else if (peer->lastms) {
16231          snprintf(status, statuslen, "OK (%d ms)", peer->lastms);
16232          res = 1;
16233       } else {
16234          ast_copy_string(status, "UNKNOWN", statuslen);
16235       }
16236    } else {
16237       ast_copy_string(status, "Unmonitored", statuslen);
16238       /* Checking if port is 0 */
16239       res = -1;
16240    }
16241    return res;
16242 }
16243 
16244 /*! \brief  Show active TCP connections */
16245 static char *sip_show_tcp(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16246 {
16247    struct sip_threadinfo *th;
16248    struct ao2_iterator i;
16249 
16250 #define FORMAT2 "%-47.47s %9.9s %6.6s\n"
16251 #define FORMAT  "%-47.47s %-9.9s %-6.6s\n"
16252 
16253    switch (cmd) {
16254    case CLI_INIT:
16255       e->command = "sip show tcp";
16256       e->usage =
16257          "Usage: sip show tcp\n"
16258          "       Lists all active TCP/TLS sessions.\n";
16259       return NULL;
16260    case CLI_GENERATE:
16261       return NULL;
16262    }
16263 
16264    if (a->argc != 3)
16265       return CLI_SHOWUSAGE;
16266 
16267    ast_cli(a->fd, FORMAT2, "Address", "Transport", "Type");
16268 
16269    i = ao2_iterator_init(threadt, 0);
16270    while ((th = ao2_t_iterator_next(&i, "iterate through tcp threads for 'sip show tcp'"))) {
16271       ast_cli(a->fd, FORMAT,
16272          ast_sockaddr_stringify(&th->tcptls_session->remote_address),
16273          get_transport(th->type),
16274          (th->tcptls_session->client ? "Client" : "Server"));
16275       ao2_t_ref(th, -1, "decrement ref from iterator");
16276    }
16277    ao2_iterator_destroy(&i);
16278 
16279    return CLI_SUCCESS;
16280 #undef FORMAT
16281 #undef FORMAT2
16282 }
16283 
16284 /*! \brief  CLI Command 'SIP Show Users' */
16285 static char *sip_show_users(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16286 {
16287    regex_t regexbuf;
16288    int havepattern = FALSE;
16289    struct ao2_iterator user_iter;
16290    struct sip_peer *user;
16291 
16292 #define FORMAT  "%-25.25s  %-15.15s  %-15.15s  %-15.15s  %-5.5s%-10.10s\n"
16293 
16294    switch (cmd) {
16295    case CLI_INIT:
16296       e->command = "sip show users";
16297       e->usage =
16298          "Usage: sip show users [like <pattern>]\n"
16299          "       Lists all known SIP users.\n"
16300          "       Optional regular expression pattern is used to filter the user list.\n";
16301       return NULL;
16302    case CLI_GENERATE:
16303       return NULL;
16304    }
16305 
16306    switch (a->argc) {
16307    case 5:
16308       if (!strcasecmp(a->argv[3], "like")) {
16309          if (regcomp(&regexbuf, a->argv[4], REG_EXTENDED | REG_NOSUB))
16310             return CLI_SHOWUSAGE;
16311          havepattern = TRUE;
16312       } else
16313          return CLI_SHOWUSAGE;
16314    case 3:
16315       break;
16316    default:
16317       return CLI_SHOWUSAGE;
16318    }
16319 
16320    ast_cli(a->fd, FORMAT, "Username", "Secret", "Accountcode", "Def.Context", "ACL", "ForcerPort");
16321 
16322    user_iter = ao2_iterator_init(peers, 0);
16323    while ((user = ao2_t_iterator_next(&user_iter, "iterate thru peers table"))) {
16324       ao2_lock(user);
16325       if (!(user->type & SIP_TYPE_USER)) {
16326          ao2_unlock(user);
16327          unref_peer(user, "sip show users");
16328          continue;
16329       }
16330 
16331       if (havepattern && regexec(&regexbuf, user->name, 0, NULL, 0)) {
16332          ao2_unlock(user);
16333          unref_peer(user, "sip show users");
16334          continue;
16335       }
16336 
16337       ast_cli(a->fd, FORMAT, user->name,
16338          user->secret,
16339          user->accountcode,
16340          user->context,
16341          AST_CLI_YESNO(user->ha != NULL),
16342          AST_CLI_YESNO(ast_test_flag(&user->flags[0], SIP_NAT_FORCE_RPORT)));
16343       ao2_unlock(user);
16344       unref_peer(user, "sip show users");
16345    }
16346    ao2_iterator_destroy(&user_iter);
16347 
16348    if (havepattern)
16349       regfree(&regexbuf);
16350 
16351    return CLI_SUCCESS;
16352 #undef FORMAT
16353 }
16354 
16355 /*! \brief Show SIP registrations in the manager API */
16356 static int manager_show_registry(struct mansession *s, const struct message *m)
16357 {
16358    const char *id = astman_get_header(m, "ActionID");
16359    char idtext[256] = "";
16360    int total = 0;
16361 
16362    if (!ast_strlen_zero(id))
16363       snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
16364 
16365    astman_send_listack(s, m, "Registrations will follow", "start");
16366 
16367    ASTOBJ_CONTAINER_TRAVERSE(&regl, 1, do {
16368       ASTOBJ_RDLOCK(iterator);
16369       astman_append(s,
16370          "Event: RegistryEntry\r\n"
16371          "%s"
16372          "Host: %s\r\n"
16373          "Port: %d\r\n"
16374          "Username: %s\r\n"
16375          "Domain: %s\r\n"
16376          "DomainPort: %d\r\n"
16377          "Refresh: %d\r\n"
16378          "State: %s\r\n"
16379          "RegistrationTime: %ld\r\n"
16380          "\r\n",
16381          idtext,
16382          iterator->hostname,
16383          iterator->portno ? iterator->portno : STANDARD_SIP_PORT,
16384          iterator->username,
16385          S_OR(iterator->regdomain,iterator->hostname),
16386          iterator->regdomainport ? iterator->regdomainport : STANDARD_SIP_PORT,
16387          iterator->refresh,
16388          regstate2str(iterator->regstate),
16389          (long) iterator->regtime.tv_sec);
16390       ASTOBJ_UNLOCK(iterator);
16391       total++;
16392    } while(0));
16393 
16394    astman_append(s,
16395       "Event: RegistrationsComplete\r\n"
16396       "EventList: Complete\r\n"
16397       "ListItems: %d\r\n"
16398       "%s"
16399       "\r\n", total, idtext);
16400    
16401    return 0;
16402 }
16403 
16404 /*! \brief  Show SIP peers in the manager API */
16405 /*    Inspired from chan_iax2 */
16406 static int manager_sip_show_peers(struct mansession *s, const struct message *m)
16407 {
16408    const char *id = astman_get_header(m, "ActionID");
16409    const char *a[] = {"sip", "show", "peers"};
16410    char idtext[256] = "";
16411    int total = 0;
16412 
16413    if (!ast_strlen_zero(id))
16414       snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
16415 
16416    astman_send_listack(s, m, "Peer status list will follow", "start");
16417    /* List the peers in separate manager events */
16418    _sip_show_peers(-1, &total, s, m, 3, a);
16419    /* Send final confirmation */
16420    astman_append(s,
16421    "Event: PeerlistComplete\r\n"
16422    "EventList: Complete\r\n"
16423    "ListItems: %d\r\n"
16424    "%s"
16425    "\r\n", total, idtext);
16426    return 0;
16427 }
16428 
16429 /*! \brief  CLI Show Peers command */
16430 static char *sip_show_peers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16431 {
16432    switch (cmd) {
16433    case CLI_INIT:
16434       e->command = "sip show peers";
16435       e->usage =
16436          "Usage: sip show peers [like <pattern>]\n"
16437          "       Lists all known SIP peers.\n"
16438          "       Optional regular expression pattern is used to filter the peer list.\n";
16439       return NULL;
16440    case CLI_GENERATE:
16441       return NULL;
16442    }
16443 
16444    return _sip_show_peers(a->fd, NULL, NULL, NULL, a->argc, (const char **) a->argv);
16445 }
16446 
16447 int peercomparefunc(const void *a, const void *b);
16448 
16449 int peercomparefunc(const void *a, const void *b)
16450 {
16451    struct sip_peer **ap = (struct sip_peer **)a;
16452    struct sip_peer **bp = (struct sip_peer **)b;
16453    return strcmp((*ap)->name, (*bp)->name);
16454 }
16455 
16456 
16457 /*! \brief Execute sip show peers command */
16458 static char *_sip_show_peers(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char *argv[])
16459 {
16460    regex_t regexbuf;
16461    int havepattern = FALSE;
16462    struct sip_peer *peer;
16463    struct ao2_iterator i;
16464    
16465 /* the last argument is left-aligned, so we don't need a size anyways */
16466 #define FORMAT2 "%-25.25s  %-39.39s %-3.3s %-10.10s %-3.3s %-8s %-10s %s\n"
16467 #define FORMAT  "%-25.25s  %-39.39s %-3.3s %-3.3s %-3.3s %-8d %-10s %s\n"
16468 
16469    char name[256];
16470    int total_peers = 0;
16471    int peers_mon_online = 0;
16472    int peers_mon_offline = 0;
16473    int peers_unmon_offline = 0;
16474    int peers_unmon_online = 0;
16475    const char *id;
16476    char idtext[256] = "";
16477    int realtimepeers;
16478    int objcount = ao2_container_count(peers);
16479    struct sip_peer **peerarray;
16480    int k;
16481    
16482    
16483    realtimepeers = ast_check_realtime("sippeers");
16484    peerarray = ast_calloc(sizeof(struct sip_peer *), objcount);
16485 
16486    if (s) { /* Manager - get ActionID */
16487       id = astman_get_header(m, "ActionID");
16488       if (!ast_strlen_zero(id))
16489          snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
16490    }
16491 
16492    switch (argc) {
16493    case 5:
16494       if (!strcasecmp(argv[3], "like")) {
16495          if (regcomp(&regexbuf, argv[4], REG_EXTENDED | REG_NOSUB))
16496             return CLI_SHOWUSAGE;
16497          havepattern = TRUE;
16498       } else
16499          return CLI_SHOWUSAGE;
16500    case 3:
16501       break;
16502    default:
16503       return CLI_SHOWUSAGE;
16504    }
16505 
16506    if (!s) /* Normal list */
16507       ast_cli(fd, FORMAT2, "Name/username", "Host", "Dyn", "Forcerport", "ACL", "Port", "Status", (realtimepeers ? "Realtime" : ""));
16508    
16509 
16510    i = ao2_iterator_init(peers, 0);
16511    while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {  
16512       ao2_lock(peer);
16513 
16514       if (!(peer->type & SIP_TYPE_PEER)) {
16515          ao2_unlock(peer);
16516          unref_peer(peer, "unref peer because it's actually a user");
16517          continue;
16518       }
16519 
16520       if (havepattern && regexec(&regexbuf, peer->name, 0, NULL, 0)) {
16521          objcount--;
16522          ao2_unlock(peer);
16523          unref_peer(peer, "toss iterator peer ptr before continue");
16524          continue;
16525       }
16526 
16527       peerarray[total_peers++] = peer;
16528       ao2_unlock(peer);
16529    }
16530    ao2_iterator_destroy(&i);
16531    
16532    qsort(peerarray, total_peers, sizeof(struct sip_peer *), peercomparefunc);
16533 
16534    for(k=0; k < total_peers; k++) {
16535       char status[20] = "";
16536       char srch[2000];
16537       char pstatus;
16538       peer = peerarray[k];
16539       
16540       ao2_lock(peer);
16541       if (havepattern && regexec(&regexbuf, peer->name, 0, NULL, 0)) {
16542          ao2_unlock(peer);
16543          peer = peerarray[k] = unref_peer(peer, "toss iterator peer ptr before continue");
16544          continue;
16545       }
16546 
16547       if (!ast_strlen_zero(peer->username) && !s)
16548          snprintf(name, sizeof(name), "%s/%s", peer->name, peer->username);
16549       else
16550          ast_copy_string(name, peer->name, sizeof(name));
16551       
16552       pstatus = peer_status(peer, status, sizeof(status));
16553       if (pstatus == 1)
16554          peers_mon_online++;
16555       else if (pstatus == 0)
16556          peers_mon_offline++;
16557       else {
16558          if (ast_sockaddr_isnull(&peer->addr) ||
16559              !ast_sockaddr_port(&peer->addr)) {
16560             peers_unmon_offline++;
16561          } else {
16562             peers_unmon_online++;
16563          }
16564       }
16565 
16566       snprintf(srch, sizeof(srch), FORMAT, name,
16567          ast_sockaddr_isnull(&peer->addr) ? "(Unspecified)" : ast_sockaddr_stringify_addr(&peer->addr),
16568          peer->host_dynamic ? " D " : "   ",    /* Dynamic or not? */
16569          ast_test_flag(&peer->flags[0], SIP_NAT_FORCE_RPORT) ? " N " : "   ", /* NAT=yes? */
16570          peer->ha ? " A " : "   ",  /* permit/deny */
16571          ast_sockaddr_isnull(&peer->addr) ? 0 : ast_sockaddr_port(&peer->addr), status,
16572          realtimepeers ? (peer->is_realtime ? "Cached RT":"") : "");
16573 
16574       if (!s)  {/* Normal CLI list */
16575          ast_cli(fd, FORMAT, name,
16576          ast_sockaddr_isnull(&peer->addr) ? "(Unspecified)" : ast_sockaddr_stringify_addr(&peer->addr),
16577          peer->host_dynamic ? " D " : "   ",    /* Dynamic or not? */
16578          ast_test_flag(&peer->flags[0], SIP_NAT_FORCE_RPORT) ? " N " : "   ", /* NAT=yes? */
16579          peer->ha ? " A " : "   ",       /* permit/deny */
16580          ast_sockaddr_isnull(&peer->addr) ? 0 : ast_sockaddr_port(&peer->addr), status,
16581          realtimepeers ? (peer->is_realtime ? "Cached RT":"") : "");
16582       } else { /* Manager format */
16583          /* The names here need to be the same as other channels */
16584          astman_append(s,
16585          "Event: PeerEntry\r\n%s"
16586          "Channeltype: SIP\r\n"
16587          "ObjectName: %s\r\n"
16588          "ChanObjectType: peer\r\n" /* "peer" or "user" */
16589          "IPaddress: %s\r\n"
16590          "IPport: %d\r\n"
16591          "Dynamic: %s\r\n"
16592          "Forcerport: %s\r\n"
16593          "VideoSupport: %s\r\n"
16594          "TextSupport: %s\r\n"
16595          "ACL: %s\r\n"
16596          "Status: %s\r\n"
16597          "RealtimeDevice: %s\r\n\r\n",
16598          idtext,
16599          peer->name,
16600          ast_sockaddr_isnull(&peer->addr) ? "-none-" : ast_sockaddr_stringify_fmt(&peer->addr, AST_SOCKADDR_STR_HOST),
16601          ast_sockaddr_isnull(&peer->addr) ? 0 : ast_sockaddr_port(&peer->addr),
16602          peer->host_dynamic ? "yes" : "no",  /* Dynamic or not? */
16603          ast_test_flag(&peer->flags[0], SIP_NAT_FORCE_RPORT) ? "yes" : "no",  /* NAT=yes? */
16604          ast_test_flag(&peer->flags[1], SIP_PAGE2_VIDEOSUPPORT) ? "yes" : "no",  /* VIDEOSUPPORT=yes? */
16605          ast_test_flag(&peer->flags[1], SIP_PAGE2_TEXTSUPPORT) ? "yes" : "no",   /* TEXTSUPPORT=yes? */
16606          peer->ha ? "yes" : "no",       /* permit/deny */
16607          status,
16608          realtimepeers ? (peer->is_realtime ? "yes":"no") : "no");
16609       }
16610       ao2_unlock(peer);
16611       peer = peerarray[k] = unref_peer(peer, "toss iterator peer ptr");
16612    }
16613    
16614    if (!s)
16615       ast_cli(fd, "%d sip peers [Monitored: %d online, %d offline Unmonitored: %d online, %d offline]\n",
16616               total_peers, peers_mon_online, peers_mon_offline, peers_unmon_online, peers_unmon_offline);
16617 
16618    if (havepattern)
16619       regfree(&regexbuf);
16620 
16621    if (total)
16622       *total = total_peers;
16623    
16624    ast_free(peerarray);
16625    
16626    return CLI_SUCCESS;
16627 #undef FORMAT
16628 #undef FORMAT2
16629 }
16630 
16631 static int peer_dump_func(void *userobj, void *arg, int flags)
16632 {
16633    struct sip_peer *peer = userobj;
16634    int refc = ao2_t_ref(userobj, 0, "");
16635    struct ast_cli_args *a = (struct ast_cli_args *) arg;
16636    
16637    ast_cli(a->fd, "name: %s\ntype: peer\nobjflags: %d\nrefcount: %d\n\n",
16638       peer->name, 0, refc);
16639    return 0;
16640 }
16641 
16642 static int dialog_dump_func(void *userobj, void *arg, int flags)
16643 {
16644    struct sip_pvt *pvt = userobj;
16645    int refc = ao2_t_ref(userobj, 0, "");
16646    struct ast_cli_args *a = (struct ast_cli_args *) arg;
16647    
16648    ast_cli(a->fd, "name: %s\ntype: dialog\nobjflags: %d\nrefcount: %d\n\n",
16649       pvt->callid, 0, refc);
16650    return 0;
16651 }
16652 
16653 
16654 /*! \brief List all allocated SIP Objects (realtime or static) */
16655 static char *sip_show_objects(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16656 {
16657    char tmp[256];
16658    
16659    switch (cmd) {
16660    case CLI_INIT:
16661       e->command = "sip show objects";
16662       e->usage =
16663          "Usage: sip show objects\n"
16664          "       Lists status of known SIP objects\n";
16665       return NULL;
16666    case CLI_GENERATE:
16667       return NULL;
16668    }  
16669 
16670    if (a->argc != 3)
16671       return CLI_SHOWUSAGE;
16672    ast_cli(a->fd, "-= Peer objects: %d static, %d realtime, %d autocreate =-\n\n", speerobjs, rpeerobjs, apeerobjs);
16673    ao2_t_callback(peers, OBJ_NODATA, peer_dump_func, a, "initiate ao2_callback to dump peers");
16674    ast_cli(a->fd, "-= Peer objects by IP =-\n\n"); 
16675    ao2_t_callback(peers_by_ip, OBJ_NODATA, peer_dump_func, a, "initiate ao2_callback to dump peers_by_ip");
16676    ast_cli(a->fd, "-= Registry objects: %d =-\n\n", regobjs);
16677    ASTOBJ_CONTAINER_DUMP(a->fd, tmp, sizeof(tmp), &regl);
16678    ast_cli(a->fd, "-= Dialog objects:\n\n");
16679    ao2_t_callback(dialogs, OBJ_NODATA, dialog_dump_func, a, "initiate ao2_callback to dump dialogs");
16680    return CLI_SUCCESS;
16681 }
16682 /*! \brief Print call group and pickup group */
16683 static void print_group(int fd, ast_group_t group, int crlf)
16684 {
16685    char buf[256];
16686    ast_cli(fd, crlf ? "%s\r\n" : "%s\n", ast_print_group(buf, sizeof(buf), group) );
16687 }
16688 
16689 /*! \brief mapping between dtmf flags and strings */
16690 static const struct _map_x_s dtmfstr[] = {
16691    { SIP_DTMF_RFC2833,     "rfc2833" },
16692    { SIP_DTMF_INFO,        "info" },
16693    { SIP_DTMF_SHORTINFO,   "shortinfo" },
16694    { SIP_DTMF_INBAND,      "inband" },
16695    { SIP_DTMF_AUTO,        "auto" },
16696    { -1,                   NULL }, /* terminator */
16697 };
16698 
16699 /*! \brief Convert DTMF mode to printable string */
16700 static const char *dtmfmode2str(int mode)
16701 {
16702    return map_x_s(dtmfstr, mode, "<error>");
16703 }
16704 
16705 /*! \brief maps a string to dtmfmode, returns -1 on error */
16706 static int str2dtmfmode(const char *str)
16707 {
16708    return map_s_x(dtmfstr, str, -1);
16709 }
16710 
16711 static const struct _map_x_s insecurestr[] = {
16712    { SIP_INSECURE_PORT,    "port" },
16713    { SIP_INSECURE_INVITE,  "invite" },
16714    { SIP_INSECURE_PORT | SIP_INSECURE_INVITE, "port,invite" },
16715    { 0,                    "no" },
16716    { -1,                   NULL }, /* terminator */
16717 };
16718 
16719 /*! \brief Convert Insecure setting to printable string */
16720 static const char *insecure2str(int mode)
16721 {
16722    return map_x_s(insecurestr, mode, "<error>");
16723 }
16724 
16725 static const struct _map_x_s allowoverlapstr[] = {
16726    { SIP_PAGE2_ALLOWOVERLAP_YES,   "Yes" },
16727    { SIP_PAGE2_ALLOWOVERLAP_DTMF,  "DTMF" },
16728    { SIP_PAGE2_ALLOWOVERLAP_NO,    "No" },
16729    { -1,                           NULL }, /* terminator */
16730 };
16731 
16732 /*! \brief Convert AllowOverlap setting to printable string */
16733 static const char *allowoverlap2str(int mode)
16734 {
16735    return map_x_s(allowoverlapstr, mode, "<error>");
16736 }
16737 
16738 /*! \brief Destroy disused contexts between reloads
16739    Only used in reload_config so the code for regcontext doesn't get ugly
16740 */
16741 static void cleanup_stale_contexts(char *new, char *old)
16742 {
16743    char *oldcontext, *newcontext, *stalecontext, *stringp, newlist[AST_MAX_CONTEXT];
16744 
16745    while ((oldcontext = strsep(&old, "&"))) {
16746       stalecontext = '\0';
16747       ast_copy_string(newlist, new, sizeof(newlist));
16748       stringp = newlist;
16749       while ((newcontext = strsep(&stringp, "&"))) {
16750          if (!strcmp(newcontext, oldcontext)) {
16751             /* This is not the context you're looking for */
16752             stalecontext = '\0';
16753             break;
16754          } else if (strcmp(newcontext, oldcontext)) {
16755             stalecontext = oldcontext;
16756          }
16757          
16758       }
16759       if (stalecontext)
16760          ast_context_destroy(ast_context_find(stalecontext), "SIP");
16761    }
16762 }
16763 
16764 /*!
16765  * \brief Match dialogs that need to be destroyed
16766  *
16767  * \details This is used with ao2_callback to unlink/delete all dialogs that
16768  * are marked needdestroy.
16769  *
16770  * \todo Re-work this to improve efficiency.  Currently, this function is called
16771  * on _every_ dialog after processing _every_ incoming SIP/UDP packet, or
16772  * potentially even more often when the scheduler has entries to run.
16773  */
16774 static int dialog_needdestroy(void *dialogobj, void *arg, int flags)
16775 {
16776    struct sip_pvt *dialog = dialogobj;
16777    time_t *t = arg;
16778 
16779    if (sip_pvt_trylock(dialog)) {
16780       /* Don't block the monitor thread.  This function is called often enough
16781        * that we can wait for the next time around. */
16782       return 0;
16783    }
16784 
16785    /* We absolutely cannot destroy the rtp struct while a bridge is active or we WILL crash */
16786    if (dialog->rtp && ast_rtp_instance_get_bridged(dialog->rtp)) {
16787       ast_debug(2, "Bridge still active.  Delaying destroy of SIP dialog '%s' Method: %s\n", dialog->callid, sip_methods[dialog->method].text);
16788       sip_pvt_unlock(dialog);
16789       return 0;
16790    }
16791 
16792    if (dialog->vrtp && ast_rtp_instance_get_bridged(dialog->vrtp)) {
16793       ast_debug(2, "Bridge still active.  Delaying destroy of SIP dialog '%s' Method: %s\n", dialog->callid, sip_methods[dialog->method].text);
16794       sip_pvt_unlock(dialog);
16795       return 0;
16796    }
16797 
16798    /* Check RTP timeouts and kill calls if we have a timeout set and do not get RTP */
16799    check_rtp_timeout(dialog, *t);
16800 
16801    /* If we have sessions that needs to be destroyed, do it now */
16802    /* Check if we have outstanding requests not responsed to or an active call
16803       - if that's the case, wait with destruction */
16804    if (dialog->needdestroy && !dialog->packets && !dialog->owner) {
16805       /* We absolutely cannot destroy the rtp struct while a bridge is active or we WILL crash */
16806       if (dialog->rtp && ast_rtp_instance_get_bridged(dialog->rtp)) {
16807          ast_debug(2, "Bridge still active.  Delaying destruction of SIP dialog '%s' Method: %s\n", dialog->callid, sip_methods[dialog->method].text);
16808          sip_pvt_unlock(dialog);
16809          return 0;
16810       }
16811       
16812       if (dialog->vrtp && ast_rtp_instance_get_bridged(dialog->vrtp)) {
16813          ast_debug(2, "Bridge still active.  Delaying destroy of SIP dialog '%s' Method: %s\n", dialog->callid, sip_methods[dialog->method].text);
16814          sip_pvt_unlock(dialog);
16815          return 0;
16816       }
16817 
16818       sip_pvt_unlock(dialog);
16819 
16820       /* This dialog needs to be destroyed. */
16821       ao2_t_link(dialogs_to_destroy, dialog, "Link dialog for destruction");
16822       return 0;
16823    }
16824 
16825    sip_pvt_unlock(dialog);
16826 
16827    return 0;
16828 }
16829 
16830 /*!
16831  * \internal
16832  * \brief ao2_callback to unlink the specified dialog object.
16833  *
16834  * \param obj Ptr to dialog to unlink.
16835  * \param arg Don't care.
16836  * \param flags Don't care.
16837  *
16838  * \retval CMP_MATCH
16839  */
16840 static int dialog_unlink_callback(void *obj, void *arg, int flags)
16841 {
16842    struct sip_pvt *dialog = obj;
16843 
16844    dialog_unlink_all(dialog);
16845 
16846    return CMP_MATCH;
16847 }
16848 
16849 /*! \brief Remove temporary realtime objects from memory (CLI) */
16850 /*! \todo XXXX Propably needs an overhaul after removal of the devices */
16851 static char *sip_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16852 {
16853    struct sip_peer *peer, *pi;
16854    int prunepeer = FALSE;
16855    int multi = FALSE;
16856    const char *name = NULL;
16857    regex_t regexbuf;
16858    int havepattern = 0;
16859    struct ao2_iterator i;
16860    static const char * const choices[] = { "all", "like", NULL };
16861    char *cmplt;
16862    
16863    if (cmd == CLI_INIT) {
16864       e->command = "sip prune realtime [peer|all]";
16865       e->usage =
16866          "Usage: sip prune realtime [peer [<name>|all|like <pattern>]|all]\n"
16867          "       Prunes object(s) from the cache.\n"
16868          "       Optional regular expression pattern is used to filter the objects.\n";
16869       return NULL;
16870    } else if (cmd == CLI_GENERATE) {
16871       if (a->pos == 4 && !strcasecmp(a->argv[3], "peer")) {
16872          cmplt = ast_cli_complete(a->word, choices, a->n);
16873          if (!cmplt)
16874             cmplt = complete_sip_peer(a->word, a->n - sizeof(choices), SIP_PAGE2_RTCACHEFRIENDS);
16875          return cmplt;
16876       }
16877       if (a->pos == 5 && !strcasecmp(a->argv[4], "like"))
16878          return complete_sip_peer(a->word, a->n, SIP_PAGE2_RTCACHEFRIENDS);
16879       return NULL;
16880    }
16881    switch (a->argc) {
16882    case 4:
16883       name = a->argv[3];
16884       /* we accept a name in position 3, but keywords are not good. */
16885       if (!strcasecmp(name, "peer") || !strcasecmp(name, "like"))
16886          return CLI_SHOWUSAGE;
16887       prunepeer = TRUE;
16888       if (!strcasecmp(name, "all")) {
16889          multi = TRUE;
16890          name = NULL;
16891       }
16892       /* else a single name, already set */
16893       break;
16894    case 5:
16895       /* sip prune realtime {peer|like} name */
16896       name = a->argv[4];
16897       if (!strcasecmp(a->argv[3], "peer"))
16898          prunepeer = TRUE;
16899       else if (!strcasecmp(a->argv[3], "like")) {
16900          prunepeer = TRUE;
16901          multi = TRUE;
16902       } else
16903          return CLI_SHOWUSAGE;
16904       if (!strcasecmp(name, "like"))
16905          return CLI_SHOWUSAGE;
16906       if (!multi && !strcasecmp(name, "all")) {
16907          multi = TRUE;
16908          name = NULL;
16909       }
16910       break;
16911    case 6:
16912       name = a->argv[5];
16913       multi = TRUE;
16914       /* sip prune realtime {peer} like name */
16915       if (strcasecmp(a->argv[4], "like"))
16916          return CLI_SHOWUSAGE;
16917       if (!strcasecmp(a->argv[3], "peer")) {
16918          prunepeer = TRUE;
16919       } else
16920          return CLI_SHOWUSAGE;
16921       break;
16922    default:
16923       return CLI_SHOWUSAGE;
16924    }
16925 
16926    if (multi && name) {
16927       if (regcomp(&regexbuf, name, REG_EXTENDED | REG_NOSUB)) {
16928          return CLI_SHOWUSAGE;
16929       }
16930       havepattern = 1;
16931    }
16932 
16933    if (multi) {
16934       if (prunepeer) {
16935          int pruned = 0;
16936          
16937          i = ao2_iterator_init(peers, 0);
16938          while ((pi = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
16939             ao2_lock(pi);
16940             if (name && regexec(&regexbuf, pi->name, 0, NULL, 0)) {
16941                unref_peer(pi, "toss iterator peer ptr before continue");
16942                ao2_unlock(pi);
16943                continue;
16944             };
16945             if (ast_test_flag(&pi->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
16946                pi->the_mark = 1;
16947                pruned++;
16948             }
16949             ao2_unlock(pi);
16950             unref_peer(pi, "toss iterator peer ptr");
16951          }
16952          ao2_iterator_destroy(&i);
16953          if (pruned) {
16954             unlink_marked_peers_from_tables();
16955             ast_cli(a->fd, "%d peers pruned.\n", pruned);
16956          } else
16957             ast_cli(a->fd, "No peers found to prune.\n");
16958       }
16959    } else {
16960       if (prunepeer) {
16961          struct sip_peer tmp;
16962          ast_copy_string(tmp.name, name, sizeof(tmp.name));
16963          if ((peer = ao2_t_find(peers, &tmp, OBJ_POINTER | OBJ_UNLINK, "finding to unlink from peers"))) {
16964             if (!ast_sockaddr_isnull(&peer->addr)) {
16965                ao2_t_unlink(peers_by_ip, peer, "unlinking peer from peers_by_ip also");
16966             }
16967             if (!ast_test_flag(&peer->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
16968                ast_cli(a->fd, "Peer '%s' is not a Realtime peer, cannot be pruned.\n", name);
16969                /* put it back! */
16970                ao2_t_link(peers, peer, "link peer into peer table");
16971                if (!ast_sockaddr_isnull(&peer->addr)) {
16972                   ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
16973                }
16974             } else
16975                ast_cli(a->fd, "Peer '%s' pruned.\n", name);
16976             unref_peer(peer, "sip_prune_realtime: unref_peer: tossing temp peer ptr");
16977          } else
16978             ast_cli(a->fd, "Peer '%s' not found.\n", name);
16979       }
16980    }
16981 
16982    if (havepattern) {
16983       regfree(&regexbuf);
16984    }
16985 
16986    return CLI_SUCCESS;
16987 }
16988 
16989 /*! \brief Print codec list from preference to CLI/manager */
16990 static void print_codec_to_cli(int fd, struct ast_codec_pref *pref)
16991 {
16992    int x;
16993    format_t codec;
16994 
16995    for(x = 0; x < 64 ; x++) {
16996       codec = ast_codec_pref_index(pref, x);
16997       if (!codec)
16998          break;
16999       ast_cli(fd, "%s", ast_getformatname(codec));
17000       ast_cli(fd, ":%d", pref->framing[x]);
17001       if (x < 31 && ast_codec_pref_index(pref, x + 1))
17002          ast_cli(fd, ",");
17003    }
17004    if (!x)
17005       ast_cli(fd, "none");
17006 }
17007 
17008 /*! \brief Print domain mode to cli */
17009 static const char *domain_mode_to_text(const enum domain_mode mode)
17010 {
17011    switch (mode) {
17012    case SIP_DOMAIN_AUTO:
17013       return "[Automatic]";
17014    case SIP_DOMAIN_CONFIG:
17015       return "[Configured]";
17016    }
17017 
17018    return "";
17019 }
17020 
17021 /*! \brief CLI command to list local domains */
17022 static char *sip_show_domains(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
17023 {
17024    struct domain *d;
17025 #define FORMAT "%-40.40s %-20.20s %-16.16s\n"
17026 
17027    switch (cmd) {
17028    case CLI_INIT:
17029       e->command = "sip show domains";
17030       e->usage =
17031          "Usage: sip show domains\n"
17032          "       Lists all configured SIP local domains.\n"
17033          "       Asterisk only responds to SIP messages to local domains.\n";
17034       return NULL;
17035    case CLI_GENERATE:
17036       return NULL;
17037    }
17038 
17039    if (AST_LIST_EMPTY(&domain_list)) {
17040       ast_cli(a->fd, "SIP Domain support not enabled.\n\n");
17041       return CLI_SUCCESS;
17042    } else {
17043       ast_cli(a->fd, FORMAT, "Our local SIP domains:", "Context", "Set by");
17044       AST_LIST_LOCK(&domain_list);
17045       AST_LIST_TRAVERSE(&domain_list, d, list)
17046          ast_cli(a->fd, FORMAT, d->domain, S_OR(d->context, "(default)"),
17047             domain_mode_to_text(d->mode));
17048       AST_LIST_UNLOCK(&domain_list);
17049       ast_cli(a->fd, "\n");
17050       return CLI_SUCCESS;
17051    }
17052 }
17053 #undef FORMAT
17054 
17055 /*! \brief Show SIP peers in the manager API  */
17056 static int manager_sip_show_peer(struct mansession *s, const struct message *m)
17057 {
17058    const char *a[4];
17059    const char *peer;
17060 
17061    peer = astman_get_header(m, "Peer");
17062    if (ast_strlen_zero(peer)) {
17063       astman_send_error(s, m, "Peer: <name> missing.");
17064       return 0;
17065    }
17066    a[0] = "sip";
17067    a[1] = "show";
17068    a[2] = "peer";
17069    a[3] = peer;
17070 
17071    _sip_show_peer(1, -1, s, m, 4, a);
17072    astman_append(s, "\r\n" );
17073    return 0;
17074 }
17075 
17076 /*! \brief Show one peer in detail */
17077 static char *sip_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
17078 {
17079    switch (cmd) {
17080    case CLI_INIT:
17081       e->command = "sip show peer";
17082       e->usage =
17083          "Usage: sip show peer <name> [load]\n"
17084          "       Shows all details on one SIP peer and the current status.\n"
17085          "       Option \"load\" forces lookup of peer in realtime storage.\n";
17086       return NULL;
17087    case CLI_GENERATE:
17088       return complete_sip_show_peer(a->line, a->word, a->pos, a->n);
17089    }
17090    return _sip_show_peer(0, a->fd, NULL, NULL, a->argc, (const char **) a->argv);
17091 }
17092 
17093 /*! \brief Send qualify message to peer from cli or manager. Mostly for debugging. */
17094 static char *_sip_qualify_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[])
17095 {
17096    struct sip_peer *peer;
17097    int load_realtime;
17098 
17099    if (argc < 4)
17100       return CLI_SHOWUSAGE;
17101 
17102    load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? TRUE : FALSE;
17103    if ((peer = find_peer(argv[3], NULL, load_realtime, FINDPEERS, FALSE, 0))) {
17104       sip_poke_peer(peer, 1);
17105       unref_peer(peer, "qualify: done with peer");
17106    } else if (type == 0) {
17107       ast_cli(fd, "Peer '%s' not found\n", argv[3]);
17108    } else {
17109       astman_send_error(s, m, "Peer not found");
17110    }
17111    return CLI_SUCCESS;
17112 }
17113 
17114 /*! \brief Qualify SIP peers in the manager API  */
17115 static int manager_sip_qualify_peer(struct mansession *s, const struct message *m)
17116 {
17117    const char *a[4];
17118    const char *peer;
17119 
17120    peer = astman_get_header(m, "Peer");
17121    if (ast_strlen_zero(peer)) {
17122       astman_send_error(s, m, "Peer: <name> missing.");
17123       return 0;
17124    }
17125    a[0] = "sip";
17126    a[1] = "qualify";
17127    a[2] = "peer";
17128    a[3] = peer;
17129 
17130    _sip_qualify_peer(1, -1, s, m, 4, a);
17131    astman_append(s, "\r\n\r\n" );
17132    return 0;
17133 }
17134 
17135 /*! \brief Send an OPTIONS packet to a SIP peer */
17136 static char *sip_qualify_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
17137 {
17138    switch (cmd) {
17139    case CLI_INIT:
17140       e->command = "sip qualify peer";
17141       e->usage =
17142          "Usage: sip qualify peer <name> [load]\n"
17143          "       Requests a response from one SIP peer and the current status.\n"
17144          "       Option \"load\" forces lookup of peer in realtime storage.\n";
17145       return NULL;
17146    case CLI_GENERATE:
17147       return complete_sip_show_peer(a->line, a->word, a->pos, a->n);
17148    }
17149    return _sip_qualify_peer(0, a->fd, NULL, NULL, a->argc, (const char **) a->argv);
17150 }
17151 
17152 /*! \brief list peer mailboxes to CLI */
17153 static void peer_mailboxes_to_str(struct ast_str **mailbox_str, struct sip_peer *peer)
17154 {
17155    struct sip_mailbox *mailbox;
17156 
17157    AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
17158       ast_str_append(mailbox_str, 0, "%s%s%s%s",
17159          mailbox->mailbox,
17160          ast_strlen_zero(mailbox->context) ? "" : "@",
17161          S_OR(mailbox->context, ""),
17162          AST_LIST_NEXT(mailbox, entry) ? "," : "");
17163    }
17164 }
17165 
17166 static struct _map_x_s faxecmodes[] = {
17167    { SIP_PAGE2_T38SUPPORT_UDPTL,       "None"},
17168    { SIP_PAGE2_T38SUPPORT_UDPTL_FEC,      "FEC"},
17169    { SIP_PAGE2_T38SUPPORT_UDPTL_REDUNDANCY,  "Redundancy"},
17170    { -1,                NULL},
17171 };
17172 
17173 static const char *faxec2str(int faxec)
17174 {
17175    return map_x_s(faxecmodes, faxec, "Unknown");
17176 }
17177 
17178 /*! \brief Show one peer in detail (main function) */
17179 static char *_sip_show_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[])
17180 {
17181    char status[30] = "";
17182    char cbuf[256];
17183    struct sip_peer *peer;
17184    char codec_buf[512];
17185    struct ast_codec_pref *pref;
17186    struct ast_variable *v;
17187    int x = 0, load_realtime;
17188    format_t codec = 0;
17189    int realtimepeers;
17190 
17191    realtimepeers = ast_check_realtime("sippeers");
17192 
17193    if (argc < 4)
17194       return CLI_SHOWUSAGE;
17195 
17196    load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? TRUE : FALSE;
17197    peer = find_peer(argv[3], NULL, load_realtime, FINDPEERS, FALSE, 0);
17198 
17199    if (s) {    /* Manager */
17200       if (peer) {
17201          const char *id = astman_get_header(m, "ActionID");
17202 
17203          astman_append(s, "Response: Success\r\n");
17204          if (!ast_strlen_zero(id))
17205             astman_append(s, "ActionID: %s\r\n", id);
17206       } else {
17207          snprintf (cbuf, sizeof(cbuf), "Peer %s not found.", argv[3]);
17208          astman_send_error(s, m, cbuf);
17209          return CLI_SUCCESS;
17210       }
17211    }
17212    if (peer && type==0 ) { /* Normal listing */
17213       struct ast_str *mailbox_str = ast_str_alloca(512);
17214       struct sip_auth_container *credentials;
17215 
17216       ao2_lock(peer);
17217       credentials = peer->auth;
17218       if (credentials) {
17219          ao2_t_ref(credentials, +1, "Ref peer auth for show");
17220       }
17221       ao2_unlock(peer);
17222 
17223       ast_cli(fd, "\n\n");
17224       ast_cli(fd, "  * Name       : %s\n", peer->name);
17225       if (realtimepeers) { /* Realtime is enabled */
17226          ast_cli(fd, "  Realtime peer: %s\n", peer->is_realtime ? "Yes, cached" : "No");
17227       }
17228       ast_cli(fd, "  Secret       : %s\n", ast_strlen_zero(peer->secret)?"<Not set>":"<Set>");
17229       ast_cli(fd, "  MD5Secret    : %s\n", ast_strlen_zero(peer->md5secret)?"<Not set>":"<Set>");
17230       ast_cli(fd, "  Remote Secret: %s\n", ast_strlen_zero(peer->remotesecret)?"<Not set>":"<Set>");
17231       if (credentials) {
17232          struct sip_auth *auth;
17233 
17234          AST_LIST_TRAVERSE(&credentials->list, auth, node) {
17235             ast_cli(fd, "  Realm-auth   : Realm %-15.15s User %-10.20s %s\n",
17236                auth->realm,
17237                auth->username,
17238                !ast_strlen_zero(auth->secret)
17239                   ? "<Secret set>"
17240                   : (!ast_strlen_zero(auth->md5secret)
17241                      ? "<MD5secret set>" : "<Not set>"));
17242          }
17243          ao2_t_ref(credentials, -1, "Unref peer auth for show");
17244       }
17245       ast_cli(fd, "  Context      : %s\n", peer->context);
17246       ast_cli(fd, "  Subscr.Cont. : %s\n", S_OR(peer->subscribecontext, "<Not set>") );
17247       ast_cli(fd, "  Language     : %s\n", peer->language);
17248       if (!ast_strlen_zero(peer->accountcode))
17249          ast_cli(fd, "  Accountcode  : %s\n", peer->accountcode);
17250       ast_cli(fd, "  AMA flags    : %s\n", ast_cdr_flags2str(peer->amaflags));
17251       ast_cli(fd, "  Transfer mode: %s\n", transfermode2str(peer->allowtransfer));
17252       ast_cli(fd, "  CallingPres  : %s\n", ast_describe_caller_presentation(peer->callingpres));
17253       if (!ast_strlen_zero(peer->fromuser))
17254          ast_cli(fd, "  FromUser     : %s\n", peer->fromuser);
17255       if (!ast_strlen_zero(peer->fromdomain))
17256          ast_cli(fd, "  FromDomain   : %s Port %d\n", peer->fromdomain, (peer->fromdomainport) ? peer->fromdomainport : STANDARD_SIP_PORT);
17257       ast_cli(fd, "  Callgroup    : ");
17258       print_group(fd, peer->callgroup, 0);
17259       ast_cli(fd, "  Pickupgroup  : ");
17260       print_group(fd, peer->pickupgroup, 0);
17261       peer_mailboxes_to_str(&mailbox_str, peer);
17262       ast_cli(fd, "  MOH Suggest  : %s\n", peer->mohsuggest);
17263       ast_cli(fd, "  Mailbox      : %s\n", mailbox_str->str);
17264       ast_cli(fd, "  VM Extension : %s\n", peer->vmexten);
17265       ast_cli(fd, "  LastMsgsSent : %d/%d\n", (peer->lastmsgssent & 0x7fff0000) >> 16, peer->lastmsgssent & 0xffff);
17266       ast_cli(fd, "  Call limit   : %d\n", peer->call_limit);
17267       ast_cli(fd, "  Max forwards : %d\n", peer->maxforwards);
17268       if (peer->busy_level)
17269          ast_cli(fd, "  Busy level   : %d\n", peer->busy_level);
17270       ast_cli(fd, "  Dynamic      : %s\n", AST_CLI_YESNO(peer->host_dynamic));
17271       ast_cli(fd, "  Callerid     : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, "<unspecified>"));
17272       ast_cli(fd, "  MaxCallBR    : %d kbps\n", peer->maxcallbitrate);
17273       ast_cli(fd, "  Expire       : %ld\n", ast_sched_when(sched, peer->expire));
17274       ast_cli(fd, "  Insecure     : %s\n", insecure2str(ast_test_flag(&peer->flags[0], SIP_INSECURE)));
17275       ast_cli(fd, "  Force rport  : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[0], SIP_NAT_FORCE_RPORT)));
17276       ast_cli(fd, "  ACL          : %s\n", AST_CLI_YESNO(peer->ha != NULL));
17277       ast_cli(fd, "  DirectMedACL : %s\n", AST_CLI_YESNO(peer->directmediaha != NULL));
17278       ast_cli(fd, "  T.38 support : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)));
17279       ast_cli(fd, "  T.38 EC mode : %s\n", faxec2str(ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)));
17280       ast_cli(fd, "  T.38 MaxDtgrm: %d\n", peer->t38_maxdatagram);
17281       ast_cli(fd, "  DirectMedia  : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[0], SIP_DIRECT_MEDIA)));
17282       ast_cli(fd, "  PromiscRedir : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[0], SIP_PROMISCREDIR)));
17283       ast_cli(fd, "  User=Phone   : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[0], SIP_USEREQPHONE)));
17284       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)));
17285       ast_cli(fd, "  Text Support : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[1], SIP_PAGE2_TEXTSUPPORT)));
17286       ast_cli(fd, "  Ign SDP ver  : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[1], SIP_PAGE2_IGNORESDPVERSION)));
17287       ast_cli(fd, "  Trust RPID   : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[0], SIP_TRUSTRPID)));
17288       ast_cli(fd, "  Send RPID    : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[0], SIP_SENDRPID)));
17289       ast_cli(fd, "  Subscriptions: %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)));
17290       ast_cli(fd, "  Overlap dial : %s\n", allowoverlap2str(ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWOVERLAP)));
17291       if (peer->outboundproxy)
17292          ast_cli(fd, "  Outb. proxy  : %s %s\n", ast_strlen_zero(peer->outboundproxy->name) ? "<not set>" : peer->outboundproxy->name,
17293                      peer->outboundproxy->force ? "(forced)" : "");
17294 
17295       /* - is enumerated */
17296       ast_cli(fd, "  DTMFmode     : %s\n", dtmfmode2str(ast_test_flag(&peer->flags[0], SIP_DTMF)));
17297       ast_cli(fd, "  Timer T1     : %d\n", peer->timer_t1);
17298       ast_cli(fd, "  Timer B      : %d\n", peer->timer_b);
17299       ast_cli(fd, "  ToHost       : %s\n", peer->tohost);
17300       ast_cli(fd, "  Addr->IP     : %s\n", ast_sockaddr_stringify(&peer->addr));
17301       ast_cli(fd, "  Defaddr->IP  : %s\n", ast_sockaddr_stringify(&peer->defaddr));
17302       ast_cli(fd, "  Prim.Transp. : %s\n", get_transport(peer->socket.type));
17303       ast_cli(fd, "  Allowed.Trsp : %s\n", get_transport_list(peer->transports));
17304       if (!ast_strlen_zero(sip_cfg.regcontext))
17305          ast_cli(fd, "  Reg. exten   : %s\n", peer->regexten);
17306       ast_cli(fd, "  Def. Username: %s\n", peer->username);
17307       ast_cli(fd, "  SIP Options  : ");
17308       if (peer->sipoptions) {
17309          int lastoption = -1;
17310          for (x = 0 ; x < ARRAY_LEN(sip_options); x++) {
17311             if (sip_options[x].id != lastoption) {
17312                if (peer->sipoptions & sip_options[x].id)
17313                   ast_cli(fd, "%s ", sip_options[x].text);
17314                lastoption = x;
17315             }
17316          }
17317       } else
17318          ast_cli(fd, "(none)");
17319 
17320       ast_cli(fd, "\n");
17321       ast_cli(fd, "  Codecs       : ");
17322       ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
17323       ast_cli(fd, "%s\n", codec_buf);
17324       ast_cli(fd, "  Codec Order  : (");
17325       print_codec_to_cli(fd, &peer->prefs);
17326       ast_cli(fd, ")\n");
17327 
17328       ast_cli(fd, "  Auto-Framing :  %s \n", AST_CLI_YESNO(peer->autoframing));
17329       ast_cli(fd, "  Status       : ");
17330       peer_status(peer, status, sizeof(status));
17331       ast_cli(fd, "%s\n", status);
17332       ast_cli(fd, "  Useragent    : %s\n", peer->useragent);
17333       ast_cli(fd, "  Reg. Contact : %s\n", peer->fullcontact);
17334       ast_cli(fd, "  Qualify Freq : %d ms\n", peer->qualifyfreq);
17335       if (peer->chanvars) {
17336          ast_cli(fd, "  Variables    :\n");
17337          for (v = peer->chanvars ; v ; v = v->next)
17338             ast_cli(fd, "                 %s = %s\n", v->name, v->value);
17339       }
17340 
17341       ast_cli(fd, "  Sess-Timers  : %s\n", stmode2str(peer->stimer.st_mode_oper));
17342       ast_cli(fd, "  Sess-Refresh : %s\n", strefresher2str(peer->stimer.st_ref));
17343       ast_cli(fd, "  Sess-Expires : %d secs\n", peer->stimer.st_max_se);
17344       ast_cli(fd, "  Min-Sess     : %d secs\n", peer->stimer.st_min_se);
17345       ast_cli(fd, "  RTP Engine   : %s\n", peer->engine);
17346       ast_cli(fd, "  Parkinglot   : %s\n", peer->parkinglot);
17347       ast_cli(fd, "  Use Reason   : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[1], SIP_PAGE2_Q850_REASON)));
17348       ast_cli(fd, "  Encryption   : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[1], SIP_PAGE2_USE_SRTP)));
17349       ast_cli(fd, "\n");
17350       peer = unref_peer(peer, "sip_show_peer: unref_peer: done with peer ptr");
17351    } else  if (peer && type == 1) { /* manager listing */
17352       char buffer[256];
17353       struct ast_str *mailbox_str = ast_str_alloca(512);
17354       astman_append(s, "Channeltype: SIP\r\n");
17355       astman_append(s, "ObjectName: %s\r\n", peer->name);
17356       astman_append(s, "ChanObjectType: peer\r\n");
17357       astman_append(s, "SecretExist: %s\r\n", ast_strlen_zero(peer->secret)?"N":"Y");
17358       astman_append(s, "RemoteSecretExist: %s\r\n", ast_strlen_zero(peer->remotesecret)?"N":"Y");
17359       astman_append(s, "MD5SecretExist: %s\r\n", ast_strlen_zero(peer->md5secret)?"N":"Y");
17360       astman_append(s, "Context: %s\r\n", peer->context);
17361       astman_append(s, "Language: %s\r\n", peer->language);
17362       if (!ast_strlen_zero(peer->accountcode))
17363          astman_append(s, "Accountcode: %s\r\n", peer->accountcode);
17364       astman_append(s, "AMAflags: %s\r\n", ast_cdr_flags2str(peer->amaflags));
17365       astman_append(s, "CID-CallingPres: %s\r\n", ast_describe_caller_presentation(peer->callingpres));
17366       if (!ast_strlen_zero(peer->fromuser))
17367          astman_append(s, "SIP-FromUser: %s\r\n", peer->fromuser);
17368       if (!ast_strlen_zero(peer->fromdomain))
17369          astman_append(s, "SIP-FromDomain: %s\r\nSip-FromDomain-Port: %d\r\n", peer->fromdomain, (peer->fromdomainport) ? peer->fromdomainport : STANDARD_SIP_PORT);
17370       astman_append(s, "Callgroup: ");
17371       astman_append(s, "%s\r\n", ast_print_group(buffer, sizeof(buffer), peer->callgroup));
17372       astman_append(s, "Pickupgroup: ");
17373       astman_append(s, "%s\r\n", ast_print_group(buffer, sizeof(buffer), peer->pickupgroup));
17374       astman_append(s, "MOHSuggest: %s\r\n", peer->mohsuggest);
17375       peer_mailboxes_to_str(&mailbox_str, peer);
17376       astman_append(s, "VoiceMailbox: %s\r\n", mailbox_str->str);
17377       astman_append(s, "TransferMode: %s\r\n", transfermode2str(peer->allowtransfer));
17378       astman_append(s, "LastMsgsSent: %d\r\n", peer->lastmsgssent);
17379       astman_append(s, "Maxforwards: %d\r\n", peer->maxforwards);
17380       astman_append(s, "Call-limit: %d\r\n", peer->call_limit);
17381       astman_append(s, "Busy-level: %d\r\n", peer->busy_level);
17382       astman_append(s, "MaxCallBR: %d kbps\r\n", peer->maxcallbitrate);
17383       astman_append(s, "Dynamic: %s\r\n", peer->host_dynamic?"Y":"N");
17384       astman_append(s, "Callerid: %s\r\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, ""));
17385       astman_append(s, "RegExpire: %ld seconds\r\n", ast_sched_when(sched, peer->expire));
17386       astman_append(s, "SIP-AuthInsecure: %s\r\n", insecure2str(ast_test_flag(&peer->flags[0], SIP_INSECURE)));
17387       astman_append(s, "SIP-Forcerport: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_NAT_FORCE_RPORT)?"Y":"N"));
17388       astman_append(s, "ACL: %s\r\n", (peer->ha?"Y":"N"));
17389       astman_append(s, "SIP-CanReinvite: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_DIRECT_MEDIA)?"Y":"N"));
17390       astman_append(s, "SIP-DirectMedia: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_DIRECT_MEDIA)?"Y":"N"));
17391       astman_append(s, "SIP-PromiscRedir: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_PROMISCREDIR)?"Y":"N"));
17392       astman_append(s, "SIP-UserPhone: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_USEREQPHONE)?"Y":"N"));
17393       astman_append(s, "SIP-VideoSupport: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_VIDEOSUPPORT)?"Y":"N"));
17394       astman_append(s, "SIP-TextSupport: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_TEXTSUPPORT)?"Y":"N"));
17395       astman_append(s, "SIP-T.38Support: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)?"Y":"N"));
17396       astman_append(s, "SIP-T.38EC: %s\r\n", faxec2str(ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)));
17397       astman_append(s, "SIP-T.38MaxDtgrm: %d\r\n", peer->t38_maxdatagram);
17398       astman_append(s, "SIP-Sess-Timers: %s\r\n", stmode2str(peer->stimer.st_mode_oper));
17399       astman_append(s, "SIP-Sess-Refresh: %s\r\n", strefresher2str(peer->stimer.st_ref));
17400       astman_append(s, "SIP-Sess-Expires: %d\r\n", peer->stimer.st_max_se);
17401       astman_append(s, "SIP-Sess-Min: %d\r\n", peer->stimer.st_min_se);
17402       astman_append(s, "SIP-RTP-Engine: %s\r\n", peer->engine);
17403       astman_append(s, "SIP-Encryption: %s\r\n", ast_test_flag(&peer->flags[1], SIP_PAGE2_USE_SRTP) ? "Y" : "N");
17404 
17405       /* - is enumerated */
17406       astman_append(s, "SIP-DTMFmode: %s\r\n", dtmfmode2str(ast_test_flag(&peer->flags[0], SIP_DTMF)));
17407       astman_append(s, "ToHost: %s\r\n", peer->tohost);
17408       astman_append(s, "Address-IP: %s\r\nAddress-Port: %d\r\n", ast_sockaddr_stringify_addr(&peer->addr), ast_sockaddr_port(&peer->addr));
17409       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));
17410       astman_append(s, "Default-Username: %s\r\n", peer->username);
17411       if (!ast_strlen_zero(sip_cfg.regcontext))
17412          astman_append(s, "RegExtension: %s\r\n", peer->regexten);
17413       astman_append(s, "Codecs: ");
17414       ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
17415       astman_append(s, "%s\r\n", codec_buf);
17416       astman_append(s, "CodecOrder: ");
17417       pref = &peer->prefs;
17418       for(x = 0; x < 64 ; x++) {
17419          codec = ast_codec_pref_index(pref, x);
17420          if (!codec)
17421             break;
17422          astman_append(s, "%s", ast_getformatname(codec));
17423          if (x < 63 && ast_codec_pref_index(pref, x+1))
17424             astman_append(s, ",");
17425       }
17426 
17427       astman_append(s, "\r\n");
17428       astman_append(s, "Status: ");
17429       peer_status(peer, status, sizeof(status));
17430       astman_append(s, "%s\r\n", status);
17431       astman_append(s, "SIP-Useragent: %s\r\n", peer->useragent);
17432       astman_append(s, "Reg-Contact: %s\r\n", peer->fullcontact);
17433       astman_append(s, "QualifyFreq: %d ms\r\n", peer->qualifyfreq);
17434       astman_append(s, "Parkinglot: %s\r\n", peer->parkinglot);
17435       if (peer->chanvars) {
17436          for (v = peer->chanvars ; v ; v = v->next) {
17437             astman_append(s, "ChanVariable: %s=%s\r\n", v->name, v->value);
17438          }
17439       }
17440       astman_append(s, "SIP-Use-Reason-Header: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_Q850_REASON)) ? "Y" : "N");
17441 
17442       peer = unref_peer(peer, "sip_show_peer: unref_peer: done with peer");
17443 
17444    } else {
17445       ast_cli(fd, "Peer %s not found.\n", argv[3]);
17446       ast_cli(fd, "\n");
17447    }
17448 
17449    return CLI_SUCCESS;
17450 }
17451 
17452 /*! \brief Do completion on user name */
17453 static char *complete_sip_user(const char *word, int state)
17454 {
17455    char *result = NULL;
17456    int wordlen = strlen(word);
17457    int which = 0;
17458    struct ao2_iterator user_iter;
17459    struct sip_peer *user;
17460 
17461    user_iter = ao2_iterator_init(peers, 0);
17462    while ((user = ao2_t_iterator_next(&user_iter, "iterate thru peers table"))) {
17463       ao2_lock(user);
17464       if (!(user->type & SIP_TYPE_USER)) {
17465          ao2_unlock(user);
17466          unref_peer(user, "complete sip user");
17467          continue;
17468       }
17469       /* locking of the object is not required because only the name and flags are being compared */
17470       if (!strncasecmp(word, user->name, wordlen) && ++which > state) {
17471          result = ast_strdup(user->name);
17472       }
17473       ao2_unlock(user);
17474       unref_peer(user, "complete sip user");
17475       if (result) {
17476          break;
17477       }
17478    }
17479    ao2_iterator_destroy(&user_iter);
17480    return result;
17481 }
17482 /*! \brief Support routine for 'sip show user' CLI */
17483 static char *complete_sip_show_user(const char *line, const char *word, int pos, int state)
17484 {
17485    if (pos == 3)
17486       return complete_sip_user(word, state);
17487 
17488    return NULL;
17489 }
17490 
17491 /*! \brief Show one user in detail */
17492 static char *sip_show_user(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
17493 {
17494    char cbuf[256];
17495    struct sip_peer *user;
17496    struct ast_variable *v;
17497    int load_realtime;
17498 
17499    switch (cmd) {
17500    case CLI_INIT:
17501       e->command = "sip show user";
17502       e->usage =
17503          "Usage: sip show user <name> [load]\n"
17504          "       Shows all details on one SIP user and the current status.\n"
17505          "       Option \"load\" forces lookup of peer in realtime storage.\n";
17506       return NULL;
17507    case CLI_GENERATE:
17508       return complete_sip_show_user(a->line, a->word, a->pos, a->n);
17509    }
17510 
17511    if (a->argc < 4)
17512       return CLI_SHOWUSAGE;
17513 
17514    /* Load from realtime storage? */
17515    load_realtime = (a->argc == 5 && !strcmp(a->argv[4], "load")) ? TRUE : FALSE;
17516 
17517    if ((user = find_peer(a->argv[3], NULL, load_realtime, FINDUSERS, FALSE, 0))) {
17518       ao2_lock(user);
17519       ast_cli(a->fd, "\n\n");
17520       ast_cli(a->fd, "  * Name       : %s\n", user->name);
17521       ast_cli(a->fd, "  Secret       : %s\n", ast_strlen_zero(user->secret)?"<Not set>":"<Set>");
17522       ast_cli(a->fd, "  MD5Secret    : %s\n", ast_strlen_zero(user->md5secret)?"<Not set>":"<Set>");
17523       ast_cli(a->fd, "  Context      : %s\n", user->context);
17524       ast_cli(a->fd, "  Language     : %s\n", user->language);
17525       if (!ast_strlen_zero(user->accountcode))
17526          ast_cli(a->fd, "  Accountcode  : %s\n", user->accountcode);
17527       ast_cli(a->fd, "  AMA flags    : %s\n", ast_cdr_flags2str(user->amaflags));
17528       ast_cli(a->fd, "  Transfer mode: %s\n", transfermode2str(user->allowtransfer));
17529       ast_cli(a->fd, "  MaxCallBR    : %d kbps\n", user->maxcallbitrate);
17530       ast_cli(a->fd, "  CallingPres  : %s\n", ast_describe_caller_presentation(user->callingpres));
17531       ast_cli(a->fd, "  Call limit   : %d\n", user->call_limit);
17532       ast_cli(a->fd, "  Callgroup    : ");
17533       print_group(a->fd, user->callgroup, 0);
17534       ast_cli(a->fd, "  Pickupgroup  : ");
17535       print_group(a->fd, user->pickupgroup, 0);
17536       ast_cli(a->fd, "  Callerid     : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), user->cid_name, user->cid_num, "<unspecified>"));
17537       ast_cli(a->fd, "  ACL          : %s\n", AST_CLI_YESNO(user->ha != NULL));
17538       ast_cli(a->fd, "  Sess-Timers  : %s\n", stmode2str(user->stimer.st_mode_oper));
17539       ast_cli(a->fd, "  Sess-Refresh : %s\n", strefresher2str(user->stimer.st_ref));
17540       ast_cli(a->fd, "  Sess-Expires : %d secs\n", user->stimer.st_max_se);
17541       ast_cli(a->fd, "  Sess-Min-SE  : %d secs\n", user->stimer.st_min_se);
17542       ast_cli(a->fd, "  RTP Engine   : %s\n", user->engine);
17543 
17544       ast_cli(a->fd, "  Codec Order  : (");
17545       print_codec_to_cli(a->fd, &user->prefs);
17546       ast_cli(a->fd, ")\n");
17547 
17548       ast_cli(a->fd, "  Auto-Framing:  %s \n", AST_CLI_YESNO(user->autoframing));
17549       if (user->chanvars) {
17550          ast_cli(a->fd, "  Variables    :\n");
17551          for (v = user->chanvars ; v ; v = v->next)
17552             ast_cli(a->fd, "                 %s = %s\n", v->name, v->value);
17553       }
17554 
17555       ast_cli(a->fd, "\n");
17556 
17557       ao2_unlock(user);
17558       unref_peer(user, "sip show user");
17559    } else {
17560       ast_cli(a->fd, "User %s not found.\n", a->argv[3]);
17561       ast_cli(a->fd, "\n");
17562    }
17563 
17564    return CLI_SUCCESS;
17565 }
17566 
17567 
17568 static char *sip_show_sched(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
17569 {
17570    struct ast_str *cbuf;
17571    struct ast_cb_names cbnames = {9, { "retrans_pkt",
17572                                         "__sip_autodestruct",
17573                                         "expire_register",
17574                                         "auto_congest",
17575                                         "sip_reg_timeout",
17576                                         "sip_poke_peer_s",
17577                                         "sip_poke_noanswer",
17578                                         "sip_reregister",
17579                                         "sip_reinvite_retry"},
17580                            { retrans_pkt,
17581                                      __sip_autodestruct,
17582                                      expire_register,
17583                                      auto_congest,
17584                                      sip_reg_timeout,
17585                                      sip_poke_peer_s,
17586                                      sip_poke_noanswer,
17587                                      sip_reregister,
17588                                      sip_reinvite_retry}};
17589    
17590    switch (cmd) {
17591    case CLI_INIT:
17592       e->command = "sip show sched";
17593       e->usage =
17594          "Usage: sip show sched\n"
17595          "       Shows stats on what's in the sched queue at the moment\n";
17596       return NULL;
17597    case CLI_GENERATE:
17598       return NULL;
17599    }
17600 
17601    cbuf = ast_str_alloca(2048);
17602 
17603    ast_cli(a->fd, "\n");
17604    ast_sched_report(sched, &cbuf, &cbnames);
17605    ast_cli(a->fd, "%s", cbuf->str);
17606 
17607    return CLI_SUCCESS;
17608 }
17609 
17610 /*! \brief  Show SIP Registry (registrations with other SIP proxies */
17611 static char *sip_show_registry(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
17612 {
17613 #define FORMAT2 "%-39.39s %-6.6s %-12.12s  %8.8s %-20.20s %-25.25s\n"
17614 #define FORMAT  "%-39.39s %-6.6s %-12.12s  %8d %-20.20s %-25.25s\n"
17615    char host[80];
17616    char user[80];
17617    char tmpdat[256];
17618    struct ast_tm tm;
17619    int counter = 0;
17620 
17621    switch (cmd) {
17622    case CLI_INIT:
17623       e->command = "sip show registry";
17624       e->usage =
17625          "Usage: sip show registry\n"
17626          "       Lists all registration requests and status.\n";
17627       return NULL;
17628    case CLI_GENERATE:
17629       return NULL;
17630    }
17631 
17632    if (a->argc != 3)
17633       return CLI_SHOWUSAGE;
17634    ast_cli(a->fd, FORMAT2, "Host", "dnsmgr", "Username", "Refresh", "State", "Reg.Time");
17635    
17636    ASTOBJ_CONTAINER_TRAVERSE(&regl, 1, do {
17637       ASTOBJ_RDLOCK(iterator);
17638       snprintf(host, sizeof(host), "%s:%d", iterator->hostname, iterator->portno ? iterator->portno : STANDARD_SIP_PORT);
17639       snprintf(user, sizeof(user), "%s", iterator->username);
17640       if (!ast_strlen_zero(iterator->regdomain)) {
17641          snprintf(tmpdat, sizeof(tmpdat), "%s", user);
17642          snprintf(user, sizeof(user), "%s@%s", tmpdat, iterator->regdomain);}
17643       if (iterator->regdomainport) {
17644          snprintf(tmpdat, sizeof(tmpdat), "%s", user);
17645          snprintf(user, sizeof(user), "%s:%d", tmpdat, iterator->regdomainport);}
17646       if (iterator->regtime.tv_sec) {
17647          ast_localtime(&iterator->regtime, &tm, NULL);
17648          ast_strftime(tmpdat, sizeof(tmpdat), "%a, %d %b %Y %T", &tm);
17649       } else
17650          tmpdat[0] = '\0';
17651       ast_cli(a->fd, FORMAT, host, (iterator->dnsmgr) ? "Y" : "N", user, iterator->refresh, regstate2str(iterator->regstate), tmpdat);
17652       ASTOBJ_UNLOCK(iterator);
17653       counter++;
17654    } while(0));
17655    ast_cli(a->fd, "%d SIP registrations.\n", counter);
17656    return CLI_SUCCESS;
17657 #undef FORMAT
17658 #undef FORMAT2
17659 }
17660 
17661 /*! \brief Unregister (force expiration) a SIP peer in the registry via CLI
17662    \note This function does not tell the SIP device what's going on,
17663    so use it with great care.
17664 */
17665 static char *sip_unregister(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
17666 {
17667    struct sip_peer *peer;
17668    int load_realtime = 0;
17669 
17670    switch (cmd) {
17671    case CLI_INIT:
17672       e->command = "sip unregister";
17673       e->usage =
17674          "Usage: sip unregister <peer>\n"
17675          "       Unregister (force expiration) a SIP peer from the registry\n";
17676       return NULL;
17677    case CLI_GENERATE:
17678       return complete_sip_unregister(a->line, a->word, a->pos, a->n);
17679    }
17680    
17681    if (a->argc != 3)
17682       return CLI_SHOWUSAGE;
17683    
17684    if ((peer = find_peer(a->argv[2], NULL, load_realtime, FINDPEERS, TRUE, 0))) {
17685       if (peer->expire > 0) {
17686          AST_SCHED_DEL_UNREF(sched, peer->expire,
17687             unref_peer(peer, "remove register expire ref"));
17688          expire_register(ref_peer(peer, "ref for expire_register"));
17689          ast_cli(a->fd, "Unregistered peer \'%s\'\n\n", a->argv[2]);
17690       } else {
17691          ast_cli(a->fd, "Peer %s not registered\n", a->argv[2]);
17692       }
17693       unref_peer(peer, "sip_unregister: unref_peer via sip_unregister: done with peer from find_peer call");
17694    } else {
17695       ast_cli(a->fd, "Peer unknown: \'%s\'. Not unregistered.\n", a->argv[2]);
17696    }
17697    
17698    return CLI_SUCCESS;
17699 }
17700 
17701 /*! \brief Callback for show_chanstats */
17702 static int show_chanstats_cb(void *__cur, void *__arg, int flags)
17703 {
17704 #define FORMAT2 "%-15.15s  %-11.11s  %-8.8s %-10.10s  %-10.10s (     %%) %-6.6s %-10.10s  %-10.10s (     %%) %-6.6s\n"
17705 #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"
17706    struct sip_pvt *cur = __cur;
17707    struct ast_rtp_instance_stats stats;
17708    char durbuf[10];
17709    int duration;
17710    int durh, durm, durs;
17711    struct ast_channel *c = cur->owner;
17712    struct __show_chan_arg *arg = __arg;
17713    int fd = arg->fd;
17714 
17715 
17716    if (cur->subscribed != NONE) /* Subscriptions */
17717       return 0;   /* don't care, we scan all channels */
17718 
17719    if (!cur->rtp) {
17720       if (sipdebug) {
17721          ast_cli(fd, "%-15.15s  %-11.11s (inv state: %s) -- %s\n",
17722             ast_sockaddr_stringify_addr(&cur->sa), cur->callid,
17723             invitestate2string[cur->invitestate].desc,
17724             "-- No RTP active");
17725       }
17726       return 0;   /* don't care, we scan all channels */
17727    }
17728 
17729    ast_rtp_instance_get_stats(cur->rtp, &stats, AST_RTP_INSTANCE_STAT_ALL);
17730 
17731    if (c && c->cdr && !ast_tvzero(c->cdr->start)) {
17732       duration = (int)(ast_tvdiff_ms(ast_tvnow(), c->cdr->start) / 1000);
17733       durh = duration / 3600;
17734       durm = (duration % 3600) / 60;
17735       durs = duration % 60;
17736       snprintf(durbuf, sizeof(durbuf), "%02d:%02d:%02d", durh, durm, durs);
17737    } else {
17738       durbuf[0] = '\0';
17739    }
17740 
17741    ast_cli(fd, FORMAT,
17742       ast_sockaddr_stringify_addr(&cur->sa),
17743       cur->callid,
17744       durbuf,
17745       stats.rxcount > (unsigned int) 100000 ? (unsigned int) (stats.rxcount)/(unsigned int) 1000 : stats.rxcount,
17746       stats.rxcount > (unsigned int) 100000 ? "K":" ",
17747       stats.rxploss,
17748       (stats.rxcount + stats.rxploss) > 0 ? (double) stats.rxploss / (stats.rxcount + stats.rxploss) * 100 : 0,
17749       stats.rxjitter,
17750       stats.txcount > (unsigned int) 100000 ? (unsigned int) (stats.txcount)/(unsigned int) 1000 : stats.txcount,
17751       stats.txcount > (unsigned int) 100000 ? "K":" ",
17752       stats.txploss,
17753       stats.txcount > 0 ? (double) stats.txploss / stats.txcount * 100 : 0,
17754       stats.txjitter
17755    );
17756    arg->numchans++;
17757 
17758    return 0;   /* don't care, we scan all channels */
17759 }
17760 
17761 /*! \brief SIP show channelstats CLI (main function) */
17762 static char *sip_show_channelstats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
17763 {
17764    struct __show_chan_arg arg = { .fd = a->fd, .numchans = 0 };
17765 
17766    switch (cmd) {
17767    case CLI_INIT:
17768       e->command = "sip show channelstats";
17769       e->usage =
17770          "Usage: sip show channelstats\n"
17771          "       Lists all currently active SIP channel's RTCP statistics.\n"
17772          "       Note that calls in the much optimized RTP P2P bridge mode will not show any packets here.";
17773       return NULL;
17774    case CLI_GENERATE:
17775       return NULL;
17776    }
17777 
17778    if (a->argc != 3)
17779       return CLI_SHOWUSAGE;
17780 
17781    ast_cli(a->fd, FORMAT2, "Peer", "Call ID", "Duration", "Recv: Pack", "Lost", "Jitter", "Send: Pack", "Lost", "Jitter");
17782    /* iterate on the container and invoke the callback on each item */
17783    ao2_t_callback(dialogs, OBJ_NODATA, show_chanstats_cb, &arg, "callback to sip show chanstats");
17784    ast_cli(a->fd, "%d active SIP channel%s\n", arg.numchans, (arg.numchans != 1) ? "s" : "");
17785    return CLI_SUCCESS;
17786 }
17787 #undef FORMAT
17788 #undef FORMAT2
17789 
17790 /*! \brief List global settings for the SIP channel */
17791 static char *sip_show_settings(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
17792 {
17793    int realtimepeers;
17794    int realtimeregs;
17795    char codec_buf[SIPBUFSIZE];
17796    const char *msg;  /* temporary msg pointer */
17797    struct sip_auth_container *credentials;
17798 
17799    switch (cmd) {
17800    case CLI_INIT:
17801       e->command = "sip show settings";
17802       e->usage =
17803          "Usage: sip show settings\n"
17804          "       Provides detailed list of the configuration of the SIP channel.\n";
17805       return NULL;
17806    case CLI_GENERATE:
17807       return NULL;
17808    }
17809 
17810    if (a->argc != 3)
17811       return CLI_SHOWUSAGE;
17812 
17813    realtimepeers = ast_check_realtime("sippeers");
17814    realtimeregs = ast_check_realtime("sipregs");
17815 
17816    ast_mutex_lock(&authl_lock);
17817    credentials = authl;
17818    if (credentials) {
17819       ao2_t_ref(credentials, +1, "Ref global auth for show");
17820    }
17821    ast_mutex_unlock(&authl_lock);
17822 
17823    ast_cli(a->fd, "\n\nGlobal Settings:\n");
17824    ast_cli(a->fd, "----------------\n");
17825    ast_cli(a->fd, "  UDP Bindaddress:        %s\n", ast_sockaddr_stringify(&bindaddr));
17826    if (ast_sockaddr_is_ipv6(&bindaddr) && ast_sockaddr_is_any(&bindaddr)) {
17827       ast_cli(a->fd, "  ** Additional Info:\n");
17828       ast_cli(a->fd, "     [::] may include IPv4 in addition to IPv6, if such a feature is enabled in the OS.\n");
17829    }
17830    ast_cli(a->fd, "  TCP SIP Bindaddress:    %s\n",
17831       sip_cfg.tcp_enabled != FALSE ?
17832             ast_sockaddr_stringify(&sip_tcp_desc.local_address) :
17833             "Disabled");
17834    ast_cli(a->fd, "  TLS SIP Bindaddress:    %s\n",
17835       default_tls_cfg.enabled != FALSE ?
17836             ast_sockaddr_stringify(&sip_tls_desc.local_address) :
17837             "Disabled");
17838    ast_cli(a->fd, "  Videosupport:           %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_VIDEOSUPPORT)));
17839    ast_cli(a->fd, "  Textsupport:            %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_TEXTSUPPORT)));
17840    ast_cli(a->fd, "  Ignore SDP sess. ver.:  %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_IGNORESDPVERSION)));
17841    ast_cli(a->fd, "  AutoCreate Peer:        %s\n", AST_CLI_YESNO(sip_cfg.autocreatepeer));
17842    ast_cli(a->fd, "  Match Auth Username:    %s\n", AST_CLI_YESNO(global_match_auth_username));
17843    ast_cli(a->fd, "  Allow unknown access:   %s\n", AST_CLI_YESNO(sip_cfg.allowguest));
17844    ast_cli(a->fd, "  Allow subscriptions:    %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)));
17845    ast_cli(a->fd, "  Allow overlap dialing:  %s\n", allowoverlap2str(ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP)));
17846    ast_cli(a->fd, "  Allow promisc. redir:   %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[0], SIP_PROMISCREDIR)));
17847    ast_cli(a->fd, "  Enable call counters:   %s\n", AST_CLI_YESNO(global_callcounter));
17848    ast_cli(a->fd, "  SIP domain support:     %s\n", AST_CLI_YESNO(!AST_LIST_EMPTY(&domain_list)));
17849    ast_cli(a->fd, "  Realm. auth:            %s\n", AST_CLI_YESNO(credentials != NULL));
17850    if (credentials) {
17851       struct sip_auth *auth;
17852 
17853       AST_LIST_TRAVERSE(&credentials->list, auth, node) {
17854          ast_cli(a->fd, "  Realm. auth entry:      Realm %-15.15s User %-10.20s %s\n",
17855             auth->realm,
17856             auth->username,
17857             !ast_strlen_zero(auth->secret)
17858                ? "<Secret set>"
17859                : (!ast_strlen_zero(auth->md5secret)
17860                   ? "<MD5secret set>" : "<Not set>"));
17861       }
17862       ao2_t_ref(credentials, -1, "Unref global auth for show");
17863    }
17864    ast_cli(a->fd, "  Our auth realm          %s\n", sip_cfg.realm);
17865    ast_cli(a->fd, "  Use domains as realms:  %s\n", AST_CLI_YESNO(sip_cfg.domainsasrealm));
17866    ast_cli(a->fd, "  Call to non-local dom.: %s\n", AST_CLI_YESNO(sip_cfg.allow_external_domains));
17867    ast_cli(a->fd, "  URI user is phone no:   %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[0], SIP_USEREQPHONE)));
17868    ast_cli(a->fd, "  Always auth rejects:    %s\n", AST_CLI_YESNO(sip_cfg.alwaysauthreject));
17869    ast_cli(a->fd, "  Direct RTP setup:       %s\n", AST_CLI_YESNO(sip_cfg.directrtpsetup));
17870    ast_cli(a->fd, "  User Agent:             %s\n", global_useragent);
17871    ast_cli(a->fd, "  SDP Session Name:       %s\n", ast_strlen_zero(global_sdpsession) ? "-" : global_sdpsession);
17872    ast_cli(a->fd, "  SDP Owner Name:         %s\n", ast_strlen_zero(global_sdpowner) ? "-" : global_sdpowner);
17873    ast_cli(a->fd, "  Reg. context:           %s\n", S_OR(sip_cfg.regcontext, "(not set)"));
17874    ast_cli(a->fd, "  Regexten on Qualify:    %s\n", AST_CLI_YESNO(sip_cfg.regextenonqualify));
17875    ast_cli(a->fd, "  Legacy userfield parse: %s\n", AST_CLI_YESNO(sip_cfg.legacy_useroption_parsing));
17876    ast_cli(a->fd, "  Caller ID:              %s\n", default_callerid);
17877    if ((default_fromdomainport) && (default_fromdomainport != STANDARD_SIP_PORT)) {
17878       ast_cli(a->fd, "  From: Domain:           %s:%d\n", default_fromdomain, default_fromdomainport);
17879    } else {
17880       ast_cli(a->fd, "  From: Domain:           %s\n", default_fromdomain);
17881    }
17882    ast_cli(a->fd, "  Record SIP history:     %s\n", AST_CLI_ONOFF(recordhistory));
17883    ast_cli(a->fd, "  Call Events:            %s\n", AST_CLI_ONOFF(sip_cfg.callevents));
17884    ast_cli(a->fd, "  Auth. Failure Events:   %s\n", AST_CLI_ONOFF(global_authfailureevents));
17885 
17886    ast_cli(a->fd, "  T.38 support:           %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_T38SUPPORT)));
17887    ast_cli(a->fd, "  T.38 EC mode:           %s\n", faxec2str(ast_test_flag(&global_flags[1], SIP_PAGE2_T38SUPPORT)));
17888    ast_cli(a->fd, "  T.38 MaxDtgrm:          %d\n", global_t38_maxdatagram);
17889    if (!realtimepeers && !realtimeregs)
17890       ast_cli(a->fd, "  SIP realtime:           Disabled\n" );
17891    else
17892       ast_cli(a->fd, "  SIP realtime:           Enabled\n" );
17893    ast_cli(a->fd, "  Qualify Freq :          %d ms\n", global_qualifyfreq);
17894    ast_cli(a->fd, "  Q.850 Reason header:    %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_Q850_REASON)));
17895    ast_cli(a->fd, "  Store SIP_CAUSE:        %s\n", AST_CLI_YESNO(global_store_sip_cause));
17896    ast_cli(a->fd, "\nNetwork QoS Settings:\n");
17897    ast_cli(a->fd, "---------------------------\n");
17898    ast_cli(a->fd, "  IP ToS SIP:             %s\n", ast_tos2str(global_tos_sip));
17899    ast_cli(a->fd, "  IP ToS RTP audio:       %s\n", ast_tos2str(global_tos_audio));
17900    ast_cli(a->fd, "  IP ToS RTP video:       %s\n", ast_tos2str(global_tos_video));
17901    ast_cli(a->fd, "  IP ToS RTP text:        %s\n", ast_tos2str(global_tos_text));
17902    ast_cli(a->fd, "  802.1p CoS SIP:         %d\n", global_cos_sip);
17903    ast_cli(a->fd, "  802.1p CoS RTP audio:   %d\n", global_cos_audio);
17904    ast_cli(a->fd, "  802.1p CoS RTP video:   %d\n", global_cos_video);
17905    ast_cli(a->fd, "  802.1p CoS RTP text:    %d\n", global_cos_text);
17906    ast_cli(a->fd, "  Jitterbuffer enabled:   %s\n", AST_CLI_YESNO(ast_test_flag(&global_jbconf, AST_JB_ENABLED)));
17907    if (ast_test_flag(&global_jbconf, AST_JB_ENABLED)) {
17908       ast_cli(a->fd, "  Jitterbuffer forced:    %s\n", AST_CLI_YESNO(ast_test_flag(&global_jbconf, AST_JB_FORCED)));
17909       ast_cli(a->fd, "  Jitterbuffer max size:  %ld\n", global_jbconf.max_size);
17910       ast_cli(a->fd, "  Jitterbuffer resync:    %ld\n", global_jbconf.resync_threshold);
17911       ast_cli(a->fd, "  Jitterbuffer impl:      %s\n", global_jbconf.impl);
17912       if (!strcasecmp(global_jbconf.impl, "adaptive")) {
17913          ast_cli(a->fd, "  Jitterbuffer tgt extra: %ld\n", global_jbconf.target_extra);
17914       }
17915       ast_cli(a->fd, "  Jitterbuffer log:       %s\n", AST_CLI_YESNO(ast_test_flag(&global_jbconf, AST_JB_LOG)));
17916    }
17917 
17918    ast_cli(a->fd, "\nNetwork Settings:\n");
17919    ast_cli(a->fd, "---------------------------\n");
17920    /* determine if/how SIP address can be remapped */
17921    if (localaddr == NULL)
17922       msg = "Disabled, no localnet list";
17923    else if (ast_sockaddr_isnull(&externaddr))
17924       msg = "Disabled";
17925    else if (!ast_strlen_zero(externhost))
17926       msg = "Enabled using externhost";
17927    else
17928       msg = "Enabled using externaddr";
17929    ast_cli(a->fd, "  SIP address remapping:  %s\n", msg);
17930    ast_cli(a->fd, "  Externhost:             %s\n", S_OR(externhost, "<none>"));
17931    ast_cli(a->fd, "  Externaddr:             %s\n", ast_sockaddr_stringify(&externaddr));
17932    ast_cli(a->fd, "  Externrefresh:          %d\n", externrefresh);
17933    {
17934       struct ast_ha *d;
17935       const char *prefix = "Localnet:";
17936 
17937       for (d = localaddr; d ; prefix = "", d = d->next) {
17938          const char *addr = ast_strdupa(ast_sockaddr_stringify_addr(&d->addr));
17939          const char *mask = ast_strdupa(ast_sockaddr_stringify_addr(&d->netmask));
17940          ast_cli(a->fd, "  %-24s%s/%s\n", prefix, addr, mask);
17941       }
17942    }
17943    ast_cli(a->fd, "\nGlobal Signalling Settings:\n");
17944    ast_cli(a->fd, "---------------------------\n");
17945    ast_cli(a->fd, "  Codecs:                 ");
17946    ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, sip_cfg.capability);
17947    ast_cli(a->fd, "%s\n", codec_buf);
17948    ast_cli(a->fd, "  Codec Order:            ");
17949    print_codec_to_cli(a->fd, &default_prefs);
17950    ast_cli(a->fd, "\n");
17951    ast_cli(a->fd, "  Relax DTMF:             %s\n", AST_CLI_YESNO(global_relaxdtmf));
17952    ast_cli(a->fd, "  RFC2833 Compensation:   %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_RFC2833_COMPENSATE)));
17953    ast_cli(a->fd, "  Symmetric RTP:          %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_SYMMETRICRTP)));
17954    ast_cli(a->fd, "  Compact SIP headers:    %s\n", AST_CLI_YESNO(sip_cfg.compactheaders));
17955    ast_cli(a->fd, "  RTP Keepalive:          %d %s\n", global_rtpkeepalive, global_rtpkeepalive ? "" : "(Disabled)" );
17956    ast_cli(a->fd, "  RTP Timeout:            %d %s\n", global_rtptimeout, global_rtptimeout ? "" : "(Disabled)" );
17957    ast_cli(a->fd, "  RTP Hold Timeout:       %d %s\n", global_rtpholdtimeout, global_rtpholdtimeout ? "" : "(Disabled)");
17958    ast_cli(a->fd, "  MWI NOTIFY mime type:   %s\n", default_notifymime);
17959    ast_cli(a->fd, "  DNS SRV lookup:         %s\n", AST_CLI_YESNO(sip_cfg.srvlookup));
17960    ast_cli(a->fd, "  Pedantic SIP support:   %s\n", AST_CLI_YESNO(sip_cfg.pedanticsipchecking));
17961    ast_cli(a->fd, "  Reg. min duration       %d secs\n", min_expiry);
17962    ast_cli(a->fd, "  Reg. max duration:      %d secs\n", max_expiry);
17963    ast_cli(a->fd, "  Reg. default duration:  %d secs\n", default_expiry);
17964    ast_cli(a->fd, "  Outbound reg. timeout:  %d secs\n", global_reg_timeout);
17965    ast_cli(a->fd, "  Outbound reg. attempts: %d\n", global_regattempts_max);
17966    ast_cli(a->fd, "  Notify ringing state:   %s\n", AST_CLI_YESNO(sip_cfg.notifyringing));
17967    if (sip_cfg.notifyringing) {
17968       ast_cli(a->fd, "    Include CID:          %s%s\n",
17969             AST_CLI_YESNO(sip_cfg.notifycid),
17970             sip_cfg.notifycid == IGNORE_CONTEXT ? " (Ignoring context)" : "");
17971    }
17972    ast_cli(a->fd, "  Notify hold state:      %s\n", AST_CLI_YESNO(sip_cfg.notifyhold));
17973    ast_cli(a->fd, "  SIP Transfer mode:      %s\n", transfermode2str(sip_cfg.allowtransfer));
17974    ast_cli(a->fd, "  Max Call Bitrate:       %d kbps\n", default_maxcallbitrate);
17975    ast_cli(a->fd, "  Auto-Framing:           %s\n", AST_CLI_YESNO(global_autoframing));
17976    ast_cli(a->fd, "  Outb. proxy:            %s %s\n", ast_strlen_zero(sip_cfg.outboundproxy.name) ? "<not set>" : sip_cfg.outboundproxy.name,
17977                      sip_cfg.outboundproxy.force ? "(forced)" : "");
17978    ast_cli(a->fd, "  Session Timers:         %s\n", stmode2str(global_st_mode));
17979    ast_cli(a->fd, "  Session Refresher:      %s\n", strefresher2str (global_st_refresher));
17980    ast_cli(a->fd, "  Session Expires:        %d secs\n", global_max_se);
17981    ast_cli(a->fd, "  Session Min-SE:         %d secs\n", global_min_se);
17982    ast_cli(a->fd, "  Timer T1:               %d\n", global_t1);
17983    ast_cli(a->fd, "  Timer T1 minimum:       %d\n", global_t1min);
17984    ast_cli(a->fd, "  Timer B:                %d\n", global_timer_b);
17985    ast_cli(a->fd, "  No premature media:     %s\n", AST_CLI_YESNO(global_prematuremediafilter));
17986    ast_cli(a->fd, "  Max forwards:           %d\n", sip_cfg.default_max_forwards);
17987 
17988    ast_cli(a->fd, "\nDefault Settings:\n");
17989    ast_cli(a->fd, "-----------------\n");
17990    ast_cli(a->fd, "  Allowed transports:     %s\n", get_transport_list(default_transports));
17991    ast_cli(a->fd, "  Outbound transport:    %s\n", get_transport(default_primary_transport));
17992    ast_cli(a->fd, "  Context:                %s\n", sip_cfg.default_context);
17993    ast_cli(a->fd, "  Force rport:            %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[0], SIP_NAT_FORCE_RPORT)));
17994    ast_cli(a->fd, "  DTMF:                   %s\n", dtmfmode2str(ast_test_flag(&global_flags[0], SIP_DTMF)));
17995    ast_cli(a->fd, "  Qualify:                %d\n", default_qualify);
17996    ast_cli(a->fd, "  Use ClientCode:         %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[0], SIP_USECLIENTCODE)));
17997    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)));
17998    ast_cli(a->fd, "  Language:               %s\n", default_language);
17999    ast_cli(a->fd, "  MOH Interpret:          %s\n", default_mohinterpret);
18000    ast_cli(a->fd, "  MOH Suggest:            %s\n", default_mohsuggest);
18001    ast_cli(a->fd, "  Voice Mail Extension:   %s\n", default_vmexten);
18002 
18003    
18004    if (realtimepeers || realtimeregs) {
18005       ast_cli(a->fd, "\nRealtime SIP Settings:\n");
18006       ast_cli(a->fd, "----------------------\n");
18007       ast_cli(a->fd, "  Realtime Peers:         %s\n", AST_CLI_YESNO(realtimepeers));
18008       ast_cli(a->fd, "  Realtime Regs:          %s\n", AST_CLI_YESNO(realtimeregs));
18009       ast_cli(a->fd, "  Cache Friends:          %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)));
18010       ast_cli(a->fd, "  Update:                 %s\n", AST_CLI_YESNO(sip_cfg.peer_rtupdate));
18011       ast_cli(a->fd, "  Ignore Reg. Expire:     %s\n", AST_CLI_YESNO(sip_cfg.ignore_regexpire));
18012       ast_cli(a->fd, "  Save sys. name:         %s\n", AST_CLI_YESNO(sip_cfg.rtsave_sysname));
18013       ast_cli(a->fd, "  Auto Clear:             %d (%s)\n", sip_cfg.rtautoclear, ast_test_flag(&global_flags[1], SIP_PAGE2_RTAUTOCLEAR) ? "Enabled" : "Disabled");
18014    }
18015    ast_cli(a->fd, "\n----\n");
18016    return CLI_SUCCESS;
18017 }
18018 
18019 static char *sip_show_mwi(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
18020 {
18021 #define FORMAT  "%-30.30s  %-12.12s  %-10.10s  %-10.10s\n"
18022    char host[80];
18023    
18024    switch (cmd) {
18025    case CLI_INIT:
18026       e->command = "sip show mwi";
18027       e->usage =
18028          "Usage: sip show mwi\n"
18029          "       Provides a list of MWI subscriptions and status.\n";
18030       return NULL;
18031    case CLI_GENERATE:
18032       return NULL;
18033    }
18034    
18035    ast_cli(a->fd, FORMAT, "Host", "Username", "Mailbox", "Subscribed");
18036    
18037    ASTOBJ_CONTAINER_TRAVERSE(&submwil, 1, do {
18038       ASTOBJ_RDLOCK(iterator);
18039       snprintf(host, sizeof(host), "%s:%d", iterator->hostname, iterator->portno ? iterator->portno : STANDARD_SIP_PORT);
18040       ast_cli(a->fd, FORMAT, host, iterator->username, iterator->mailbox, AST_CLI_YESNO(iterator->subscribed));
18041       ASTOBJ_UNLOCK(iterator);
18042    } while(0));
18043 
18044    return CLI_SUCCESS;
18045 #undef FORMAT
18046 }
18047 
18048 
18049 /*! \brief Show subscription type in string format */
18050 static const char *subscription_type2str(enum subscriptiontype subtype)
18051 {
18052    int i;
18053 
18054    for (i = 1; i < ARRAY_LEN(subscription_types); i++) {
18055       if (subscription_types[i].type == subtype) {
18056          return subscription_types[i].text;
18057       }
18058    }
18059    return subscription_types[0].text;
18060 }
18061 
18062 /*! \brief Find subscription type in array */
18063 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype)
18064 {
18065    int i;
18066 
18067    for (i = 1; i < ARRAY_LEN(subscription_types); i++) {
18068       if (subscription_types[i].type == subtype) {
18069          return &subscription_types[i];
18070       }
18071    }
18072    return &subscription_types[0];
18073 }
18074 
18075 /*
18076  * We try to structure all functions that loop on data structures as
18077  * a handler for individual entries, and a mainloop that iterates
18078  * on the main data structure. This way, moving the code to containers
18079  * that support iteration through callbacks will be a lot easier.
18080  */
18081 
18082 #define FORMAT4 "%-15.15s  %-15.15s  %-15.15s  %-15.15s  %-13.13s  %-15.15s %-10.10s %-6.6d\n"
18083 #define FORMAT3 "%-15.15s  %-15.15s  %-15.15s  %-15.15s  %-13.13s  %-15.15s %-10.10s %-6.6s\n"
18084 #define FORMAT2 "%-15.15s  %-15.15s  %-15.15s  %-15.15s  %-7.7s  %-15.15s %-10.10s %-10.10s\n"
18085 #define FORMAT  "%-15.15s  %-15.15s  %-15.15s  %-15.15s  %-3.3s %-3.3s  %-15.15s %-10.10s %-10.10s\n"
18086 
18087 /*! \brief callback for show channel|subscription */
18088 static int show_channels_cb(void *__cur, void *__arg, int flags)
18089 {
18090    struct sip_pvt *cur = __cur;
18091    struct __show_chan_arg *arg = __arg;
18092    const struct ast_sockaddr *dst = sip_real_dst(cur);
18093    
18094    /* XXX indentation preserved to reduce diff. Will be fixed later */
18095    if (cur->subscribed == NONE && !arg->subscriptions) {
18096       /* set if SIP transfer in progress */
18097       const char *referstatus = cur->refer ? referstatus2str(cur->refer->status) : "";
18098       char formatbuf[SIPBUFSIZE/2];
18099       
18100       ast_cli(arg->fd, FORMAT, ast_sockaddr_stringify_addr(dst),
18101             S_OR(cur->username, S_OR(cur->cid_num, "(None)")),
18102             cur->callid,
18103             ast_getformatname_multiple(formatbuf, sizeof(formatbuf), cur->owner ? cur->owner->nativeformats : 0),
18104             AST_CLI_YESNO(ast_test_flag(&cur->flags[1], SIP_PAGE2_CALL_ONHOLD)),
18105             cur->needdestroy ? "(d)" : "",
18106             cur->lastmsg ,
18107             referstatus,
18108             cur->relatedpeer ? cur->relatedpeer->name : "<guest>"
18109          );
18110       arg->numchans++;
18111    }
18112    if (cur->subscribed != NONE && arg->subscriptions) {
18113       struct ast_str *mailbox_str = ast_str_alloca(512);
18114       if (cur->subscribed == MWI_NOTIFICATION && cur->relatedpeer)
18115          peer_mailboxes_to_str(&mailbox_str, cur->relatedpeer);
18116       ast_cli(arg->fd, FORMAT4, ast_sockaddr_stringify_addr(dst),
18117             S_OR(cur->username, S_OR(cur->cid_num, "(None)")),
18118                cur->callid,
18119             /* the 'complete' exten/context is hidden in the refer_to field for subscriptions */
18120             cur->subscribed == MWI_NOTIFICATION ? "--" : cur->subscribeuri,
18121             cur->subscribed == MWI_NOTIFICATION ? "<none>" : ast_extension_state2str(cur->laststate),
18122             subscription_type2str(cur->subscribed),
18123             cur->subscribed == MWI_NOTIFICATION ? S_OR(mailbox_str->str, "<none>") : "<none>",
18124             cur->expiry
18125          );
18126       arg->numchans++;
18127    }
18128    return 0;   /* don't care, we scan all channels */
18129 }
18130 
18131 /*! \brief CLI for show channels or subscriptions.
18132  * This is a new-style CLI handler so a single function contains
18133  * the prototype for the function, the 'generator' to produce multiple
18134  * entries in case it is required, and the actual handler for the command.
18135  */
18136 static char *sip_show_channels(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
18137 {
18138    struct __show_chan_arg arg = { .fd = a->fd, .numchans = 0 };
18139 
18140 
18141    if (cmd == CLI_INIT) {
18142       e->command = "sip show {channels|subscriptions}";
18143       e->usage =
18144          "Usage: sip show channels\n"
18145          "       Lists all currently active SIP calls (dialogs).\n"
18146          "Usage: sip show subscriptions\n"
18147          "       Lists active SIP subscriptions.\n";
18148       return NULL;
18149    } else if (cmd == CLI_GENERATE)
18150       return NULL;
18151 
18152    if (a->argc != e->args)
18153       return CLI_SHOWUSAGE;
18154    arg.subscriptions = !strcasecmp(a->argv[e->args - 1], "subscriptions");
18155    if (!arg.subscriptions)
18156       ast_cli(arg.fd, FORMAT2, "Peer", "User/ANR", "Call ID", "Format", "Hold", "Last Message", "Expiry", "Peer");
18157    else
18158       ast_cli(arg.fd, FORMAT3, "Peer", "User", "Call ID", "Extension", "Last state", "Type", "Mailbox", "Expiry");
18159 
18160    /* iterate on the container and invoke the callback on each item */
18161    ao2_t_callback(dialogs, OBJ_NODATA, show_channels_cb, &arg, "callback to show channels");
18162    
18163    /* print summary information */
18164    ast_cli(arg.fd, "%d active SIP %s%s\n", arg.numchans,
18165       (arg.subscriptions ? "subscription" : "dialog"),
18166       ESS(arg.numchans));  /* ESS(n) returns an "s" if n>1 */
18167    return CLI_SUCCESS;
18168 #undef FORMAT
18169 #undef FORMAT2
18170 #undef FORMAT3
18171 }
18172 
18173 /*! \brief Support routine for 'sip show channel' and 'sip show history' CLI
18174  * This is in charge of generating all strings that match a prefix in the
18175  * given position. As many functions of this kind, each invokation has
18176  * O(state) time complexity so be careful in using it.
18177  */
18178 static char *complete_sipch(const char *line, const char *word, int pos, int state)
18179 {
18180    int which=0;
18181    struct sip_pvt *cur;
18182    char *c = NULL;
18183    int wordlen = strlen(word);
18184    struct ao2_iterator i;
18185 
18186    if (pos != 3) {
18187       return NULL;
18188    }
18189 
18190    i = ao2_iterator_init(dialogs, 0);
18191    while ((cur = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
18192       sip_pvt_lock(cur);
18193       if (!strncasecmp(word, cur->callid, wordlen) && ++which > state) {
18194          c = ast_strdup(cur->callid);
18195          sip_pvt_unlock(cur);
18196          dialog_unref(cur, "drop ref in iterator loop break");
18197          break;
18198       }
18199       sip_pvt_unlock(cur);
18200       dialog_unref(cur, "drop ref in iterator loop");
18201    }
18202    ao2_iterator_destroy(&i);
18203    return c;
18204 }
18205 
18206 
18207 /*! \brief Do completion on peer name */
18208 static char *complete_sip_peer(const char *word, int state, int flags2)
18209 {
18210    char *result = NULL;
18211    int wordlen = strlen(word);
18212    int which = 0;
18213    struct ao2_iterator i = ao2_iterator_init(peers, 0);
18214    struct sip_peer *peer;
18215 
18216    while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
18217       /* locking of the object is not required because only the name and flags are being compared */
18218       if (!strncasecmp(word, peer->name, wordlen) &&
18219             (!flags2 || ast_test_flag(&peer->flags[1], flags2)) &&
18220             ++which > state)
18221          result = ast_strdup(peer->name);
18222       unref_peer(peer, "toss iterator peer ptr before break");
18223       if (result) {
18224          break;
18225       }
18226    }
18227    ao2_iterator_destroy(&i);
18228    return result;
18229 }
18230 
18231 /*! \brief Do completion on registered peer name */
18232 static char *complete_sip_registered_peer(const char *word, int state, int flags2)
18233 {
18234        char *result = NULL;
18235        int wordlen = strlen(word);
18236        int which = 0;
18237        struct ao2_iterator i;
18238        struct sip_peer *peer;
18239        
18240        i = ao2_iterator_init(peers, 0);
18241        while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
18242           if (!strncasecmp(word, peer->name, wordlen) &&
18243          (!flags2 || ast_test_flag(&peer->flags[1], flags2)) &&
18244          ++which > state && peer->expire > 0)
18245              result = ast_strdup(peer->name);
18246           if (result) {
18247              unref_peer(peer, "toss iterator peer ptr before break");
18248              break;
18249           }
18250           unref_peer(peer, "toss iterator peer ptr");
18251        }
18252        ao2_iterator_destroy(&i);
18253        return result;
18254 }
18255 
18256 /*! \brief Support routine for 'sip show history' CLI */
18257 static char *complete_sip_show_history(const char *line, const char *word, int pos, int state)
18258 {
18259    if (pos == 3)
18260       return complete_sipch(line, word, pos, state);
18261 
18262    return NULL;
18263 }
18264 
18265 /*! \brief Support routine for 'sip show peer' CLI */
18266 static char *complete_sip_show_peer(const char *line, const char *word, int pos, int state)
18267 {
18268    if (pos == 3) {
18269       return complete_sip_peer(word, state, 0);
18270    }
18271 
18272    return NULL;
18273 }
18274 
18275 /*! \brief Support routine for 'sip unregister' CLI */
18276 static char *complete_sip_unregister(const char *line, const char *word, int pos, int state)
18277 {
18278        if (pos == 2)
18279                return complete_sip_registered_peer(word, state, 0);
18280 
18281        return NULL;
18282 }
18283 
18284 /*! \brief Support routine for 'sip notify' CLI */
18285 static char *complete_sipnotify(const char *line, const char *word, int pos, int state)
18286 {
18287    char *c = NULL;
18288 
18289    if (pos == 2) {
18290       int which = 0;
18291       char *cat = NULL;
18292       int wordlen = strlen(word);
18293 
18294       /* do completion for notify type */
18295 
18296       if (!notify_types)
18297          return NULL;
18298       
18299       while ( (cat = ast_category_browse(notify_types, cat)) ) {
18300          if (!strncasecmp(word, cat, wordlen) && ++which > state) {
18301             c = ast_strdup(cat);
18302             break;
18303          }
18304       }
18305       return c;
18306    }
18307 
18308    if (pos > 2)
18309       return complete_sip_peer(word, state, 0);
18310 
18311    return NULL;
18312 }
18313 
18314 /*! \brief Show details of one active dialog */
18315 static char *sip_show_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
18316 {
18317    struct sip_pvt *cur;
18318    size_t len;
18319    int found = 0;
18320    struct ao2_iterator i;
18321 
18322    switch (cmd) {
18323    case CLI_INIT:
18324       e->command = "sip show channel";
18325       e->usage =
18326          "Usage: sip show channel <call-id>\n"
18327          "       Provides detailed status on a given SIP dialog (identified by SIP call-id).\n";
18328       return NULL;
18329    case CLI_GENERATE:
18330       return complete_sipch(a->line, a->word, a->pos, a->n);
18331    }
18332 
18333    if (a->argc != 4)
18334       return CLI_SHOWUSAGE;
18335    len = strlen(a->argv[3]);
18336    
18337    i = ao2_iterator_init(dialogs, 0);
18338    while ((cur = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
18339       sip_pvt_lock(cur);
18340 
18341       if (!strncasecmp(cur->callid, a->argv[3], len)) {
18342          char formatbuf[SIPBUFSIZE/2];
18343          ast_cli(a->fd, "\n");
18344          if (cur->subscribed != NONE)
18345             ast_cli(a->fd, "  * Subscription (type: %s)\n", subscription_type2str(cur->subscribed));
18346          else
18347             ast_cli(a->fd, "  * SIP Call\n");
18348          ast_cli(a->fd, "  Curr. trans. direction:  %s\n", ast_test_flag(&cur->flags[0], SIP_OUTGOING) ? "Outgoing" : "Incoming");
18349          ast_cli(a->fd, "  Call-ID:                %s\n", cur->callid);
18350          ast_cli(a->fd, "  Owner channel ID:       %s\n", cur->owner ? cur->owner->name : "<none>");
18351          ast_cli(a->fd, "  Our Codec Capability:   %s\n", ast_getformatname_multiple(formatbuf, sizeof(formatbuf), cur->capability));
18352          ast_cli(a->fd, "  Non-Codec Capability (DTMF):   %d\n", cur->noncodeccapability);
18353          ast_cli(a->fd, "  Their Codec Capability:   %s\n", ast_getformatname_multiple(formatbuf, sizeof(formatbuf), cur->peercapability));
18354          ast_cli(a->fd, "  Joint Codec Capability:   %s\n", ast_getformatname_multiple(formatbuf, sizeof(formatbuf), cur->jointcapability));
18355          ast_cli(a->fd, "  Format:                 %s\n", ast_getformatname_multiple(formatbuf, sizeof(formatbuf), cur->owner ? cur->owner->nativeformats : 0) );
18356          ast_cli(a->fd, "  T.38 support            %s\n", AST_CLI_YESNO(cur->udptl != NULL));
18357          ast_cli(a->fd, "  Video support           %s\n", AST_CLI_YESNO(cur->vrtp != NULL));
18358          ast_cli(a->fd, "  MaxCallBR:              %d kbps\n", cur->maxcallbitrate);
18359          ast_cli(a->fd, "  Theoretical Address:    %s\n", ast_sockaddr_stringify(&cur->sa));
18360          ast_cli(a->fd, "  Received Address:       %s\n", ast_sockaddr_stringify(&cur->recv));
18361          ast_cli(a->fd, "  SIP Transfer mode:      %s\n", transfermode2str(cur->allowtransfer));
18362          ast_cli(a->fd, "  Force rport:            %s\n", AST_CLI_YESNO(ast_test_flag(&cur->flags[0], SIP_NAT_FORCE_RPORT)));
18363          if (ast_sockaddr_isnull(&cur->redirip)) {
18364             ast_cli(a->fd,
18365                "  Audio IP:               %s (local)\n",
18366                ast_sockaddr_stringify_addr(&cur->ourip));
18367          } else {
18368             ast_cli(a->fd,
18369                "  Audio IP:               %s (Outside bridge)\n",
18370                ast_sockaddr_stringify_addr(&cur->redirip));
18371          }
18372          ast_cli(a->fd, "  Our Tag:                %s\n", cur->tag);
18373          ast_cli(a->fd, "  Their Tag:              %s\n", cur->theirtag);
18374          ast_cli(a->fd, "  SIP User agent:         %s\n", cur->useragent);
18375          if (!ast_strlen_zero(cur->username))
18376             ast_cli(a->fd, "  Username:               %s\n", cur->username);
18377          if (!ast_strlen_zero(cur->peername))
18378             ast_cli(a->fd, "  Peername:               %s\n", cur->peername);
18379          if (!ast_strlen_zero(cur->uri))
18380             ast_cli(a->fd, "  Original uri:           %s\n", cur->uri);
18381          if (!ast_strlen_zero(cur->cid_num))
18382             ast_cli(a->fd, "  Caller-ID:              %s\n", cur->cid_num);
18383          ast_cli(a->fd, "  Need Destroy:           %s\n", AST_CLI_YESNO(cur->needdestroy));
18384          ast_cli(a->fd, "  Last Message:           %s\n", cur->lastmsg);
18385          ast_cli(a->fd, "  Promiscuous Redir:      %s\n", AST_CLI_YESNO(ast_test_flag(&cur->flags[0], SIP_PROMISCREDIR)));
18386          ast_cli(a->fd, "  Route:                  %s\n", cur->route ? cur->route->hop : "N/A");
18387          ast_cli(a->fd, "  DTMF Mode:              %s\n", dtmfmode2str(ast_test_flag(&cur->flags[0], SIP_DTMF)));
18388          ast_cli(a->fd, "  SIP Options:            ");
18389          if (cur->sipoptions) {
18390             int x;
18391             for (x = 0 ; x < ARRAY_LEN(sip_options); x++) {
18392                if (cur->sipoptions & sip_options[x].id)
18393                   ast_cli(a->fd, "%s ", sip_options[x].text);
18394             }
18395             ast_cli(a->fd, "\n");
18396          } else
18397             ast_cli(a->fd, "(none)\n");
18398 
18399          if (!cur->stimer)
18400             ast_cli(a->fd, "  Session-Timer:          Uninitiallized\n");
18401          else {
18402             ast_cli(a->fd, "  Session-Timer:          %s\n", cur->stimer->st_active ? "Active" : "Inactive");
18403             if (cur->stimer->st_active == TRUE) {
18404                ast_cli(a->fd, "  S-Timer Interval:       %d\n", cur->stimer->st_interval);
18405                ast_cli(a->fd, "  S-Timer Refresher:      %s\n", strefresher2str(cur->stimer->st_ref));
18406                ast_cli(a->fd, "  S-Timer Expirys:        %d\n", cur->stimer->st_expirys);
18407                ast_cli(a->fd, "  S-Timer Sched Id:       %d\n", cur->stimer->st_schedid);
18408                ast_cli(a->fd, "  S-Timer Peer Sts:       %s\n", cur->stimer->st_active_peer_ua ? "Active" : "Inactive");
18409                ast_cli(a->fd, "  S-Timer Cached Min-SE:  %d\n", cur->stimer->st_cached_min_se);
18410                ast_cli(a->fd, "  S-Timer Cached SE:      %d\n", cur->stimer->st_cached_max_se);
18411                ast_cli(a->fd, "  S-Timer Cached Ref:     %s\n", strefresher2str(cur->stimer->st_cached_ref));
18412                ast_cli(a->fd, "  S-Timer Cached Mode:    %s\n", stmode2str(cur->stimer->st_cached_mode));
18413             }
18414          }
18415 
18416          ast_cli(a->fd, "\n\n");
18417 
18418          found++;
18419       }
18420 
18421       sip_pvt_unlock(cur);
18422 
18423       ao2_t_ref(cur, -1, "toss dialog ptr set by iterator_next");
18424    }
18425    ao2_iterator_destroy(&i);
18426 
18427    if (!found)
18428       ast_cli(a->fd, "No such SIP Call ID starting with '%s'\n", a->argv[3]);
18429 
18430    return CLI_SUCCESS;
18431 }
18432 
18433 /*! \brief Show history details of one dialog */
18434 static char *sip_show_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
18435 {
18436    struct sip_pvt *cur;
18437    size_t len;
18438    int found = 0;
18439    struct ao2_iterator i;
18440 
18441    switch (cmd) {
18442    case CLI_INIT:
18443       e->command = "sip show history";
18444       e->usage =
18445          "Usage: sip show history <call-id>\n"
18446          "       Provides detailed dialog history on a given SIP call (specified by call-id).\n";
18447       return NULL;
18448    case CLI_GENERATE:
18449       return complete_sip_show_history(a->line, a->word, a->pos, a->n);
18450    }
18451 
18452    if (a->argc != 4)
18453       return CLI_SHOWUSAGE;
18454 
18455    if (!recordhistory)
18456       ast_cli(a->fd, "\n***Note: History recording is currently DISABLED.  Use 'sip set history on' to ENABLE.\n");
18457 
18458    len = strlen(a->argv[3]);
18459 
18460    i = ao2_iterator_init(dialogs, 0);
18461    while ((cur = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
18462       sip_pvt_lock(cur);
18463       if (!strncasecmp(cur->callid, a->argv[3], len)) {
18464          struct sip_history *hist;
18465          int x = 0;
18466 
18467          ast_cli(a->fd, "\n");
18468          if (cur->subscribed != NONE)
18469             ast_cli(a->fd, "  * Subscription\n");
18470          else
18471             ast_cli(a->fd, "  * SIP Call\n");
18472          if (cur->history)
18473             AST_LIST_TRAVERSE(cur->history, hist, list)
18474                ast_cli(a->fd, "%d. %s\n", ++x, hist->event);
18475          if (x == 0)
18476             ast_cli(a->fd, "Call '%s' has no history\n", cur->callid);
18477          found++;
18478       }
18479       sip_pvt_unlock(cur);
18480       ao2_t_ref(cur, -1, "toss dialog ptr from iterator_next");
18481    }
18482    ao2_iterator_destroy(&i);
18483 
18484    if (!found)
18485       ast_cli(a->fd, "No such SIP Call ID starting with '%s'\n", a->argv[3]);
18486 
18487    return CLI_SUCCESS;
18488 }
18489 
18490 /*! \brief Dump SIP history to debug log file at end of lifespan for SIP dialog */
18491 static void sip_dump_history(struct sip_pvt *dialog)
18492 {
18493    int x = 0;
18494    struct sip_history *hist;
18495    static int errmsg = 0;
18496 
18497    if (!dialog)
18498       return;
18499 
18500    if (!option_debug && !sipdebug) {
18501       if (!errmsg) {
18502          ast_log(LOG_NOTICE, "You must have debugging enabled (SIP or Asterisk) in order to dump SIP history.\n");
18503          errmsg = 1;
18504       }
18505       return;
18506    }
18507 
18508    ast_debug(1, "\n---------- SIP HISTORY for '%s' \n", dialog->callid);
18509    if (dialog->subscribed)
18510       ast_debug(1, "  * Subscription\n");
18511    else
18512       ast_debug(1, "  * SIP Call\n");
18513    if (dialog->history)
18514       AST_LIST_TRAVERSE(dialog->history, hist, list)
18515          ast_debug(1, "  %-3.3d. %s\n", ++x, hist->event);
18516    if (!x)
18517       ast_debug(1, "Call '%s' has no history\n", dialog->callid);
18518    ast_debug(1, "\n---------- END SIP HISTORY for '%s' \n", dialog->callid);
18519 }
18520 
18521 
18522 /*! \brief  Receive SIP INFO Message */
18523 static void handle_request_info(struct sip_pvt *p, struct sip_request *req)
18524 {
18525    char buf[1024] = "";
18526    unsigned int event;
18527    const char *c = get_header(req, "Content-Type");
18528 
18529    /* Need to check the media/type */
18530    if (!strcasecmp(c, "application/dtmf-relay") ||
18531        !strcasecmp(c, "application/vnd.nortelnetworks.digits")) {
18532       unsigned int duration = 0;
18533 
18534       if (!p->owner) {  /* not a PBX call */
18535          transmit_response(p, "481 Call leg/transaction does not exist", req);
18536          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
18537          return;
18538       }
18539 
18540       /* Try getting the "signal=" part */
18541       if (ast_strlen_zero(c = get_body(req, "Signal", '=')) && ast_strlen_zero(c = get_body(req, "d", '='))) {
18542          ast_log(LOG_WARNING, "Unable to retrieve DTMF signal from INFO message from %s\n", p->callid);
18543          transmit_response(p, "200 OK", req); /* Should return error */
18544          return;
18545       } else {
18546          ast_copy_string(buf, c, sizeof(buf));
18547       }
18548 
18549       if (!ast_strlen_zero((c = get_body(req, "Duration", '='))))
18550          duration = atoi(c);
18551       if (!duration)
18552          duration = 100; /* 100 ms */
18553 
18554 
18555       if (ast_strlen_zero(buf)) {
18556          transmit_response(p, "200 OK", req);
18557          return;
18558       }
18559 
18560       if ('0' <= buf[0] && buf[0] <= '9') {
18561          event = buf[0] - '0';
18562       } else if (buf[0] == '*') {
18563          event = 10;
18564       } else if (buf[0] == '#') {
18565          event = 11;
18566       } else if ('A' <= buf[0] && buf[0] <= 'D') {
18567          event = 12 + buf[0] - 'A';
18568       } else if ('a' <= buf[0] && buf[0] <= 'd') {
18569          event = 12 + buf[0] - 'a';
18570       } else if (buf[0] == '!') {
18571          event = 16;
18572       } else {
18573          /* Unknown digit */
18574          event = 0;
18575       }
18576       if (event == 16) {
18577          /* send a FLASH event */
18578          struct ast_frame f = { AST_FRAME_CONTROL, { AST_CONTROL_FLASH, } };
18579          ast_queue_frame(p->owner, &f);
18580          if (sipdebug)
18581             ast_verbose("* DTMF-relay event received: FLASH\n");
18582       } else {
18583          /* send a DTMF event */
18584          struct ast_frame f = { AST_FRAME_DTMF, };
18585          if (event < 10) {
18586             f.subclass.integer = '0' + event;
18587          } else if (event == 10) {
18588             f.subclass.integer = '*';
18589          } else if (event == 11) {
18590             f.subclass.integer = '#';
18591          } else if (event < 16) {
18592             f.subclass.integer = 'A' + (event - 12);
18593          }
18594          f.len = duration;
18595          ast_queue_frame(p->owner, &f);
18596          if (sipdebug)
18597             ast_verbose("* DTMF-relay event received: %c\n", (int) f.subclass.integer);
18598       }
18599       transmit_response(p, "200 OK", req);
18600       return;
18601    } else if (!strcasecmp(c, "application/dtmf")) {
18602       /*! \todo Note: Doesn't read the duration of the DTMF. Should be fixed. */
18603       unsigned int duration = 0;
18604 
18605       if (!p->owner) {  /* not a PBX call */
18606          transmit_response(p, "481 Call leg/transaction does not exist", req);
18607          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
18608          return;
18609       }
18610 
18611       get_msg_text(buf, sizeof(buf), req);
18612       duration = 100; /* 100 ms */
18613 
18614       if (ast_strlen_zero(buf)) {
18615          transmit_response(p, "200 OK", req);
18616          return;
18617       }
18618       event = atoi(buf);
18619       if (event == 16) {
18620          /* send a FLASH event */
18621          struct ast_frame f = { AST_FRAME_CONTROL, { AST_CONTROL_FLASH }, };
18622          ast_queue_frame(p->owner, &f);
18623          if (sipdebug)
18624             ast_verbose("* DTMF-relay event received: FLASH\n");
18625       } else {
18626          /* send a DTMF event */
18627          struct ast_frame f = { AST_FRAME_DTMF, };
18628          if (event < 10) {
18629             f.subclass.integer = '0' + event;
18630          } else if (event == 10) {
18631             f.subclass.integer = '*';
18632          } else if (event == 11) {
18633             f.subclass.integer = '#';
18634          } else if (event < 16) {
18635             f.subclass.integer = 'A' + (event - 12);
18636          } else {
18637             /* Unknown digit. */
18638             f.subclass.integer = '0';
18639          }
18640          f.len = duration;
18641          ast_queue_frame(p->owner, &f);
18642          if (sipdebug)
18643             ast_verbose("* DTMF-relay event received: %c\n", (int) f.subclass.integer);
18644       }
18645       transmit_response(p, "200 OK", req);
18646       return;
18647 
18648    } else if (!strcasecmp(c, "application/media_control+xml")) {
18649       /* Eh, we'll just assume it's a fast picture update for now */
18650       if (p->owner)
18651          ast_queue_control(p->owner, AST_CONTROL_VIDUPDATE);
18652       transmit_response(p, "200 OK", req);
18653       return;
18654    } else if (!ast_strlen_zero(c = get_header(req, "X-ClientCode"))) {
18655       /* Client code (from SNOM phone) */
18656       if (ast_test_flag(&p->flags[0], SIP_USECLIENTCODE)) {
18657          if (p->owner && p->owner->cdr)
18658             ast_cdr_setuserfield(p->owner, c);
18659          if (p->owner && ast_bridged_channel(p->owner) && ast_bridged_channel(p->owner)->cdr)
18660             ast_cdr_setuserfield(ast_bridged_channel(p->owner), c);
18661          transmit_response(p, "200 OK", req);
18662       } else {
18663          transmit_response(p, "403 Forbidden", req);
18664       }
18665       return;
18666    } else if (!ast_strlen_zero(c = get_header(req, "Record"))) {
18667       /* INFO messages generated by some phones to start/stop recording
18668          on phone calls.
18669          OEJ: I think this should be something that is enabled/disabled
18670          per device. I don't want incoming callers to record calls in my
18671          pbx.
18672       */
18673       
18674       struct ast_call_feature *feat;
18675       int j;
18676       struct ast_frame f = { AST_FRAME_DTMF, };
18677 
18678       if (!p->owner) {        /* not a PBX call */
18679          transmit_response(p, "481 Call leg/transaction does not exist", req);
18680          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
18681          return;
18682       }
18683 
18684       /* first, get the feature string, if it exists */
18685       ast_rdlock_call_features();
18686       feat = ast_find_call_feature("automon");
18687       if (!feat || ast_strlen_zero(feat->exten)) {
18688          ast_log(LOG_WARNING, "Recording requested, but no One Touch Monitor registered. (See features.conf)\n");
18689          /* 403 means that we don't support this feature, so don't request it again */
18690          transmit_response(p, "403 Forbidden", req);
18691          ast_unlock_call_features();
18692          return;
18693       }
18694       /* Send the feature code to the PBX as DTMF, just like the handset had sent it */
18695       f.len = 100;
18696       for (j=0; j < strlen(feat->exten); j++) {
18697          f.subclass.integer = feat->exten[j];
18698          ast_queue_frame(p->owner, &f);
18699          if (sipdebug)
18700             ast_verbose("* DTMF-relay event faked: %c\n", f.subclass.integer);
18701       }
18702       ast_unlock_call_features();
18703 
18704       ast_debug(1, "Got a Request to Record the channel, state %s\n", c);
18705       transmit_response(p, "200 OK", req);
18706       return;
18707    } else if (ast_strlen_zero(c = get_header(req, "Content-Length")) || !strcasecmp(c, "0")) {
18708       /* This is probably just a packet making sure the signalling is still up, just send back a 200 OK */
18709       transmit_response(p, "200 OK", req);
18710       return;
18711    }
18712 
18713    /* Other type of INFO message, not really understood by Asterisk */
18714    /* if (get_msg_text(buf, sizeof(buf), req)) { */
18715 
18716    ast_log(LOG_WARNING, "Unable to parse INFO message from %s. Content %s\n", p->callid, buf);
18717    transmit_response(p, "415 Unsupported media type", req);
18718    return;
18719 }
18720 
18721 /*! \brief Enable SIP Debugging for a single IP */
18722 static char *sip_do_debug_ip(int fd, const char *arg)
18723 {
18724    if (ast_sockaddr_resolve_first(&debugaddr, arg, 0)) {
18725       return CLI_SHOWUSAGE;
18726    }
18727 
18728    ast_cli(fd, "SIP Debugging Enabled for IP: %s\n", ast_sockaddr_stringify_addr(&debugaddr));
18729    sipdebug |= sip_debug_console;
18730 
18731    return CLI_SUCCESS;
18732 }
18733 
18734 /*! \brief  Turn on SIP debugging for a given peer */
18735 static char *sip_do_debug_peer(int fd, const char *arg)
18736 {
18737    struct sip_peer *peer = find_peer(arg, NULL, TRUE, FINDPEERS, FALSE, 0);
18738    if (!peer)
18739       ast_cli(fd, "No such peer '%s'\n", arg);
18740    else if (ast_sockaddr_isnull(&peer->addr))
18741       ast_cli(fd, "Unable to get IP address of peer '%s'\n", arg);
18742    else {
18743       ast_sockaddr_copy(&debugaddr, &peer->addr);
18744       ast_cli(fd, "SIP Debugging Enabled for IP: %s\n", ast_sockaddr_stringify_addr(&debugaddr));
18745       sipdebug |= sip_debug_console;
18746    }
18747    if (peer)
18748       unref_peer(peer, "sip_do_debug_peer: unref_peer, from find_peer call");
18749    return CLI_SUCCESS;
18750 }
18751 
18752 /*! \brief Turn on SIP debugging (CLI command) */
18753 static char *sip_do_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
18754 {
18755    int oldsipdebug = sipdebug & sip_debug_console;
18756    const char *what;
18757 
18758    if (cmd == CLI_INIT) {
18759       e->command = "sip set debug {on|off|ip|peer}";
18760       e->usage =
18761          "Usage: sip set debug {off|on|ip addr[:port]|peer peername}\n"
18762          "       Globally disables dumping of SIP packets,\n"
18763          "       or enables it either globally or for a (single)\n"
18764          "       IP address or registered peer.\n";
18765       return NULL;
18766    } else if (cmd == CLI_GENERATE) {
18767       if (a->pos == 4 && !strcasecmp(a->argv[3], "peer"))
18768          return complete_sip_peer(a->word, a->n, 0);
18769       return NULL;
18770         }
18771 
18772    what = a->argv[e->args-1];      /* guaranteed to exist */
18773    if (a->argc == e->args) {       /* on/off */
18774       if (!strcasecmp(what, "on")) {
18775          sipdebug |= sip_debug_console;
18776          sipdebug_text = 1;   /*! \note this can be a special debug command - "sip debug text" or something */
18777          memset(&debugaddr, 0, sizeof(debugaddr));
18778          ast_cli(a->fd, "SIP Debugging %senabled\n", oldsipdebug ? "re-" : "");
18779          return CLI_SUCCESS;
18780       } else if (!strcasecmp(what, "off")) {
18781          sipdebug &= ~sip_debug_console;
18782          sipdebug_text = 0;
18783          ast_cli(a->fd, "SIP Debugging Disabled\n");
18784          return CLI_SUCCESS;
18785       }
18786    } else if (a->argc == e->args +1) {/* ip/peer */
18787       if (!strcasecmp(what, "ip"))
18788          return sip_do_debug_ip(a->fd, a->argv[e->args]);
18789       else if (!strcasecmp(what, "peer"))
18790          return sip_do_debug_peer(a->fd, a->argv[e->args]);
18791    }
18792    return CLI_SHOWUSAGE;   /* default, failure */
18793 }
18794 
18795 /*! \brief Cli command to send SIP notify to peer */
18796 static char *sip_cli_notify(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
18797 {
18798    struct ast_variable *varlist;
18799    int i;
18800 
18801    switch (cmd) {
18802    case CLI_INIT:
18803       e->command = "sip notify";
18804       e->usage =
18805          "Usage: sip notify <type> <peer> [<peer>...]\n"
18806          "       Send a NOTIFY message to a SIP peer or peers\n"
18807          "       Message types are defined in sip_notify.conf\n";
18808       return NULL;
18809    case CLI_GENERATE:
18810       return complete_sipnotify(a->line, a->word, a->pos, a->n);
18811    }
18812 
18813    if (a->argc < 4)
18814       return CLI_SHOWUSAGE;
18815 
18816    if (!notify_types) {
18817       ast_cli(a->fd, "No %s file found, or no types listed there\n", notify_config);
18818       return CLI_FAILURE;
18819    }
18820 
18821    varlist = ast_variable_browse(notify_types, a->argv[2]);
18822 
18823    if (!varlist) {
18824       ast_cli(a->fd, "Unable to find notify type '%s'\n", a->argv[2]);
18825       return CLI_FAILURE;
18826    }
18827 
18828    for (i = 3; i < a->argc; i++) {
18829       struct sip_pvt *p;
18830       char buf[512];
18831       struct ast_variable *header, *var;
18832 
18833       if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY, NULL))) {
18834          ast_log(LOG_WARNING, "Unable to build sip pvt data for notify (memory/socket error)\n");
18835          return CLI_FAILURE;
18836       }
18837 
18838       if (create_addr(p, a->argv[i], NULL, 1, NULL)) {
18839          /* Maybe they're not registered, etc. */
18840          dialog_unlink_all(p);
18841          dialog_unref(p, "unref dialog inside for loop" );
18842          /* sip_destroy(p); */
18843          ast_cli(a->fd, "Could not create address for '%s'\n", a->argv[i]);
18844          continue;
18845       }
18846 
18847       /* Notify is outgoing call */
18848       ast_set_flag(&p->flags[0], SIP_OUTGOING);
18849       sip_notify_allocate(p);
18850       p->notify->headers = header = ast_variable_new("Subscription-State", "terminated", "");
18851 
18852       for (var = varlist; var; var = var->next) {
18853          ast_copy_string(buf, var->value, sizeof(buf));
18854          ast_unescape_semicolon(buf);
18855 
18856          if (!strcasecmp(var->name, "Content")) {
18857             if (ast_str_strlen(p->notify->content))
18858                ast_str_append(&p->notify->content, 0, "\r\n");
18859             ast_str_append(&p->notify->content, 0, "%s", buf);
18860          } else if (!strcasecmp(var->name, "Content-Length")) {
18861             ast_log(LOG_WARNING, "it is not necessary to specify Content-Length in sip_notify.conf, ignoring");
18862          } else {
18863             header->next = ast_variable_new(var->name, buf, "");
18864             header = header->next;
18865          }
18866       }
18867 
18868       /* Recalculate our side, and recalculate Call ID */
18869       ast_cli(a->fd, "Sending NOTIFY of type '%s' to '%s'\n", a->argv[2], a->argv[i]);
18870       sip_scheddestroy(p, SIP_TRANS_TIMEOUT);
18871       transmit_invite(p, SIP_NOTIFY, 0, 2, NULL);
18872       dialog_unref(p, "bump down the count of p since we're done with it.");
18873    }
18874 
18875    return CLI_SUCCESS;
18876 }
18877 
18878 /*! \brief Enable/Disable SIP History logging (CLI) */
18879 static char *sip_set_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
18880 {
18881    switch (cmd) {
18882    case CLI_INIT:
18883       e->command = "sip set history {on|off}";
18884       e->usage =
18885          "Usage: sip set history {on|off}\n"
18886          "       Enables/Disables recording of SIP dialog history for debugging purposes.\n"
18887          "       Use 'sip show history' to view the history of a call number.\n";
18888       return NULL;
18889    case CLI_GENERATE:
18890       return NULL;
18891    }
18892 
18893    if (a->argc != e->args)
18894       return CLI_SHOWUSAGE;
18895 
18896    if (!strncasecmp(a->argv[e->args - 1], "on", 2)) {
18897       recordhistory = TRUE;
18898       ast_cli(a->fd, "SIP History Recording Enabled (use 'sip show history')\n");
18899    } else if (!strncasecmp(a->argv[e->args - 1], "off", 3)) {
18900       recordhistory = FALSE;
18901       ast_cli(a->fd, "SIP History Recording Disabled\n");
18902    } else {
18903       return CLI_SHOWUSAGE;
18904    }
18905    return CLI_SUCCESS;
18906 }
18907 
18908 /*! \brief Authenticate for outbound registration */
18909 static int do_register_auth(struct sip_pvt *p, struct sip_request *req, enum sip_auth_type code)
18910 {
18911    char *header, *respheader;
18912    char digest[1024];
18913 
18914    p->authtries++;
18915    auth_headers(code, &header, &respheader);
18916    memset(digest, 0, sizeof(digest));
18917    if (reply_digest(p, req, header, SIP_REGISTER, digest, sizeof(digest))) {
18918       /* There's nothing to use for authentication */
18919       /* No digest challenge in request */
18920       if (sip_debug_test_pvt(p) && p->registry)
18921          ast_verbose("No authentication challenge, sending blank registration to domain/host name %s\n", p->registry->hostname);
18922          /* No old challenge */
18923       return -1;
18924    }
18925    if (p->do_history)
18926       append_history(p, "RegistryAuth", "Try: %d", p->authtries);
18927    if (sip_debug_test_pvt(p) && p->registry)
18928       ast_verbose("Responding to challenge, registration to domain/host name %s\n", p->registry->hostname);
18929    return transmit_register(p->registry, SIP_REGISTER, digest, respheader);
18930 }
18931 
18932 /*! \brief Add authentication on outbound SIP packet */
18933 static int do_proxy_auth(struct sip_pvt *p, struct sip_request *req, enum sip_auth_type code, int sipmethod, int init)
18934 {
18935    char *header, *respheader;
18936    char digest[1024];
18937 
18938    if (!p->options && !(p->options = ast_calloc(1, sizeof(*p->options))))
18939       return -2;
18940 
18941    p->authtries++;
18942    auth_headers(code, &header, &respheader);
18943    ast_debug(2, "Auth attempt %d on %s\n", p->authtries, sip_methods[sipmethod].text);
18944    memset(digest, 0, sizeof(digest));
18945    if (reply_digest(p, req, header, sipmethod, digest, sizeof(digest) )) {
18946       /* No way to authenticate */
18947       return -1;
18948    }
18949    /* Now we have a reply digest */
18950    p->options->auth = digest;
18951    p->options->authheader = respheader;
18952    return transmit_invite(p, sipmethod, sipmethod == SIP_INVITE, init, NULL);
18953 }
18954 
18955 /*! \brief  reply to authentication for outbound registrations
18956 \return  Returns -1 if we have no auth
18957 \note This is used for register= servers in sip.conf, SIP proxies we register
18958    with  for receiving calls from.  */
18959 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod,  char *digest, int digest_len)
18960 {
18961    char tmp[512];
18962    char *c;
18963    char oldnonce[256];
18964 
18965    /* table of recognised keywords, and places where they should be copied */
18966    const struct x {
18967       const char *key;
18968       const ast_string_field *field;
18969    } *i, keys[] = {
18970       { "realm=", &p->realm },
18971       { "nonce=", &p->nonce },
18972       { "opaque=", &p->opaque },
18973       { "qop=", &p->qop },
18974       { "domain=", &p->domain },
18975       { NULL, 0 },
18976    };
18977 
18978    ast_copy_string(tmp, get_header(req, header), sizeof(tmp));
18979    if (ast_strlen_zero(tmp))
18980       return -1;
18981    if (strncasecmp(tmp, "Digest ", strlen("Digest "))) {
18982       ast_log(LOG_WARNING, "missing Digest.\n");
18983       return -1;
18984    }
18985    c = tmp + strlen("Digest ");
18986    ast_copy_string(oldnonce, p->nonce, sizeof(oldnonce));
18987    while (c && *(c = ast_skip_blanks(c))) {  /* lookup for keys */
18988       for (i = keys; i->key != NULL; i++) {
18989          char *src, *separator;
18990          if (strncasecmp(c, i->key, strlen(i->key)) != 0)
18991             continue;
18992          /* Found. Skip keyword, take text in quotes or up to the separator. */
18993          c += strlen(i->key);
18994          if (*c == '"') {
18995             src = ++c;
18996             separator = "\"";
18997          } else {
18998             src = c;
18999             separator = ",";
19000          }
19001          strsep(&c, separator); /* clear separator and move ptr */
19002          ast_string_field_ptr_set(p, i->field, src);
19003          break;
19004       }
19005       if (i->key == NULL) /* not found, try ',' */
19006          strsep(&c, ",");
19007    }
19008    /* Reset nonce count */
19009    if (strcmp(p->nonce, oldnonce))
19010       p->noncecount = 0;
19011 
19012    /* Save auth data for following registrations */
19013    if (p->registry) {
19014       struct sip_registry *r = p->registry;
19015 
19016       if (strcmp(r->nonce, p->nonce)) {
19017          ast_string_field_set(r, realm, p->realm);
19018          ast_string_field_set(r, nonce, p->nonce);
19019          ast_string_field_set(r, authdomain, p->domain);
19020          ast_string_field_set(r, opaque, p->opaque);
19021          ast_string_field_set(r, qop, p->qop);
19022          r->noncecount = 0;
19023       }
19024    }
19025    return build_reply_digest(p, sipmethod, digest, digest_len);
19026 }
19027 
19028 /*! \brief  Build reply digest
19029 \return  Returns -1 if we have no auth
19030 \note Build digest challenge for authentication of registrations and calls
19031    Also used for authentication of BYE
19032 */
19033 static int build_reply_digest(struct sip_pvt *p, int method, char* digest, int digest_len)
19034 {
19035    char a1[256];
19036    char a2[256];
19037    char a1_hash[256];
19038    char a2_hash[256];
19039    char resp[256];
19040    char resp_hash[256];
19041    char uri[256];
19042    char opaque[256] = "";
19043    char cnonce[80];
19044    const char *username;
19045    const char *secret;
19046    const char *md5secret;
19047    struct sip_auth *auth;  /* Realm authentication credential */
19048    struct sip_auth_container *credentials;
19049 
19050    if (!ast_strlen_zero(p->domain))
19051       snprintf(uri, sizeof(uri), "%s:%s", p->socket.type == SIP_TRANSPORT_TLS ? "sips" : "sip", p->domain);
19052    else if (!ast_strlen_zero(p->uri))
19053       ast_copy_string(uri, p->uri, sizeof(uri));
19054    else
19055       snprintf(uri, sizeof(uri), "%s:%s@%s", p->socket.type == SIP_TRANSPORT_TLS ? "sips" : "sip", p->username, ast_sockaddr_stringify_host_remote(&p->sa));
19056 
19057    snprintf(cnonce, sizeof(cnonce), "%08lx", ast_random());
19058 
19059    /* Check if we have peer credentials */
19060    ao2_lock(p);
19061    credentials = p->peerauth;
19062    if (credentials) {
19063       ao2_t_ref(credentials, +1, "Ref peer auth for digest");
19064    }
19065    ao2_unlock(p);
19066    auth = find_realm_authentication(credentials, p->realm);
19067    if (!auth) {
19068       /* If not, check global credentials */
19069       if (credentials) {
19070          ao2_t_ref(credentials, -1, "Unref peer auth for digest");
19071       }
19072       ast_mutex_lock(&authl_lock);
19073       credentials = authl;
19074       if (credentials) {
19075          ao2_t_ref(credentials, +1, "Ref global auth for digest");
19076       }
19077       ast_mutex_unlock(&authl_lock);
19078       auth = find_realm_authentication(credentials, p->realm);
19079    }
19080 
19081    if (auth) {
19082       ast_debug(3, "use realm [%s] from peer [%s][%s]\n", auth->username, p->peername, p->username);
19083       username = auth->username;
19084       secret = auth->secret;
19085       md5secret = auth->md5secret;
19086       if (sipdebug)
19087          ast_debug(1, "Using realm %s authentication for call %s\n", p->realm, p->callid);
19088    } else {
19089       /* No authentication, use peer or register= config */
19090       username = p->authname;
19091       secret = p->relatedpeer 
19092          && !ast_strlen_zero(p->relatedpeer->remotesecret)
19093             ? p->relatedpeer->remotesecret : p->peersecret;
19094       md5secret = p->peermd5secret;
19095    }
19096    if (ast_strlen_zero(username)) {
19097       /* We have no authentication */
19098       if (credentials) {
19099          ao2_t_ref(credentials, -1, "Unref auth for digest");
19100       }
19101       return -1;
19102    }
19103 
19104    /* Calculate SIP digest response */
19105    snprintf(a1, sizeof(a1), "%s:%s:%s", username, p->realm, secret);
19106    snprintf(a2, sizeof(a2), "%s:%s", sip_methods[method].text, uri);
19107    if (!ast_strlen_zero(md5secret))
19108       ast_copy_string(a1_hash, md5secret, sizeof(a1_hash));
19109    else
19110       ast_md5_hash(a1_hash, a1);
19111    ast_md5_hash(a2_hash, a2);
19112 
19113    p->noncecount++;
19114    if (!ast_strlen_zero(p->qop))
19115       snprintf(resp, sizeof(resp), "%s:%s:%08x:%s:%s:%s", a1_hash, p->nonce, p->noncecount, cnonce, "auth", a2_hash);
19116    else
19117       snprintf(resp, sizeof(resp), "%s:%s:%s", a1_hash, p->nonce, a2_hash);
19118    ast_md5_hash(resp_hash, resp);
19119 
19120    /* only include the opaque string if it's set */
19121    if (!ast_strlen_zero(p->opaque)) {
19122       snprintf(opaque, sizeof(opaque), ", opaque=\"%s\"", p->opaque);
19123    }
19124 
19125    /* XXX We hard code our qop to "auth" for now.  XXX */
19126    if (!ast_strlen_zero(p->qop))
19127       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);
19128    else
19129       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);
19130 
19131    append_history(p, "AuthResp", "Auth response sent for %s in realm %s - nc %d", username, p->realm, p->noncecount);
19132 
19133    if (credentials) {
19134       ao2_t_ref(credentials, -1, "Unref auth for digest");
19135    }
19136    return 0;
19137 }
19138    
19139 /*! \brief Read SIP header (dialplan function) */
19140 static int func_header_read(struct ast_channel *chan, const char *function, char *data, char *buf, size_t len)
19141 {
19142    struct sip_pvt *p;
19143    const char *content = NULL;
19144    AST_DECLARE_APP_ARGS(args,
19145       AST_APP_ARG(header);
19146       AST_APP_ARG(number);
19147    );
19148    int i, number, start = 0;
19149 
19150    if (ast_strlen_zero(data)) {
19151       ast_log(LOG_WARNING, "This function requires a header name.\n");
19152       return -1;
19153    }
19154 
19155    ast_channel_lock(chan);
19156    if (!IS_SIP_TECH(chan->tech)) {
19157       ast_log(LOG_WARNING, "This function can only be used on SIP channels.\n");
19158       ast_channel_unlock(chan);
19159       return -1;
19160    }
19161 
19162    AST_STANDARD_APP_ARGS(args, data);
19163    if (!args.number) {
19164       number = 1;
19165    } else {
19166       sscanf(args.number, "%30d", &number);
19167       if (number < 1)
19168          number = 1;
19169    }
19170 
19171    p = chan->tech_pvt;
19172 
19173    /* If there is no private structure, this channel is no longer alive */
19174    if (!p) {
19175       ast_channel_unlock(chan);
19176       return -1;
19177    }
19178 
19179    for (i = 0; i < number; i++)
19180       content = __get_header(&p->initreq, args.header, &start);
19181 
19182    if (ast_strlen_zero(content)) {
19183       ast_channel_unlock(chan);
19184       return -1;
19185    }
19186 
19187    ast_copy_string(buf, content, len);
19188    ast_channel_unlock(chan);
19189 
19190    return 0;
19191 }
19192 
19193 static struct ast_custom_function sip_header_function = {
19194    .name = "SIP_HEADER",
19195    .read = func_header_read,
19196 };
19197 
19198 /*! \brief  Dial plan function to check if domain is local */
19199 static int func_check_sipdomain(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
19200 {
19201    if (ast_strlen_zero(data)) {
19202       ast_log(LOG_WARNING, "CHECKSIPDOMAIN requires an argument - A domain name\n");
19203       return -1;
19204    }
19205    if (check_sip_domain(data, NULL, 0))
19206       ast_copy_string(buf, data, len);
19207    else
19208       buf[0] = '\0';
19209    return 0;
19210 }
19211 
19212 static struct ast_custom_function checksipdomain_function = {
19213    .name = "CHECKSIPDOMAIN",
19214    .read = func_check_sipdomain,
19215 };
19216 
19217 /*! \brief  ${SIPPEER()} Dialplan function - reads peer data */
19218 static int function_sippeer(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
19219 {
19220    struct sip_peer *peer;
19221    char *colname;
19222 
19223    if ((colname = strchr(data, ':'))) {   /*! \todo Will be deprecated after 1.4 */
19224       static int deprecation_warning = 0;
19225       *colname++ = '\0';
19226       if (deprecation_warning++ % 10 == 0)
19227          ast_log(LOG_WARNING, "SIPPEER(): usage of ':' to separate arguments is deprecated.  Please use ',' instead.\n");
19228    } else if ((colname = strchr(data, ',')))
19229       *colname++ = '\0';
19230    else
19231       colname = "ip";
19232 
19233    if (!(peer = find_peer(data, NULL, TRUE, FINDPEERS, FALSE, 0)))
19234       return -1;
19235 
19236    if (!strcasecmp(colname, "ip")) {
19237       ast_copy_string(buf, ast_sockaddr_stringify_addr(&peer->addr), len);
19238    } else  if (!strcasecmp(colname, "port")) {
19239       snprintf(buf, len, "%d", ast_sockaddr_port(&peer->addr));
19240    } else  if (!strcasecmp(colname, "status")) {
19241       peer_status(peer, buf, len);
19242    } else  if (!strcasecmp(colname, "language")) {
19243       ast_copy_string(buf, peer->language, len);
19244    } else  if (!strcasecmp(colname, "regexten")) {
19245       ast_copy_string(buf, peer->regexten, len);
19246    } else  if (!strcasecmp(colname, "limit")) {
19247       snprintf(buf, len, "%d", peer->call_limit);
19248    } else  if (!strcasecmp(colname, "busylevel")) {
19249       snprintf(buf, len, "%d", peer->busy_level);
19250    } else  if (!strcasecmp(colname, "curcalls")) {
19251       snprintf(buf, len, "%d", peer->inUse);
19252    } else if (!strcasecmp(colname, "maxforwards")) {
19253       snprintf(buf, len, "%d", peer->maxforwards);
19254    } else  if (!strcasecmp(colname, "accountcode")) {
19255       ast_copy_string(buf, peer->accountcode, len);
19256    } else  if (!strcasecmp(colname, "callgroup")) {
19257       ast_print_group(buf, len, peer->callgroup);
19258    } else  if (!strcasecmp(colname, "pickupgroup")) {
19259       ast_print_group(buf, len, peer->pickupgroup);
19260    } else  if (!strcasecmp(colname, "useragent")) {
19261       ast_copy_string(buf, peer->useragent, len);
19262    } else  if (!strcasecmp(colname, "mailbox")) {
19263       struct ast_str *mailbox_str = ast_str_alloca(512);
19264       peer_mailboxes_to_str(&mailbox_str, peer);
19265       ast_copy_string(buf, mailbox_str->str, len);
19266    } else  if (!strcasecmp(colname, "context")) {
19267       ast_copy_string(buf, peer->context, len);
19268    } else  if (!strcasecmp(colname, "expire")) {
19269       snprintf(buf, len, "%d", peer->expire);
19270    } else  if (!strcasecmp(colname, "dynamic")) {
19271       ast_copy_string(buf, peer->host_dynamic ? "yes" : "no", len);
19272    } else  if (!strcasecmp(colname, "callerid_name")) {
19273       ast_copy_string(buf, peer->cid_name, len);
19274    } else  if (!strcasecmp(colname, "callerid_num")) {
19275       ast_copy_string(buf, peer->cid_num, len);
19276    } else  if (!strcasecmp(colname, "codecs")) {
19277       ast_getformatname_multiple(buf, len -1, peer->capability);
19278    } else if (!strcasecmp(colname, "encryption")) {
19279       snprintf(buf, len, "%d", ast_test_flag(&peer->flags[1], SIP_PAGE2_USE_SRTP));
19280    } else  if (!strncasecmp(colname, "chanvar[", 8)) {
19281       char *chanvar=colname + 8;
19282       struct ast_variable *v;
19283    
19284       chanvar = strsep(&chanvar, "]");
19285       for (v = peer->chanvars ; v ; v = v->next) {
19286          if (!strcasecmp(v->name, chanvar)) {
19287             ast_copy_string(buf, v->value, len);
19288          }
19289       }
19290    } else  if (!strncasecmp(colname, "codec[", 6)) {
19291       char *codecnum;
19292       format_t codec = 0;
19293       
19294       codecnum = colname + 6; /* move past the '[' */
19295       codecnum = strsep(&codecnum, "]"); /* trim trailing ']' if any */
19296       if((codec = ast_codec_pref_index(&peer->prefs, atoi(codecnum)))) {
19297          ast_copy_string(buf, ast_getformatname(codec), len);
19298       } else {
19299          buf[0] = '\0';
19300       }
19301    } else {
19302       buf[0] = '\0';
19303    }
19304 
19305    unref_peer(peer, "unref_peer from function_sippeer, just before return");
19306 
19307    return 0;
19308 }
19309 
19310 /*! \brief Structure to declare a dialplan function: SIPPEER */
19311 static struct ast_custom_function sippeer_function = {
19312    .name = "SIPPEER",
19313    .read = function_sippeer,
19314 };
19315 
19316 /*! \brief ${SIPCHANINFO()} Dialplan function - reads sip channel data */
19317 static int function_sipchaninfo_read(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
19318 {
19319    struct sip_pvt *p;
19320    static int deprecated = 0;
19321 
19322    *buf = 0;
19323    
19324    if (!data) {
19325       ast_log(LOG_WARNING, "This function requires a parameter name.\n");
19326       return -1;
19327    }
19328 
19329    ast_channel_lock(chan);
19330    if (!IS_SIP_TECH(chan->tech)) {
19331       ast_log(LOG_WARNING, "This function can only be used on SIP channels.\n");
19332       ast_channel_unlock(chan);
19333       return -1;
19334    }
19335 
19336    if (deprecated++ % 20 == 0) {
19337       /* Deprecated in 1.6.1 */
19338       ast_log(LOG_WARNING, "SIPCHANINFO() is deprecated.  Please transition to using CHANNEL().\n");
19339    }
19340 
19341    p = chan->tech_pvt;
19342 
19343    /* If there is no private structure, this channel is no longer alive */
19344    if (!p) {
19345       ast_channel_unlock(chan);
19346       return -1;
19347    }
19348 
19349    if (!strcasecmp(data, "peerip")) {
19350       ast_copy_string(buf, ast_sockaddr_stringify_addr(&p->sa), len);
19351    } else  if (!strcasecmp(data, "recvip")) {
19352       ast_copy_string(buf, ast_sockaddr_stringify_addr(&p->recv), len);
19353    } else  if (!strcasecmp(data, "from")) {
19354       ast_copy_string(buf, p->from, len);
19355    } else  if (!strcasecmp(data, "uri")) {
19356       ast_copy_string(buf, p->uri, len);
19357    } else  if (!strcasecmp(data, "useragent")) {
19358       ast_copy_string(buf, p->useragent, len);
19359    } else  if (!strcasecmp(data, "peername")) {
19360       ast_copy_string(buf, p->peername, len);
19361    } else if (!strcasecmp(data, "t38passthrough")) {
19362       if (p->t38.state == T38_DISABLED) {
19363          ast_copy_string(buf, "0", len);
19364       } else { /* T38 is offered or enabled in this call */
19365          ast_copy_string(buf, "1", len);
19366       }
19367    } else {
19368       ast_channel_unlock(chan);
19369       return -1;
19370    }
19371    ast_channel_unlock(chan);
19372 
19373    return 0;
19374 }
19375 
19376 /*! \brief Structure to declare a dialplan function: SIPCHANINFO */
19377 static struct ast_custom_function sipchaninfo_function = {
19378    .name = "SIPCHANINFO",
19379    .read = function_sipchaninfo_read,
19380 };
19381 
19382 /*! \brief update redirecting information for a channel based on headers
19383  *
19384  */
19385 static void change_redirecting_information(struct sip_pvt *p, struct sip_request *req,
19386    struct ast_party_redirecting *redirecting,
19387    struct ast_set_party_redirecting *update_redirecting, int set_call_forward)
19388 {
19389    char *redirecting_from_name = NULL;
19390    char *redirecting_from_number = NULL;
19391    char *redirecting_to_name = NULL;
19392    char *redirecting_to_number = NULL;
19393    int reason = AST_REDIRECTING_REASON_UNCONDITIONAL;
19394    int is_response = req->method == SIP_RESPONSE;
19395    int res = 0;
19396 
19397    res = get_rdnis(p, req, &redirecting_from_name, &redirecting_from_number, &reason);
19398    if (res == -1) {
19399       if (is_response) {
19400          get_name_and_number(get_header(req, "TO"), &redirecting_from_name, &redirecting_from_number);
19401       } else {
19402          return;
19403       }
19404    }
19405 
19406    /* At this point, all redirecting "from" info should be filled in appropriately
19407     * on to the "to" info
19408     */
19409 
19410    if (is_response) {
19411       parse_moved_contact(p, req, &redirecting_to_name, &redirecting_to_number, set_call_forward);
19412    } else {
19413       get_name_and_number(get_header(req, "TO"), &redirecting_to_name, &redirecting_to_number);
19414    }
19415 
19416    if (!ast_strlen_zero(redirecting_from_number)) {
19417       ast_debug(3, "Got redirecting from number %s\n", redirecting_from_number);
19418       update_redirecting->from.number = 1;
19419       redirecting->from.number.valid = 1;
19420       ast_free(redirecting->from.number.str);
19421       redirecting->from.number.str = redirecting_from_number;
19422    }
19423    if (!ast_strlen_zero(redirecting_from_name)) {
19424       ast_debug(3, "Got redirecting from name %s\n", redirecting_from_name);
19425       update_redirecting->from.name = 1;
19426       redirecting->from.name.valid = 1;
19427       ast_free(redirecting->from.name.str);
19428       redirecting->from.name.str = redirecting_from_name;
19429    }
19430    if (!ast_strlen_zero(p->cid_tag)) {
19431       ast_free(redirecting->from.tag);
19432       redirecting->from.tag = ast_strdup(p->cid_tag);
19433       ast_free(redirecting->to.tag);
19434       redirecting->to.tag = ast_strdup(p->cid_tag);
19435    }
19436    if (!ast_strlen_zero(redirecting_to_number)) {
19437       ast_debug(3, "Got redirecting to number %s\n", redirecting_to_number);
19438       update_redirecting->to.number = 1;
19439       redirecting->to.number.valid = 1;
19440       ast_free(redirecting->to.number.str);
19441       redirecting->to.number.str = redirecting_to_number;
19442    }
19443    if (!ast_strlen_zero(redirecting_to_name)) {
19444       ast_debug(3, "Got redirecting to name %s\n", redirecting_from_number);
19445       update_redirecting->to.name = 1;
19446       redirecting->to.name.valid = 1;
19447       ast_free(redirecting->to.name.str);
19448       redirecting->to.name.str = redirecting_to_name;
19449    }
19450    redirecting->reason = reason;
19451 }
19452 
19453 /*! \brief Parse 302 Moved temporalily response
19454    \todo XXX Doesn't redirect over TLS on sips: uri's.
19455       If we get a redirect to a SIPS: uri, this needs to be going back to the
19456       dialplan (this is a request for a secure signalling path).
19457       Note that transport=tls is deprecated, but we need to support it on incoming requests.
19458 */
19459 static void parse_moved_contact(struct sip_pvt *p, struct sip_request *req, char **name, char **number, int set_call_forward)
19460 {
19461    char contact[SIPBUFSIZE];
19462    char *contact_name = NULL;
19463    char *contact_number = NULL;
19464    char *separator, *trans;
19465    char *domain;
19466    enum sip_transport transport = SIP_TRANSPORT_UDP;
19467 
19468    ast_copy_string(contact, get_header(req, "Contact"), sizeof(contact));
19469    if ((separator = strchr(contact, ',')))
19470       *separator = '\0';
19471 
19472    contact_number = get_in_brackets(contact);
19473    if ((trans = strcasestr(contact_number, ";transport="))) {
19474       trans += 11;
19475 
19476       if ((separator = strchr(trans, ';')))
19477          *separator = '\0';
19478 
19479       if (!strncasecmp(trans, "tcp", 3))
19480          transport = SIP_TRANSPORT_TCP;
19481       else if (!strncasecmp(trans, "tls", 3))
19482          transport = SIP_TRANSPORT_TLS;
19483       else {
19484          if (strncasecmp(trans, "udp", 3))
19485             ast_debug(1, "received contact with an invalid transport, '%s'\n", contact_number);
19486          /* This will assume UDP for all unknown transports */
19487          transport = SIP_TRANSPORT_UDP;
19488       }
19489    }
19490    contact_number = remove_uri_parameters(contact_number);
19491 
19492    if (p->socket.tcptls_session) {
19493       ao2_ref(p->socket.tcptls_session, -1);
19494       p->socket.tcptls_session = NULL;
19495    }
19496 
19497    set_socket_transport(&p->socket, transport);
19498 
19499    if (set_call_forward && ast_test_flag(&p->flags[0], SIP_PROMISCREDIR)) {
19500       char *host = NULL;
19501       if (!strncasecmp(contact_number, "sip:", 4))
19502          contact_number += 4;
19503       else if (!strncasecmp(contact_number, "sips:", 5))
19504          contact_number += 5;
19505       separator = strchr(contact_number, '/');
19506       if (separator)
19507          *separator = '\0';
19508       if ((host = strchr(contact_number, '@'))) {
19509          *host++ = '\0';
19510          ast_debug(2, "Found promiscuous redirection to 'SIP/%s::::%s@%s'\n", contact_number, get_transport(transport), host);
19511          if (p->owner)
19512             ast_string_field_build(p->owner, call_forward, "SIP/%s::::%s@%s", contact_number, get_transport(transport), host);
19513       } else {
19514          ast_debug(2, "Found promiscuous redirection to 'SIP/::::%s@%s'\n", get_transport(transport), contact_number);
19515          if (p->owner)
19516             ast_string_field_build(p->owner, call_forward, "SIP/::::%s@%s", get_transport(transport), contact_number);
19517       }
19518    } else {
19519       separator = strchr(contact, '@');
19520       if (separator) {
19521          *separator++ = '\0';
19522          domain = separator;
19523       } else {
19524          /* No username part */
19525          domain = contact;
19526       }
19527       separator = strchr(contact, '/');   /* WHEN do we hae a forward slash in the URI? */
19528       if (separator)
19529          *separator = '\0';
19530 
19531       if (!strncasecmp(contact_number, "sip:", 4))
19532          contact_number += 4;
19533       else if (!strncasecmp(contact_number, "sips:", 5))
19534          contact_number += 5;
19535       separator = strchr(contact_number, ';');  /* And username ; parameters? */
19536       if (separator)
19537          *separator = '\0';
19538       ast_uri_decode(contact_number);
19539       if (set_call_forward) {
19540          ast_debug(2, "Received 302 Redirect to extension '%s' (domain %s)\n", contact_number, domain);
19541          if (p->owner) {
19542             pbx_builtin_setvar_helper(p->owner, "SIPDOMAIN", domain);
19543             ast_string_field_set(p->owner, call_forward, contact_number);
19544          }
19545       }
19546    }
19547 
19548    /* We've gotten the number for the contact, now get the name */
19549 
19550    if (*contact == '\"') {
19551       contact_name = contact + 1;
19552       if (!(separator = (char *)find_closing_quote(contact_name, NULL))) {
19553          ast_log(LOG_NOTICE, "No closing quote on name in Contact header? %s\n", contact);
19554       }
19555       *separator = '\0';
19556    }
19557 
19558    if (name && !ast_strlen_zero(contact_name)) {
19559       *name = ast_strdup(contact_name);
19560    }
19561    if (number) {
19562       *number = ast_strdup(contact_number);
19563    }
19564 }
19565 
19566 /*! \brief Check pending actions on SIP call 
19567  *
19568  * \note both sip_pvt and sip_pvt's owner channel (if present)
19569  *  must be locked for this function.
19570  */
19571 static void check_pendings(struct sip_pvt *p)
19572 {
19573    if (ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
19574       /* if we can't BYE, then this is really a pending CANCEL */
19575       if (p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA) {
19576          p->invitestate = INV_CANCELLED;
19577          transmit_request(p, SIP_CANCEL, p->lastinvite, XMIT_RELIABLE, FALSE);
19578          /* Actually don't destroy us yet, wait for the 487 on our original
19579             INVITE, but do set an autodestruct just in case we never get it. */
19580       } else {
19581          /* We have a pending outbound invite, don't send something
19582             new in-transaction */
19583          if (p->pendinginvite)
19584             return;
19585 
19586          if (p->owner) {
19587             ast_softhangup_nolock(p->owner, AST_SOFTHANGUP_DEV);
19588          }
19589          /* Perhaps there is an SD change INVITE outstanding */
19590          transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, TRUE);
19591       }
19592       ast_clear_flag(&p->flags[0], SIP_PENDINGBYE);   
19593       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19594    } else if (ast_test_flag(&p->flags[0], SIP_NEEDREINVITE)) {
19595       /* if we can't REINVITE, hold it for later */
19596       if (p->pendinginvite || p->invitestate == INV_CALLING || p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA || p->waitid > 0) {
19597          ast_debug(2, "NOT Sending pending reinvite (yet) on '%s'\n", p->callid);
19598       } else {
19599          ast_debug(2, "Sending pending reinvite on '%s'\n", p->callid);
19600          /* Didn't get to reinvite yet, so do it now */
19601          transmit_reinvite_with_sdp(p, (p->t38.state == T38_LOCAL_REINVITE ? TRUE : FALSE), FALSE);
19602          ast_clear_flag(&p->flags[0], SIP_NEEDREINVITE); 
19603       }
19604    }
19605 }
19606 
19607 /*! \brief Reset the NEEDREINVITE flag after waiting when we get 491 on a Re-invite
19608    to avoid race conditions between asterisk servers.
19609    Called from the scheduler.
19610 */
19611 static int sip_reinvite_retry(const void *data)
19612 {
19613    struct sip_pvt *p = (struct sip_pvt *) data;
19614    struct ast_channel *owner;
19615 
19616    sip_pvt_lock(p); /* called from schedule thread which requires a lock */
19617    while ((owner = p->owner) && ast_channel_trylock(owner)) {
19618       sip_pvt_unlock(p);
19619       usleep(1);
19620       sip_pvt_lock(p);
19621    }
19622    ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
19623    p->waitid = -1;
19624    check_pendings(p);
19625    sip_pvt_unlock(p);
19626    if (owner) {
19627       ast_channel_unlock(owner);
19628    }
19629    dialog_unref(p, "unref the dialog ptr from sip_reinvite_retry, because it held a dialog ptr");
19630    return 0;
19631 }
19632 
19633 /*!
19634  * \brief Handle authentication challenge for SIP UPDATE
19635  *
19636  * This function is only called upon the receipt of a 401/407 response to an UPDATE.
19637  */
19638 static void handle_response_update(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno)
19639 {
19640    if (p->options) {
19641       p->options->auth_type = (resp == 401 ? WWW_AUTH : PROXY_AUTH);
19642    }
19643    if ((p->authtries == MAX_AUTHTRIES) || do_proxy_auth(p, req, resp, SIP_UPDATE, 1)) {
19644       ast_log(LOG_NOTICE, "Failed to authenticate on UPDATE to '%s'\n", get_header(&p->initreq, "From"));
19645    }
19646 }
19647 
19648 static void cc_handle_publish_error(struct sip_pvt *pvt, const int resp, struct sip_request *req, struct sip_epa_entry *epa_entry)
19649 {
19650    struct cc_epa_entry *cc_entry = epa_entry->instance_data;
19651    struct sip_monitor_instance *monitor_instance = ao2_callback(sip_monitor_instances, 0,
19652          find_sip_monitor_instance_by_suspension_entry, epa_entry);
19653    const char *min_expires;
19654 
19655    if (!monitor_instance) {
19656       ast_log(LOG_WARNING, "Can't find monitor_instance corresponding to epa_entry %p.\n", epa_entry);
19657       return;
19658    }
19659 
19660    if (resp != 423) {
19661       ast_cc_monitor_failed(cc_entry->core_id, monitor_instance->device_name,
19662             "Received error response to our PUBLISH");
19663       ao2_ref(monitor_instance, -1);
19664       return;
19665    }
19666 
19667    /* Allrighty, the other end doesn't like our Expires value. They think it's
19668     * too small, so let's see if they've provided a more sensible value. If they
19669     * haven't, then we'll just double our Expires value and see if they like that
19670     * instead.
19671     *
19672     * XXX Ideally this logic could be placed into its own function so that SUBSCRIBE,
19673     * PUBLISH, and REGISTER could all benefit from the same shared code.
19674     */
19675    min_expires = get_header(req, "Min-Expires");
19676    if (ast_strlen_zero(min_expires)) {
19677       pvt->expiry *= 2;
19678       if (pvt->expiry < 0) {
19679          /* You dork! You overflowed! */
19680          ast_cc_monitor_failed(cc_entry->core_id, monitor_instance->device_name,
19681                "PUBLISH expiry overflowed");
19682          ao2_ref(monitor_instance, -1);
19683          return;
19684       }
19685    } else if (sscanf(min_expires, "%d", &pvt->expiry) != 1) {
19686       ast_cc_monitor_failed(cc_entry->core_id, monitor_instance->device_name,
19687             "Min-Expires has non-numeric value");
19688       ao2_ref(monitor_instance, -1);
19689       return;
19690    }
19691    /* At this point, we have most certainly changed pvt->expiry, so try transmitting
19692     * again
19693     */
19694    transmit_invite(pvt, SIP_PUBLISH, FALSE, 0, NULL);
19695    ao2_ref(monitor_instance, -1);
19696 }
19697 
19698 static void handle_response_publish(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno)
19699 {
19700    struct sip_epa_entry *epa_entry = p->epa_entry;
19701    const char *etag = get_header(req, "Sip-ETag");
19702 
19703    ast_assert(epa_entry != NULL);
19704 
19705    if (resp == 401 || resp == 407) {
19706       ast_string_field_set(p, theirtag, NULL);
19707       if (p->options) {
19708          p->options->auth_type = (resp == 401 ? WWW_AUTH : PROXY_AUTH);
19709       }
19710       if ((p->authtries == MAX_AUTHTRIES) || do_proxy_auth(p, req, resp, SIP_PUBLISH, 0)) {
19711          ast_log(LOG_NOTICE, "Failed to authenticate on PUBLISH to '%s'\n", get_header(&p->initreq, "From"));
19712          pvt_set_needdestroy(p, "Failed to authenticate on PUBLISH");
19713          sip_alreadygone(p);
19714       }
19715       return;
19716    }
19717 
19718    if (resp == 501 || resp == 405) {
19719       mark_method_unallowed(&p->allowed_methods, SIP_PUBLISH);
19720    }
19721 
19722    if (resp == 200) {
19723       p->authtries = 0;
19724       /* If I've read section 6, item 6 of RFC 3903 correctly,
19725        * an ESC will only generate a new etag when it sends a 200 OK
19726        */
19727       if (!ast_strlen_zero(etag)) {
19728          ast_copy_string(epa_entry->entity_tag, etag, sizeof(epa_entry->entity_tag));
19729       }
19730       /* The nominal case. Everything went well. Everybody is happy.
19731        * Each EPA will have a specific action to take as a result of this
19732        * development, so ... callbacks!
19733        */
19734       if (epa_entry->static_data->handle_ok) {
19735          epa_entry->static_data->handle_ok(p, req, epa_entry);
19736       }
19737    } else {
19738       /* Rather than try to make individual callbacks for each error
19739        * type, there is just a single error callback. The callback
19740        * can distinguish between error messages and do what it needs to
19741        */
19742       if (epa_entry->static_data->handle_error) {
19743          epa_entry->static_data->handle_error(p, resp, req, epa_entry);
19744       }
19745    }
19746 }
19747 
19748 /*! \brief Handle SIP response to INVITE dialogue */
19749 static void handle_response_invite(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno)
19750 {
19751    int outgoing = ast_test_flag(&p->flags[0], SIP_OUTGOING);
19752    int res = 0;
19753    int xmitres = 0;
19754    int reinvite = (p->owner && p->owner->_state == AST_STATE_UP);
19755    char *p_hdrval;
19756    int rtn;
19757    struct ast_party_connected_line connected;
19758    struct ast_set_party_connected_line update_connected;
19759 
19760    if (reinvite)
19761       ast_debug(4, "SIP response %d to RE-invite on %s call %s\n", resp, outgoing ? "outgoing" : "incoming", p->callid);
19762    else
19763       ast_debug(4, "SIP response %d to standard invite\n", resp);
19764 
19765    if (p->alreadygone) { /* This call is already gone */
19766       ast_debug(1, "Got response on call that is already terminated: %s (ignoring)\n", p->callid);
19767       return;
19768    }
19769 
19770    /* Acknowledge sequence number - This only happens on INVITE from SIP-call */
19771    /* Don't auto congest anymore since we've gotten something useful back */
19772    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"));
19773 
19774    /* RFC3261 says we must treat every 1xx response (but not 100)
19775       that we don't recognize as if it was 183.
19776    */
19777    if (resp > 100 && resp < 200 && resp!=101 && resp != 180 && resp != 181 && resp != 182 && resp != 183)
19778       resp = 183;
19779 
19780    /* Any response between 100 and 199 is PROCEEDING */
19781    if (resp >= 100 && resp < 200 && p->invitestate == INV_CALLING)
19782       p->invitestate = INV_PROCEEDING;
19783 
19784    /* Final response, not 200 ? */
19785    if (resp >= 300 && (p->invitestate == INV_CALLING || p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA ))
19786       p->invitestate = INV_COMPLETED;
19787    
19788    /* Final response, clear out pending invite */
19789    if ((resp == 200 || resp >= 300) && p->pendinginvite && seqno == p->pendinginvite)
19790       p->pendinginvite = 0;
19791 
19792    /* If this is a response to our initial INVITE, we need to set what we can use
19793     * for this peer.
19794     */
19795    if (!reinvite) {
19796       set_pvt_allowed_methods(p, req);
19797    }     
19798 
19799    switch (resp) {
19800    case 100:   /* Trying */
19801    case 101:   /* Dialog establishment */
19802       if (!req->ignore && p->invitestate != INV_CANCELLED && sip_cancel_destroy(p))
19803          ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
19804       check_pendings(p);
19805       break;
19806 
19807    case 180:   /* 180 Ringing */
19808    case 182:       /* 182 Queued */
19809       if (!req->ignore && p->invitestate != INV_CANCELLED && sip_cancel_destroy(p))
19810          ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
19811       /* Store Route-set from provisional SIP responses so
19812        * early-dialog request can be routed properly
19813        * */
19814       parse_ok_contact(p, req);
19815       if (!reinvite) {
19816          build_route(p, req, 1);
19817       }
19818       if (!req->ignore && p->owner) {
19819          if (get_rpid(p, req)) {
19820             /* Queue a connected line update */
19821             ast_party_connected_line_init(&connected);
19822             memset(&update_connected, 0, sizeof(update_connected));
19823 
19824             update_connected.id.number = 1;
19825             connected.id.number.valid = 1;
19826             connected.id.number.str = (char *) p->cid_num;
19827             connected.id.number.presentation = p->callingpres;
19828 
19829             update_connected.id.name = 1;
19830             connected.id.name.valid = 1;
19831             connected.id.name.str = (char *) p->cid_name;
19832             connected.id.name.presentation = p->callingpres;
19833 
19834             connected.id.tag = (char *) p->cid_tag;
19835             connected.source = AST_CONNECTED_LINE_UPDATE_SOURCE_ANSWER;
19836             ast_channel_queue_connected_line_update(p->owner, &connected,
19837                &update_connected);
19838          }
19839          sip_handle_cc(p, req, AST_CC_CCNR);
19840          ast_queue_control(p->owner, AST_CONTROL_RINGING);
19841          if (p->owner->_state != AST_STATE_UP) {
19842             ast_setstate(p->owner, AST_STATE_RINGING);
19843          }
19844       }
19845       if (find_sdp(req)) {
19846          if (p->invitestate != INV_CANCELLED)
19847             p->invitestate = INV_EARLY_MEDIA;
19848          res = process_sdp(p, req, SDP_T38_NONE);
19849          if (!req->ignore && p->owner) {
19850             /* Queue a progress frame only if we have SDP in 180 or 182 */
19851             ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
19852          }
19853          ast_rtp_instance_activate(p->rtp);
19854       }
19855       check_pendings(p);
19856       break;
19857 
19858    case 181:   /* Call Is Being Forwarded */
19859       if (!req->ignore && (p->invitestate != INV_CANCELLED) && sip_cancel_destroy(p))
19860          ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
19861       /* Store Route-set from provisional SIP responses so
19862        * early-dialog request can be routed properly
19863        * */
19864       parse_ok_contact(p, req);
19865       if (!reinvite) {
19866          build_route(p, req, 1);
19867       }
19868       if (!req->ignore && p->owner) {
19869          struct ast_party_redirecting redirecting;
19870          struct ast_set_party_redirecting update_redirecting;
19871 
19872          ast_party_redirecting_init(&redirecting);
19873          memset(&update_redirecting, 0, sizeof(update_redirecting));
19874          change_redirecting_information(p, req, &redirecting, &update_redirecting,
19875             FALSE);
19876          ast_channel_queue_redirecting_update(p->owner, &redirecting,
19877             &update_redirecting);
19878          ast_party_redirecting_free(&redirecting);
19879          sip_handle_cc(p, req, AST_CC_CCNR);
19880       }
19881       check_pendings(p);
19882       break;
19883 
19884    case 183:   /* Session progress */
19885       if (!req->ignore && (p->invitestate != INV_CANCELLED) && sip_cancel_destroy(p))
19886          ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
19887       /* Store Route-set from provisional SIP responses so
19888        * early-dialog request can be routed properly
19889        * */
19890       parse_ok_contact(p, req);
19891       if (!reinvite) {
19892          build_route(p, req, 1);
19893       }
19894       if (!req->ignore && p->owner) {
19895          if (get_rpid(p, req)) {
19896             /* Queue a connected line update */
19897             ast_party_connected_line_init(&connected);
19898             memset(&update_connected, 0, sizeof(update_connected));
19899 
19900             update_connected.id.number = 1;
19901             connected.id.number.valid = 1;
19902             connected.id.number.str = (char *) p->cid_num;
19903             connected.id.number.presentation = p->callingpres;
19904 
19905             update_connected.id.name = 1;
19906             connected.id.name.valid = 1;
19907             connected.id.name.str = (char *) p->cid_name;
19908             connected.id.name.presentation = p->callingpres;
19909 
19910             connected.id.tag = (char *) p->cid_tag;
19911             connected.source = AST_CONNECTED_LINE_UPDATE_SOURCE_ANSWER;
19912             ast_channel_queue_connected_line_update(p->owner, &connected,
19913                &update_connected);
19914          }
19915          sip_handle_cc(p, req, AST_CC_CCNR);
19916       }
19917       if (find_sdp(req)) {
19918          if (p->invitestate != INV_CANCELLED)
19919             p->invitestate = INV_EARLY_MEDIA;
19920          res = process_sdp(p, req, SDP_T38_NONE);
19921          if (!req->ignore && p->owner) {
19922             /* Queue a progress frame */
19923             ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
19924          }
19925          ast_rtp_instance_activate(p->rtp);
19926       } else {
19927          /* Alcatel PBXs are known to send 183s with no SDP after sending
19928           * a 100 Trying response. We're just going to treat this sort of thing
19929           * the same as we would treat a 180 Ringing
19930           */
19931          if (!req->ignore && p->owner) {
19932             ast_queue_control(p->owner, AST_CONTROL_RINGING);
19933          }
19934       }
19935       check_pendings(p);
19936       break;
19937 
19938    case 200:   /* 200 OK on invite - someone's answering our call */
19939       if (!req->ignore && (p->invitestate != INV_CANCELLED) && sip_cancel_destroy(p))
19940          ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
19941       p->authtries = 0;
19942       if (find_sdp(req)) {
19943          if ((res = process_sdp(p, req, SDP_T38_ACCEPT)) && !req->ignore)
19944             if (!reinvite)
19945                /* This 200 OK's SDP is not acceptable, so we need to ack, then hangup */
19946                /* For re-invites, we try to recover */
19947                ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
19948          ast_rtp_instance_activate(p->rtp);
19949       }
19950 
19951       if (!req->ignore && p->owner) {
19952          int rpid_changed;
19953 
19954          rpid_changed = get_rpid(p, req);
19955          if (rpid_changed || !reinvite) {
19956             /* Queue a connected line update */
19957             ast_party_connected_line_init(&connected);
19958             memset(&update_connected, 0, sizeof(update_connected));
19959             if (rpid_changed
19960                || !ast_strlen_zero(p->cid_num)
19961                || (p->callingpres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED) {
19962                update_connected.id.number = 1;
19963                connected.id.number.valid = 1;
19964                connected.id.number.str = (char *) p->cid_num;
19965                connected.id.number.presentation = p->callingpres;
19966             }
19967             if (rpid_changed
19968                || !ast_strlen_zero(p->cid_name)
19969                || (p->callingpres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED) {
19970                update_connected.id.name = 1;
19971                connected.id.name.valid = 1;
19972                connected.id.name.str = (char *) p->cid_name;
19973                connected.id.name.presentation = p->callingpres;
19974             }
19975             if (update_connected.id.number || update_connected.id.name) {
19976                connected.id.tag = (char *) p->cid_tag;
19977                connected.source = AST_CONNECTED_LINE_UPDATE_SOURCE_ANSWER;
19978                ast_channel_queue_connected_line_update(p->owner, &connected,
19979                   &update_connected);
19980             }
19981          }
19982       }
19983 
19984       /* Parse contact header for continued conversation */
19985       /* When we get 200 OK, we know which device (and IP) to contact for this call */
19986       /* This is important when we have a SIP proxy between us and the phone */
19987       if (outgoing) {
19988          update_call_counter(p, DEC_CALL_RINGING);
19989          parse_ok_contact(p, req);
19990          /* Save Record-Route for any later requests we make on this dialogue */
19991          if (!reinvite)
19992             build_route(p, req, 1);
19993 
19994          if(set_address_from_contact(p)) {
19995             /* Bad contact - we don't know how to reach this device */
19996             /* We need to ACK, but then send a bye */
19997             if (!p->route && !req->ignore)
19998                ast_set_flag(&p->flags[0], SIP_PENDINGBYE);  
19999          }
20000 
20001       }
20002 
20003       if (!req->ignore && p->owner) {
20004          if (!reinvite) {
20005             ast_queue_control(p->owner, AST_CONTROL_ANSWER);
20006             if (sip_cfg.callevents)
20007                manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
20008                   "Channel: %s\r\nChanneltype: %s\r\nUniqueid: %s\r\nSIPcallid: %s\r\nSIPfullcontact: %s\r\nPeername: %s\r\n",
20009                   p->owner->name, "SIP", p->owner->uniqueid, p->callid, p->fullcontact, p->peername);
20010          } else { /* RE-invite */
20011             if (p->t38.state == T38_DISABLED) {
20012                ast_queue_control(p->owner, AST_CONTROL_UPDATE_RTP_PEER);
20013             } else {
20014                ast_queue_frame(p->owner, &ast_null_frame);
20015             }
20016          }
20017       } else {
20018           /* It's possible we're getting an 200 OK after we've tried to disconnect
20019               by sending CANCEL */
20020          /* First send ACK, then send bye */
20021          if (!req->ignore)
20022             ast_set_flag(&p->flags[0], SIP_PENDINGBYE);  
20023       }
20024 
20025       /* Check for Session-Timers related headers */
20026       if (st_get_mode(p, 0) != SESSION_TIMER_MODE_REFUSE && p->outgoing_call == TRUE && !reinvite) {
20027          p_hdrval = (char*)get_header(req, "Session-Expires");
20028          if (!ast_strlen_zero(p_hdrval)) {
20029             /* UAS supports Session-Timers */
20030             enum st_refresher tmp_st_ref = SESSION_TIMER_REFRESHER_AUTO;
20031             int tmp_st_interval = 0;
20032             rtn = parse_session_expires(p_hdrval, &tmp_st_interval, &tmp_st_ref);
20033             if (rtn != 0) {
20034                ast_set_flag(&p->flags[0], SIP_PENDINGBYE);  
20035             }
20036             if (tmp_st_ref == SESSION_TIMER_REFRESHER_UAC ||
20037                tmp_st_ref == SESSION_TIMER_REFRESHER_UAS) {
20038                p->stimer->st_ref = tmp_st_ref;
20039             }
20040             if (tmp_st_interval) {
20041                p->stimer->st_interval = tmp_st_interval;
20042             }
20043             p->stimer->st_active = TRUE;
20044             p->stimer->st_active_peer_ua = TRUE;
20045             start_session_timer(p);
20046          } else {
20047             /* UAS doesn't support Session-Timers */
20048             if (st_get_mode(p, 0) == SESSION_TIMER_MODE_ORIGINATE) {
20049                p->stimer->st_ref = SESSION_TIMER_REFRESHER_UAC;
20050                p->stimer->st_active_peer_ua = FALSE;
20051                start_session_timer(p);
20052             }
20053          }
20054       }
20055 
20056 
20057       /* If I understand this right, the branch is different for a non-200 ACK only */
20058       p->invitestate = INV_TERMINATED;
20059       ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
20060       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, TRUE);
20061       check_pendings(p);
20062       break;
20063 
20064    case 407: /* Proxy authentication */
20065    case 401: /* Www auth */
20066       /* First we ACK */
20067       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
20068       if (p->options)
20069          p->options->auth_type = resp;
20070 
20071       /* Then we AUTH */
20072       ast_string_field_set(p, theirtag, NULL);  /* forget their old tag, so we don't match tags when getting response */
20073       if (!req->ignore) {
20074          if (p->authtries < MAX_AUTHTRIES)
20075             p->invitestate = INV_CALLING;
20076          if (p->authtries == MAX_AUTHTRIES || do_proxy_auth(p, req, resp, SIP_INVITE, 1)) {
20077             ast_log(LOG_NOTICE, "Failed to authenticate on INVITE to '%s'\n", get_header(&p->initreq, "From"));
20078             pvt_set_needdestroy(p, "failed to authenticate on INVITE");
20079             sip_alreadygone(p);
20080             if (p->owner)
20081                ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
20082          }
20083       }
20084       break;
20085 
20086    case 403: /* Forbidden */
20087       /* First we ACK */
20088       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
20089       ast_log(LOG_WARNING, "Received response: \"Forbidden\" from '%s'\n", get_header(&p->initreq, "From"));
20090       if (!req->ignore && p->owner) {
20091          ast_set_hangupsource(p->owner, p->owner->name, 0);
20092          ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
20093       }
20094       pvt_set_needdestroy(p, "received 403 response");
20095       sip_alreadygone(p);
20096       break;
20097 
20098    case 404: /* Not found */
20099       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
20100       if (p->owner && !req->ignore) {
20101          ast_set_hangupsource(p->owner, p->owner->name, 0);
20102          ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
20103       }
20104       sip_alreadygone(p);
20105       break;
20106 
20107    case 408: /* Request timeout */
20108    case 481: /* Call leg does not exist */
20109       /* Could be REFER caused INVITE with replaces */
20110       ast_log(LOG_WARNING, "Re-invite to non-existing call leg on other UA. SIP dialog '%s'. Giving up.\n", p->callid);
20111       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
20112       if (p->owner)
20113          ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
20114       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20115       break;
20116 
20117    case 422: /* Session-Timers: Session interval too small */
20118       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
20119       ast_string_field_set(p, theirtag, NULL);
20120       proc_422_rsp(p, req);
20121       break;
20122 
20123    case 428: /* Use identity header - rfc 4474 - not supported by Asterisk yet */
20124       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
20125       append_history(p, "Identity", "SIP identity is required. Not supported by Asterisk.");
20126       ast_log(LOG_WARNING, "SIP identity required by proxy. SIP dialog '%s'. Giving up.\n", p->callid);
20127       if (p->owner)
20128          ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
20129       break;
20130 
20131       
20132 
20133    case 487: /* Cancelled transaction */
20134       /* We have sent CANCEL on an outbound INVITE
20135          This transaction is already scheduled to be killed by sip_hangup().
20136       */
20137       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
20138       if (p->owner && !req->ignore) {
20139          ast_queue_hangup_with_cause(p->owner, AST_CAUSE_NORMAL_CLEARING);
20140          append_history(p, "Hangup", "Got 487 on CANCEL request from us. Queued AST hangup request");
20141       } else if (!req->ignore) {
20142          update_call_counter(p, DEC_CALL_LIMIT);
20143          append_history(p, "Hangup", "Got 487 on CANCEL request from us on call without owner. Killing this dialog.");
20144          pvt_set_needdestroy(p, "received 487 response");
20145          sip_alreadygone(p);
20146       }
20147       break;
20148    case 415: /* Unsupported media type */
20149    case 488: /* Not acceptable here */
20150    case 606: /* Not Acceptable */
20151       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
20152       if (p->udptl && p->t38.state == T38_LOCAL_REINVITE) {
20153          change_t38_state(p, T38_DISABLED);
20154          /* Try to reset RTP timers */
20155          //ast_rtp_set_rtptimers_onhold(p->rtp);
20156 
20157          /* Trigger a reinvite back to audio */
20158          transmit_reinvite_with_sdp(p, FALSE, FALSE);
20159       } else {
20160          /* We can't set up this call, so give up */
20161          if (p->owner && !req->ignore)
20162             ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
20163          pvt_set_needdestroy(p, "received 488 response");
20164          /* If there's no dialog to end, then mark p as already gone */
20165          if (!reinvite)
20166             sip_alreadygone(p);
20167       }
20168       break;
20169    case 491: /* Pending */
20170       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
20171       if (p->owner && !req->ignore) {
20172          if (p->owner->_state != AST_STATE_UP) {
20173             ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
20174             pvt_set_needdestroy(p, "received 491 response");
20175          } else {
20176             /* This is a re-invite that failed. */
20177             /* Reset the flag after a while
20178              */
20179             int wait;
20180             /* RFC 3261, if owner of call, wait between 2.1 to 4 seconds,
20181              * if not owner of call, wait 0 to 2 seconds */
20182             if (p->outgoing_call) {
20183                wait = 2100 + ast_random() % 2000;
20184             } else {
20185                wait = ast_random() % 2000;
20186             }
20187             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."));
20188             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);
20189             ast_debug(2, "Reinvite race. Waiting %d secs before retry\n", wait);
20190          }
20191       }
20192       break;
20193 
20194    case 405: /* Not allowed */
20195    case 501: /* Not implemented */
20196       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
20197       if (p->owner)
20198          ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
20199       break;
20200    }
20201    if (xmitres == XMIT_ERROR)
20202       ast_log(LOG_WARNING, "Could not transmit message in dialog %s\n", p->callid);
20203 }
20204 
20205 /* \brief Handle SIP response in NOTIFY transaction
20206        We've sent a NOTIFY, now handle responses to it
20207   */
20208 static void handle_response_notify(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno)
20209 {
20210    switch (resp) {
20211    case 200:   /* Notify accepted */
20212       /* They got the notify, this is the end */
20213       if (p->owner) {
20214          if (p->refer) {
20215             ast_log(LOG_NOTICE, "Got OK on REFER Notify message\n");
20216          } else {
20217             ast_log(LOG_WARNING, "Notify answer on an owned channel? - %s\n", p->owner->name);
20218             /*
20219              * XXX There is discrepancy on whether a hangup should be queued
20220              * or not. This code used to be duplicated in two places, and the more
20221              * frequently hit area had this disabled, making it the de facto
20222              * "correct" way to go.
20223              *
20224              * ast_queue_hangup_with_cause(p->owner, AST_CAUSE_NORMAL_UNSPECIFIED);
20225              */
20226          }
20227       } else {
20228          if (p->subscribed == NONE && !p->refer) {
20229             ast_debug(4, "Got 200 accepted on NOTIFY %s\n", p->callid);
20230             pvt_set_needdestroy(p, "received 200 response");
20231          }
20232          if (ast_test_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE)) {
20233             /* Ready to send the next state we have on queue */
20234             ast_clear_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE);
20235             cb_extensionstate((char *)p->context, (char *)p->exten, p->laststate, (void *) p);
20236          }
20237       }
20238       break;
20239    case 401:   /* Not www-authorized on SIP method */
20240    case 407:   /* Proxy auth */
20241       if (!p->notify) {
20242          break; /* Only device notify can use NOTIFY auth */
20243       }
20244       ast_string_field_set(p, theirtag, NULL);
20245       if (ast_strlen_zero(p->authname)) {
20246          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));
20247          pvt_set_needdestroy(p, "unable to authenticate NOTIFY");
20248       }
20249       if (p->authtries > 1 || do_proxy_auth(p, req, resp, SIP_NOTIFY, 0)) {
20250          ast_log(LOG_NOTICE, "Failed to authenticate on NOTIFY to '%s'\n", get_header(&p->initreq, "From"));
20251          pvt_set_needdestroy(p, "failed to authenticate NOTIFY");
20252       }
20253       break;
20254    case 481: /* Call leg does not exist */
20255       pvt_set_needdestroy(p, "Received 481 response for NOTIFY");
20256       break;
20257    }
20258 }
20259 
20260 /* \brief Handle SIP response in SUBSCRIBE transaction */
20261 static void handle_response_subscribe(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno)
20262 {
20263    if (p->subscribed == CALL_COMPLETION) {
20264       struct sip_monitor_instance *monitor_instance;
20265 
20266       if (resp < 300) {
20267          return;
20268       }
20269 
20270       /* Final failure response received. */
20271       monitor_instance = ao2_callback(sip_monitor_instances, 0,
20272          find_sip_monitor_instance_by_subscription_pvt, p);
20273       if (monitor_instance) {
20274          ast_cc_monitor_failed(monitor_instance->core_id,
20275             monitor_instance->device_name,
20276             "Received error response to our SUBSCRIBE");
20277       }
20278       return;
20279    }
20280 
20281    if (p->subscribed != MWI_NOTIFICATION) {
20282       return;
20283    }
20284    if (!p->mwi) {
20285       return;
20286    }
20287 
20288    switch (resp) {
20289    case 200: /* Subscription accepted */
20290       ast_debug(3, "Got 200 OK on subscription for MWI\n");
20291       set_pvt_allowed_methods(p, req);
20292       if (p->options) {
20293          ast_free(p->options);
20294          p->options = NULL;
20295       }
20296       p->mwi->subscribed = 1;
20297       if ((p->mwi->resub = ast_sched_add(sched, mwi_expiry * 1000, sip_subscribe_mwi_do, ASTOBJ_REF(p->mwi))) < 0) {
20298          ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
20299       }
20300       break;
20301    case 401:
20302    case 407:
20303       ast_string_field_set(p, theirtag, NULL);
20304       if (p->authtries > 1 || do_proxy_auth(p, req, resp, SIP_SUBSCRIBE, 0)) {
20305          ast_log(LOG_NOTICE, "Failed to authenticate on SUBSCRIBE to '%s'\n", get_header(&p->initreq, "From"));
20306          p->mwi->call = NULL;
20307          ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
20308          pvt_set_needdestroy(p, "failed to authenticate SUBSCRIBE");
20309       }
20310       break;
20311    case 403:
20312       transmit_response_with_date(p, "200 OK", req);
20313       ast_log(LOG_WARNING, "Authentication failed while trying to subscribe for MWI.\n");
20314       p->mwi->call = NULL;
20315       ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
20316       pvt_set_needdestroy(p, "received 403 response");
20317       sip_alreadygone(p);
20318       break;
20319    case 404:
20320       ast_log(LOG_WARNING, "Subscription failed for MWI. The remote side said that a mailbox may not have been configured.\n");
20321       p->mwi->call = NULL;
20322       ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
20323       pvt_set_needdestroy(p, "received 404 response");
20324       break;
20325    case 481:
20326       ast_log(LOG_WARNING, "Subscription failed for MWI. The remote side said that our dialog did not exist.\n");
20327       p->mwi->call = NULL;
20328       ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
20329       pvt_set_needdestroy(p, "received 481 response");
20330       break;
20331    case 500:
20332    case 501:
20333       ast_log(LOG_WARNING, "Subscription failed for MWI. The remote side may have suffered a heart attack.\n");
20334       p->mwi->call = NULL;
20335       ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
20336       pvt_set_needdestroy(p, "received 500/501 response");
20337       break;
20338    }
20339 }
20340 
20341 /* \brief Handle SIP response in REFER transaction
20342    We've sent a REFER, now handle responses to it
20343   */
20344 static void handle_response_refer(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno)
20345 {
20346    enum ast_control_transfer message = AST_TRANSFER_FAILED;
20347 
20348    /* If no refer structure exists, then do nothing */
20349    if (!p->refer)
20350       return;
20351 
20352    switch (resp) {
20353    case 202:   /* Transfer accepted */
20354       /* We need  to do something here */
20355       /* The transferee is now sending INVITE to target */
20356       p->refer->status = REFER_ACCEPTED;
20357       /* Now wait for next message */
20358       ast_debug(3, "Got 202 accepted on transfer\n");
20359       /* We should hang along, waiting for NOTIFY's here */
20360       break;
20361 
20362    case 401:   /* Not www-authorized on SIP method */
20363    case 407:   /* Proxy auth */
20364       if (ast_strlen_zero(p->authname)) {
20365          ast_log(LOG_WARNING, "Asked to authenticate REFER to %s but we have no matching peer or realm auth!\n",
20366             ast_sockaddr_stringify(&p->recv));
20367          if (p->owner) {
20368             ast_queue_control_data(p->owner, AST_CONTROL_TRANSFER, &message, sizeof(message));
20369          }
20370          pvt_set_needdestroy(p, "unable to authenticate REFER");
20371       }
20372       if (p->authtries > 1 || do_proxy_auth(p, req, resp, SIP_REFER, 0)) {
20373          ast_log(LOG_NOTICE, "Failed to authenticate on REFER to '%s'\n", get_header(&p->initreq, "From"));
20374          p->refer->status = REFER_NOAUTH;
20375          if (p->owner) {
20376             ast_queue_control_data(p->owner, AST_CONTROL_TRANSFER, &message, sizeof(message));
20377          }
20378          pvt_set_needdestroy(p, "failed to authenticate REFER");
20379       }
20380       break;
20381    
20382    case 405:   /* Method not allowed */
20383       /* Return to the current call onhold */
20384       /* Status flag needed to be reset */
20385       ast_log(LOG_NOTICE, "SIP transfer to %s failed, REFER not allowed. \n", p->refer->refer_to);
20386       pvt_set_needdestroy(p, "received 405 response");
20387       p->refer->status = REFER_FAILED;
20388       if (p->owner) {
20389          ast_queue_control_data(p->owner, AST_CONTROL_TRANSFER, &message, sizeof(message));
20390       }
20391       break;
20392 
20393    case 481: /* Call leg does not exist */
20394 
20395       /* A transfer with Replaces did not work */
20396       /* OEJ: We should Set flag, cancel the REFER, go back
20397       to original call - but right now we can't */
20398       ast_log(LOG_WARNING, "Remote host can't match REFER request to call '%s'. Giving up.\n", p->callid);
20399       if (p->owner)
20400          ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
20401       pvt_set_needdestroy(p, "received 481 response");
20402       break;
20403 
20404    case 500:   /* Server error */
20405    case 501:   /* Method not implemented */
20406       /* Return to the current call onhold */
20407       /* Status flag needed to be reset */
20408       ast_log(LOG_NOTICE, "SIP transfer to %s failed, call miserably fails. \n", p->refer->refer_to);
20409       pvt_set_needdestroy(p, "received 500/501 response");
20410       p->refer->status = REFER_FAILED;
20411       if (p->owner) {
20412          ast_queue_control_data(p->owner, AST_CONTROL_TRANSFER, &message, sizeof(message));
20413       }
20414       break;
20415    case 603:   /* Transfer declined */
20416       ast_log(LOG_NOTICE, "SIP transfer to %s declined, call miserably fails. \n", p->refer->refer_to);
20417       p->refer->status = REFER_FAILED;
20418       pvt_set_needdestroy(p, "received 603 response");
20419       if (p->owner) {
20420          ast_queue_control_data(p->owner, AST_CONTROL_TRANSFER, &message, sizeof(message));
20421       }
20422       break;
20423    default:
20424       /* We should treat unrecognized 9xx as 900.  400 is actually
20425          specified as a possible response, but any 4-6xx is 
20426          theoretically possible. */
20427 
20428       if (resp < 299) { /* 1xx cases don't get here */
20429          ast_log(LOG_WARNING, "SIP transfer to %s had unxpected 2xx response (%d), confusion is possible. \n", p->refer->refer_to, resp);
20430       } else {
20431          ast_log(LOG_WARNING, "SIP transfer to %s with response (%d). \n", p->refer->refer_to, resp);
20432       }
20433 
20434       p->refer->status = REFER_FAILED;
20435       pvt_set_needdestroy(p, "received failure response");
20436       if (p->owner) {
20437          ast_queue_control_data(p->owner, AST_CONTROL_TRANSFER, &message, sizeof(message));
20438       }
20439       break;
20440    }
20441 }
20442 
20443 /*! \brief Handle responses on REGISTER to services */
20444 static int handle_response_register(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno)
20445 {
20446    int expires, expires_ms;
20447    struct sip_registry *r;
20448    r=p->registry;
20449    
20450    switch (resp) {
20451    case 401:   /* Unauthorized */
20452       if (p->authtries == MAX_AUTHTRIES || do_register_auth(p, req, resp)) {
20453          ast_log(LOG_NOTICE, "Failed to authenticate on REGISTER to '%s@%s' (Tries %d)\n", p->registry->username, p->registry->hostname, p->authtries);
20454          pvt_set_needdestroy(p, "failed to authenticate REGISTER");
20455       }
20456       break;
20457    case 403:   /* Forbidden */
20458       ast_log(LOG_WARNING, "Forbidden - wrong password on authentication for REGISTER for '%s' to '%s'\n", p->registry->username, p->registry->hostname);
20459       AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 403"));
20460       r->regstate = REG_STATE_NOAUTH;
20461       pvt_set_needdestroy(p, "received 403 response");
20462       break;
20463    case 404:   /* Not found */
20464       ast_log(LOG_WARNING, "Got 404 Not found on SIP register to service %s@%s, giving up\n", p->registry->username, p->registry->hostname);
20465       pvt_set_needdestroy(p, "received 404 response");
20466       if (r->call)
20467          r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 404");
20468       r->regstate = REG_STATE_REJECTED;
20469       AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 404"));
20470       break;
20471    case 407:   /* Proxy auth */
20472       if (p->authtries == MAX_AUTHTRIES || do_register_auth(p, req, resp)) {
20473          ast_log(LOG_NOTICE, "Failed to authenticate on REGISTER to '%s' (tries '%d')\n", get_header(&p->initreq, "From"), p->authtries);
20474          pvt_set_needdestroy(p, "failed to authenticate REGISTER");
20475       }
20476       break;
20477    case 408:   /* Request timeout */
20478       /* Got a timeout response, so reset the counter of failed responses */
20479       if (r) {
20480          r->regattempts = 0;
20481       } else {
20482          ast_log(LOG_WARNING, "Got a 408 response to our REGISTER on call %s after we had destroyed the registry object\n", p->callid);
20483       }
20484       break;
20485    case 423:   /* Interval too brief */
20486       r->expiry = atoi(get_header(req, "Min-Expires"));
20487       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);
20488       AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 423"));
20489       if (r->call) {
20490          r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 423");
20491          pvt_set_needdestroy(p, "received 423 response");
20492       }
20493       if (r->expiry > max_expiry) {
20494          ast_log(LOG_WARNING, "Required expiration time from %s@%s is too high, giving up\n", p->registry->username, p->registry->hostname);
20495          r->expiry = r->configured_expiry;
20496          r->regstate = REG_STATE_REJECTED;
20497       } else {
20498          r->regstate = REG_STATE_UNREGISTERED;
20499          transmit_register(r, SIP_REGISTER, NULL, NULL);
20500       }
20501       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));
20502       break;
20503    case 479:   /* SER: Not able to process the URI - address is wrong in register*/
20504       ast_log(LOG_WARNING, "Got error 479 on register to %s@%s, giving up (check config)\n", p->registry->username, p->registry->hostname);
20505       pvt_set_needdestroy(p, "received 479 response");
20506       if (r->call)
20507          r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 479");
20508       r->regstate = REG_STATE_REJECTED;
20509       AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 479"));
20510       break;
20511    case 200:   /* 200 OK */
20512       if (!r) {
20513          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));
20514          pvt_set_needdestroy(p, "received erroneous 200 response");
20515          return 0;
20516       }
20517       
20518       r->regstate = REG_STATE_REGISTERED;
20519       r->regtime = ast_tvnow();     /* Reset time of last successful registration */
20520       manager_event(EVENT_FLAG_SYSTEM, "Registry", "ChannelType: SIP\r\nDomain: %s\r\nStatus: %s\r\n", r->hostname, regstate2str(r->regstate));
20521       r->regattempts = 0;
20522       ast_debug(1, "Registration successful\n");
20523       if (r->timeout > -1) {
20524          ast_debug(1, "Cancelling timeout %d\n", r->timeout);
20525       }
20526       AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 200"));
20527       if (r->call)
20528          r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 200");
20529       p->registry = registry_unref(p->registry, "unref registry entry p->registry");
20530       /* Let this one hang around until we have all the responses */
20531       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20532       /* p->needdestroy = 1; */
20533       
20534       /* set us up for re-registering
20535        * figure out how long we got registered for
20536        * according to section 6.13 of RFC, contact headers override
20537        * expires headers, so check those first */
20538       expires = 0;
20539 
20540       /* XXX todo: try to save the extra call */
20541       if (!ast_strlen_zero(get_header(req, "Contact"))) {
20542          const char *contact = NULL;
20543          const char *tmptmp = NULL;
20544          int start = 0;
20545          for(;;) {
20546             contact = __get_header(req, "Contact", &start);
20547             /* this loop ensures we get a contact header about our register request */
20548             if(!ast_strlen_zero(contact)) {
20549                if( (tmptmp=strstr(contact, p->our_contact))) {
20550                   contact=tmptmp;
20551                   break;
20552                }
20553             } else
20554                break;
20555          }
20556          tmptmp = strcasestr(contact, "expires=");
20557          if (tmptmp) {
20558             if (sscanf(tmptmp + 8, "%30d;", &expires) != 1)
20559                expires = 0;
20560          }
20561          
20562       }
20563       if (!expires)
20564          expires=atoi(get_header(req, "expires"));
20565       if (!expires)
20566          expires=default_expiry;
20567       
20568       expires_ms = expires * 1000;
20569       if (expires <= EXPIRY_GUARD_LIMIT)
20570          expires_ms -= MAX((expires_ms * EXPIRY_GUARD_PCT), EXPIRY_GUARD_MIN);
20571       else
20572          expires_ms -= EXPIRY_GUARD_SECS * 1000;
20573       if (sipdebug)
20574          ast_log(LOG_NOTICE, "Outbound Registration: Expiry for %s is %d sec (Scheduling reregistration in %d s)\n", r->hostname, expires, expires_ms/1000);
20575       
20576       r->refresh= (int) expires_ms / 1000;
20577       
20578       /* Schedule re-registration before we expire */
20579       AST_SCHED_REPLACE_UNREF(r->expire, sched, expires_ms, sip_reregister, r,
20580                         registry_unref(_data,"unref in REPLACE del fail"),
20581                         registry_unref(r,"unref in REPLACE add fail"),
20582                         registry_addref(r,"The Addition side of REPLACE"));
20583    }
20584    return 1;
20585 }
20586 
20587 /*! \brief Handle qualification responses (OPTIONS) */
20588 static void handle_response_peerpoke(struct sip_pvt *p, int resp, struct sip_request *req)
20589 {
20590    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! */
20591    int statechanged, is_reachable, was_reachable;
20592    int pingtime = ast_tvdiff_ms(ast_tvnow(), peer->ps);
20593 
20594    /*
20595     * Compute the response time to a ping (goes in peer->lastms.)
20596     * -1 means did not respond, 0 means unknown,
20597     * 1..maxms is a valid response, >maxms means late response.
20598     */
20599    if (pingtime < 1) {  /* zero = unknown, so round up to 1 */
20600       pingtime = 1;
20601    }
20602 
20603    if (!peer->maxms) { /* this should never happens */
20604       pvt_set_needdestroy(p, "got OPTIONS response but qualify is not enabled");
20605       return;
20606    }
20607 
20608    /* Now determine new state and whether it has changed.
20609     * Use some helper variables to simplify the writing
20610     * of the expressions.
20611     */
20612    was_reachable = peer->lastms > 0 && peer->lastms <= peer->maxms;
20613    is_reachable = pingtime <= peer->maxms;
20614    statechanged = peer->lastms == 0 /* yes, unknown before */
20615       || was_reachable != is_reachable;
20616 
20617    peer->lastms = pingtime;
20618    peer->call = dialog_unref(peer->call, "unref dialog peer->call");
20619    if (statechanged) {
20620       const char *s = is_reachable ? "Reachable" : "Lagged";
20621       char str_lastms[20];
20622       snprintf(str_lastms, sizeof(str_lastms), "%d", pingtime);
20623 
20624       ast_log(LOG_NOTICE, "Peer '%s' is now %s. (%dms / %dms)\n",
20625          peer->name, s, pingtime, peer->maxms);
20626       ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", peer->name);
20627       if (sip_cfg.peer_rtupdate) {
20628          ast_update_realtime(ast_check_realtime("sipregs") ? "sipregs" : "sippeers", "name", peer->name, "lastms", str_lastms, SENTINEL);
20629       }
20630       manager_event(EVENT_FLAG_SYSTEM, "PeerStatus",
20631          "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: %s\r\nTime: %d\r\n",
20632          peer->name, s, pingtime);
20633       if (is_reachable && sip_cfg.regextenonqualify)
20634          register_peer_exten(peer, TRUE);
20635    }
20636 
20637    pvt_set_needdestroy(p, "got OPTIONS response");
20638 
20639    /* Try again eventually */
20640    AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched,
20641          is_reachable ? peer->qualifyfreq : DEFAULT_FREQ_NOTOK,
20642          sip_poke_peer_s, peer,
20643          unref_peer(_data, "removing poke peer ref"),
20644          unref_peer(peer, "removing poke peer ref"),
20645          ref_peer(peer, "adding poke peer ref"));
20646 }
20647 
20648 /*!
20649  * \internal
20650  * \brief Handle responses to INFO messages
20651  *
20652  * \note The INFO method MUST NOT change the state of calls or
20653  * related sessions (RFC 2976).
20654  */
20655 static void handle_response_info(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno)
20656 {
20657    int sipmethod = SIP_INFO;
20658 
20659    switch (resp) {
20660    case 401: /* Not www-authorized on SIP method */
20661    case 407: /* Proxy auth required */
20662       ast_log(LOG_WARNING, "Host '%s' requests authentication (%d) for '%s'\n",
20663          ast_sockaddr_stringify(&p->sa), resp, sip_methods[sipmethod].text);
20664       break;
20665    case 405: /* Method not allowed */
20666    case 501: /* Not Implemented */
20667       mark_method_unallowed(&p->allowed_methods, sipmethod);
20668       if (p->relatedpeer) {
20669          mark_method_allowed(&p->relatedpeer->disallowed_methods, sipmethod);
20670       }
20671       ast_log(LOG_WARNING, "Host '%s' does not implement '%s'\n",
20672          ast_sockaddr_stringify(&p->sa), sip_methods[sipmethod].text);
20673       break;
20674    default:
20675       if (300 <= resp && resp < 700) {
20676          ast_verb(3, "Got SIP %s response %d \"%s\" back from host '%s'\n",
20677             sip_methods[sipmethod].text, resp, rest, ast_sockaddr_stringify(&p->sa));
20678       }
20679       break;
20680    }
20681 }
20682 
20683 /*!
20684  * \internal
20685  * \brief Handle responses to MESSAGE messages
20686  *
20687  * \note The MESSAGE method should not change the state of calls
20688  * or related sessions if associated with a dialog. (Implied by
20689  * RFC 3428 Section 2).
20690  */
20691 static void handle_response_message(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno)
20692 {
20693    int sipmethod = SIP_MESSAGE;
20694    /* Out-of-dialog MESSAGE currently not supported. */
20695    //int in_dialog = ast_test_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
20696 
20697    switch (resp) {
20698    case 401: /* Not www-authorized on SIP method */
20699    case 407: /* Proxy auth required */
20700       ast_log(LOG_WARNING, "Host '%s' requests authentication (%d) for '%s'\n",
20701          ast_sockaddr_stringify(&p->sa), resp, sip_methods[sipmethod].text);
20702       break;
20703    case 405: /* Method not allowed */
20704    case 501: /* Not Implemented */
20705       mark_method_unallowed(&p->allowed_methods, sipmethod);
20706       if (p->relatedpeer) {
20707          mark_method_allowed(&p->relatedpeer->disallowed_methods, sipmethod);
20708       }
20709       ast_log(LOG_WARNING, "Host '%s' does not implement '%s'\n",
20710          ast_sockaddr_stringify(&p->sa), sip_methods[sipmethod].text);
20711       break;
20712    default:
20713       if (100 <= resp && resp < 200) {
20714          /* Must allow provisional responses for out-of-dialog requests. */
20715       } else if (200 <= resp && resp < 300) {
20716          p->authtries = 0; /* Reset authentication counter */
20717       } else if (300 <= resp && resp < 700) {
20718          ast_verb(3, "Got SIP %s response %d \"%s\" back from host '%s'\n",
20719             sip_methods[sipmethod].text, resp, rest, ast_sockaddr_stringify(&p->sa));
20720       }
20721       break;
20722    }
20723 }
20724 
20725 /*! \brief Immediately stop RTP, VRTP and UDPTL as applicable */
20726 static void stop_media_flows(struct sip_pvt *p)
20727 {
20728    /* Immediately stop RTP, VRTP and UDPTL as applicable */
20729    if (p->rtp)
20730       ast_rtp_instance_stop(p->rtp);
20731    if (p->vrtp)
20732       ast_rtp_instance_stop(p->vrtp);
20733    if (p->trtp)
20734       ast_rtp_instance_stop(p->trtp);
20735    if (p->udptl)
20736       ast_udptl_stop(p->udptl);
20737 }
20738 
20739 /*! \brief Handle SIP response in dialogue
20740    \note only called by handle_incoming */
20741 static void handle_response(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno)
20742 {
20743    struct ast_channel *owner;
20744    int sipmethod;
20745    const char *c = get_header(req, "Cseq");
20746    /* 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 */
20747    char *c_copy = ast_strdupa(c);
20748    /* Skip the Cseq and its subsequent spaces */
20749    const char *msg = ast_skip_blanks(ast_skip_nonblanks(c_copy));
20750 
20751    if (!msg)
20752       msg = "";
20753 
20754    sipmethod = find_sip_method(msg);
20755 
20756    owner = p->owner;
20757    if (owner) {
20758       const char *rp = NULL, *rh = NULL;
20759 
20760       owner->hangupcause = 0;
20761       if (ast_test_flag(&p->flags[1], SIP_PAGE2_Q850_REASON) && (rh = get_header(req, "Reason"))) {
20762          rh = ast_skip_blanks(rh);
20763          if (!strncasecmp(rh, "Q.850", 5)) {
20764             rp = strstr(rh, "cause=");
20765             if (rp && sscanf(rp + 6, "%30d", &owner->hangupcause) == 1) {
20766                owner->hangupcause &= 0x7f;
20767                if (req->debug)
20768                   ast_verbose("Using Reason header for cause code: %d\n", owner->hangupcause);
20769             }
20770          }
20771       }
20772 
20773       if (!owner->hangupcause)
20774          owner->hangupcause = hangup_sip2cause(resp);
20775    }
20776 
20777    if (p->socket.type == SIP_TRANSPORT_UDP) {
20778       int ack_res = FALSE;
20779 
20780       /* Acknowledge whatever it is destined for */
20781       if ((resp >= 100) && (resp <= 199)) {
20782          /* NON-INVITE messages do not ack a 1XX response. RFC 3261 section 17.1.2.2 */
20783          if (sipmethod == SIP_INVITE) {
20784             ack_res = __sip_semi_ack(p, seqno, 0, sipmethod);
20785          }
20786       } else {
20787          ack_res = __sip_ack(p, seqno, 0, sipmethod);
20788       }
20789 
20790       if (ack_res == FALSE) {
20791          /* RFC 3261 13.2.2.4 and 17.1.1.2 - We must re-send ACKs to re-transmitted final responses */
20792          if (sipmethod == SIP_INVITE && resp >= 200) {
20793             transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, resp < 300 ? TRUE: FALSE);
20794          }
20795 
20796          append_history(p, "Ignore", "Ignoring this retransmit\n");
20797          return;
20798       }
20799    }
20800 
20801    /* If this is a NOTIFY for a subscription clear the flag that indicates that we have a NOTIFY pending */
20802    if (!p->owner && sipmethod == SIP_NOTIFY && p->pendinginvite)
20803       p->pendinginvite = 0;
20804 
20805    /* Get their tag if we haven't already */
20806    if (ast_strlen_zero(p->theirtag) || (resp >= 200)) {
20807       char tag[128];
20808 
20809       gettag(req, "To", tag, sizeof(tag));
20810       ast_string_field_set(p, theirtag, tag);
20811    }
20812    /* This needs to be configurable on a channel/peer level,
20813       not mandatory for all communication. Sadly enough, NAT implementations
20814       are not so stable so we can always rely on these headers.
20815       Temporarily disabled, while waiting for fix.
20816       Fix assigned to Rizzo :-)
20817    */
20818    /* check_via_response(p, req); */
20819 
20820    /* RFC 3261 Section 15 specifies that if we receive a 408 or 481
20821     * in response to a BYE, then we should end the current dialog
20822     * and session.  It is known that at least one phone manufacturer
20823     * potentially will send a 404 in response to a BYE, so we'll be
20824     * liberal in what we accept and end the dialog and session if we
20825     * receive any of those responses to a BYE.
20826     */
20827    if ((resp == 404 || resp == 408 || resp == 481) && sipmethod == SIP_BYE) {
20828       pvt_set_needdestroy(p, "received 4XX response to a BYE");
20829       return;
20830    }
20831 
20832    if (p->relatedpeer && sipmethod == SIP_OPTIONS) {
20833       /* We don't really care what the response is, just that it replied back.
20834          Well, as long as it's not a 100 response...  since we might
20835          need to hang around for something more "definitive" */
20836       if (resp != 100)
20837          handle_response_peerpoke(p, resp, req);
20838    } else if (sipmethod == SIP_REFER && resp >= 200) {
20839       handle_response_refer(p, resp, rest, req, seqno);
20840    } else if (sipmethod == SIP_PUBLISH) {
20841       /* SIP PUBLISH transcends this morass of doodoo and instead
20842        * we just always call the response handler. Good gravy!
20843        */
20844       handle_response_publish(p, resp, rest, req, seqno);
20845    } else if (sipmethod == SIP_INFO) {
20846       /* More good gravy! */
20847       handle_response_info(p, resp, rest, req, seqno);
20848    } else if (sipmethod == SIP_MESSAGE) {
20849       /* More good gravy! */
20850       handle_response_message(p, resp, rest, req, seqno);
20851    } else if (sipmethod == SIP_NOTIFY) {
20852       /* The gravy train continues to roll */
20853       handle_response_notify(p, resp, rest, req, seqno);
20854    } else if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
20855       switch(resp) {
20856       case 100:   /* 100 Trying */
20857       case 101:   /* 101 Dialog establishment */
20858       case 183:   /* 183 Session Progress */
20859       case 180:   /* 180 Ringing */
20860       case 182:   /* 182 Queued */
20861       case 181:   /* 181 Call Is Being Forwarded */
20862          if (sipmethod == SIP_INVITE)
20863             handle_response_invite(p, resp, rest, req, seqno);
20864          break;
20865       case 200:   /* 200 OK */
20866          p->authtries = 0; /* Reset authentication counter */
20867          if (sipmethod == SIP_INVITE) {
20868             handle_response_invite(p, resp, rest, req, seqno);
20869          } else if (sipmethod == SIP_REGISTER) {
20870             handle_response_register(p, resp, rest, req, seqno);
20871          } else if (sipmethod == SIP_SUBSCRIBE) {
20872             ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
20873             handle_response_subscribe(p, resp, rest, req, seqno);
20874          } else if (sipmethod == SIP_BYE) {     /* Ok, we're ready to go */
20875             pvt_set_needdestroy(p, "received 200 response");
20876             ast_clear_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
20877          }
20878          break;
20879       case 401: /* Not www-authorized on SIP method */
20880       case 407: /* Proxy auth required */
20881          if (sipmethod == SIP_INVITE)
20882             handle_response_invite(p, resp, rest, req, seqno);
20883          else if (sipmethod == SIP_SUBSCRIBE)
20884             handle_response_subscribe(p, resp, rest, req, seqno);
20885          else if (p->registry && sipmethod == SIP_REGISTER)
20886             handle_response_register(p, resp, rest, req, seqno);
20887          else if (sipmethod == SIP_UPDATE) {
20888             handle_response_update(p, resp, rest, req, seqno);
20889          } else if (sipmethod == SIP_BYE) {
20890             if (p->options)
20891                p->options->auth_type = resp;
20892             if (ast_strlen_zero(p->authname)) {
20893                ast_log(LOG_WARNING, "Asked to authenticate %s, to %s but we have no matching peer!\n",
20894                      msg, ast_sockaddr_stringify(&p->recv));
20895                pvt_set_needdestroy(p, "unable to authenticate BYE");
20896             } else if ((p->authtries == MAX_AUTHTRIES) || do_proxy_auth(p, req, resp,  sipmethod, 0)) {
20897                ast_log(LOG_NOTICE, "Failed to authenticate on %s to '%s'\n", msg, get_header(&p->initreq, "From"));
20898                pvt_set_needdestroy(p, "failed to authenticate BYE");
20899             }
20900          } else {
20901             ast_log(LOG_WARNING, "Got authentication request (%d) on %s to '%s'\n", resp, sip_methods[sipmethod].text, get_header(req, "To"));
20902             pvt_set_needdestroy(p, "received 407 response");
20903          }
20904          break;
20905       case 403: /* Forbidden - we failed authentication */
20906          if (sipmethod == SIP_INVITE)
20907             handle_response_invite(p, resp, rest, req, seqno);
20908          else if (sipmethod == SIP_SUBSCRIBE)
20909             handle_response_subscribe(p, resp, rest, req, seqno);
20910          else if (p->registry && sipmethod == SIP_REGISTER)
20911             handle_response_register(p, resp, rest, req, seqno);
20912          else {
20913             ast_log(LOG_WARNING, "Forbidden - maybe wrong password on authentication for %s\n", msg);
20914             pvt_set_needdestroy(p, "received 403 response");
20915          }
20916          break;
20917       case 404: /* Not found */
20918          if (p->registry && sipmethod == SIP_REGISTER)
20919             handle_response_register(p, resp, rest, req, seqno);
20920          else if (sipmethod == SIP_INVITE)
20921             handle_response_invite(p, resp, rest, req, seqno);
20922          else if (sipmethod == SIP_SUBSCRIBE)
20923             handle_response_subscribe(p, resp, rest, req, seqno);
20924          else if (owner)
20925             ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
20926          break;
20927       case 423: /* Interval too brief */
20928          if (sipmethod == SIP_REGISTER)
20929             handle_response_register(p, resp, rest, req, seqno);
20930          break;
20931       case 408: /* Request timeout - terminate dialog */
20932          if (sipmethod == SIP_INVITE)
20933             handle_response_invite(p, resp, rest, req, seqno);
20934          else if (sipmethod == SIP_REGISTER)
20935             handle_response_register(p, resp, rest, req, seqno);
20936          else if (sipmethod == SIP_BYE) {
20937             pvt_set_needdestroy(p, "received 408 response");
20938             ast_debug(4, "Got timeout on bye. Thanks for the answer. Now, kill this call\n");
20939          } else {
20940             if (owner)
20941                ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
20942             pvt_set_needdestroy(p, "received 408 response");
20943          }
20944          break;
20945 
20946       case 422: /* Session-Timers: Session Interval Too Small */
20947          if (sipmethod == SIP_INVITE) {
20948             handle_response_invite(p, resp, rest, req, seqno);
20949          }
20950          break;
20951 
20952       case 481: /* Call leg does not exist */
20953          if (sipmethod == SIP_INVITE) {
20954             handle_response_invite(p, resp, rest, req, seqno);
20955          } else if (sipmethod == SIP_SUBSCRIBE) {
20956             handle_response_subscribe(p, resp, rest, req, seqno);
20957          } else if (sipmethod == SIP_BYE) {
20958             /* The other side has no transaction to bye,
20959             just assume it's all right then */
20960             ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
20961          } else if (sipmethod == SIP_CANCEL) {
20962             /* The other side has no transaction to cancel,
20963             just assume it's all right then */
20964             ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
20965          } else {
20966             ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
20967             /* Guessing that this is not an important request */
20968          }
20969          break;
20970       case 487:
20971          if (sipmethod == SIP_INVITE)
20972             handle_response_invite(p, resp, rest, req, seqno);
20973          break;
20974       case 415: /* Unsupported media type */
20975       case 488: /* Not acceptable here - codec error */
20976       case 606: /* Not Acceptable */
20977          if (sipmethod == SIP_INVITE)
20978             handle_response_invite(p, resp, rest, req, seqno);
20979          break;
20980       case 491: /* Pending */
20981          if (sipmethod == SIP_INVITE)
20982             handle_response_invite(p, resp, rest, req, seqno);
20983          else {
20984             ast_debug(1, "Got 491 on %s, unsupported. Call ID %s\n", sip_methods[sipmethod].text, p->callid);
20985             pvt_set_needdestroy(p, "received 491 response");
20986          }
20987          break;
20988       case 405: /* Method not allowed */
20989       case 501: /* Not Implemented */
20990          mark_method_unallowed(&p->allowed_methods, sipmethod);
20991          if (p->relatedpeer) {
20992             mark_method_allowed(&p->relatedpeer->disallowed_methods, sipmethod);
20993          }
20994          if (sipmethod == SIP_INVITE)
20995             handle_response_invite(p, resp, rest, req, seqno);
20996          else
20997             ast_log(LOG_WARNING, "Host '%s' does not implement '%s'\n", ast_sockaddr_stringify(&p->sa), msg);
20998          break;
20999       default:
21000          if ((resp >= 300) && (resp < 700)) {
21001             /* Fatal response */
21002             if ((resp != 487))
21003                ast_verb(3, "Got SIP response %d \"%s\" back from %s\n", resp, rest, ast_sockaddr_stringify(&p->sa));
21004    
21005             if (sipmethod == SIP_INVITE)
21006                stop_media_flows(p); /* Immediately stop RTP, VRTP and UDPTL as applicable */
21007 
21008             /* XXX Locking issues?? XXX */
21009             switch(resp) {
21010             case 300: /* Multiple Choices */
21011             case 301: /* Moved permanently */
21012             case 302: /* Moved temporarily */
21013             case 305: /* Use Proxy */
21014                if (p->owner) {
21015                   struct ast_party_redirecting redirecting;
21016                   struct ast_set_party_redirecting update_redirecting;
21017 
21018                   ast_party_redirecting_init(&redirecting);
21019                   change_redirecting_information(p, req, &redirecting,
21020                      &update_redirecting, TRUE);
21021                   ast_channel_set_redirecting(p->owner, &redirecting,
21022                      &update_redirecting);
21023                   ast_party_redirecting_free(&redirecting);
21024                }
21025                /* Fall through */
21026             case 486: /* Busy here */
21027             case 600: /* Busy everywhere */
21028             case 603: /* Decline */
21029                if (p->owner) {
21030                   sip_handle_cc(p, req, AST_CC_CCBS);
21031                   ast_queue_control(p->owner, AST_CONTROL_BUSY);
21032                }
21033                break;
21034             case 482: /* Loop Detected */
21035             case 480: /* Temporarily Unavailable */
21036             case 404: /* Not Found */
21037             case 410: /* Gone */
21038             case 400: /* Bad Request */
21039             case 500: /* Server error */
21040                if (sipmethod == SIP_SUBSCRIBE) {
21041                   handle_response_subscribe(p, resp, rest, req, seqno);
21042                   break;
21043                }
21044                /* Fall through */
21045             case 502: /* Bad gateway */
21046             case 503: /* Service Unavailable */
21047             case 504: /* Server Timeout */
21048                if (owner)
21049                   ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
21050                break;
21051             case 484: /* Address Incomplete */
21052                if (owner && sipmethod != SIP_BYE) {
21053                   switch (ast_test_flag(&p->flags[1], SIP_PAGE2_ALLOWOVERLAP)) {
21054                   case SIP_PAGE2_ALLOWOVERLAP_YES:
21055                      ast_queue_hangup_with_cause(p->owner, hangup_sip2cause(resp));
21056                      break;
21057                   default:
21058                      ast_queue_hangup_with_cause(p->owner, hangup_sip2cause(404));
21059                      break;
21060                   }
21061                }
21062                break;
21063             default:
21064                /* Send hangup */ 
21065                if (owner && sipmethod != SIP_BYE)
21066                   ast_queue_hangup_with_cause(p->owner, AST_CAUSE_PROTOCOL_ERROR);
21067                break;
21068             }
21069             /* ACK on invite */
21070             if (sipmethod == SIP_INVITE)
21071                transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
21072             sip_alreadygone(p);
21073             if (!p->owner) {
21074                pvt_set_needdestroy(p, "transaction completed");
21075             }
21076          } else if ((resp >= 100) && (resp < 200)) {
21077             if (sipmethod == SIP_INVITE) {
21078                if (!req->ignore && sip_cancel_destroy(p))
21079                   ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
21080                if (find_sdp(req))
21081                   process_sdp(p, req, SDP_T38_NONE);
21082                if (p->owner) {
21083                   /* Queue a progress frame */
21084                   ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
21085                }
21086             }
21087          } else
21088             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));
21089       }
21090    } else { 
21091       /* Responses to OUTGOING SIP requests on INCOMING calls
21092          get handled here. As well as out-of-call message responses */
21093       if (req->debug)
21094          ast_verbose("SIP Response message for INCOMING dialog %s arrived\n", msg);
21095 
21096       if (sipmethod == SIP_INVITE && resp == 200) {
21097          /* Tags in early session is replaced by the tag in 200 OK, which is
21098          the final reply to our INVITE */
21099          char tag[128];
21100 
21101          gettag(req, "To", tag, sizeof(tag));
21102          ast_string_field_set(p, theirtag, tag);
21103       }
21104 
21105       switch(resp) {
21106       case 200:
21107          if (sipmethod == SIP_INVITE) {
21108             handle_response_invite(p, resp, rest, req, seqno);
21109          } else if (sipmethod == SIP_CANCEL) {
21110             ast_debug(1, "Got 200 OK on CANCEL\n");
21111 
21112             /* Wait for 487, then destroy */
21113          } else if (sipmethod == SIP_BYE) {
21114             pvt_set_needdestroy(p, "transaction completed");
21115          }
21116          break;
21117       case 401:   /* www-auth */
21118       case 407:
21119          if (sipmethod == SIP_INVITE)
21120             handle_response_invite(p, resp, rest, req, seqno);
21121          else if (sipmethod == SIP_BYE) {
21122             if (p->authtries == MAX_AUTHTRIES || do_proxy_auth(p, req, resp, sipmethod, 0)) {
21123                ast_log(LOG_NOTICE, "Failed to authenticate on %s to '%s'\n", msg, get_header(&p->initreq, "From"));
21124                pvt_set_needdestroy(p, "failed to authenticate BYE");
21125             }
21126          }
21127          break;
21128       case 481:   /* Call leg does not exist */
21129          if (sipmethod == SIP_INVITE) {
21130             /* Re-invite failed */
21131             handle_response_invite(p, resp, rest, req, seqno);
21132          } else if (sipmethod == SIP_BYE) {
21133             pvt_set_needdestroy(p, "received 481 response");
21134          } else if (sipdebug) {
21135             ast_debug(1, "Remote host can't match request %s to call '%s'. Giving up\n", sip_methods[sipmethod].text, p->callid);
21136          }
21137          break;
21138       case 501: /* Not Implemented */
21139          if (sipmethod == SIP_INVITE)
21140             handle_response_invite(p, resp, rest, req, seqno);
21141          break;
21142       default: /* Errors without handlers */
21143          if ((resp >= 100) && (resp < 200)) {
21144             if (sipmethod == SIP_INVITE) {   /* re-invite */
21145                if (!req->ignore && sip_cancel_destroy(p))
21146                   ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
21147             }
21148          }
21149          if ((resp >= 300) && (resp < 700)) {
21150             if ((resp != 487))
21151                ast_verb(3, "Incoming call: Got SIP response %d \"%s\" back from %s\n", resp, rest, ast_sockaddr_stringify(&p->sa));
21152             switch(resp) {
21153             case 415: /* Unsupported media type */
21154             case 488: /* Not acceptable here - codec error */
21155             case 603: /* Decline */
21156             case 500: /* Server error */
21157             case 502: /* Bad gateway */
21158             case 503: /* Service Unavailable */
21159             case 504: /* Server timeout */
21160 
21161                /* re-invite failed */
21162                if (sipmethod == SIP_INVITE && sip_cancel_destroy(p))
21163                   ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
21164                break;
21165             }
21166          }
21167          break;
21168       }
21169    }
21170 }
21171 
21172 
21173 /*! \brief Park SIP call support function
21174    Starts in a new thread, then parks the call
21175    XXX Should we add a wait period after streaming audio and before hangup?? Sometimes the
21176       audio can't be heard before hangup
21177 */
21178 static void *sip_park_thread(void *stuff)
21179 {
21180    struct ast_channel *transferee, *transferer; /* Chan1: The transferee, Chan2: The transferer */
21181    struct sip_dual *d;
21182    int ext;
21183    int res;
21184 
21185    d = stuff;
21186    transferee = d->chan1;
21187    transferer = d->chan2;
21188 
21189    ast_debug(4, "SIP Park: Transferer channel %s, Transferee %s\n", transferer->name, transferee->name);
21190 
21191    res = ast_park_call_exten(transferee, transferer, d->park_exten, d->park_context, 0, &ext);
21192 
21193 #ifdef WHEN_WE_KNOW_THAT_THE_CLIENT_SUPPORTS_MESSAGE
21194    if (res) {
21195       transmit_message_with_text(transferer->tech_pvt, "Unable to park call.\n");
21196    } else {
21197       /* Then tell the transferer what happened */
21198       sprintf(buf, "Call parked on extension '%d'", ext);
21199       transmit_message_with_text(transferer->tech_pvt, buf);
21200    }
21201 #endif
21202 
21203    /* Any way back to the current call??? */
21204    /* Transmit response to the REFER request */
21205    if (!res)   {
21206       /* Transfer succeeded */
21207       append_history(transferer->tech_pvt, "SIPpark", "Parked call on %d", ext);
21208       transmit_notify_with_sipfrag(transferer->tech_pvt, d->seqno, "200 OK", TRUE);
21209       transferer->hangupcause = AST_CAUSE_NORMAL_CLEARING;
21210       ast_hangup(transferer); /* This will cause a BYE */
21211       ast_debug(1, "SIP Call parked on extension '%d'\n", ext);
21212    } else {
21213       transmit_notify_with_sipfrag(transferer->tech_pvt, d->seqno, "503 Service Unavailable", TRUE);
21214       append_history(transferer->tech_pvt, "SIPpark", "Parking failed\n");
21215       ast_debug(1, "SIP Call parked failed \n");
21216       /* Do not hangup call */
21217    }
21218    deinit_req(&d->req);
21219    ast_free(d->park_exten);
21220    ast_free(d->park_context);
21221    ast_free(d);
21222    return NULL;
21223 }
21224 
21225 /*! DO NOT hold any locks while calling sip_park */
21226 static int sip_park(struct ast_channel *chan1, struct ast_channel *chan2, struct sip_request *req, int seqno, const char *park_exten, const char *park_context)
21227 {
21228    struct sip_dual *d;
21229    struct ast_channel *transferee, *transferer;
21230    pthread_t th;
21231 
21232    transferee = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, chan1->accountcode, chan1->exten, chan1->context, chan1->linkedid, chan1->amaflags, "Parking/%s", chan1->name);
21233    transferer = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, chan2->accountcode, chan2->exten, chan2->context, chan2->linkedid, chan2->amaflags, "SIPPeer/%s", chan2->name);
21234    d = ast_calloc(1, sizeof(*d));
21235    if (!transferee || !transferer || !d) {
21236       if (transferee) {
21237          ast_hangup(transferee);
21238       }
21239       if (transferer) {
21240          ast_hangup(transferer);
21241       }
21242       ast_free(d);
21243       return -1;
21244    }
21245    d->park_exten = ast_strdup(park_exten);
21246    d->park_context = ast_strdup(park_context);
21247    if (!d->park_exten || !d->park_context) {
21248       ast_hangup(transferee);
21249       ast_hangup(transferer);
21250       ast_free(d->park_exten);
21251       ast_free(d->park_context);
21252       ast_free(d);
21253       return -1;
21254    }
21255 
21256    /* Make formats okay */
21257    transferee->readformat = chan1->readformat;
21258    transferee->writeformat = chan1->writeformat;
21259 
21260    /* Prepare for taking over the channel */
21261    if (ast_channel_masquerade(transferee, chan1)) {
21262       ast_hangup(transferee);
21263       ast_hangup(transferer);
21264       ast_free(d->park_exten);
21265       ast_free(d->park_context);
21266       ast_free(d);
21267       return -1;
21268    }
21269 
21270    /* Setup the extensions and such */
21271    ast_copy_string(transferee->context, chan1->context, sizeof(transferee->context));
21272    ast_copy_string(transferee->exten, chan1->exten, sizeof(transferee->exten));
21273    transferee->priority = chan1->priority;
21274 
21275    ast_do_masquerade(transferee);
21276 
21277    /* We make a clone of the peer channel too, so we can play
21278       back the announcement */
21279 
21280    /* Make formats okay */
21281    transferer->readformat = chan2->readformat;
21282    transferer->writeformat = chan2->writeformat;
21283    ast_string_field_set(transferer, parkinglot, chan2->parkinglot);
21284 
21285    /* Prepare for taking over the channel */
21286    if (ast_channel_masquerade(transferer, chan2)) {
21287       ast_hangup(transferer);
21288       ast_free(d->park_exten);
21289       ast_free(d->park_context);
21290       ast_free(d);
21291       return -1;
21292    }
21293 
21294    /* Setup the extensions and such */
21295    ast_copy_string(transferer->context, chan2->context, sizeof(transferer->context));
21296    ast_copy_string(transferer->exten, chan2->exten, sizeof(transferer->exten));
21297    transferer->priority = chan2->priority;
21298 
21299    ast_do_masquerade(transferer);
21300 
21301    /* Save original request for followup */
21302    copy_request(&d->req, req);
21303    d->chan1 = transferee;  /* Transferee */
21304    d->chan2 = transferer;  /* Transferer */
21305    d->seqno = seqno;
21306    if (ast_pthread_create_detached_background(&th, NULL, sip_park_thread, d) < 0) {
21307       /* Could not start thread */
21308       deinit_req(&d->req);
21309       ast_free(d->park_exten);
21310       ast_free(d->park_context);
21311       ast_free(d);   /* We don't need it anymore. If thread is created, d will be free'd
21312                by sip_park_thread() */
21313       return -1;
21314    }
21315    return 0;
21316 }
21317 
21318 
21319 /*! \brief SIP pickup support function
21320  * Starts in a new thread, then pickup the call
21321  */
21322 static void *sip_pickup_thread(void *stuff)
21323 {
21324    struct ast_channel *chan;
21325    chan = stuff;
21326 
21327    if (ast_pickup_call(chan)) {
21328       chan->hangupcause = AST_CAUSE_CALL_REJECTED;
21329    } else {
21330       chan->hangupcause = AST_CAUSE_NORMAL_CLEARING;
21331    }
21332    ast_hangup(chan);
21333    ast_channel_unref(chan);
21334    chan = NULL;
21335    return NULL;
21336 }
21337 
21338 /*! \brief Pickup a call using the subsystem in features.c
21339  * This is executed in a separate thread
21340  */
21341 static int sip_pickup(struct ast_channel *chan)
21342 {
21343    pthread_t threadid;
21344 
21345    ast_channel_ref(chan);
21346 
21347    if (ast_pthread_create_detached_background(&threadid, NULL, sip_pickup_thread, chan)) {
21348       ast_debug(1, "Unable to start Group pickup thread on channel %s\n", chan->name);
21349       ast_channel_unref(chan);
21350       return -1;
21351    }
21352    ast_debug(1, "Started Group pickup thread on channel %s\n", chan->name);
21353    return 0;
21354 }
21355 
21356 
21357 /*! \brief Turn off generator data
21358    XXX Does this function belong in the SIP channel?
21359 */
21360 static void ast_quiet_chan(struct ast_channel *chan)
21361 {
21362    if (chan && chan->_state == AST_STATE_UP) {
21363       if (ast_test_flag(chan, AST_FLAG_MOH))
21364          ast_moh_stop(chan);
21365       else if (chan->generatordata)
21366          ast_deactivate_generator(chan);
21367    }
21368 }
21369 
21370 /*! \brief Attempt transfer of SIP call
21371    This fix for attended transfers on a local PBX */
21372 static int attempt_transfer(struct sip_dual *transferer, struct sip_dual *target)
21373 {
21374    int res = 0;
21375    struct ast_channel *peera = NULL,   
21376       *peerb = NULL,
21377       *peerc = NULL,
21378       *peerd = NULL;
21379 
21380 
21381    /* We will try to connect the transferee with the target and hangup
21382       all channels to the transferer */   
21383    ast_debug(4, "Sip transfer:--------------------\n");
21384    if (transferer->chan1)
21385       ast_debug(4, "-- Transferer to PBX channel: %s State %s\n", transferer->chan1->name, ast_state2str(transferer->chan1->_state));
21386    else
21387       ast_debug(4, "-- No transferer first channel - odd??? \n");
21388    if (target->chan1)
21389       ast_debug(4, "-- Transferer to PBX second channel (target): %s State %s\n", target->chan1->name, ast_state2str(target->chan1->_state));
21390    else
21391       ast_debug(4, "-- No target first channel ---\n");
21392    if (transferer->chan2)
21393       ast_debug(4, "-- Bridged call to transferee: %s State %s\n", transferer->chan2->name, ast_state2str(transferer->chan2->_state));
21394    else
21395       ast_debug(4, "-- No bridged call to transferee\n");
21396    if (target->chan2)
21397       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)");
21398    else
21399       ast_debug(4, "-- No target second channel ---\n");
21400    ast_debug(4, "-- END Sip transfer:--------------------\n");
21401    if (transferer->chan2) { /* We have a bridge on the transferer's channel */
21402       peera = transferer->chan1; /* Transferer - PBX -> transferee channel * the one we hangup */
21403       peerb = target->chan1;     /* Transferer - PBX -> target channel - This will get lost in masq */
21404       peerc = transferer->chan2; /* Asterisk to Transferee */
21405       peerd = target->chan2;     /* Asterisk to Target */
21406       ast_debug(3, "SIP transfer: Four channels to handle\n");
21407    } else if (target->chan2) {   /* Transferer has no bridge (IVR), but transferee */
21408       peera = target->chan1;     /* Transferer to PBX -> target channel */
21409       peerb = transferer->chan1; /* Transferer to IVR*/
21410       peerc = target->chan2;     /* Asterisk to Target */
21411       peerd = transferer->chan2; /* Nothing */
21412       ast_debug(3, "SIP transfer: Three channels to handle\n");
21413    }
21414 
21415    if (peera && peerb && peerc && (peerb != peerc)) {
21416       ast_quiet_chan(peera);     /* Stop generators */
21417       ast_quiet_chan(peerb);  
21418       ast_quiet_chan(peerc);
21419       if (peerd)
21420          ast_quiet_chan(peerd);
21421 
21422       ast_debug(4, "SIP transfer: trying to masquerade %s into %s\n", peerc->name, peerb->name);
21423       if (ast_channel_masquerade(peerb, peerc)) {
21424          ast_log(LOG_WARNING, "Failed to masquerade %s into %s\n", peerb->name, peerc->name);
21425          res = -1;
21426       } else
21427          ast_debug(4, "SIP transfer: Succeeded to masquerade channels.\n");
21428       return res;
21429    } else {
21430       ast_log(LOG_NOTICE, "SIP Transfer attempted with no appropriate bridged calls to transfer\n");
21431       if (transferer->chan1)
21432          ast_softhangup_nolock(transferer->chan1, AST_SOFTHANGUP_DEV);
21433       if (target->chan1)
21434          ast_softhangup_nolock(target->chan1, AST_SOFTHANGUP_DEV);
21435       return -1;
21436    }
21437    return 0;
21438 }
21439 
21440 /*! \brief Get tag from packet
21441  *
21442  * \return Returns the pointer to the provided tag buffer,
21443  *         or NULL if the tag was not found.
21444  */
21445 static const char *gettag(const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize)
21446 {
21447    const char *thetag;
21448 
21449    if (!tagbuf)
21450       return NULL;
21451    tagbuf[0] = '\0';    /* reset the buffer */
21452    thetag = get_header(req, header);
21453    thetag = strcasestr(thetag, ";tag=");
21454    if (thetag) {
21455       thetag += 5;
21456       ast_copy_string(tagbuf, thetag, tagbufsize);
21457       return strsep(&tagbuf, ";");
21458    }
21459    return NULL;
21460 }
21461 
21462 static int handle_cc_notify(struct sip_pvt *pvt, struct sip_request *req)
21463 {
21464    struct sip_monitor_instance *monitor_instance = ao2_callback(sip_monitor_instances, 0,
21465          find_sip_monitor_instance_by_subscription_pvt, pvt);
21466    const char *status = get_body(req, "cc-state", ':');
21467    struct cc_epa_entry *cc_entry;
21468    char *uri;
21469 
21470    if (!monitor_instance) {
21471       transmit_response(pvt, "400 Bad Request", req);
21472       return -1;
21473    }
21474 
21475    if (ast_strlen_zero(status)) {
21476       ao2_ref(monitor_instance, -1);
21477       transmit_response(pvt, "400 Bad Request", req);
21478       return -1;
21479    }
21480 
21481    if (!strcmp(status, "queued")) {
21482       /* We've been told that we're queued. This is the endpoint's way of telling
21483        * us that it has accepted our CC request. We need to alert the core of this
21484        * development
21485        */
21486       ast_cc_monitor_request_acked(monitor_instance->core_id, "SIP endpoint %s accepted request", monitor_instance->device_name);
21487       transmit_response(pvt, "200 OK", req);
21488       ao2_ref(monitor_instance, -1);
21489       return 0;
21490    }
21491 
21492    /* It's open! Yay! */
21493    uri = get_body(req, "cc-URI", ':');
21494    if (ast_strlen_zero(uri)) {
21495       uri = get_in_brackets((char *)get_header(req, "From"));
21496    }
21497 
21498    ast_string_field_set(monitor_instance, notify_uri, uri);
21499    if (monitor_instance->suspension_entry) {
21500       cc_entry = monitor_instance->suspension_entry->instance_data;
21501       if (cc_entry->current_state == CC_CLOSED) {
21502          /* If we've created a suspension entry and the current state is closed, then that means
21503           * we got a notice from the CC core earlier to suspend monitoring, but because this particular
21504           * call leg had not yet notified us that it was ready for recall, it meant that we
21505           * could not yet send a PUBLISH. Now, however, we can.
21506           */
21507          construct_pidf_body(CC_CLOSED, monitor_instance->suspension_entry->body,
21508                sizeof(monitor_instance->suspension_entry->body), monitor_instance->peername);
21509          transmit_publish(monitor_instance->suspension_entry, SIP_PUBLISH_INITIAL, monitor_instance->notify_uri);
21510       } else {
21511          ast_cc_monitor_callee_available(monitor_instance->core_id, "SIP monitored callee has become available");
21512       }
21513    } else {
21514       ast_cc_monitor_callee_available(monitor_instance->core_id, "SIP monitored callee has become available");
21515    }
21516    ao2_ref(monitor_instance, -1);
21517    transmit_response(pvt, "200 OK", req);
21518 
21519    return 0;
21520 }
21521 
21522 /*! \brief Handle incoming notifications */
21523 static int handle_request_notify(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, int seqno, const char *e)
21524 {
21525    /* This is mostly a skeleton for future improvements */
21526    /* Mostly created to return proper answers on notifications on outbound REFER's */
21527    int res = 0;
21528    const char *event = get_header(req, "Event");
21529    char *sep;
21530 
21531    if( (sep = strchr(event, ';')) ) {  /* XXX bug here - overwriting string ? */
21532       *sep++ = '\0';
21533    }
21534    
21535    if (sipdebug)
21536       ast_debug(2, "Got NOTIFY Event: %s\n", event);
21537 
21538    if (!strcmp(event, "refer")) {
21539       /* Save nesting depth for now, since there might be other events we will
21540          support in the future */
21541 
21542       /* Handle REFER notifications */
21543 
21544       char buf[1024];
21545       char *cmd, *code;
21546       int respcode;
21547       int success = TRUE;
21548 
21549       /* EventID for each transfer... EventID is basically the REFER cseq
21550 
21551        We are getting notifications on a call that we transfered
21552        We should hangup when we are getting a 200 OK in a sipfrag
21553        Check if we have an owner of this event */
21554       
21555       /* Check the content type */
21556       if (strncasecmp(get_header(req, "Content-Type"), "message/sipfrag", strlen("message/sipfrag"))) {
21557          /* We need a sipfrag */
21558          transmit_response(p, "400 Bad request", req);
21559          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
21560          return -1;
21561       }
21562 
21563       /* Get the text of the attachment */
21564       if (get_msg_text(buf, sizeof(buf), req)) {
21565          ast_log(LOG_WARNING, "Unable to retrieve attachment from NOTIFY %s\n", p->callid);
21566          transmit_response(p, "400 Bad request", req);
21567          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
21568          return -1;
21569       }
21570 
21571       /*
21572       From the RFC...
21573       A minimal, but complete, implementation can respond with a single
21574       NOTIFY containing either the body:
21575          SIP/2.0 100 Trying
21576       
21577       if the subscription is pending, the body:
21578          SIP/2.0 200 OK
21579       if the reference was successful, the body:
21580          SIP/2.0 503 Service Unavailable
21581       if the reference failed, or the body:
21582          SIP/2.0 603 Declined
21583 
21584       if the REFER request was accepted before approval to follow the
21585       reference could be obtained and that approval was subsequently denied
21586       (see Section 2.4.7).
21587       
21588       If there are several REFERs in the same dialog, we need to
21589       match the ID of the event header...
21590       */
21591       ast_debug(3, "* SIP Transfer NOTIFY Attachment: \n---%s\n---\n", buf);
21592       cmd = ast_skip_blanks(buf);
21593       code = cmd;
21594       /* We are at SIP/2.0 */
21595       while(*code && (*code > 32)) {   /* Search white space */
21596          code++;
21597       }
21598       *code++ = '\0';
21599       code = ast_skip_blanks(code);
21600       sep = code;
21601       sep++;
21602       while(*sep && (*sep > 32)) {  /* Search white space */
21603          sep++;
21604       }
21605       *sep++ = '\0';       /* Response string */
21606       respcode = atoi(code);
21607       switch (respcode) {
21608       case 200:   /* OK: The new call is up, hangup this call */
21609          /* Hangup the call that we are replacing */
21610          break;
21611       case 301: /* Moved permenantly */
21612       case 302: /* Moved temporarily */
21613          /* Do we get the header in the packet in this case? */
21614          success = FALSE;
21615          break;
21616       case 503:   /* Service Unavailable: The new call failed */
21617       case 603:   /* Declined: Not accepted */
21618             /* Cancel transfer, continue the current call */
21619          success = FALSE;
21620          break;
21621       case 0:     /* Parse error */
21622             /* Cancel transfer, continue the current call */
21623          ast_log(LOG_NOTICE, "Error parsing sipfrag in NOTIFY in response to REFER.\n");
21624          success = FALSE;
21625          break;
21626       default:
21627          if (respcode < 200) {
21628             /* ignore provisional responses */
21629             success = -1;
21630          } else {
21631             ast_log(LOG_NOTICE, "Got unknown code '%d' in NOTIFY in response to REFER.\n", respcode);
21632             success = FALSE;
21633          }
21634          break;
21635       }
21636       if (success == FALSE) {
21637          ast_log(LOG_NOTICE, "Transfer failed. Sorry. Nothing further to do with this call\n");
21638       }
21639 
21640       if (p->owner && success != -1) {
21641          enum ast_control_transfer message = success ? AST_TRANSFER_SUCCESS : AST_TRANSFER_FAILED;
21642          ast_queue_control_data(p->owner, AST_CONTROL_TRANSFER, &message, sizeof(message));
21643       }
21644       /* Confirm that we received this packet */
21645       transmit_response(p, "200 OK", req);
21646    } else if (!strcmp(event, "message-summary")) {
21647       const char *mailbox = NULL;
21648       char *c = ast_strdupa(get_body(req, "Voice-Message", ':'));
21649 
21650       if (!p->mwi) {
21651          struct sip_peer *peer = find_peer(NULL, &p->recv, TRUE, FINDPEERS, FALSE, p->socket.type);
21652 
21653          if (peer) {
21654             mailbox = ast_strdupa(peer->unsolicited_mailbox);
21655             unref_peer(peer, "removing unsolicited mwi ref");
21656          }
21657       } else {
21658          mailbox = p->mwi->mailbox;
21659       }
21660 
21661       if (!ast_strlen_zero(mailbox) && !ast_strlen_zero(c)) {
21662          char *old = strsep(&c, " ");
21663          char *new = strsep(&old, "/");
21664          struct ast_event *event;
21665 
21666          if ((event = ast_event_new(AST_EVENT_MWI,
21667                      AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, mailbox,
21668                      AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, "SIP_Remote",
21669                      AST_EVENT_IE_NEWMSGS, AST_EVENT_IE_PLTYPE_UINT, atoi(new),
21670                      AST_EVENT_IE_OLDMSGS, AST_EVENT_IE_PLTYPE_UINT, atoi(old),
21671                      AST_EVENT_IE_END))) {
21672             ast_event_queue_and_cache(event);
21673          }
21674          transmit_response(p, "200 OK", req);
21675       } else {
21676          transmit_response(p, "489 Bad event", req);
21677          res = -1;
21678       }
21679    } else if (!strcmp(event, "keep-alive")) {
21680        /* Used by Sipura/Linksys for NAT pinhole,
21681         * just confirm that we received the packet. */
21682       transmit_response(p, "200 OK", req);
21683    } else if (!strcmp(event, "call-completion")) {
21684       res = handle_cc_notify(p, req);
21685    } else {
21686       /* We don't understand this event. */
21687       transmit_response(p, "489 Bad event", req);
21688       res = -1;
21689    }
21690 
21691    if (!p->lastinvite)
21692       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
21693 
21694    return res;
21695 }
21696 
21697 /*! \brief Handle incoming OPTIONS request
21698    An OPTIONS request should be answered like an INVITE from the same UA, including SDP
21699 */
21700 static int handle_request_options(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, const char *e)
21701 {
21702    const char *msg;
21703    enum sip_get_dest_result gotdest;
21704    int res;
21705 
21706    if (p->lastinvite) {
21707       /* if this is a request in an active dialog, just confirm that the dialog exists. */
21708       transmit_response_with_allow(p, "200 OK", req, 0);
21709       return 0;
21710    }
21711 
21712    if (sip_cfg.auth_options_requests) {
21713       /* Do authentication if this OPTIONS request began the dialog */
21714       copy_request(&p->initreq, req);
21715       set_pvt_allowed_methods(p, req);
21716       res = check_user(p, req, SIP_OPTIONS, e, XMIT_UNRELIABLE, addr);
21717       if (res == AUTH_CHALLENGE_SENT) {
21718          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
21719          return 0;
21720       }
21721       if (res < 0) { /* Something failed in authentication */
21722          if (res == AUTH_FAKE_AUTH) {
21723             ast_log(LOG_NOTICE, "Sending fake auth rejection for device %s\n", get_header(req, "From"));
21724             transmit_fake_auth_response(p, SIP_OPTIONS, req, XMIT_UNRELIABLE);
21725          } else {
21726             ast_log(LOG_NOTICE, "Failed to authenticate device %s\n", get_header(req, "From"));
21727             transmit_response(p, "403 Forbidden", req);
21728          }
21729          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
21730          return 0;
21731       }
21732    }
21733 
21734    /* must go through authentication before getting here */
21735    gotdest = get_destination(p, req, NULL);
21736    build_contact(p);
21737 
21738    if (ast_strlen_zero(p->context))
21739       ast_string_field_set(p, context, sip_cfg.default_context);
21740 
21741    if (ast_shutting_down()) {
21742       msg = "503 Unavailable";
21743    } else {
21744       msg = "404 Not Found";
21745       switch (gotdest) {
21746       case SIP_GET_DEST_INVALID_URI:
21747          msg = "416 Unsupported URI scheme";
21748          break;
21749       case SIP_GET_DEST_EXTEN_MATCHMORE:
21750       case SIP_GET_DEST_REFUSED:
21751       case SIP_GET_DEST_EXTEN_NOT_FOUND:
21752          //msg = "404 Not Found";
21753          break;
21754       case SIP_GET_DEST_EXTEN_FOUND:
21755          msg = "200 OK";
21756          break;
21757       }
21758    }
21759    transmit_response_with_allow(p, msg, req, 0);
21760 
21761    /* Destroy if this OPTIONS was the opening request, but not if
21762       it's in the middle of a normal call flow. */
21763    sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
21764 
21765    return 0;
21766 }
21767 
21768 /*! \brief Handle the transfer part of INVITE with a replaces: header,
21769     meaning a target pickup or an attended transfer.
21770     Used only once.
21771    XXX 'ignore' is unused.
21772 
21773    \note this function is called by handle_request_invite(). Four locks
21774    held at the beginning of this function, p, p->owner, p->refer->refer_call and
21775    p->refere->refer_call->owner.  only p's lock should remain at the end of this
21776    function.  p's lock as well as the channel p->owner's lock are held by
21777    handle_request_do(), we unlock p->owner before the masq.  By setting nounlock
21778    we are indicating to handle_request_do() that we have already unlocked the owner.
21779  */
21780 static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, struct ast_sockaddr *addr, int *nounlock)
21781 {
21782    int earlyreplace = 0;
21783    int oneleggedreplace = 0;     /* Call with no bridge, propably IVR or voice message */
21784    struct ast_channel *c = p->owner;   /* Our incoming call */
21785    struct ast_channel *replacecall = p->refer->refer_call->owner; /* The channel we're about to take over */
21786    struct ast_channel *targetcall;     /* The bridge to the take-over target */
21787 
21788    /* Check if we're in ring state */
21789    if (replacecall->_state == AST_STATE_RING)
21790       earlyreplace = 1;
21791 
21792    /* Check if we have a bridge */
21793    if (!(targetcall = ast_bridged_channel(replacecall))) {
21794       /* We have no bridge */
21795       if (!earlyreplace) {
21796          ast_debug(2, " Attended transfer attempted to replace call with no bridge (maybe ringing). Channel %s!\n", replacecall->name);
21797          oneleggedreplace = 1;
21798       }
21799    }
21800    if (targetcall && targetcall->_state == AST_STATE_RINGING)
21801       ast_debug(4, "SIP transfer: Target channel is in ringing state\n");
21802 
21803    if (targetcall)
21804       ast_debug(4, "SIP transfer: Invite Replace incoming channel should bridge to channel %s while hanging up channel %s\n", targetcall->name, replacecall->name);
21805    else
21806       ast_debug(4, "SIP transfer: Invite Replace incoming channel should replace and hang up channel %s (one call leg)\n", replacecall->name);
21807 
21808    if (req->ignore) {
21809       ast_log(LOG_NOTICE, "Ignoring this INVITE with replaces in a stupid way.\n");
21810       /* We should answer something here. If we are here, the
21811          call we are replacing exists, so an accepted
21812          can't harm */
21813       transmit_response_with_sdp(p, "200 OK", req, XMIT_RELIABLE, FALSE, FALSE);
21814       /* Do something more clever here */
21815       if (c) {
21816          *nounlock = 1;
21817          ast_channel_unlock(c);
21818       }
21819       ast_channel_unlock(replacecall);
21820       sip_pvt_unlock(p->refer->refer_call);
21821       return 1;
21822    }
21823    if (!c) {
21824       /* What to do if no channel ??? */
21825       ast_log(LOG_ERROR, "Unable to create new channel.  Invite/replace failed.\n");
21826       transmit_response_reliable(p, "503 Service Unavailable", req);
21827       append_history(p, "Xfer", "INVITE/Replace Failed. No new channel.");
21828       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
21829       ast_channel_unlock(replacecall);
21830       sip_pvt_unlock(p->refer->refer_call);
21831       return 1;
21832    }
21833    append_history(p, "Xfer", "INVITE/Replace received");
21834    /* We have three channels to play with
21835       channel c: New incoming call
21836       targetcall: Call from PBX to target
21837       p->refer->refer_call: SIP pvt dialog from transferer to pbx.
21838       replacecall: The owner of the previous
21839       We need to masq C into refer_call to connect to
21840       targetcall;
21841       If we are talking to internal audio stream, target call is null.
21842    */
21843 
21844    /* Fake call progress */
21845    transmit_response(p, "100 Trying", req);
21846    ast_setstate(c, AST_STATE_RING);
21847 
21848    /* Masquerade the new call into the referred call to connect to target call
21849       Targetcall is not touched by the masq */
21850 
21851    /* Answer the incoming call and set channel to UP state */
21852    transmit_response_with_sdp(p, "200 OK", req, XMIT_RELIABLE, FALSE, FALSE);
21853 
21854    ast_setstate(c, AST_STATE_UP);
21855 
21856    /* Stop music on hold and other generators */
21857    ast_quiet_chan(replacecall);
21858    ast_quiet_chan(targetcall);
21859    ast_debug(4, "Invite/Replaces: preparing to masquerade %s into %s\n", c->name, replacecall->name);
21860 
21861    /* Make sure that the masq does not free our PVT for the old call */
21862    if (! earlyreplace && ! oneleggedreplace )
21863       ast_set_flag(&p->refer->refer_call->flags[0], SIP_DEFER_BYE_ON_TRANSFER);  /* Delay hangup */
21864 
21865    /* Prepare the masquerade - if this does not happen, we will be gone */
21866    if(ast_channel_masquerade(replacecall, c))
21867       ast_log(LOG_ERROR, "Failed to masquerade C into Replacecall\n");
21868    else
21869       ast_debug(4, "Invite/Replaces: Going to masquerade %s into %s\n", c->name, replacecall->name);
21870 
21871    /* C should now be in place of replacecall. all channel locks and pvt locks should be removed
21872     * before issuing the masq.  Since we are unlocking both the pvt (p) and its owner channel (c)
21873     * it is possible for channel c to be destroyed on us.  To prevent this, we must give c a reference
21874     * before any unlocking takes place and remove it only once we are completely done with it */
21875    ast_channel_ref(c);
21876    ast_channel_unlock(replacecall);
21877    ast_channel_unlock(c);
21878    sip_pvt_unlock(p->refer->refer_call);
21879    sip_pvt_unlock(p);
21880    if (ast_do_masquerade(replacecall)) {
21881       ast_log(LOG_WARNING, "Failed to perform masquerade with INVITE replaces\n");
21882    }
21883    ast_channel_lock(c);
21884    if (earlyreplace || oneleggedreplace ) {
21885       c->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
21886    }
21887    ast_setstate(c, AST_STATE_DOWN);
21888    ast_channel_unlock(c);
21889 
21890    /* The call should be down with no ast_channel, so hang it up */
21891    c->tech_pvt = dialog_unref(c->tech_pvt, "unref dialog c->tech_pvt");
21892 
21893    /* c and c's tech pvt must be unlocked at this point for ast_hangup */
21894    ast_hangup(c);
21895    /* this indicates to handle_request_do that the owner channel has already been unlocked */
21896    *nounlock = 1;
21897    /* lock PVT structure again after hangup */
21898    sip_pvt_lock(p);
21899    ast_channel_unref(c);
21900    return 0;
21901 }
21902 
21903 /*! \note No channel or pvt locks should be held while calling this function. */
21904 static int do_magic_pickup(struct ast_channel *channel, const char *extension, const char *context)
21905 {
21906    struct ast_str *str = ast_str_alloca(AST_MAX_EXTENSION + AST_MAX_CONTEXT + 2);
21907    struct ast_app *pickup = pbx_findapp("Pickup");
21908 
21909    if (!pickup) {
21910       ast_log(LOG_ERROR, "Unable to perform pickup: Application 'Pickup' not loaded (app_directed_pickup.so).\n");
21911       return -1;
21912    }
21913 
21914    ast_str_set(&str, 0, "%s@%s", extension, sip_cfg.notifycid == IGNORE_CONTEXT ? "PICKUPMARK" : context);
21915 
21916    ast_debug(2, "About to call Pickup(%s)\n", str->str);
21917 
21918    /* There is no point in capturing the return value since pickup_exec
21919       doesn't return anything meaningful unless the passed data is an empty
21920       string (which in our case it will not be) */
21921    pbx_exec(channel, pickup, str->str);
21922 
21923    return 0;
21924 }
21925 
21926 /*! \brief Called to deny a T38 reinvite if the core does not respond to our request */
21927 static int sip_t38_abort(const void *data)
21928 {
21929    struct sip_pvt *p = (struct sip_pvt *) data;
21930 
21931    sip_pvt_lock(p);
21932    /* an application may have taken ownership of the T.38 negotiation on this
21933     * channel while we were waiting to grab the lock... if it did, the scheduler
21934     * id will have been reset to -1, which is our indication that we do *not*
21935     * want to abort the negotiation process
21936     */
21937    if (p->t38id != -1) {
21938       change_t38_state(p, T38_DISABLED);
21939       transmit_response_reliable(p, "488 Not acceptable here", &p->initreq);
21940       p->t38id = -1;
21941       dialog_unref(p, "unref the dialog ptr from sip_t38_abort, because it held a dialog ptr");
21942    }
21943    sip_pvt_unlock(p);
21944    return 0;
21945 }
21946 
21947 /*!
21948  * \brief bare-bones support for SIP UPDATE
21949  *
21950  * XXX This is not even close to being RFC 3311-compliant. We don't advertise
21951  * that we support the UPDATE method, so no one should ever try sending us
21952  * an UPDATE anyway. However, Asterisk can send an UPDATE to change connected
21953  * line information, so we need to be prepared to handle this. The way we distinguish
21954  * such an UPDATE is through the X-Asterisk-rpid-update header.
21955  *
21956  * Actually updating the media session may be some future work.
21957  */
21958 static int handle_request_update(struct sip_pvt *p, struct sip_request *req)
21959 {
21960    if (ast_strlen_zero(get_header(req, "X-Asterisk-rpid-update"))) {
21961       transmit_response(p, "501 Method Not Implemented", req);
21962       return 0;
21963    }
21964    if (get_rpid(p, req)) {
21965       struct ast_party_connected_line connected;
21966       struct ast_set_party_connected_line update_connected;
21967 
21968       ast_party_connected_line_init(&connected);
21969       memset(&update_connected, 0, sizeof(update_connected));
21970 
21971       update_connected.id.number = 1;
21972       connected.id.number.valid = 1;
21973       connected.id.number.str = (char *) p->cid_num;
21974       connected.id.number.presentation = p->callingpres;
21975 
21976       update_connected.id.name = 1;
21977       connected.id.name.valid = 1;
21978       connected.id.name.str = (char *) p->cid_name;
21979       connected.id.name.presentation = p->callingpres;
21980 
21981       connected.id.tag = (char *) p->cid_tag;
21982       connected.source = AST_CONNECTED_LINE_UPDATE_SOURCE_TRANSFER;
21983       ast_channel_queue_connected_line_update(p->owner, &connected, &update_connected);
21984    }
21985    transmit_response(p, "200 OK", req);
21986    return 0;
21987 }
21988 
21989 /*!
21990  * \brief Handle incoming INVITE request
21991  * \note If the INVITE has a Replaces header, it is part of an
21992  * attended transfer. If so, we do not go through the dial
21993  * plan but try to find the active call and masquerade
21994  * into it
21995  */
21996 static int handle_request_invite(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, struct ast_sockaddr *addr, int *recount, const char *e, int *nounlock)
21997 {
21998    int res = 1;
21999    int gotdest;
22000    const char *p_replaces;
22001    char *replace_id = NULL;
22002    int refer_locked = 0;
22003    const char *required;
22004    unsigned int required_profile = 0;
22005    struct ast_channel *c = NULL;    /* New channel */
22006    struct sip_peer *authpeer = NULL;   /* Matching Peer */
22007    int reinvite = 0;
22008    int rtn;
22009    struct ast_party_redirecting redirecting;
22010    struct ast_set_party_redirecting update_redirecting;
22011 
22012    const char *p_uac_se_hdr;       /* UAC's Session-Expires header string                      */
22013    const char *p_uac_min_se;       /* UAC's requested Min-SE interval (char string)            */
22014    int uac_max_se = -1;            /* UAC's Session-Expires in integer format                  */
22015    int uac_min_se = -1;            /* UAC's Min-SE in integer format                           */
22016    int st_active = FALSE;          /* Session-Timer on/off boolean                             */
22017    int st_interval = 0;            /* Session-Timer negotiated refresh interval                */
22018    enum st_refresher st_ref;       /* Session-Timer session refresher                          */
22019    int dlg_min_se = -1;
22020    struct {
22021       char exten[AST_MAX_EXTENSION];
22022       char context[AST_MAX_CONTEXT];
22023    } pickup = {
22024          .exten = "",
22025    };
22026    st_ref = SESSION_TIMER_REFRESHER_AUTO;
22027 
22028    /* Find out what they support */
22029    if (!p->sipoptions) {
22030       const char *supported = get_header(req, "Supported");
22031       if (!ast_strlen_zero(supported)) {
22032          p->sipoptions = parse_sip_options(supported, NULL, 0);
22033       }
22034    }
22035 
22036    /* Find out what they require */
22037    required = get_header(req, "Require");
22038    if (!ast_strlen_zero(required)) {
22039       char unsupported[256] = { 0, };
22040       required_profile = parse_sip_options(required, unsupported, ARRAY_LEN(unsupported));
22041 
22042       /* If there are any options required that we do not support,
22043        * then send a 420 with only those unsupported options listed */
22044       if (!ast_strlen_zero(unsupported)) {
22045          transmit_response_with_unsupported(p, "420 Bad extension (unsupported)", req, unsupported);
22046          ast_log(LOG_WARNING, "Received SIP INVITE with unsupported required extension: required:%s unsupported:%s\n", required, unsupported);
22047          p->invitestate = INV_COMPLETED;
22048          if (!p->lastinvite)
22049             sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
22050          res = -1;
22051          goto request_invite_cleanup;
22052       }
22053    }
22054 
22055    /* The option tags may be present in Supported: or Require: headers.
22056    Include the Require: option tags for further processing as well */
22057    p->sipoptions |= required_profile;
22058    p->reqsipoptions = required_profile;
22059 
22060    /* Check if this is a loop */
22061    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) {
22062       /* This is a call to ourself.  Send ourselves an error code and stop
22063          processing immediately, as SIP really has no good mechanism for
22064          being able to call yourself */
22065       /* If pedantic is on, we need to check the tags. If they're different, this is
22066          in fact a forked call through a SIP proxy somewhere. */
22067       int different;
22068       const char *initial_rlPart2 = REQ_OFFSET_TO_STR(&p->initreq, rlPart2);
22069       const char *this_rlPart2 = REQ_OFFSET_TO_STR(req, rlPart2);
22070       if (sip_cfg.pedanticsipchecking)
22071          different = sip_uri_cmp(initial_rlPart2, this_rlPart2);
22072       else
22073          different = strcmp(initial_rlPart2, this_rlPart2);
22074       if (!different) {
22075          transmit_response(p, "482 Loop Detected", req);
22076          p->invitestate = INV_COMPLETED;
22077          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
22078          res = 0;
22079          goto request_invite_cleanup;
22080       } else {
22081          /*! This is a spiral. What we need to do is to just change the outgoing INVITE
22082           * so that it now routes to the new Request URI. Since we created the INVITE ourselves
22083           * that should be all we need to do.
22084           *
22085           * \todo XXX This needs to be reviewed.  YOu don't change the request URI really, you route the packet
22086           * correctly instead...
22087           */
22088          char *uri = ast_strdupa(this_rlPart2);
22089          char *at = strchr(uri, '@');
22090          char *peerorhost;
22091          ast_debug(2, "Potential spiral detected. Original RURI was %s, new RURI is %s\n", initial_rlPart2, this_rlPart2);
22092          transmit_response(p, "100 Trying", req);
22093          if (at) {
22094             *at = '\0';
22095          }
22096          /* Parse out "sip:" */
22097          if ((peerorhost = strchr(uri, ':'))) {
22098             *peerorhost++ = '\0';
22099          }
22100          ast_string_field_set(p, theirtag, NULL);
22101          /* Treat this as if there were a call forward instead...
22102           */
22103          ast_string_field_set(p->owner, call_forward, peerorhost);
22104          ast_queue_control(p->owner, AST_CONTROL_BUSY);
22105          res = 0;
22106          goto request_invite_cleanup;
22107       }
22108    }
22109 
22110    if (!req->ignore && p->pendinginvite) {
22111       if (!ast_test_flag(&p->flags[0], SIP_OUTGOING) && (p->invitestate == INV_COMPLETED || p->invitestate == INV_TERMINATED)) {
22112          /* What do these circumstances mean? We have received an INVITE for an "incoming" dialog for which we
22113           * have sent a final response. We have not yet received an ACK, though (which is why p->pendinginvite is non-zero).
22114           * We also know that the INVITE is not a retransmission, because otherwise the "ignore" flag would be set.
22115           * This means that either we are receiving a reinvite for a terminated dialog, or we are receiving an INVITE with
22116           * credentials based on one we challenged earlier.
22117           *
22118           * The action to take in either case is to treat the INVITE as though it contains an implicit ACK for the previous
22119           * transaction. Calling __sip_ack will take care of this by clearing the p->pendinginvite and removing the response
22120           * from the previous transaction from the list of outstanding packets.
22121           */
22122          __sip_ack(p, p->pendinginvite, 1, 0);
22123       } else {
22124          /* We already have a pending invite. Sorry. You are on hold. */
22125          p->glareinvite = seqno;
22126          if (p->rtp && find_sdp(req)) {
22127             struct ast_sockaddr addr;
22128             if (get_ip_and_port_from_sdp(req, SDP_AUDIO, &addr)) {
22129                ast_log(LOG_WARNING, "Failed to set an alternate media source on glared reinvite. Audio may not work properly on this call.\n");
22130             } else {
22131                ast_rtp_instance_set_alt_remote_address(p->rtp, &addr);
22132             }
22133             if (p->vrtp) {
22134                if (get_ip_and_port_from_sdp(req, SDP_VIDEO, &addr)) {
22135                   ast_log(LOG_WARNING, "Failed to set an alternate media source on glared reinvite. Video may not work properly on this call.\n");
22136                } else {
22137                   ast_rtp_instance_set_alt_remote_address(p->vrtp, &addr);
22138                }
22139             }
22140          }
22141          transmit_response_reliable(p, "491 Request Pending", req);
22142          ast_debug(1, "Got INVITE on call where we already have pending INVITE, deferring that - %s\n", p->callid);
22143          /* Don't destroy dialog here */
22144          res = 0;
22145          goto request_invite_cleanup;
22146       }
22147    }
22148 
22149    p_replaces = get_header(req, "Replaces");
22150    if (!ast_strlen_zero(p_replaces)) {
22151       /* We have a replaces header */
22152       char *ptr;
22153       char *fromtag = NULL;
22154       char *totag = NULL;
22155       char *start, *to;
22156       int error = 0;
22157 
22158       if (p->owner) {
22159          ast_debug(3, "INVITE w Replaces on existing call? Refusing action. [%s]\n", p->callid);
22160          transmit_response_reliable(p, "400 Bad request", req);   /* The best way to not not accept the transfer */
22161          /* Do not destroy existing call */
22162          res = -1;
22163          goto request_invite_cleanup;
22164       }
22165 
22166       if (sipdebug)
22167          ast_debug(3, "INVITE part of call transfer. Replaces [%s]\n", p_replaces);
22168       /* Create a buffer we can manipulate */
22169       replace_id = ast_strdupa(p_replaces);
22170       ast_uri_decode(replace_id);
22171 
22172       if (!p->refer && !sip_refer_allocate(p)) {
22173          transmit_response_reliable(p, "500 Server Internal Error", req);
22174          append_history(p, "Xfer", "INVITE/Replace Failed. Out of memory.");
22175          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
22176          p->invitestate = INV_COMPLETED;
22177          res = -1;
22178          goto request_invite_cleanup;
22179       }
22180 
22181       /*  Todo: (When we find phones that support this)
22182          if the replaces header contains ";early-only"
22183          we can only replace the call in early
22184          stage, not after it's up.
22185 
22186          If it's not in early mode, 486 Busy.
22187       */
22188 
22189       /* Skip leading whitespace */
22190       replace_id = ast_skip_blanks(replace_id);
22191 
22192       start = replace_id;
22193       while ( (ptr = strsep(&start, ";")) ) {
22194          ptr = ast_skip_blanks(ptr); /* XXX maybe unnecessary ? */
22195          if ( (to = strcasestr(ptr, "to-tag=") ) )
22196             totag = to + 7;   /* skip the keyword */
22197          else if ( (to = strcasestr(ptr, "from-tag=") ) ) {
22198             fromtag = to + 9; /* skip the keyword */
22199             fromtag = strsep(&fromtag, "&"); /* trim what ? */
22200          }
22201       }
22202 
22203       if (sipdebug)
22204          ast_debug(4, "Invite/replaces: Will use Replace-Call-ID : %s Fromtag: %s Totag: %s\n",
22205                  replace_id,
22206                  fromtag ? fromtag : "<no from tag>",
22207                  totag ? totag : "<no to tag>");
22208 
22209       /* Try to find call that we are replacing.
22210          If we have a Replaces header, we need to cancel that call if we succeed with this call.
22211          First we cheat a little and look for a magic call-id from phones that support
22212          dialog-info+xml so we can do technology independent pickup... */
22213       if (strncmp(replace_id, "pickup-", 7) == 0) {
22214          struct sip_pvt *subscription = NULL;
22215          replace_id += 7; /* Worst case we are looking at \0 */
22216 
22217          if ((subscription = get_sip_pvt_byid_locked(replace_id, totag, fromtag)) == NULL) {
22218             ast_log(LOG_NOTICE, "Unable to find subscription with call-id: %s\n", replace_id);
22219             transmit_response_reliable(p, "481 Call Leg Does Not Exist (Replaces)", req);
22220             error = 1;
22221          } else {
22222             ast_log(LOG_NOTICE, "Trying to pick up %s@%s\n", subscription->exten, subscription->context);
22223             ast_copy_string(pickup.exten, subscription->exten, sizeof(pickup.exten));
22224             ast_copy_string(pickup.context, subscription->context, sizeof(pickup.context));
22225             sip_pvt_unlock(subscription);
22226             if (subscription->owner) {
22227                ast_channel_unlock(subscription->owner);
22228             }
22229          }
22230       }
22231 
22232       /* This locks both refer_call pvt and refer_call pvt's owner!!!*/
22233       if (!error && ast_strlen_zero(pickup.exten) && (p->refer->refer_call = get_sip_pvt_byid_locked(replace_id, totag, fromtag)) == NULL) {
22234          ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-existent call id (%s)!\n", replace_id);
22235          transmit_response_reliable(p, "481 Call Leg Does Not Exist (Replaces)", req);
22236          error = 1;
22237       } else {
22238          refer_locked = 1;
22239       }
22240 
22241       /* The matched call is the call from the transferer to Asterisk .
22242          We want to bridge the bridged part of the call to the
22243          incoming invite, thus taking over the refered call */
22244 
22245       if (p->refer->refer_call == p) {
22246          ast_log(LOG_NOTICE, "INVITE with replaces into it's own call id (%s == %s)!\n", replace_id, p->callid);
22247          p->refer->refer_call = dialog_unref(p->refer->refer_call, "unref dialog p->refer->refer_call");
22248          transmit_response_reliable(p, "400 Bad request", req);   /* The best way to not not accept the transfer */
22249          error = 1;
22250       }
22251 
22252       if (!error && ast_strlen_zero(pickup.exten) && !p->refer->refer_call->owner) {
22253          /* Oops, someting wrong anyway, no owner, no call */
22254          ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-existing call id (%s)!\n", replace_id);
22255          /* Check for better return code */
22256          transmit_response_reliable(p, "481 Call Leg Does Not Exist (Replace)", req);
22257          error = 1;
22258       }
22259 
22260       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) {
22261          ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-ringing or active call id (%s)!\n", replace_id);
22262          transmit_response_reliable(p, "603 Declined (Replaces)", req);
22263          error = 1;
22264       }
22265 
22266       if (error) {   /* Give up this dialog */
22267          append_history(p, "Xfer", "INVITE/Replace Failed.");
22268          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
22269          sip_pvt_unlock(p);
22270          if (p->refer->refer_call) {
22271             sip_pvt_unlock(p->refer->refer_call);
22272             if (p->refer->refer_call->owner) {
22273                ast_channel_unlock(p->refer->refer_call->owner);
22274             }
22275          }
22276          refer_locked = 0;
22277          p->invitestate = INV_COMPLETED;
22278          res = -1;
22279          goto request_invite_cleanup;
22280       }
22281    }
22282 
22283    /* Check if this is an INVITE that sets up a new dialog or
22284       a re-invite in an existing dialog */
22285 
22286    if (!req->ignore) {
22287       int newcall = (p->initreq.headers ? TRUE : FALSE);
22288 
22289       if (sip_cancel_destroy(p))
22290          ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
22291       /* This also counts as a pending invite */
22292       p->pendinginvite = seqno;
22293       check_via(p, req);
22294 
22295       copy_request(&p->initreq, req);     /* Save this INVITE as the transaction basis */
22296       if (sipdebug)
22297          ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
22298       if (!p->owner) {  /* Not a re-invite */
22299          if (debug)
22300             ast_verbose("Using INVITE request as basis request - %s\n", p->callid);
22301          if (newcall)
22302             append_history(p, "Invite", "New call: %s", p->callid);
22303          parse_ok_contact(p, req);
22304       } else { /* Re-invite on existing call */
22305          ast_clear_flag(&p->flags[0], SIP_OUTGOING);  /* This is now an inbound dialog */
22306          if (get_rpid(p, req)) {
22307             struct ast_party_connected_line connected;
22308             struct ast_set_party_connected_line update_connected;
22309 
22310             ast_party_connected_line_init(&connected);
22311             memset(&update_connected, 0, sizeof(update_connected));
22312 
22313             update_connected.id.number = 1;
22314             connected.id.number.valid = 1;
22315             connected.id.number.str = (char *) p->cid_num;
22316             connected.id.number.presentation = p->callingpres;
22317 
22318             update_connected.id.name = 1;
22319             connected.id.name.valid = 1;
22320             connected.id.name.str = (char *) p->cid_name;
22321             connected.id.name.presentation = p->callingpres;
22322 
22323             connected.id.tag = (char *) p->cid_tag;
22324             connected.source = AST_CONNECTED_LINE_UPDATE_SOURCE_TRANSFER;
22325             ast_channel_queue_connected_line_update(p->owner, &connected,
22326                &update_connected);
22327          }
22328          /* Handle SDP here if we already have an owner */
22329          if (find_sdp(req)) {
22330             if (process_sdp(p, req, SDP_T38_INITIATE)) {
22331                if (!ast_strlen_zero(get_header(req, "Content-Encoding"))) {
22332                   /* Asterisk does not yet support any Content-Encoding methods.  Always
22333                    * attempt to process the sdp, but return a 415 if a Content-Encoding header
22334                    * was present after processing failed.  */
22335                   transmit_response_reliable(p, "415 Unsupported Media type", req);
22336                } else {
22337                   transmit_response_reliable(p, "488 Not acceptable here", req);
22338                }
22339                if (!p->lastinvite)
22340                   sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
22341                res = -1;
22342                goto request_invite_cleanup;
22343             }
22344             ast_queue_control(p->owner, AST_CONTROL_SRCUPDATE);
22345          } else {
22346             p->jointcapability = p->capability;
22347             ast_debug(1, "Hm....  No sdp for the moment\n");
22348             /* Some devices signal they want to be put off hold by sending a re-invite
22349                *without* an SDP, which is supposed to mean "Go back to your state"
22350                and since they put os on remote hold, we go back to off hold */
22351             if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
22352                ast_queue_control(p->owner, AST_CONTROL_UNHOLD);
22353                /* Activate a re-invite */
22354                ast_queue_frame(p->owner, &ast_null_frame);
22355                change_hold_state(p, req, FALSE, 0);
22356             }
22357          }
22358          if (p->do_history) /* This is a response, note what it was for */
22359             append_history(p, "ReInv", "Re-invite received");
22360       }
22361    } else if (debug)
22362       ast_verbose("Ignoring this INVITE request\n");
22363 
22364    if (!p->lastinvite && !req->ignore && !p->owner) {
22365       /* This is a new invite */
22366       /* Handle authentication if this is our first invite */
22367       int cc_recall_core_id = -1;
22368       set_pvt_allowed_methods(p, req);
22369       res = check_user_full(p, req, SIP_INVITE, e, XMIT_RELIABLE, addr, &authpeer);
22370       if (res == AUTH_CHALLENGE_SENT) {
22371          p->invitestate = INV_COMPLETED;     /* Needs to restart in another INVITE transaction */
22372          res = 0;
22373          goto request_invite_cleanup;
22374       }
22375       if (res < 0) { /* Something failed in authentication */
22376          if (res == AUTH_FAKE_AUTH) {
22377             ast_log(LOG_NOTICE, "Sending fake auth rejection for device %s\n", get_header(req, "From"));
22378             transmit_fake_auth_response(p, SIP_INVITE, req, XMIT_RELIABLE);
22379          } else {
22380             ast_log(LOG_NOTICE, "Failed to authenticate device %s\n", get_header(req, "From"));
22381             transmit_response_reliable(p, "403 Forbidden", req);
22382          }
22383          p->invitestate = INV_COMPLETED;
22384          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
22385          res = 0;
22386          goto request_invite_cleanup;
22387       }
22388 
22389       /* Successful authentication and peer matching so record the peer related to this pvt (for easy access to peer settings) */
22390       if (p->relatedpeer) {
22391          p->relatedpeer = unref_peer(p->relatedpeer,"unsetting the relatedpeer field in the dialog, before it is set to something else.");
22392       }
22393       if (authpeer) {
22394          p->relatedpeer = ref_peer(authpeer, "setting dialog's relatedpeer pointer");
22395       }
22396       /* If T38 is needed but not present, then make it magically appear */
22397       if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) && !p->udptl) {
22398          if ((p->udptl = ast_udptl_new_with_bindaddr(sched, io, 0, &bindaddr))) {
22399             p->t38_maxdatagram = global_t38_maxdatagram;
22400             set_t38_capabilities(p);
22401          } else {
22402             /* udptl creation failed, T38 can not be supported on this dialog */
22403             ast_debug(1, "UDPTL creation failed on dialog.\n");
22404             ast_clear_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT);
22405          }
22406       }
22407 
22408       req->authenticated = 1;
22409 
22410       /* We have a successful authentication, process the SDP portion if there is one */
22411       if (find_sdp(req)) {
22412          if (process_sdp(p, req, SDP_T38_INITIATE)) {
22413             /* Asterisk does not yet support any Content-Encoding methods.  Always
22414              * attempt to process the sdp, but return a 415 if a Content-Encoding header
22415              * was present after processing fails. */
22416             if (!ast_strlen_zero(get_header(req, "Content-Encoding"))) {
22417                transmit_response_reliable(p, "415 Unsupported Media type", req);
22418             } else {
22419                /* Unacceptable codecs */
22420                transmit_response_reliable(p, "488 Not acceptable here", req);
22421             }
22422             p->invitestate = INV_COMPLETED;
22423             sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
22424             ast_debug(1, "No compatible codecs for this SIP call.\n");
22425             res = -1;
22426             goto request_invite_cleanup;
22427          }
22428       } else { /* No SDP in invite, call control session */
22429          p->jointcapability = p->capability;
22430          ast_debug(2, "No SDP in Invite, third party call control\n");
22431       }
22432 
22433       /* Queue NULL frame to prod ast_rtp_bridge if appropriate */
22434       /* This seems redundant ... see !p-owner above */
22435       if (p->owner)
22436          ast_queue_frame(p->owner, &ast_null_frame);
22437 
22438 
22439       /* Initialize the context if it hasn't been already */
22440       if (ast_strlen_zero(p->context))
22441          ast_string_field_set(p, context, sip_cfg.default_context);
22442 
22443 
22444       /* Check number of concurrent calls -vs- incoming limit HERE */
22445       ast_debug(1, "Checking SIP call limits for device %s\n", p->username);
22446       if ((res = update_call_counter(p, INC_CALL_LIMIT))) {
22447          if (res < 0) {
22448             ast_log(LOG_NOTICE, "Failed to place call for device %s, too many calls\n", p->username);
22449             transmit_response_reliable(p, "480 Temporarily Unavailable (Call limit) ", req);
22450             sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
22451             p->invitestate = INV_COMPLETED;
22452          }
22453          res = 0;
22454          goto request_invite_cleanup;
22455       }
22456       gotdest = get_destination(p, NULL, &cc_recall_core_id);  /* Get destination right away */
22457       extract_uri(p, req);       /* Get the Contact URI */
22458       build_contact(p);       /* Build our contact header */
22459 
22460       if (p->rtp) {
22461          ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_DTMF, ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
22462          ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_DTMF_COMPENSATE, ast_test_flag(&p->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
22463       }
22464 
22465       if (!replace_id && (gotdest != SIP_GET_DEST_EXTEN_FOUND)) { /* No matching extension found */
22466          switch(gotdest) {
22467          case SIP_GET_DEST_INVALID_URI:
22468             transmit_response_reliable(p, "416 Unsupported URI scheme", req);
22469             break;
22470          case SIP_GET_DEST_EXTEN_MATCHMORE:
22471             if (ast_test_flag(&p->flags[1], SIP_PAGE2_ALLOWOVERLAP)
22472                == SIP_PAGE2_ALLOWOVERLAP_YES) {
22473                transmit_response_reliable(p, "484 Address Incomplete", req);
22474                break;
22475             }
22476             /*
22477              * XXX We would have to implement collecting more digits in
22478              * chan_sip for any other schemes of overlap dialing.
22479              *
22480              * For SIP_PAGE2_ALLOWOVERLAP_DTMF it is better to do this in
22481              * the dialplan using the Incomplete application rather than
22482              * having the channel driver do it.
22483              */
22484             /* Fall through */
22485          case SIP_GET_DEST_EXTEN_NOT_FOUND:
22486          case SIP_GET_DEST_REFUSED:
22487          default:
22488             {
22489                char *decoded_exten = ast_strdupa(p->exten);
22490                transmit_response_reliable(p, "404 Not Found", req);
22491                ast_uri_decode(decoded_exten);
22492                ast_log(LOG_NOTICE, "Call from '%s' (%s) to extension"
22493                   " '%s' rejected because extension not found in context '%s'.\n",
22494                   S_OR(p->username, p->peername), ast_sockaddr_stringify(&p->recv), decoded_exten, p->context);
22495             }
22496          } /* end switch */
22497 
22498          p->invitestate = INV_COMPLETED;
22499          update_call_counter(p, DEC_CALL_LIMIT);
22500          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
22501          res = 0;
22502          goto request_invite_cleanup;
22503       } else {
22504 
22505          /* If no extension was specified, use the s one */
22506          /* Basically for calling to IP/Host name only */
22507          if (ast_strlen_zero(p->exten))
22508             ast_string_field_set(p, exten, "s");
22509          /* Initialize our tag */
22510 
22511          make_our_tag(p->tag, sizeof(p->tag));
22512          /* First invitation - create the channel.  Allocation
22513           * failures are handled below. */
22514          c = sip_new(p, AST_STATE_DOWN, S_OR(p->peername, NULL), NULL);
22515          if (cc_recall_core_id != -1) {
22516             ast_setup_cc_recall_datastore(c, cc_recall_core_id);
22517             ast_cc_agent_set_interfaces_chanvar(c);
22518          }
22519          *recount = 1;
22520 
22521          /* Save Record-Route for any later requests we make on this dialogue */
22522          build_route(p, req, 0);
22523 
22524          if (c) {
22525             ast_party_redirecting_init(&redirecting);
22526             memset(&update_redirecting, 0, sizeof(update_redirecting));
22527             change_redirecting_information(p, req, &redirecting, &update_redirecting,
22528                FALSE); /*Will return immediately if no Diversion header is present */
22529             ast_channel_set_redirecting(c, &redirecting, &update_redirecting);
22530             ast_party_redirecting_free(&redirecting);
22531          }
22532       }
22533    } else {
22534       ast_party_redirecting_init(&redirecting);
22535       memset(&update_redirecting, 0, sizeof(update_redirecting));
22536       if (sipdebug) {
22537          if (!req->ignore)
22538             ast_debug(2, "Got a SIP re-invite for call %s\n", p->callid);
22539          else
22540             ast_debug(2, "Got a SIP re-transmit of INVITE for call %s\n", p->callid);
22541       }
22542       if (!req->ignore)
22543          reinvite = 1;
22544       c = p->owner;
22545       change_redirecting_information(p, req, &redirecting, &update_redirecting, FALSE); /*Will return immediately if no Diversion header is present */
22546       if (c) {
22547          ast_channel_set_redirecting(c, &redirecting, &update_redirecting);
22548       }
22549       ast_party_redirecting_free(&redirecting);
22550    }
22551 
22552    /* Session-Timers */
22553    if ((p->sipoptions & SIP_OPT_TIMER) && !ast_strlen_zero(get_header(req, "Session-Expires"))) {
22554       /* The UAC has requested session-timers for this session. Negotiate
22555       the session refresh interval and who will be the refresher */
22556       ast_debug(2, "Incoming INVITE with 'timer' option supported and \"Session-Expires\" header.\n");
22557 
22558       /* Allocate Session-Timers struct w/in the dialog */
22559       if (!p->stimer)
22560          sip_st_alloc(p);
22561 
22562       /* Parse the Session-Expires header */
22563       p_uac_se_hdr = get_header(req, "Session-Expires");
22564       rtn = parse_session_expires(p_uac_se_hdr, &uac_max_se, &st_ref);
22565       if (rtn != 0) {
22566          transmit_response_reliable(p, "400 Session-Expires Invalid Syntax", req);
22567          p->invitestate = INV_COMPLETED;
22568          if (!p->lastinvite) {
22569             sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
22570          }
22571          res = -1;
22572          goto request_invite_cleanup;
22573       }
22574 
22575       /* Parse the Min-SE header */
22576       p_uac_min_se = get_header(req, "Min-SE");
22577       if (!ast_strlen_zero(p_uac_min_se)) {
22578          rtn = parse_minse(p_uac_min_se, &uac_min_se);
22579          if (rtn != 0) {
22580             transmit_response_reliable(p, "400 Min-SE Invalid Syntax", req);
22581             p->invitestate = INV_COMPLETED;
22582             if (!p->lastinvite) {
22583                sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
22584             }
22585             res = -1;
22586             goto request_invite_cleanup;
22587          }
22588       }
22589 
22590       dlg_min_se = st_get_se(p, FALSE);
22591       switch (st_get_mode(p, 1)) {
22592       case SESSION_TIMER_MODE_ACCEPT:
22593       case SESSION_TIMER_MODE_ORIGINATE:
22594          if (uac_max_se > 0 && uac_max_se < dlg_min_se) {
22595             transmit_response_with_minse(p, "422 Session Interval Too Small", req, dlg_min_se);
22596             p->invitestate = INV_COMPLETED;
22597             if (!p->lastinvite) {
22598                sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
22599             }
22600             res = -1;
22601             goto request_invite_cleanup;
22602          }
22603 
22604          p->stimer->st_active_peer_ua = TRUE;
22605          st_active = TRUE;
22606          if (st_ref == SESSION_TIMER_REFRESHER_AUTO) {
22607             st_ref = st_get_refresher(p);
22608          }
22609 
22610          if (uac_max_se > 0) {
22611             int dlg_max_se = st_get_se(p, TRUE);
22612             if (dlg_max_se >= uac_min_se) {
22613                st_interval = (uac_max_se < dlg_max_se) ? uac_max_se : dlg_max_se;
22614             } else {
22615                st_interval = uac_max_se;
22616             }
22617          } else {
22618             /* Set to default max value */
22619             st_interval = global_max_se;
22620          }
22621          break;
22622 
22623       case SESSION_TIMER_MODE_REFUSE:
22624          if (p->reqsipoptions & SIP_OPT_TIMER) {
22625             transmit_response_with_unsupported(p, "420 Option Disabled", req, required);
22626             ast_log(LOG_WARNING, "Received SIP INVITE with supported but disabled option: %s\n", required);
22627             p->invitestate = INV_COMPLETED;
22628             if (!p->lastinvite) {
22629                sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
22630             }
22631             res = -1;
22632             goto request_invite_cleanup;
22633          }
22634          break;
22635 
22636       default:
22637          ast_log(LOG_ERROR, "Internal Error %d at %s:%d\n", st_get_mode(p, 1), __FILE__, __LINE__);
22638          break;
22639       }
22640    } else {
22641       /* The UAC did not request session-timers.  Asterisk (UAS), will now decide
22642       (based on session-timer-mode in sip.conf) whether to run session-timers for
22643       this session or not. */
22644       switch (st_get_mode(p, 1)) {
22645       case SESSION_TIMER_MODE_ORIGINATE:
22646          st_active = TRUE;
22647          st_interval = st_get_se(p, TRUE);
22648          st_ref = SESSION_TIMER_REFRESHER_UAS;
22649          p->stimer->st_active_peer_ua = FALSE;
22650          break;
22651 
22652       default:
22653          break;
22654       }
22655    }
22656 
22657    if (reinvite == 0) {
22658       /* Session-Timers: Start session refresh timer based on negotiation/config */
22659       if (st_active == TRUE) {
22660          p->stimer->st_active   = TRUE;
22661          p->stimer->st_interval = st_interval;
22662          p->stimer->st_ref      = st_ref;
22663          start_session_timer(p);
22664       }
22665    } else {
22666       if (p->stimer->st_active == TRUE) {
22667          /* Session-Timers:  A re-invite request sent within a dialog will serve as
22668          a refresh request, no matter whether the re-invite was sent for refreshing
22669          the session or modifying it.*/
22670          ast_debug (2, "Restarting session-timers on a refresh - %s\n", p->callid);
22671 
22672          /* The UAC may be adjusting the session-timers mid-session */
22673          if (st_interval > 0) {
22674             p->stimer->st_interval = st_interval;
22675             p->stimer->st_ref      = st_ref;
22676          }
22677 
22678          restart_session_timer(p);
22679          if (p->stimer->st_expirys > 0) {
22680             p->stimer->st_expirys--;
22681          }
22682       }
22683    }
22684 
22685    if (!req->ignore && p)
22686       p->lastinvite = seqno;
22687 
22688    if (c && replace_id) {  /* Attended transfer or call pickup - we're the target */
22689       if (!ast_strlen_zero(pickup.exten)) {
22690          append_history(p, "Xfer", "INVITE/Replace received");
22691 
22692          /* Let the caller know we're giving it a shot */
22693          transmit_response(p, "100 Trying", req);
22694          p->invitestate = INV_PROCEEDING;
22695          ast_setstate(c, AST_STATE_RING);
22696 
22697          /* Do the pickup itself */
22698          ast_channel_unlock(c);
22699          *nounlock = 1;
22700 
22701          /* since p->owner (c) is unlocked, we need to go ahead and unlock pvt for both
22702           * magic pickup and ast_hangup.  Both of these functions will attempt to lock
22703           * p->owner again, which can cause a deadlock if we already hold a lock on p.
22704           * Locking order is, channel then pvt.  Dead lock avoidance must be used if
22705           * called the other way around. */
22706          sip_pvt_unlock(p);
22707          do_magic_pickup(c, pickup.exten, pickup.context);
22708          /* Now we're either masqueraded or we failed to pickup, in either case we... */
22709          ast_hangup(c);
22710          sip_pvt_lock(p); /* pvt is expected to remain locked on return, so re-lock it */
22711 
22712          res = 0;
22713          goto request_invite_cleanup;
22714       } else {
22715          /* Go and take over the target call */
22716          if (sipdebug)
22717             ast_debug(4, "Sending this call to the invite/replcaes handler %s\n", p->callid);
22718          res = handle_invite_replaces(p, req, debug, seqno, addr, nounlock);
22719          refer_locked = 0;
22720          goto request_invite_cleanup;
22721       }
22722    }
22723 
22724 
22725    if (c) { /* We have a call  -either a new call or an old one (RE-INVITE) */
22726       enum ast_channel_state c_state = c->_state;
22727 
22728       if (c_state != AST_STATE_UP && reinvite &&
22729          (p->invitestate == INV_TERMINATED || p->invitestate == INV_CONFIRMED)) {
22730          /* If these conditions are true, and the channel is still in the 'ringing'
22731           * state, then this likely means that we have a situation where the initial
22732           * INVITE transaction has completed *but* the channel's state has not yet been
22733           * changed to UP. The reason this could happen is if the reinvite is received
22734           * on the SIP socket prior to an application calling ast_read on this channel
22735           * to read the answer frame we earlier queued on it. In this case, the reinvite
22736           * is completely legitimate so we need to handle this the same as if the channel
22737           * were already UP. Thus we are purposely falling through to the AST_STATE_UP case.
22738           */
22739          c_state = AST_STATE_UP;
22740       }
22741 
22742       switch(c_state) {
22743       case AST_STATE_DOWN:
22744          ast_debug(2, "%s: New call is still down.... Trying... \n", c->name);
22745          transmit_provisional_response(p, "100 Trying", req, 0);
22746          p->invitestate = INV_PROCEEDING;
22747          ast_setstate(c, AST_STATE_RING);
22748          if (strcmp(p->exten, ast_pickup_ext())) { /* Call to extension -start pbx on this call */
22749             enum ast_pbx_result result;
22750 
22751             result = ast_pbx_start(c);
22752 
22753             switch(result) {
22754             case AST_PBX_FAILED:
22755                ast_log(LOG_WARNING, "Failed to start PBX :(\n");
22756                p->invitestate = INV_COMPLETED;
22757                transmit_response_reliable(p, "503 Unavailable", req);
22758                break;
22759             case AST_PBX_CALL_LIMIT:
22760                ast_log(LOG_WARNING, "Failed to start PBX (call limit reached) \n");
22761                p->invitestate = INV_COMPLETED;
22762                transmit_response_reliable(p, "480 Temporarily Unavailable", req);
22763                break;
22764             case AST_PBX_SUCCESS:
22765                /* nothing to do */
22766                break;
22767             }
22768 
22769             if (result) {
22770 
22771                /* Unlock locks so ast_hangup can do its magic */
22772                ast_channel_unlock(c);
22773                *nounlock = 1;
22774                sip_pvt_unlock(p);
22775                ast_hangup(c);
22776                sip_pvt_lock(p);
22777                c = NULL;
22778             }
22779          } else { /* Pickup call in call group */
22780             if (sip_pickup(c)) {
22781                ast_log(LOG_WARNING, "Failed to start Group pickup by %s\n", c->name);
22782                transmit_response_reliable(p, "480 Temporarily Unavailable", req);
22783                sip_alreadygone(p);
22784                c->hangupcause = AST_CAUSE_FAILURE;
22785 
22786                /* Unlock locks so ast_hangup can do its magic */
22787                ast_channel_unlock(c);
22788                *nounlock = 1;
22789 
22790                p->invitestate = INV_COMPLETED;
22791                sip_pvt_unlock(p);
22792                ast_hangup(c);
22793                sip_pvt_lock(p);
22794                c = NULL;
22795             }
22796          }
22797          break;
22798       case AST_STATE_RING:
22799          transmit_provisional_response(p, "100 Trying", req, 0);
22800          p->invitestate = INV_PROCEEDING;
22801          break;
22802       case AST_STATE_RINGING:
22803          transmit_provisional_response(p, "180 Ringing", req, 0);
22804          p->invitestate = INV_PROCEEDING;
22805          break;
22806       case AST_STATE_UP:
22807          ast_debug(2, "%s: This call is UP.... \n", c->name);
22808 
22809          transmit_response(p, "100 Trying", req);
22810 
22811          if (p->t38.state == T38_PEER_REINVITE) {
22812             if (p->t38id > -1) {
22813                /* reset t38 abort timer */
22814                AST_SCHED_DEL_UNREF(sched, p->t38id, dialog_unref(p, "remove ref for t38id"));
22815             }
22816             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."));
22817          } else if (p->t38.state == T38_ENABLED) {
22818             ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
22819             transmit_response_with_t38_sdp(p, "200 OK", req, (reinvite ? XMIT_RELIABLE : (req->ignore ?  XMIT_UNRELIABLE : XMIT_CRITICAL)));
22820          } else if (p->t38.state == T38_DISABLED) {
22821             /* If this is not a re-invite or something to ignore - it's critical */
22822             if (p->srtp && !ast_test_flag(p->srtp, SRTP_CRYPTO_OFFER_OK)) {
22823                ast_log(LOG_WARNING, "Target does not support required crypto\n");
22824                transmit_response_reliable(p, "488 Not Acceptable Here (crypto)", req);
22825             } else {
22826                ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
22827                transmit_response_with_sdp(p, "200 OK", req, (reinvite ? XMIT_RELIABLE : (req->ignore ?  XMIT_UNRELIABLE : XMIT_CRITICAL)), p->session_modify == TRUE ? FALSE : TRUE, FALSE);
22828                ast_queue_control(p->owner, AST_CONTROL_UPDATE_RTP_PEER);
22829             }
22830          }
22831 
22832          p->invitestate = INV_TERMINATED;
22833          break;
22834       default:
22835          ast_log(LOG_WARNING, "Don't know how to handle INVITE in state %d\n", c->_state);
22836          transmit_response(p, "100 Trying", req);
22837          break;
22838       }
22839    } else {
22840       if (p && (p->autokillid == -1)) {
22841          const char *msg;
22842 
22843          if (!p->jointcapability)
22844             msg = "488 Not Acceptable Here (codec error)";
22845          else {
22846             ast_log(LOG_NOTICE, "Unable to create/find SIP channel for this INVITE\n");
22847             msg = "503 Unavailable";
22848          }
22849          transmit_response_reliable(p, msg, req);
22850          p->invitestate = INV_COMPLETED;
22851          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
22852       }
22853    }
22854 
22855 request_invite_cleanup:
22856 
22857    if (refer_locked && p->refer && p->refer->refer_call) {
22858       sip_pvt_unlock(p->refer->refer_call);
22859       if (p->refer->refer_call->owner) {
22860          ast_channel_unlock(p->refer->refer_call->owner);
22861       }
22862    }
22863    if (authpeer) {
22864       authpeer = unref_peer(authpeer, "unref_peer, from handle_request_invite authpeer");
22865    }
22866 
22867    return res;
22868 }
22869 
22870 /*! \brief  Find all call legs and bridge transferee with target
22871  * called from handle_request_refer
22872  *
22873  * \note this function assumes two locks to begin with, sip_pvt transferer and current.chan1 (the pvt's owner)... 
22874  * 2 additional locks are held at the beginning of the function, targetcall_pvt, and targetcall_pvt's owner
22875  * channel (which is stored in target.chan1).  These 2 locks _MUST_ be let go by the end of the function.  Do
22876  * not be confused into thinking a pvt's owner is the same thing as the channels locked at the beginning of
22877  * this function, after the masquerade this may not be true.  Be consistent and unlock only the exact same
22878  * pointers that were locked to begin with.
22879  *
22880  * If this function is successful, only the transferer pvt lock will remain on return.  Setting nounlock indicates
22881  * to handle_request_do() that the pvt's owner it locked does not require an unlock.
22882  */
22883 static int local_attended_transfer(struct sip_pvt *transferer, struct sip_dual *current, struct sip_request *req, int seqno, int *nounlock)
22884 {
22885    struct sip_dual target;    /* Chan 1: Call from tranferer to Asterisk */
22886                /* Chan 2: Call from Asterisk to target */
22887    int res = 0;
22888    struct sip_pvt *targetcall_pvt;
22889    struct ast_party_connected_line connected_to_transferee;
22890    struct ast_party_connected_line connected_to_target;
22891    char transferer_linkedid[32];
22892    struct ast_channel *chans[2];
22893 
22894    /* Check if the call ID of the replaces header does exist locally */
22895    if (!(targetcall_pvt = get_sip_pvt_byid_locked(transferer->refer->replaces_callid, transferer->refer->replaces_callid_totag,
22896       transferer->refer->replaces_callid_fromtag))) {
22897       if (transferer->refer->localtransfer) {
22898          /* We did not find the refered call. Sorry, can't accept then */
22899          /* Let's fake a response from someone else in order
22900             to follow the standard */
22901          transmit_notify_with_sipfrag(transferer, seqno, "481 Call leg/transaction does not exist", TRUE);
22902          append_history(transferer, "Xfer", "Refer failed");
22903          ast_clear_flag(&transferer->flags[0], SIP_GOTREFER);
22904          transferer->refer->status = REFER_FAILED;
22905          return -1;
22906       }
22907       /* Fall through for remote transfers that we did not find locally */
22908       ast_debug(3, "SIP attended transfer: Not our call - generating INVITE with replaces\n");
22909       return 0;
22910    }
22911 
22912    /* Ok, we can accept this transfer */
22913    append_history(transferer, "Xfer", "Refer accepted");
22914    if (!targetcall_pvt->owner) { /* No active channel */
22915       ast_debug(4, "SIP attended transfer: Error: No owner of target call\n");
22916       /* Cancel transfer */
22917       transmit_notify_with_sipfrag(transferer, seqno, "503 Service Unavailable", TRUE);
22918       append_history(transferer, "Xfer", "Refer failed");
22919       ast_clear_flag(&transferer->flags[0], SIP_GOTREFER);
22920       transferer->refer->status = REFER_FAILED;
22921       sip_pvt_unlock(targetcall_pvt);
22922       if (targetcall_pvt)
22923          ao2_t_ref(targetcall_pvt, -1, "Drop targetcall_pvt pointer");
22924       return -1;
22925    }
22926 
22927    /* We have a channel, find the bridge */
22928    target.chan1 = targetcall_pvt->owner;           /* Transferer to Asterisk */
22929    target.chan2 = ast_bridged_channel(targetcall_pvt->owner);  /* Asterisk to target */
22930 
22931    if (!target.chan2 || !(target.chan2->_state == AST_STATE_UP || target.chan2->_state == AST_STATE_RINGING) ) {
22932       /* Wrong state of new channel */
22933       if (target.chan2)
22934          ast_debug(4, "SIP attended transfer: Error: Wrong state of target call: %s\n", ast_state2str(target.chan2->_state));
22935       else if (target.chan1->_state != AST_STATE_RING)
22936          ast_debug(4, "SIP attended transfer: Error: No target channel\n");
22937       else
22938          ast_debug(4, "SIP attended transfer: Attempting transfer in ringing state\n");
22939    }
22940 
22941    /* Transfer */
22942    if (sipdebug) {
22943       if (current->chan2)  /* We have two bridges */
22944          ast_debug(4, "SIP attended transfer: trying to bridge %s and %s\n", target.chan1->name, current->chan2->name);
22945       else        /* One bridge, propably transfer of IVR/voicemail etc */
22946          ast_debug(4, "SIP attended transfer: trying to make %s take over (masq) %s\n", target.chan1->name, current->chan1->name);
22947    }
22948 
22949    ast_set_flag(&transferer->flags[0], SIP_DEFER_BYE_ON_TRANSFER);   /* Delay hangup */
22950 
22951    ast_copy_string(transferer_linkedid, transferer->owner->linkedid, sizeof(transferer_linkedid));
22952 
22953    /* Perform the transfer */
22954    chans[0] = transferer->owner;
22955    chans[1] = target.chan1;
22956    ast_manager_event_multichan(EVENT_FLAG_CALL, "Transfer", 2, chans,
22957       "TransferMethod: SIP\r\n"
22958       "TransferType: Attended\r\n"
22959       "Channel: %s\r\n"
22960       "Uniqueid: %s\r\n"
22961       "SIP-Callid: %s\r\n"
22962       "TargetChannel: %s\r\n"
22963       "TargetUniqueid: %s\r\n",
22964       transferer->owner->name,
22965       transferer->owner->uniqueid,
22966       transferer->callid,
22967       target.chan1->name,
22968       target.chan1->uniqueid);
22969    ast_party_connected_line_init(&connected_to_transferee);
22970    ast_party_connected_line_init(&connected_to_target);
22971    /* No need to lock current->chan1 here since it was locked in sipsock_read */
22972    ast_party_connected_line_copy(&connected_to_transferee, &current->chan1->connected);
22973    /* No need to lock target.chan1 here since it was locked in get_sip_pvt_byid_locked */
22974    ast_party_connected_line_copy(&connected_to_target, &target.chan1->connected);
22975    connected_to_target.source = connected_to_transferee.source = AST_CONNECTED_LINE_UPDATE_SOURCE_TRANSFER;
22976    res = attempt_transfer(current, &target);
22977    if (res) {
22978       /* Failed transfer */
22979       transmit_notify_with_sipfrag(transferer, seqno, "486 Busy Here", TRUE);
22980       append_history(transferer, "Xfer", "Refer failed");
22981       ast_clear_flag(&transferer->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
22982       /* if transfer failed, go ahead and unlock targetcall_pvt and it's owner channel */
22983       sip_pvt_unlock(targetcall_pvt);
22984       ast_channel_unlock(target.chan1);
22985    } else {
22986       /* Transfer succeeded! */
22987       const char *xfersound = pbx_builtin_getvar_helper(target.chan1, "ATTENDED_TRANSFER_COMPLETE_SOUND");
22988 
22989       /* target.chan1 was locked in get_sip_pvt_byid_locked, do not unlock target.chan1 before this */
22990       ast_cel_report_event(target.chan1, AST_CEL_ATTENDEDTRANSFER, NULL, transferer_linkedid, target.chan2);
22991 
22992       /* Tell transferer that we're done. */
22993       transmit_notify_with_sipfrag(transferer, seqno, "200 OK", TRUE);
22994       append_history(transferer, "Xfer", "Refer succeeded");
22995       transferer->refer->status = REFER_200OK;
22996       if (target.chan2 && !ast_strlen_zero(xfersound) && ast_streamfile(target.chan2, xfersound, target.chan2->language) >= 0) {
22997          ast_waitstream(target.chan2, "");
22998       }
22999 
23000       /* By forcing the masquerade, we know that target.chan1 and target.chan2 are bridged. We then
23001        * can queue connected line updates where they need to go.
23002        *
23003        * before a masquerade, all channel and pvt locks must be unlocked.  Any recursive
23004        * channel locks held before this function invalidates channel container locking order.
23005        * Since we are unlocking both the pvt (transferer) and its owner channel (current.chan1)
23006        * it is possible for current.chan1 to be destroyed in the pbx thread.  To prevent this
23007        * we must give c a reference before any unlocking takes place.
23008        */
23009 
23010       ast_channel_ref(current->chan1);
23011       ast_channel_unlock(current->chan1); /* current.chan1 is p->owner before the masq, it was locked by socket_read()*/
23012       ast_channel_unlock(target.chan1);
23013       *nounlock = 1;  /* we just unlocked the dialog's channel and have no plans of locking it again. */
23014       sip_pvt_unlock(targetcall_pvt);
23015       sip_pvt_unlock(transferer);
23016 
23017       ast_do_masquerade(target.chan1);
23018 
23019       ast_indicate(target.chan1, AST_CONTROL_UNHOLD);
23020       if (target.chan2) {
23021          ast_indicate(target.chan2, AST_CONTROL_UNHOLD);
23022       }
23023 
23024       if (current->chan2 && current->chan2->_state == AST_STATE_RING) {
23025          ast_indicate(target.chan1, AST_CONTROL_RINGING);
23026       }
23027 
23028       if (target.chan2) {
23029          ast_channel_queue_connected_line_update(target.chan1, &connected_to_transferee, NULL);
23030          ast_channel_queue_connected_line_update(target.chan2, &connected_to_target, NULL);
23031       } else {
23032          /* Since target.chan1 isn't actually connected to another channel, there is no way for us
23033           * to queue a frame so that its connected line status will be updated.
23034           *
23035           * Instead, we use the somewhat hackish approach of using a special control frame type that
23036           * instructs ast_read to perform a specific action. In this case, the frame we queue tells
23037           * ast_read to call the connected line interception macro configured for target.chan1.
23038           */
23039          struct ast_control_read_action_payload *frame_payload;
23040          int payload_size;
23041          int frame_size;
23042          unsigned char connected_line_data[1024];
23043          payload_size = ast_connected_line_build_data(connected_line_data,
23044             sizeof(connected_line_data), &connected_to_target, NULL);
23045          frame_size = payload_size + sizeof(*frame_payload);
23046          if (payload_size != -1 && (frame_payload = alloca(frame_size))) {
23047             frame_payload->payload_size = payload_size;
23048             memcpy(frame_payload->payload, connected_line_data, payload_size);
23049             frame_payload->action = AST_FRAME_READ_ACTION_CONNECTED_LINE_MACRO;
23050             ast_queue_control_data(target.chan1, AST_CONTROL_READ_ACTION, frame_payload, frame_size);
23051          }
23052          /* In addition to queueing the read action frame so that target.chan1's connected line info
23053           * will be updated, we also are going to queue a plain old connected line update on target.chan1. This
23054           * way, either Dial or Queue can apply this connected line update to the outgoing ringing channel.
23055           */
23056          ast_channel_queue_connected_line_update(target.chan1, &connected_to_transferee, NULL);
23057 
23058       }
23059       sip_pvt_lock(transferer); /* the transferer pvt is expected to remain locked on return */
23060 
23061       ast_channel_unref(current->chan1);
23062    }
23063 
23064    /* at this point if the transfer is successful only the transferer pvt should be locked. */
23065    ast_party_connected_line_free(&connected_to_target);
23066    ast_party_connected_line_free(&connected_to_transferee);
23067    if (targetcall_pvt)
23068       ao2_t_ref(targetcall_pvt, -1, "drop targetcall_pvt");
23069    return 1;
23070 }
23071 
23072 
23073 /*! \brief Handle incoming REFER request */
23074 /*! \page SIP_REFER SIP transfer Support (REFER)
23075 
23076    REFER is used for call transfer in SIP. We get a REFER
23077    to place a new call with an INVITE somwhere and then
23078    keep the transferor up-to-date of the transfer. If the
23079    transfer fails, get back on line with the orginal call.
23080 
23081    - REFER can be sent outside or inside of a dialog.
23082      Asterisk only accepts REFER inside of a dialog.
23083 
23084    - If we get a replaces header, it is an attended transfer
23085 
23086    \par Blind transfers
23087    The transferor provides the transferee
23088    with the transfer targets contact. The signalling between
23089    transferer or transferee should not be cancelled, so the
23090    call is recoverable if the transfer target can not be reached
23091    by the transferee.
23092 
23093    In this case, Asterisk receives a TRANSFER from
23094    the transferor, thus is the transferee. We should
23095    try to set up a call to the contact provided
23096    and if that fails, re-connect the current session.
23097    If the new call is set up, we issue a hangup.
23098    In this scenario, we are following section 5.2
23099    in the SIP CC Transfer draft. (Transfer without
23100    a GRUU)
23101 
23102    \par Transfer with consultation hold
23103    In this case, the transferor
23104    talks to the transfer target before the transfer takes place.
23105    This is implemented with SIP hold and transfer.
23106    Note: The invite From: string could indicate a transfer.
23107    (Section 6. Transfer with consultation hold)
23108    The transferor places the transferee on hold, starts a call
23109    with the transfer target to alert them to the impending
23110    transfer, terminates the connection with the target, then
23111    proceeds with the transfer (as in Blind transfer above)
23112 
23113    \par Attended transfer
23114    The transferor places the transferee
23115    on hold, calls the transfer target to alert them,
23116    places the target on hold, then proceeds with the transfer
23117    using a Replaces header field in the Refer-to header. This
23118    will force the transfee to send an Invite to the target,
23119    with a replaces header that instructs the target to
23120    hangup the call between the transferor and the target.
23121    In this case, the Refer/to: uses the AOR address. (The same
23122    URI that the transferee used to establish the session with
23123    the transfer target (To: ). The Require: replaces header should
23124    be in the INVITE to avoid the wrong UA in a forked SIP proxy
23125    scenario to answer and have no call to replace with.
23126 
23127    The referred-by header is *NOT* required, but if we get it,
23128    can be copied into the INVITE to the transfer target to
23129    inform the target about the transferor
23130 
23131    "Any REFER request has to be appropriately authenticated.".
23132    
23133    We can't destroy dialogs, since we want the call to continue.
23134    
23135    */
23136 static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, int *nounlock)
23137 {
23138    /*!
23139     * Chan1: Call between asterisk and transferer
23140     * Chan2: Call between asterisk and transferee
23141     */
23142    struct sip_dual current = { 0, };
23143    struct ast_channel *chans[2] = { 0, };
23144    char *refer_to = NULL;
23145    char *refer_to_domain = NULL;
23146    char *refer_to_context = NULL;
23147    char *referred_by = NULL;
23148    char *callid = NULL;
23149    int localtransfer = 0;
23150    int attendedtransfer = 0;
23151    int res = 0;
23152 
23153    if (req->debug) {
23154       ast_verbose("Call %s got a SIP call transfer from %s: (REFER)!\n",
23155          p->callid,
23156          ast_test_flag(&p->flags[0], SIP_OUTGOING) ? "callee" : "caller");
23157    }
23158 
23159    if (!p->owner) {
23160       /* This is a REFER outside of an existing SIP dialog */
23161       /* We can't handle that, so decline it */
23162       ast_debug(3, "Call %s: Declined REFER, outside of dialog...\n", p->callid);
23163       transmit_response(p, "603 Declined (No dialog)", req);
23164       if (!req->ignore) {
23165          append_history(p, "Xfer", "Refer failed. Outside of dialog.");
23166          sip_alreadygone(p);
23167          pvt_set_needdestroy(p, "outside of dialog");
23168       }
23169       res = 0;
23170       goto handle_refer_cleanup;
23171    }
23172 
23173    /* Check if transfer is allowed from this device */
23174    if (p->allowtransfer == TRANSFER_CLOSED ) {
23175       /* Transfer not allowed, decline */
23176       transmit_response(p, "603 Declined (policy)", req);
23177       append_history(p, "Xfer", "Refer failed. Allowtransfer == closed.");
23178       /* Do not destroy SIP session */
23179       res = 0;
23180       goto handle_refer_cleanup;
23181    }
23182 
23183    if (!req->ignore && ast_test_flag(&p->flags[0], SIP_GOTREFER)) {
23184       /* Already have a pending REFER */
23185       transmit_response(p, "491 Request pending", req);
23186       append_history(p, "Xfer", "Refer failed. Request pending.");
23187       res = 0;
23188       goto handle_refer_cleanup;
23189    }
23190 
23191    /* Allocate memory for call transfer data */
23192    if (!p->refer && !sip_refer_allocate(p)) {
23193       transmit_response(p, "500 Internal Server Error", req);
23194       append_history(p, "Xfer", "Refer failed. Memory allocation error.");
23195       res = -3;
23196       goto handle_refer_cleanup;
23197    }
23198 
23199    res = get_refer_info(p, req); /* Extract headers */
23200 
23201    p->refer->status = REFER_SENT;
23202 
23203    if (res != 0) {
23204       switch (res) {
23205       case -2: /* Syntax error */
23206          transmit_response(p, "400 Bad Request (Refer-to missing)", req);
23207          append_history(p, "Xfer", "Refer failed. Refer-to missing.");
23208          if (req->debug) {
23209             ast_debug(1, "SIP transfer to black hole can't be handled (no refer-to: )\n");
23210          }
23211          break;
23212       case -3:
23213          transmit_response(p, "603 Declined (Non sip: uri)", req);
23214          append_history(p, "Xfer", "Refer failed. Non SIP uri");
23215          if (req->debug) {
23216             ast_debug(1, "SIP transfer to non-SIP uri denied\n");
23217          }
23218          break;
23219       default:
23220          /* Refer-to extension not found, fake a failed transfer */
23221          transmit_response(p, "202 Accepted", req);
23222          append_history(p, "Xfer", "Refer failed. Bad extension.");
23223          transmit_notify_with_sipfrag(p, seqno, "404 Not found", TRUE);
23224          ast_clear_flag(&p->flags[0], SIP_GOTREFER);  
23225          if (req->debug) {
23226             ast_debug(1, "SIP transfer to bad extension: %s\n", p->refer->refer_to);
23227          }
23228          break;
23229       }
23230       res = 0;
23231       goto handle_refer_cleanup;
23232    }
23233    if (ast_strlen_zero(p->context)) {
23234       ast_string_field_set(p, context, sip_cfg.default_context);
23235    }
23236 
23237    /* If we do not support SIP domains, all transfers are local */
23238    if (sip_cfg.allow_external_domains && check_sip_domain(p->refer->refer_to_domain, NULL, 0)) {
23239       p->refer->localtransfer = 1;
23240       if (sipdebug) {
23241          ast_debug(3, "This SIP transfer is local : %s\n", p->refer->refer_to_domain);
23242       }
23243    } else if (AST_LIST_EMPTY(&domain_list) || check_sip_domain(p->refer->refer_to_domain, NULL, 0)) {
23244       /* This PBX doesn't bother with SIP domains or domain is local, so this transfer is local */
23245       p->refer->localtransfer = 1;
23246    } else if (sipdebug) {
23247       ast_debug(3, "This SIP transfer is to a remote SIP extension (remote domain %s)\n", p->refer->refer_to_domain);
23248    }
23249 
23250    /* Is this a repeat of a current request? Ignore it */
23251    /* Don't know what else to do right now. */
23252    if (req->ignore) {
23253       goto handle_refer_cleanup;
23254    }
23255 
23256    /* If this is a blind transfer, we have the following
23257    channels to work with:
23258    - chan1, chan2: The current call between transferer and transferee (2 channels)
23259    - target_channel: A new call from the transferee to the target (1 channel)
23260    We need to stay tuned to what happens in order to be able
23261    to bring back the call to the transferer */
23262 
23263    /* If this is a attended transfer, we should have all call legs within reach:
23264    - chan1, chan2: The call between the transferer and transferee (2 channels)
23265    - target_channel, targetcall_pvt: The call between the transferer and the target (2 channels)
23266    We want to bridge chan2 with targetcall_pvt!
23267    
23268    The replaces call id in the refer message points
23269    to the call leg between Asterisk and the transferer.
23270    So we need to connect the target and the transferee channel
23271    and hangup the two other channels silently
23272    
23273    If the target is non-local, the call ID could be on a remote
23274    machine and we need to send an INVITE with replaces to the
23275    target. We basically handle this as a blind transfer
23276    and let the sip_call function catch that we need replaces
23277    header in the INVITE.
23278    */
23279 
23280    /* Get the transferer's channel */
23281    chans[0] = current.chan1 = p->owner;
23282 
23283    /* Find the other part of the bridge (2) - transferee */
23284    chans[1] = current.chan2 = ast_bridged_channel(current.chan1);
23285 
23286    ast_channel_ref(current.chan1);
23287    if (current.chan2) {
23288       ast_channel_ref(current.chan2);
23289    }
23290 
23291    if (sipdebug) {
23292       ast_debug(3, "SIP %s transfer: Transferer channel %s, transferee channel %s\n",
23293          p->refer->attendedtransfer ? "attended" : "blind",
23294          current.chan1->name,
23295          current.chan2 ? current.chan2->name : "<none>");
23296    }
23297 
23298    if (!current.chan2 && !p->refer->attendedtransfer) {
23299       /* No bridged channel, propably IVR or echo or similar... */
23300       /* Guess we should masquerade or something here */
23301       /* Until we figure it out, refuse transfer of such calls */
23302       if (sipdebug) {
23303          ast_debug(3, "Refused SIP transfer on non-bridged channel.\n");
23304       }
23305       p->refer->status = REFER_FAILED;
23306       append_history(p, "Xfer", "Refer failed. Non-bridged channel.");
23307       transmit_response(p, "603 Declined", req);
23308       res = -1;
23309       goto handle_refer_cleanup;
23310    }
23311 
23312    if (current.chan2) {
23313       if (sipdebug) {
23314          ast_debug(4, "Got SIP transfer, applying to bridged peer '%s'\n", current.chan2->name);
23315       }
23316       ast_queue_control(current.chan1, AST_CONTROL_UNHOLD);
23317    }
23318 
23319    ast_set_flag(&p->flags[0], SIP_GOTREFER);
23320 
23321    /* From here on failures will be indicated with NOTIFY requests */
23322    transmit_response(p, "202 Accepted", req);
23323 
23324    /* Attended transfer: Find all call legs and bridge transferee with target*/
23325    if (p->refer->attendedtransfer) {
23326       /* both p and p->owner _MUST_ be locked while calling local_attended_transfer */
23327       if ((res = local_attended_transfer(p, &current, req, seqno, nounlock))) {
23328          goto handle_refer_cleanup; /* We're done with the transfer */
23329       }
23330       /* Fall through for remote transfers that we did not find locally */
23331       if (sipdebug) {
23332          ast_debug(4, "SIP attended transfer: Still not our call - generating INVITE with replaces\n");
23333       }
23334       /* Fallthrough if we can't find the call leg internally */
23335    }
23336 
23337    /* Copy data we can not safely access after letting the pvt lock go. */
23338    refer_to = ast_strdupa(p->refer->refer_to);
23339    refer_to_domain = ast_strdupa(p->refer->refer_to_domain);
23340    refer_to_context = ast_strdupa(p->refer->refer_to_context);
23341    referred_by = ast_strdupa(p->refer->referred_by);
23342    callid = ast_strdupa(p->callid);
23343    localtransfer = p->refer->localtransfer;
23344    attendedtransfer = p->refer->attendedtransfer;
23345 
23346    if (!*nounlock) {
23347       ast_channel_unlock(p->owner);
23348       *nounlock = 1;
23349    }
23350    sip_pvt_unlock(p);
23351 
23352    /* Parking a call.  DO NOT hold any locks while calling ast_parking_ext_valid() */
23353    if (localtransfer && ast_parking_ext_valid(refer_to, current.chan1, current.chan1->context)) {
23354       sip_pvt_lock(p);
23355       ast_clear_flag(&p->flags[0], SIP_GOTREFER);
23356       p->refer->status = REFER_200OK;
23357       append_history(p, "Xfer", "REFER to call parking.");
23358       sip_pvt_unlock(p);
23359 
23360       ast_manager_event_multichan(EVENT_FLAG_CALL, "Transfer", 2, chans,
23361          "TransferMethod: SIP\r\n"
23362          "TransferType: Blind\r\n"
23363          "Channel: %s\r\n"
23364          "Uniqueid: %s\r\n"
23365          "SIP-Callid: %s\r\n"
23366          "TargetChannel: %s\r\n"
23367          "TargetUniqueid: %s\r\n"
23368          "TransferExten: %s\r\n"
23369          "Transfer2Parking: Yes\r\n",
23370          current.chan1->name,
23371          current.chan1->uniqueid,
23372          callid,
23373          current.chan2->name,
23374          current.chan2->uniqueid,
23375          refer_to);
23376 
23377       if (sipdebug) {
23378          ast_debug(4, "SIP transfer to parking: trying to park %s. Parked by %s\n", current.chan2->name, current.chan1->name);
23379       }
23380 
23381       /* DO NOT hold any locks while calling sip_park */
23382       if (sip_park(current.chan2, current.chan1, req, seqno, refer_to, current.chan1->context)) {
23383          sip_pvt_lock(p);
23384          transmit_notify_with_sipfrag(p, seqno, "500 Internal Server Error", TRUE);
23385       } else {
23386          sip_pvt_lock(p);
23387       }
23388       goto handle_refer_cleanup;
23389    }
23390 
23391    /* Blind transfers and remote attended xfers.
23392     * Locks should not be held while calling pbx_builtin_setvar_helper. This function
23393     * locks the channel being passed into it.*/
23394    if (current.chan1 && current.chan2) {
23395       ast_debug(3, "chan1->name: %s\n", current.chan1->name);
23396       pbx_builtin_setvar_helper(current.chan1, "BLINDTRANSFER", current.chan2->name);
23397    }
23398 
23399    if (current.chan2) {
23400       pbx_builtin_setvar_helper(current.chan2, "BLINDTRANSFER", current.chan1->name);
23401       pbx_builtin_setvar_helper(current.chan2, "SIPDOMAIN", refer_to_domain);
23402       pbx_builtin_setvar_helper(current.chan2, "SIPTRANSFER", "yes");
23403       /* One for the new channel */
23404       pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER", "yes");
23405       /* Attended transfer to remote host, prepare headers for the INVITE */
23406       if (!ast_strlen_zero(referred_by)) {
23407          pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER_REFERER", referred_by);
23408       }
23409    }
23410 
23411    sip_pvt_lock(p);
23412    /* Generate a Replaces string to be used in the INVITE during attended transfer */
23413    if (!ast_strlen_zero(p->refer->replaces_callid)) {
23414       char tempheader[SIPBUFSIZE];
23415       snprintf(tempheader, sizeof(tempheader), "%s%s%s%s%s", p->refer->replaces_callid,
23416          p->refer->replaces_callid_totag ? ";to-tag=" : "",
23417          p->refer->replaces_callid_totag,
23418          p->refer->replaces_callid_fromtag ? ";from-tag=" : "",
23419          p->refer->replaces_callid_fromtag);
23420 
23421       if (current.chan2) {
23422          sip_pvt_unlock(p);
23423          pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER_REPLACES", tempheader);
23424          sip_pvt_lock(p);
23425       }
23426    }
23427 
23428    /* Connect the call */
23429 
23430    /* FAKE ringing if not attended transfer */
23431    if (!p->refer->attendedtransfer) {
23432       transmit_notify_with_sipfrag(p, seqno, "180 Ringing", FALSE);
23433    }
23434 
23435    /* For blind transfer, this will lead to a new call */
23436    /* For attended transfer to remote host, this will lead to
23437       a new SIP call with a replaces header, if the dial plan allows it
23438    */
23439    if (!current.chan2) {
23440       /* We have no bridge, so we're talking with Asterisk somehow */
23441       /* We need to masquerade this call */
23442       /* What to do to fix this situation:
23443          * Set up the new call in a new channel
23444          * Let the new channel masq into this channel
23445          Please add that code here :-)
23446       */
23447       p->refer->status = REFER_FAILED;
23448       transmit_notify_with_sipfrag(p, seqno, "503 Service Unavailable (can't handle one-legged xfers)", TRUE);
23449       ast_clear_flag(&p->flags[0], SIP_GOTREFER);  
23450       append_history(p, "Xfer", "Refer failed (only bridged calls).");
23451       res = -1;
23452       goto handle_refer_cleanup;
23453    }
23454    ast_set_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER);   /* Delay hangup */
23455 
23456    /* Do not hold the pvt lock during the indicate and async_goto. Those functions
23457     * lock channels which will invalidate locking order if the pvt lock is held.*/
23458    /* For blind transfers, move the call to the new extensions. For attended transfers on multiple
23459     * servers - generate an INVITE with Replaces. Either way, let the dial plan decided
23460     * indicate before masquerade so the indication actually makes it to the real channel
23461     * when using local channels with MOH passthru */
23462    sip_pvt_unlock(p);
23463    ast_indicate(current.chan2, AST_CONTROL_UNHOLD);
23464    res = ast_async_goto(current.chan2, refer_to_context, refer_to, 1);
23465 
23466    if (!res) {
23467       ast_manager_event_multichan(EVENT_FLAG_CALL, "Transfer", 2, chans,
23468          "TransferMethod: SIP\r\n"
23469          "TransferType: Blind\r\n"
23470          "Channel: %s\r\n"
23471          "Uniqueid: %s\r\n"
23472          "SIP-Callid: %s\r\n"
23473          "TargetChannel: %s\r\n"
23474          "TargetUniqueid: %s\r\n"
23475          "TransferExten: %s\r\n"
23476          "TransferContext: %s\r\n",
23477          current.chan1->name,
23478          current.chan1->uniqueid,
23479          callid,
23480          current.chan2->name,
23481          current.chan2->uniqueid,
23482          refer_to,
23483          refer_to_context);
23484       /* Success  - we have a new channel */
23485       ast_debug(3, "%s transfer succeeded. Telling transferer.\n", attendedtransfer? "Attended" : "Blind");
23486 
23487       /* XXX - what to we put in CEL 'extra' for attended transfers to external systems? NULL for now */
23488       ast_channel_lock(current.chan1);
23489       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);
23490       ast_channel_unlock(current.chan1);
23491 
23492       sip_pvt_lock(p);
23493       transmit_notify_with_sipfrag(p, seqno, "200 Ok", TRUE);
23494       if (p->refer->localtransfer) {
23495          p->refer->status = REFER_200OK;
23496       }
23497       if (p->owner) {
23498          p->owner->hangupcause = AST_CAUSE_NORMAL_CLEARING;
23499       }
23500       append_history(p, "Xfer", "Refer succeeded.");
23501       ast_clear_flag(&p->flags[0], SIP_GOTREFER);  
23502       /* Do not hangup call, the other side do that when we say 200 OK */
23503       /* We could possibly implement a timer here, auto congestion */
23504       res = 0;
23505    } else {
23506       sip_pvt_lock(p);
23507       ast_clear_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER); /* Don't delay hangup */
23508       ast_debug(3, "%s transfer failed. Resuming original call.\n", p->refer->attendedtransfer? "Attended" : "Blind");
23509       append_history(p, "Xfer", "Refer failed.");
23510       /* Failure of some kind */
23511       p->refer->status = REFER_FAILED;
23512       transmit_notify_with_sipfrag(p, seqno, "503 Service Unavailable", TRUE);
23513       ast_clear_flag(&p->flags[0], SIP_GOTREFER);  
23514       res = -1;
23515    }
23516 
23517 handle_refer_cleanup:
23518    if (current.chan1) {
23519       ast_channel_unref(current.chan1);
23520    }
23521    if (current.chan2) {
23522       ast_channel_unref(current.chan2);
23523    }
23524 
23525    /* Make sure we exit with the pvt locked */
23526    return res;
23527 }
23528 
23529 /*! \brief Handle incoming CANCEL request */
23530 static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req)
23531 {
23532 
23533    check_via(p, req);
23534    sip_alreadygone(p);
23535 
23536    if (p->owner && p->owner->_state == AST_STATE_UP) {
23537       /* This call is up, cancel is ignored, we need a bye */
23538       transmit_response(p, "200 OK", req);
23539       ast_debug(1, "Got CANCEL on an answered call. Ignoring... \n");
23540       return 0;
23541    }
23542 
23543    /* At this point, we could have cancelled the invite at the same time
23544       as the other side sends a CANCEL. Our final reply with error code
23545       might not have been received by the other side before the CANCEL
23546       was sent, so let's just give up retransmissions and waiting for
23547       ACK on our error code. The call is hanging up any way. */
23548    if (p->invitestate == INV_TERMINATED || p->invitestate == INV_COMPLETED) {
23549       __sip_pretend_ack(p);
23550    }
23551    if (p->invitestate != INV_TERMINATED)
23552       p->invitestate = INV_CANCELLED;
23553 
23554    if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD))
23555       update_call_counter(p, DEC_CALL_LIMIT);
23556 
23557    stop_media_flows(p); /* Immediately stop RTP, VRTP and UDPTL as applicable */
23558    if (p->owner) {
23559       ast_set_hangupsource(p->owner, p->owner->name, 0);
23560       ast_queue_hangup(p->owner);
23561    }
23562    else
23563       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
23564    if (ast_str_strlen(p->initreq.data) > 0) {
23565       struct sip_pkt *pkt, *prev_pkt;
23566       /* If the CANCEL we are receiving is a retransmission, and we already have scheduled
23567        * a reliable 487, then we don't want to schedule another one on top of the previous
23568        * one.
23569        *
23570        * As odd as this may sound, we can't rely on the previously-transmitted "reliable"
23571        * response in this situation. What if we've sent all of our reliable responses
23572        * already and now all of a sudden, we get this second CANCEL?
23573        *
23574        * The only way to do this correctly is to cancel our previously-scheduled reliably-
23575        * transmitted response and send a new one in its place.
23576        */
23577       for (pkt = p->packets, prev_pkt = NULL; pkt; prev_pkt = pkt, pkt = pkt->next) {
23578          if (pkt->seqno == p->lastinvite && pkt->response_code == 487) {
23579             AST_SCHED_DEL(sched, pkt->retransid);
23580             UNLINK(pkt, p->packets, prev_pkt);
23581             dialog_unref(pkt->owner, "unref packet->owner from dialog");
23582             if (pkt->data) {
23583                ast_free(pkt->data);
23584             }
23585             ast_free(pkt);
23586             break;
23587          }
23588       }
23589       transmit_response_reliable(p, "487 Request Terminated", &p->initreq);
23590       transmit_response(p, "200 OK", req);
23591       return 1;
23592    } else {
23593       transmit_response(p, "481 Call Leg Does Not Exist", req);
23594       return 0;
23595    }
23596 }
23597 
23598 /*! \brief Handle incoming BYE request */
23599 static int handle_request_bye(struct sip_pvt *p, struct sip_request *req)
23600 {
23601    struct ast_channel *c=NULL;
23602    int res;
23603    struct ast_channel *bridged_to;
23604    const char *required;
23605 
23606    /* If we have an INCOMING invite that we haven't answered, terminate that transaction */
23607    if (p->pendinginvite && !ast_test_flag(&p->flags[0], SIP_OUTGOING) && !req->ignore) {
23608       transmit_response_reliable(p, "487 Request Terminated", &p->initreq);
23609    }
23610 
23611    __sip_pretend_ack(p);
23612 
23613    p->invitestate = INV_TERMINATED;
23614 
23615    copy_request(&p->initreq, req);
23616    if (sipdebug)
23617       ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
23618    check_via(p, req);
23619    sip_alreadygone(p);
23620 
23621    /* Get RTCP quality before end of call */
23622    if (p->do_history || p->owner) {
23623       char quality_buf[AST_MAX_USER_FIELD], *quality;
23624       struct ast_channel *bridge = p->owner ? ast_bridged_channel(p->owner) : NULL;
23625 
23626       /* We need to get the lock on bridge because ast_rtp_instance_set_stats_vars will attempt
23627        * to lock the bridge. This may get hairy...
23628        */
23629       while (bridge && ast_channel_trylock(bridge)) {
23630          ast_channel_unlock(p->owner);
23631          do {
23632             /* Can't use DEADLOCK_AVOIDANCE since p is an ao2 object */
23633             sip_pvt_unlock(p);
23634             usleep(1);
23635             sip_pvt_lock(p);
23636          } while (p->owner && ast_channel_trylock(p->owner));
23637          bridge = p->owner ? ast_bridged_channel(p->owner) : NULL;
23638       }
23639 
23640 
23641       if (p->rtp && (quality = ast_rtp_instance_get_quality(p->rtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY, quality_buf, sizeof(quality_buf)))) {
23642          if (p->do_history) {
23643             append_history(p, "RTCPaudio", "Quality:%s", quality);
23644 
23645             if ((quality = ast_rtp_instance_get_quality(p->rtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY_JITTER, quality_buf, sizeof(quality_buf)))) {
23646                append_history(p, "RTCPaudioJitter", "Quality:%s", quality);
23647             }
23648             if ((quality = ast_rtp_instance_get_quality(p->rtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY_LOSS, quality_buf, sizeof(quality_buf)))) {
23649                append_history(p, "RTCPaudioLoss", "Quality:%s", quality);
23650             }
23651             if ((quality = ast_rtp_instance_get_quality(p->rtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY_RTT, quality_buf, sizeof(quality_buf)))) {
23652                append_history(p, "RTCPaudioRTT", "Quality:%s", quality);
23653             }
23654          }
23655 
23656          if (p->owner) {
23657             ast_rtp_instance_set_stats_vars(p->owner, p->rtp);
23658          }
23659 
23660       }
23661 
23662       if (bridge) {
23663          struct sip_pvt *q = bridge->tech_pvt;
23664 
23665          if (IS_SIP_TECH(bridge->tech) && q && q->rtp) {
23666             ast_rtp_instance_set_stats_vars(bridge, q->rtp);
23667          }
23668          ast_channel_unlock(bridge);
23669       }
23670 
23671       if (p->vrtp && (quality = ast_rtp_instance_get_quality(p->vrtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY, quality_buf, sizeof(quality_buf)))) {
23672          if (p->do_history) {
23673             append_history(p, "RTCPvideo", "Quality:%s", quality);
23674          }
23675          if (p->owner) {
23676             pbx_builtin_setvar_helper(p->owner, "RTPVIDEOQOS", quality);
23677          }
23678       }
23679       if (p->trtp && (quality = ast_rtp_instance_get_quality(p->trtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY, quality_buf, sizeof(quality_buf)))) {
23680          if (p->do_history) {
23681             append_history(p, "RTCPtext", "Quality:%s", quality);
23682          }
23683          if (p->owner) {
23684             pbx_builtin_setvar_helper(p->owner, "RTPTEXTQOS", quality);
23685          }
23686       }
23687    }
23688 
23689    stop_media_flows(p); /* Immediately stop RTP, VRTP and UDPTL as applicable */
23690    stop_session_timer(p); /* Stop Session-Timer */
23691 
23692    if (!ast_strlen_zero(get_header(req, "Also"))) {
23693       ast_log(LOG_NOTICE, "Client '%s' using deprecated BYE/Also transfer method.  Ask vendor to support REFER instead\n",
23694          ast_sockaddr_stringify(&p->recv));
23695       if (ast_strlen_zero(p->context))
23696          ast_string_field_set(p, context, sip_cfg.default_context);
23697       res = get_also_info(p, req);
23698       if (!res) {
23699          c = p->owner;
23700          if (c) {
23701             bridged_to = ast_bridged_channel(c);
23702             if (bridged_to) {
23703                /* Don't actually hangup here... */
23704                ast_queue_control(c, AST_CONTROL_UNHOLD);
23705                ast_channel_unlock(c);  /* async_goto can do a masquerade, no locks can be held during a masq */
23706                ast_async_goto(bridged_to, p->context, p->refer->refer_to, 1);
23707                ast_channel_lock(c);
23708             } else
23709                ast_queue_hangup(p->owner);
23710          }
23711       } else {
23712          ast_log(LOG_WARNING, "Invalid transfer information from '%s'\n", ast_sockaddr_stringify(&p->recv));
23713          if (p->owner)
23714             ast_queue_hangup_with_cause(p->owner, AST_CAUSE_PROTOCOL_ERROR);
23715       }
23716    } else if (p->owner) {
23717       ast_set_hangupsource(p->owner, p->owner->name, 0);
23718       ast_queue_hangup(p->owner);
23719       sip_scheddestroy_final(p, DEFAULT_TRANS_TIMEOUT);
23720       ast_debug(3, "Received bye, issuing owner hangup\n");
23721    } else {
23722       sip_scheddestroy_final(p, DEFAULT_TRANS_TIMEOUT);
23723       ast_debug(3, "Received bye, no owner, selfdestruct soon.\n");
23724    }
23725    ast_clear_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
23726 
23727    /* Find out what they require */
23728    required = get_header(req, "Require");
23729    if (!ast_strlen_zero(required)) {
23730       char unsupported[256] = { 0, };
23731       parse_sip_options(required, unsupported, ARRAY_LEN(unsupported));
23732       /* If there are any options required that we do not support,
23733        * then send a 420 with only those unsupported options listed */
23734       if (!ast_strlen_zero(unsupported)) {
23735          transmit_response_with_unsupported(p, "420 Bad extension (unsupported)", req, unsupported);
23736          ast_log(LOG_WARNING, "Received SIP BYE with unsupported required extension: required:%s unsupported:%s\n", required, unsupported);
23737       } else {
23738          transmit_response(p, "200 OK", req);
23739       }
23740    } else {
23741       transmit_response(p, "200 OK", req);
23742    }
23743 
23744    return 1;
23745 }
23746 
23747 /*! \brief Handle incoming MESSAGE request */
23748 static int handle_request_message(struct sip_pvt *p, struct sip_request *req)
23749 {
23750    if (!req->ignore) {
23751       if (req->debug)
23752          ast_verbose("Receiving message!\n");
23753       receive_message(p, req);
23754    } else
23755       transmit_response(p, "202 Accepted", req);
23756    return 1;
23757 }
23758 
23759 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)
23760 {
23761    int etag_present = !ast_strlen_zero(etag);
23762    int body_present = req->lines > 0;
23763 
23764    ast_assert(expires_int != NULL);
23765 
23766    if (ast_strlen_zero(expires)) {
23767       /* Section 6, item 4, second bullet point of RFC 3903 says to
23768        * use a locally-configured default expiration if none is provided
23769        * in the request
23770        */
23771       *expires_int = DEFAULT_PUBLISH_EXPIRES;
23772    } else if (sscanf(expires, "%30d", expires_int) != 1) {
23773       return SIP_PUBLISH_UNKNOWN;
23774    }
23775 
23776    if (*expires_int == 0) {
23777       return SIP_PUBLISH_REMOVE;
23778    } else if (!etag_present && body_present) {
23779       return SIP_PUBLISH_INITIAL;
23780    } else if (etag_present && !body_present) {
23781       return SIP_PUBLISH_REFRESH;
23782    } else if (etag_present && body_present) {
23783       return SIP_PUBLISH_MODIFY;
23784    }
23785 
23786    return SIP_PUBLISH_UNKNOWN;
23787 }
23788 
23789 #ifdef HAVE_LIBXML2
23790 static void get_pidf_body(struct sip_request *req, char *pidf_body, size_t size)
23791 {
23792    int i;
23793    struct ast_str *str = ast_str_alloca(size);
23794    for (i = 0; i < req->lines; ++i) {
23795       ast_str_append(&str, 0, "%s", REQ_OFFSET_TO_STR(req, line[i]));
23796    }
23797    ast_copy_string(pidf_body, ast_str_buffer(str), size);
23798 }
23799 
23800 static int pidf_validate_tuple(struct ast_xml_node *tuple_node)
23801 {
23802    const char *id;
23803    int status_found = FALSE;
23804    struct ast_xml_node *tuple_children;
23805    struct ast_xml_node *tuple_children_iterator;
23806    /* Tuples have to have an id attribute or they're invalid */
23807    if (!(id = ast_xml_get_attribute(tuple_node, "id"))) {
23808       ast_log(LOG_WARNING, "Tuple XML element has no attribute 'id'\n");
23809       return FALSE;
23810    }
23811    /* We don't care what it actually is, just that it's there */
23812    ast_xml_free_attr(id);
23813    /* This is a tuple. It must have a status element */
23814    if (!(tuple_children = ast_xml_node_get_children(tuple_node))) {
23815       /* The tuple has no children. It sucks */
23816       ast_log(LOG_WARNING, "Tuple XML element has no child elements\n");
23817       return FALSE;
23818    }
23819    for (tuple_children_iterator = tuple_children; tuple_children_iterator;
23820          tuple_children_iterator = ast_xml_node_get_next(tuple_children_iterator)) {
23821       /* Similar to the wording used regarding tuples, the status element should appear
23822        * first. However, we will once again relax things and accept the status at any
23823        * position. We will enforce that only a single status element can be present.
23824        */
23825       if (strcmp(ast_xml_node_get_name(tuple_children_iterator), "status")) {
23826          /* Not the status, we don't care */
23827          continue;
23828       }
23829       if (status_found == TRUE) {
23830          /* THERE CAN BE ONLY ONE!!! */
23831          ast_log(LOG_WARNING, "Multiple status elements found in tuple. Only one allowed\n");
23832          return FALSE;
23833       }
23834       status_found = TRUE;
23835    }
23836    return status_found;
23837 }
23838 
23839 
23840 static int pidf_validate_presence(struct ast_xml_doc *doc)
23841 {
23842    struct ast_xml_node *presence_node = ast_xml_get_root(doc);
23843    struct ast_xml_node *child_nodes;
23844    struct ast_xml_node *node_iterator;
23845    struct ast_xml_ns *ns;
23846    const char *entity;
23847    const char *namespace;
23848    const char presence_namespace[] = "urn:ietf:params:xml:ns:pidf";
23849 
23850    if (!presence_node) {
23851       ast_log(LOG_WARNING, "Unable to retrieve root node of the XML document\n");
23852       return FALSE;
23853    }
23854    /* Okay, we managed to open the document! YAY! Now, let's start making sure it's all PIDF-ified
23855     * correctly.
23856     */
23857    if (strcmp(ast_xml_node_get_name(presence_node), "presence")) {
23858       ast_log(LOG_WARNING, "Root node of PIDF document is not 'presence'. Invalid\n");
23859       return FALSE;
23860    }
23861 
23862    /* The presence element must have an entity attribute and an xmlns attribute. Furthermore
23863     * the xmlns attribute must be "urn:ietf:params:xml:ns:pidf"
23864     */
23865    if (!(entity = ast_xml_get_attribute(presence_node, "entity"))) {
23866       ast_log(LOG_WARNING, "Presence element of PIDF document has no 'entity' attribute\n");
23867       return FALSE;
23868    }
23869    /* We're not interested in what the entity is, just that it exists */
23870    ast_xml_free_attr(entity);
23871 
23872    if (!(ns = ast_xml_find_namespace(doc, presence_node, NULL))) {
23873       ast_log(LOG_WARNING, "Couldn't find default namespace...\n");
23874       return FALSE;
23875    }
23876 
23877    namespace = ast_xml_get_ns_href(ns);
23878    if (ast_strlen_zero(namespace) || strcmp(namespace, presence_namespace)) {
23879       ast_log(LOG_WARNING, "PIDF document has invalid namespace value %s\n", namespace);
23880       return FALSE;
23881    }
23882 
23883    if (!(child_nodes = ast_xml_node_get_children(presence_node))) {
23884       ast_log(LOG_WARNING, "PIDF document has no elements as children of 'presence'. Invalid\n");
23885       return FALSE;
23886    }
23887 
23888    /* Check for tuple elements. RFC 3863 says that PIDF documents can have any number of
23889     * tuples, including 0. The big thing here is that if there are tuple elements present,
23890     * they have to have a single status element within.
23891     *
23892     * The RFC is worded such that tuples should appear as the first elements as children of
23893     * the presence element. However, we'll be accepting of documents which may place other elements
23894     * before the tuple(s).
23895     */
23896    for (node_iterator = child_nodes; node_iterator;
23897          node_iterator = ast_xml_node_get_next(node_iterator)) {
23898       if (strcmp(ast_xml_node_get_name(node_iterator), "tuple")) {
23899          /* Not a tuple. We don't give a rat's hind quarters */
23900          continue;
23901       }
23902       if (pidf_validate_tuple(node_iterator) == FALSE) {
23903          ast_log(LOG_WARNING, "Unable to validate tuple\n");
23904          return FALSE;
23905       }
23906    }
23907 
23908    return TRUE;
23909 }
23910 
23911 /*!
23912  * \brief Makes sure that body is properly formatted PIDF
23913  *
23914  * Specifically, we check that the document has a "presence" element
23915  * at the root and that within that, there is at least one "tuple" element
23916  * that contains a "status" element.
23917  *
23918  * XXX This function currently assumes a default namespace is used. Of course
23919  * if you're not using a default namespace, you're probably a stupid jerk anyway.
23920  *
23921  * \param req The SIP request to check
23922  * \param[out] pidf_doc The validated PIDF doc.
23923  * \retval FALSE The XML was malformed or the basic PIDF structure was marred
23924  * \retval TRUE The PIDF document is of a valid format
23925  */
23926 static int sip_pidf_validate(struct sip_request *req, struct ast_xml_doc **pidf_doc)
23927 {
23928    struct ast_xml_doc *doc;
23929    int content_length;
23930    const char *content_length_str = get_header(req, "Content-Length");
23931    const char *content_type = get_header(req, "Content-Type");
23932    char pidf_body[SIPBUFSIZE];
23933    int res;
23934 
23935    if (ast_strlen_zero(content_type) || strcmp(content_type, "application/pidf+xml")) {
23936       ast_log(LOG_WARNING, "Content type is not PIDF\n");
23937       return FALSE;
23938    }
23939 
23940    if (ast_strlen_zero(content_length_str)) {
23941       ast_log(LOG_WARNING, "No content length. Can't determine bounds of PIDF document\n");
23942       return FALSE;
23943    }
23944 
23945    if (sscanf(content_length_str, "%30d", &content_length) != 1) {
23946       ast_log(LOG_WARNING, "Invalid content length provided\n");
23947       return FALSE;
23948    }
23949 
23950    if (content_length > sizeof(pidf_body)) {
23951       ast_log(LOG_WARNING, "Content length of PIDF document truncated to %d bytes\n", (int) sizeof(pidf_body));
23952       content_length = sizeof(pidf_body);
23953    }
23954 
23955    get_pidf_body(req, pidf_body, content_length);
23956 
23957    if (!(doc = ast_xml_read_memory(pidf_body, content_length))) {
23958       ast_log(LOG_WARNING, "Unable to open XML PIDF document. Is it malformed?\n");
23959       return FALSE;
23960    }
23961 
23962    res = pidf_validate_presence(doc);
23963    if (res == TRUE) {
23964       *pidf_doc = doc;
23965    } else {
23966       ast_xml_close(doc);
23967    }
23968    return res;
23969 }
23970 
23971 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)
23972 {
23973    const char *uri = REQ_OFFSET_TO_STR(req, rlPart2);
23974    struct ast_cc_agent *agent;
23975    struct sip_cc_agent_pvt *agent_pvt;
23976    struct ast_xml_doc *pidf_doc = NULL;
23977    const char *basic_status = NULL;
23978    struct ast_xml_node *presence_node;
23979    struct ast_xml_node *presence_children;
23980    struct ast_xml_node *tuple_node;
23981    struct ast_xml_node *tuple_children;
23982    struct ast_xml_node *status_node;
23983    struct ast_xml_node *status_children;
23984    struct ast_xml_node *basic_node;
23985    int res = 0;
23986 
23987    if (!((agent = find_sip_cc_agent_by_notify_uri(uri)) || (agent = find_sip_cc_agent_by_subscribe_uri(uri)))) {
23988       ast_log(LOG_WARNING, "Could not find agent using uri '%s'\n", uri);
23989       transmit_response(pvt, "412 Conditional Request Failed", req);
23990       return -1;
23991    }
23992 
23993    agent_pvt = agent->private_data;
23994 
23995    if (sip_pidf_validate(req, &pidf_doc) == FALSE) {
23996       res = -1;
23997       goto cc_publish_cleanup;
23998    }
23999 
24000    /* It's important to note that the PIDF validation routine has no knowledge
24001     * of what we specifically want in this instance. A valid PIDF document could
24002     * have no tuples, or it could have tuples whose status element has no basic
24003     * element contained within. While not violating the PIDF spec, these are
24004     * insufficient for our needs in this situation
24005     */
24006    presence_node = ast_xml_get_root(pidf_doc);
24007    if (!(presence_children = ast_xml_node_get_children(presence_node))) {
24008       ast_log(LOG_WARNING, "No tuples within presence element.\n");
24009       res = -1;
24010       goto cc_publish_cleanup;
24011    }
24012 
24013    if (!(tuple_node = ast_xml_find_element(presence_children, "tuple", NULL, NULL))) {
24014       ast_log(LOG_NOTICE, "Couldn't find tuple node?\n");
24015       res = -1;
24016       goto cc_publish_cleanup;
24017    }
24018 
24019    /* We already made sure that the tuple has a status node when we validated the PIDF
24020     * document earlier. So there's no need to enclose this operation in an if statement.
24021     */
24022    tuple_children = ast_xml_node_get_children(tuple_node);
24023    status_node = ast_xml_find_element(tuple_children, "status", NULL, NULL);
24024 
24025    if (!(status_children = ast_xml_node_get_children(status_node))) {
24026       ast_log(LOG_WARNING, "No basic elements within status element.\n");
24027       res = -1;
24028       goto cc_publish_cleanup;
24029    }
24030 
24031    if (!(basic_node = ast_xml_find_element(status_children, "basic", NULL, NULL))) {
24032       ast_log(LOG_WARNING, "Couldn't find basic node?\n");
24033       res = -1;
24034       goto cc_publish_cleanup;
24035    }
24036 
24037    basic_status = ast_xml_get_text(basic_node);
24038 
24039    if (ast_strlen_zero(basic_status)) {
24040       ast_log(LOG_NOTICE, "NOthing in basic node?\n");
24041       res = -1;
24042       goto cc_publish_cleanup;
24043    }
24044 
24045    if (!strcmp(basic_status, "open")) {
24046       agent_pvt->is_available = TRUE;
24047       ast_cc_agent_caller_available(agent->core_id, "Received PUBLISH stating SIP caller %s is available",
24048             agent->device_name);
24049    } else if (!strcmp(basic_status, "closed")) {
24050       agent_pvt->is_available = FALSE;
24051       ast_cc_agent_caller_busy(agent->core_id, "Received PUBLISH stating SIP caller %s is busy",
24052             agent->device_name);
24053    } else {
24054       ast_log(LOG_NOTICE, "Invalid content in basic element: %s\n", basic_status);
24055    }
24056 
24057 cc_publish_cleanup:
24058    if (basic_status) {
24059       ast_xml_free_text(basic_status);
24060    }
24061    if (pidf_doc) {
24062       ast_xml_close(pidf_doc);
24063    }
24064    ao2_ref(agent, -1);
24065    if (res) {
24066       transmit_response(pvt, "400 Bad Request", req);
24067    }
24068    return res;
24069 }
24070 
24071 #endif /* HAVE_LIBXML2 */
24072 
24073 static int handle_sip_publish_initial(struct sip_pvt *p, struct sip_request *req, struct event_state_compositor *esc, const int expires)
24074 {
24075    struct sip_esc_entry *esc_entry = create_esc_entry(esc, req, expires);
24076    int res = 0;
24077 
24078    if (!esc_entry) {
24079       transmit_response(p, "503 Internal Server Failure", req);
24080       return -1;
24081    }
24082 
24083    if (esc->callbacks->initial_handler) {
24084       res = esc->callbacks->initial_handler(p, req, esc, esc_entry);
24085    }
24086 
24087    if (!res) {
24088       transmit_response_with_sip_etag(p, "200 OK", req, esc_entry, 0);
24089    }
24090 
24091    ao2_ref(esc_entry, -1);
24092    return res;
24093 }
24094 
24095 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)
24096 {
24097    struct sip_esc_entry *esc_entry = get_esc_entry(etag, esc);
24098    int expires_ms = expires * 1000;
24099    int res = 0;
24100 
24101    if (!esc_entry) {
24102       transmit_response(p, "412 Conditional Request Failed", req);
24103       return -1;
24104    }
24105 
24106    AST_SCHED_REPLACE_UNREF(esc_entry->sched_id, sched, expires_ms, publish_expire, esc_entry,
24107          ao2_ref(_data, -1),
24108          ao2_ref(esc_entry, -1),
24109          ao2_ref(esc_entry, +1));
24110 
24111    if (esc->callbacks->refresh_handler) {
24112       res = esc->callbacks->refresh_handler(p, req, esc, esc_entry);
24113    }
24114 
24115    if (!res) {
24116       transmit_response_with_sip_etag(p, "200 OK", req, esc_entry, 1);
24117    }
24118 
24119    ao2_ref(esc_entry, -1);
24120    return res;
24121 }
24122 
24123 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)
24124 {
24125    struct sip_esc_entry *esc_entry = get_esc_entry(etag, esc);
24126    int expires_ms = expires * 1000;
24127    int res = 0;
24128 
24129    if (!esc_entry) {
24130       transmit_response(p, "412 Conditional Request Failed", req);
24131       return -1;
24132    }
24133 
24134    AST_SCHED_REPLACE_UNREF(esc_entry->sched_id, sched, expires_ms, publish_expire, esc_entry,
24135          ao2_ref(_data, -1),
24136          ao2_ref(esc_entry, -1),
24137          ao2_ref(esc_entry, +1));
24138 
24139    if (esc->callbacks->modify_handler) {
24140       res = esc->callbacks->modify_handler(p, req, esc, esc_entry);
24141    }
24142 
24143    if (!res) {
24144       transmit_response_with_sip_etag(p, "200 OK", req, esc_entry, 1);
24145    }
24146 
24147    ao2_ref(esc_entry, -1);
24148    return res;
24149 }
24150 
24151 static int handle_sip_publish_remove(struct sip_pvt *p, struct sip_request *req, struct event_state_compositor *esc, const char * const etag)
24152 {
24153    struct sip_esc_entry *esc_entry = get_esc_entry(etag, esc);
24154    int res = 0;
24155 
24156    if (!esc_entry) {
24157       transmit_response(p, "412 Conditional Request Failed", req);
24158       return -1;
24159    }
24160 
24161    AST_SCHED_DEL(sched, esc_entry->sched_id);
24162    /* Scheduler's ref of the esc_entry */
24163    ao2_ref(esc_entry, -1);
24164 
24165    if (esc->callbacks->remove_handler) {
24166       res = esc->callbacks->remove_handler(p, req, esc, esc_entry);
24167    }
24168 
24169    if (!res) {
24170       transmit_response_with_sip_etag(p, "200 OK", req, esc_entry, 1);
24171    }
24172 
24173    /* Ref from finding the esc_entry earlier in function */
24174    ao2_unlink(esc->compositor, esc_entry);
24175    ao2_ref(esc_entry, -1);
24176    return res;
24177 }
24178 
24179 static int handle_request_publish(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, const int seqno, const char *uri)
24180 {
24181    const char *etag = get_header(req, "SIP-If-Match");
24182    const char *event = get_header(req, "Event");
24183    struct event_state_compositor *esc;
24184    enum sip_publish_type publish_type;
24185    const char *expires_str = get_header(req, "Expires");
24186    int expires_int;
24187    int auth_result;
24188    int handler_result = -1;
24189 
24190    if (ast_strlen_zero(event)) {
24191       transmit_response(p, "489 Bad Event", req);
24192       pvt_set_needdestroy(p, "missing Event: header");
24193       return -1;
24194    }
24195 
24196    if (!(esc = get_esc(event))) {
24197       transmit_response(p, "489 Bad Event", req);
24198       pvt_set_needdestroy(p, "unknown event package in publish");
24199       return -1;
24200    }
24201 
24202    auth_result = check_user(p, req, SIP_PUBLISH, uri, XMIT_RELIABLE, addr);
24203    if (auth_result == AUTH_CHALLENGE_SENT) {
24204       p->lastinvite = seqno;
24205       return 0;
24206    } else if (auth_result < 0) {
24207       if (auth_result == AUTH_FAKE_AUTH) {
24208          ast_log(LOG_NOTICE, "Sending fake auth rejection for device %s\n", get_header(req, "From"));
24209          transmit_fake_auth_response(p, SIP_INVITE, req, XMIT_RELIABLE);
24210       } else {
24211          ast_log(LOG_NOTICE, "Failed to authenticate device %s\n", get_header(req, "From"));
24212          transmit_response_reliable(p, "403 Forbidden", req);
24213       }
24214       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
24215       ast_string_field_set(p, theirtag, NULL);
24216       return 0;
24217    } else if (auth_result == AUTH_SUCCESSFUL && p->lastinvite) {
24218       /* We need to stop retransmitting the 401 */
24219       __sip_ack(p, p->lastinvite, 1, 0);
24220    }
24221 
24222    publish_type = determine_sip_publish_type(req, event, etag, expires_str, &expires_int);
24223 
24224    if (expires_int > max_expiry) {
24225       expires_int = max_expiry;
24226    } else if (expires_int < min_expiry && expires_int > 0) {
24227       transmit_response_with_minexpires(p, "423 Interval too small", req);
24228       pvt_set_needdestroy(p, "Expires is less that the min expires allowed.");
24229       return 0;
24230    }
24231    p->expiry = expires_int;
24232 
24233    /* It is the responsibility of these handlers to formulate any response
24234     * sent for a PUBLISH
24235     */
24236    switch (publish_type) {
24237    case SIP_PUBLISH_UNKNOWN:
24238       transmit_response(p, "400 Bad Request", req);
24239       break;
24240    case SIP_PUBLISH_INITIAL:
24241       handler_result = handle_sip_publish_initial(p, req, esc, expires_int);
24242       break;
24243    case SIP_PUBLISH_REFRESH:
24244       handler_result = handle_sip_publish_refresh(p, req, esc, etag, expires_int);
24245       break;
24246    case SIP_PUBLISH_MODIFY:
24247       handler_result = handle_sip_publish_modify(p, req, esc, etag, expires_int);
24248       break;
24249    case SIP_PUBLISH_REMOVE:
24250       handler_result = handle_sip_publish_remove(p, req, esc, etag);
24251       break;
24252    default:
24253       transmit_response(p, "400 Impossible Condition", req);
24254       break;
24255    }
24256    if (!handler_result && p->expiry > 0) {
24257       sip_scheddestroy(p, (p->expiry + 10) * 1000);
24258    } else {
24259       pvt_set_needdestroy(p, "forcing expiration");
24260    }
24261 
24262    return handler_result;
24263 }
24264 
24265 /*! \internal \brief Subscribe to MWI events for the specified peer
24266  * \note The peer cannot be locked during this method.  sip_send_mwi_peer will
24267  * attempt to lock the peer after the event subscription lock is held; if the peer is locked during
24268  * this method then we will attempt to lock the event subscription lock but after the peer, creating
24269  * a locking inversion.
24270  */
24271 static void add_peer_mwi_subs(struct sip_peer *peer)
24272 {
24273    struct sip_mailbox *mailbox;
24274 
24275    AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
24276       if (mailbox->event_sub) {
24277          ast_event_unsubscribe(mailbox->event_sub);
24278       }
24279 
24280       mailbox->event_sub = ast_event_subscribe(AST_EVENT_MWI, mwi_event_cb, "SIP mbox event", peer,
24281          AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, mailbox->mailbox,
24282          AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, S_OR(mailbox->context, "default"),
24283          AST_EVENT_IE_END);
24284    }
24285 }
24286 
24287 static int handle_cc_subscribe(struct sip_pvt *p, struct sip_request *req)
24288 {
24289    const char *uri = REQ_OFFSET_TO_STR(req, rlPart2);
24290    char *param_separator;
24291    struct ast_cc_agent *agent;
24292    struct sip_cc_agent_pvt *agent_pvt;
24293    const char *expires_str = get_header(req, "Expires");
24294    int expires = -1; /* Just need it to be non-zero */
24295 
24296    if (!ast_strlen_zero(expires_str)) {
24297       sscanf(expires_str, "%d", &expires);
24298    }
24299 
24300    if ((param_separator = strchr(uri, ';'))) {
24301       *param_separator = '\0';
24302    }
24303 
24304    p->subscribed = CALL_COMPLETION;
24305 
24306    if (!(agent = find_sip_cc_agent_by_subscribe_uri(uri))) {
24307       if (!expires) {
24308          /* Typically, if a 0 Expires reaches us and we can't find
24309           * the corresponding agent, it means that the CC transaction
24310           * has completed and so the calling side is just trying to
24311           * clean up its subscription. We'll just respond with a
24312           * 200 OK and be done with it
24313           */
24314          transmit_response(p, "200 OK", req);
24315          return 0;
24316       }
24317       ast_log(LOG_WARNING, "Invalid URI '%s' in CC subscribe\n", uri);
24318       transmit_response(p, "404 Not Found", req);
24319       return -1;
24320    }
24321 
24322    agent_pvt = agent->private_data;
24323 
24324    if (!expires) {
24325       /* We got sent a SUBSCRIBE and found an agent. This means that CC
24326        * is being canceled.
24327        */
24328       ast_cc_failed(agent->core_id, "CC is being canceled by %s", agent->device_name);
24329       transmit_response(p, "200 OK", req);
24330       ao2_ref(agent, -1);
24331       return 0;
24332    }
24333 
24334    agent_pvt->subscribe_pvt = dialog_ref(p, "SIP CC agent gains reference to subscription dialog");
24335    ast_cc_agent_accept_request(agent->core_id, "SIP caller %s has requested CC via SUBSCRIBE",
24336          agent->device_name);
24337 
24338    /* We don't send a response here. That is done in the agent's ack callback or in the
24339     * agent destructor, should a failure occur before we have responded
24340     */
24341    ao2_ref(agent, -1);
24342    return 0;
24343 }
24344 
24345 /*! \brief  Handle incoming SUBSCRIBE request */
24346 static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, int seqno, const char *e)
24347 {
24348    int gotdest = 0;
24349    int res = 0;
24350    int firststate;
24351    struct sip_peer *authpeer = NULL;
24352    const char *eventheader = get_header(req, "Event");   /* Get Event package name */
24353    int resubscribe = (p->subscribed != NONE) && !req->ignore;
24354    char *temp, *event;
24355 
24356    if (p->initreq.headers) {  
24357       /* We already have a dialog */
24358       if (p->initreq.method != SIP_SUBSCRIBE) {
24359          /* This is a SUBSCRIBE within another SIP dialog, which we do not support */
24360          /* For transfers, this could happen, but since we haven't seen it happening, let us just refuse this */
24361          transmit_response(p, "403 Forbidden (within dialog)", req);
24362          /* Do not destroy session, since we will break the call if we do */
24363          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);
24364          return 0;
24365       } else if (req->debug) {
24366          if (resubscribe)
24367             ast_debug(1, "Got a re-subscribe on existing subscription %s\n", p->callid);
24368          else
24369             ast_debug(1, "Got a new subscription %s (possibly with auth) or retransmission\n", p->callid);
24370       }
24371    }
24372 
24373    /* Check if we have a global disallow setting on subscriptions.
24374       if so, we don't have to check peer settings after auth, which saves a lot of processing
24375    */
24376    if (!sip_cfg.allowsubscribe) {
24377       transmit_response(p, "403 Forbidden (policy)", req);
24378       pvt_set_needdestroy(p, "forbidden");
24379       return 0;
24380    }
24381 
24382    if (!req->ignore && !resubscribe) { /* Set up dialog, new subscription */
24383       const char *to = get_header(req, "To");
24384       char totag[128];
24385       set_pvt_allowed_methods(p, req);
24386 
24387       /* Check to see if a tag was provided, if so this is actually a resubscription of a dialog we no longer know about */
24388       if (!ast_strlen_zero(to) && gettag(req, "To", totag, sizeof(totag))) {
24389          if (req->debug)
24390             ast_verbose("Received resubscription for a dialog we no longer know about. Telling remote side to subscribe again.\n");
24391          transmit_response(p, "481 Subscription does not exist", req);
24392          pvt_set_needdestroy(p, "subscription does not exist");
24393          return 0;
24394       }
24395 
24396       /* Use this as the basis */
24397       if (req->debug)
24398          ast_verbose("Creating new subscription\n");
24399 
24400       copy_request(&p->initreq, req);
24401       if (sipdebug)
24402          ast_debug(4, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
24403       check_via(p, req);
24404       build_route(p, req, 0);
24405    } else if (req->debug && req->ignore)
24406       ast_verbose("Ignoring this SUBSCRIBE request\n");
24407 
24408    /* Find parameters to Event: header value and remove them for now */
24409    if (ast_strlen_zero(eventheader)) {
24410       transmit_response(p, "489 Bad Event", req);
24411       ast_debug(2, "Received SIP subscribe for unknown event package: <none>\n");
24412       pvt_set_needdestroy(p, "unknown event package in subscribe");
24413       return 0;
24414    }
24415 
24416    if ( (strchr(eventheader, ';'))) {
24417       event = ast_strdupa(eventheader);   /* Since eventheader is a const, we can't change it */
24418       temp = strchr(event, ';');       
24419       *temp = '\0';           /* Remove any options for now */
24420                      /* We might need to use them later :-) */
24421    } else
24422       event = (char *) eventheader;    /* XXX is this legal ? */
24423 
24424    /* Handle authentication if we're new and not a retransmission. We can't just
24425     * use if !req->ignore, because then we'll end up sending
24426     * a 200 OK if someone retransmits without sending auth */
24427    if (p->subscribed == NONE || resubscribe) {
24428       res = check_user_full(p, req, SIP_SUBSCRIBE, e, 0, addr, &authpeer);
24429 
24430       /* if an authentication response was sent, we are done here */
24431       if (res == AUTH_CHALLENGE_SENT)  /* authpeer = NULL here */
24432          return 0;
24433       if (res != AUTH_SUCCESSFUL) {
24434          if (res == AUTH_FAKE_AUTH) {
24435             ast_log(LOG_NOTICE, "Sending fake auth rejection for device %s\n", get_header(req, "From"));
24436             transmit_fake_auth_response(p, SIP_SUBSCRIBE, req, XMIT_UNRELIABLE);
24437          } else {
24438             ast_log(LOG_NOTICE, "Failed to authenticate device %s for SUBSCRIBE\n", get_header(req, "From"));
24439             transmit_response_reliable(p, "403 Forbidden", req);
24440          }
24441 
24442          pvt_set_needdestroy(p, "authentication failed");
24443          return 0;
24444       }
24445    }
24446 
24447    /* At this point, we hold a reference to authpeer (if not NULL).  It
24448     * must be released when done.
24449     */
24450 
24451    /* Check if this device  is allowed to subscribe at all */
24452    if (!ast_test_flag(&p->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)) {
24453       transmit_response(p, "403 Forbidden (policy)", req);
24454       pvt_set_needdestroy(p, "subscription not allowed");
24455       if (authpeer) {
24456          unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 1)");
24457       }
24458       return 0;
24459    }
24460 
24461    if (strcmp(event, "message-summary") && strcmp(event, "call-completion")) {
24462       /* Get destination right away */
24463       gotdest = get_destination(p, NULL, NULL);
24464    }
24465 
24466    /* Get full contact header - this needs to be used as a request URI in NOTIFY's */
24467    parse_ok_contact(p, req);
24468 
24469    build_contact(p);
24470    if (gotdest != SIP_GET_DEST_EXTEN_FOUND) {
24471       if (gotdest == SIP_GET_DEST_INVALID_URI) {
24472          transmit_response(p, "416 Unsupported URI scheme", req);
24473       } else {
24474          transmit_response(p, "404 Not Found", req);
24475       }
24476       pvt_set_needdestroy(p, "subscription target not found");
24477       if (authpeer) {
24478          unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 2)");
24479       }
24480       return 0;
24481    }
24482 
24483    /* Initialize tag for new subscriptions */   
24484    if (ast_strlen_zero(p->tag))
24485       make_our_tag(p->tag, sizeof(p->tag));
24486 
24487    if (!strcmp(event, "presence") || !strcmp(event, "dialog")) { /* Presence, RFC 3842 */
24488       unsigned int pidf_xml;
24489       const char *accept;
24490       int start = 0;
24491       enum subscriptiontype subscribed = NONE;
24492       const char *unknown_acceptheader = NULL;
24493 
24494       /* Header from Xten Eye-beam Accept: multipart/related, application/rlmi+xml, application/pidf+xml, application/xpidf+xml */
24495       accept = __get_header(req, "Accept", &start);
24496       while ((subscribed == NONE) && !ast_strlen_zero(accept)) {
24497          pidf_xml = strstr(accept, "application/pidf+xml") ? 1 : 0;
24498 
24499          /* Older versions of Polycom firmware will claim pidf+xml, but really
24500           * they only support xpidf+xml. */
24501          if (pidf_xml && strstr(p->useragent, "Polycom")) {
24502             subscribed = XPIDF_XML;
24503          } else if (pidf_xml) {
24504             subscribed = PIDF_XML;         /* RFC 3863 format */
24505          } else if (strstr(accept, "application/dialog-info+xml")) {
24506             subscribed = DIALOG_INFO_XML;
24507             /* IETF draft: draft-ietf-sipping-dialog-package-05.txt */
24508          } else if (strstr(accept, "application/cpim-pidf+xml")) {
24509             subscribed = CPIM_PIDF_XML;    /* RFC 3863 format */
24510          } else if (strstr(accept, "application/xpidf+xml")) {
24511             subscribed = XPIDF_XML;        /* Early pre-RFC 3863 format with MSN additions (Microsoft Messenger) */
24512          } else {
24513             unknown_acceptheader = accept;
24514          }
24515          /* check to see if there is another Accept header present */
24516          accept = __get_header(req, "Accept", &start);
24517       }
24518 
24519       if (!start) {
24520          if (p->subscribed == NONE) { /* if the subscribed field is not already set, and there is no accept header... */
24521             transmit_response(p, "489 Bad Event", req);
24522             ast_log(LOG_WARNING,"SUBSCRIBE failure: no Accept header: pvt: "
24523                "stateid: %d, laststate: %d, dialogver: %d, subscribecont: "
24524                "'%s', subscribeuri: '%s'\n",
24525                p->stateid,
24526                p->laststate,
24527                p->dialogver,
24528                p->subscribecontext,
24529                p->subscribeuri);
24530             pvt_set_needdestroy(p, "no Accept header");
24531             if (authpeer) {
24532                unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 2)");
24533             }
24534             return 0;
24535          }
24536          /* if p->subscribed is non-zero, then accept is not obligatory; according to rfc 3265 section 3.1.3, at least.
24537             so, we'll just let it ride, keeping the value from a previous subscription, and not abort the subscription */
24538       } else if (subscribed == NONE) {
24539          /* Can't find a format for events that we know about */
24540          char mybuf[200];
24541          if (!ast_strlen_zero(unknown_acceptheader)) {
24542             snprintf(mybuf, sizeof(mybuf), "489 Bad Event (format %s)", unknown_acceptheader);
24543          } else {
24544             snprintf(mybuf, sizeof(mybuf), "489 Bad Event");
24545          }
24546          transmit_response(p, mybuf, req);
24547          ast_log(LOG_WARNING,"SUBSCRIBE failure: unrecognized format:"
24548             "'%s' pvt: subscribed: %d, stateid: %d, laststate: %d,"
24549             "dialogver: %d, subscribecont: '%s', subscribeuri: '%s'\n",
24550             unknown_acceptheader,
24551             (int)p->subscribed,
24552             p->stateid,
24553             p->laststate,
24554             p->dialogver,
24555             p->subscribecontext,
24556             p->subscribeuri);
24557          pvt_set_needdestroy(p, "unrecognized format");
24558          if (authpeer) {
24559             unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 2)");
24560          }
24561          return 0;
24562       } else {
24563          p->subscribed = subscribed;
24564       }
24565    } else if (!strcmp(event, "message-summary")) {
24566       int start = 0;
24567       int found_supported = 0;
24568       const char *acceptheader;
24569 
24570       acceptheader = __get_header(req, "Accept", &start);
24571       while (!found_supported && !ast_strlen_zero(acceptheader)) {
24572          found_supported = strcmp(acceptheader, "application/simple-message-summary") ? 0 : 1;
24573          if (!found_supported && (option_debug > 2)) {
24574             ast_log(LOG_DEBUG, "Received SIP mailbox subscription for unknown format: %s\n", acceptheader);
24575          }
24576          acceptheader = __get_header(req, "Accept", &start);
24577       }
24578       if (start && !found_supported) {
24579          /* Format requested that we do not support */
24580          transmit_response(p, "406 Not Acceptable", req);
24581          ast_debug(2, "Received SIP mailbox subscription for unknown format: %s\n", acceptheader);
24582          pvt_set_needdestroy(p, "unknown format");
24583          if (authpeer) {
24584             unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 3)");
24585          }
24586          return 0;
24587       }
24588       /* Looks like they actually want a mailbox status
24589         This version of Asterisk supports mailbox subscriptions
24590         The subscribed URI needs to exist in the dial plan
24591         In most devices, this is configurable to the voicemailmain extension you use
24592       */
24593       if (!authpeer || AST_LIST_EMPTY(&authpeer->mailboxes)) {
24594          if (!authpeer) {
24595             transmit_response(p, "404 Not found", req);
24596          } else {
24597             transmit_response(p, "404 Not found (no mailbox)", req);
24598             ast_log(LOG_NOTICE, "Received SIP subscribe for peer without mailbox: %s\n", S_OR(authpeer->name, ""));
24599          }
24600          pvt_set_needdestroy(p, "received 404 response");
24601          if (authpeer) {
24602             unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 3)");
24603          }
24604          return 0;
24605       }
24606 
24607       p->subscribed = MWI_NOTIFICATION;
24608       if (ast_test_flag(&authpeer->flags[1], SIP_PAGE2_SUBSCRIBEMWIONLY)) {
24609          ao2_unlock(p);
24610          add_peer_mwi_subs(authpeer);
24611          ao2_lock(p);
24612       }
24613       if (authpeer->mwipvt != p) {  /* Destroy old PVT if this is a new one */
24614          /* We only allow one subscription per peer */
24615          if (authpeer->mwipvt) {
24616             dialog_unlink_all(authpeer->mwipvt);
24617             authpeer->mwipvt = dialog_unref(authpeer->mwipvt, "unref dialog authpeer->mwipvt");
24618          }
24619          authpeer->mwipvt = dialog_ref(p, "setting peers' mwipvt to p");
24620       }
24621       if (p->relatedpeer != authpeer) {
24622          if (p->relatedpeer) {
24623             unref_peer(p->relatedpeer, "Unref previously stored relatedpeer ptr");
24624          }
24625          p->relatedpeer = ref_peer(authpeer, "setting dialog's relatedpeer pointer");
24626       }
24627       /* Do not release authpeer here */
24628    } else if (!strcmp(event, "call-completion")) {
24629       handle_cc_subscribe(p, req);
24630    } else { /* At this point, Asterisk does not understand the specified event */
24631       transmit_response(p, "489 Bad Event", req);
24632       ast_debug(2, "Received SIP subscribe for unknown event package: %s\n", event);
24633       pvt_set_needdestroy(p, "unknown event package");
24634       if (authpeer) {
24635          unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 5)");
24636       }
24637       return 0;
24638    }
24639 
24640    /* Add subscription for extension state from the PBX core */
24641    if (p->subscribed != MWI_NOTIFICATION  && p->subscribed != CALL_COMPLETION && !resubscribe) {
24642       if (p->stateid != -1) {
24643          ast_extension_state_del(p->stateid, cb_extensionstate);
24644       }
24645       dialog_ref(p, "copying dialog ptr into extension state struct");
24646       p->stateid = ast_extension_state_add_destroy(p->context, p->exten,
24647          cb_extensionstate, cb_extensionstate_destroy, p);
24648       if (p->stateid == -1) {
24649          dialog_unref(p, "copying dialog ptr into extension state struct failed");
24650       }
24651    }
24652 
24653    if (!req->ignore && p)
24654       p->lastinvite = seqno;
24655    if (p && !p->needdestroy) {
24656       p->expiry = atoi(get_header(req, "Expires"));
24657 
24658       /* check if the requested expiry-time is within the approved limits from sip.conf */
24659       if (p->expiry > max_expiry) {
24660          p->expiry = max_expiry;
24661       } else if (p->expiry < min_expiry && p->expiry > 0) {
24662          transmit_response_with_minexpires(p, "423 Interval too small", req);
24663          ast_log(LOG_WARNING, "Received subscription for extension \"%s\" context \"%s\" "
24664             "with Expire header less that 'minexpire' limit. Received \"Expire: %d\" min is %d\n",
24665             p->exten, p->context, p->expiry, min_expiry);
24666          pvt_set_needdestroy(p, "Expires is less that the min expires allowed.");
24667          if (authpeer) {
24668             unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 6)");
24669          }
24670          return 0;
24671       }
24672 
24673       if (sipdebug) {
24674          if (p->subscribed == MWI_NOTIFICATION && p->relatedpeer) {
24675             ast_debug(2, "Adding subscription for mailbox notification - peer %s\n", p->relatedpeer->name);
24676          } else if (p->subscribed == CALL_COMPLETION) {
24677             ast_debug(2, "Adding CC subscription for peer %s\n", p->username);
24678          } else {
24679             ast_debug(2, "Adding subscription for extension %s context %s for peer %s\n", p->exten, p->context, p->username);
24680          }
24681       }
24682       if (p->autokillid > -1 && sip_cancel_destroy(p))   /* Remove subscription expiry for renewals */
24683          ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
24684       if (p->expiry > 0)
24685          sip_scheddestroy(p, (p->expiry + 10) * 1000);   /* Set timer for destruction of call at expiration */
24686 
24687       if (p->subscribed == MWI_NOTIFICATION) {
24688          ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
24689          transmit_response(p, "200 OK", req);
24690          if (p->relatedpeer) {   /* Send first notification */
24691             struct sip_peer *peer = p->relatedpeer;
24692             ref_peer(peer, "ensure a peer ref is held during MWI sending");
24693             ao2_unlock(p);
24694             sip_send_mwi_to_peer(peer, 0);
24695             ao2_lock(p);
24696             unref_peer(peer, "release a peer ref now that MWI is sent");
24697          }
24698       } else if (p->subscribed != CALL_COMPLETION) {
24699          if ((firststate = ast_extension_state(NULL, p->context, p->exten)) < 0) {
24700 
24701             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));
24702             transmit_response(p, "404 Not found", req);
24703             pvt_set_needdestroy(p, "no extension for SUBSCRIBE");
24704             if (authpeer) {
24705                unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 6)");
24706             }
24707             return 0;
24708          }
24709          ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
24710          transmit_response(p, "200 OK", req);
24711          transmit_state_notify(p, firststate, 1, FALSE); /* Send first notification */
24712          append_history(p, "Subscribestatus", "%s", ast_extension_state2str(firststate));
24713          /* hide the 'complete' exten/context in the refer_to field for later display */
24714          ast_string_field_build(p, subscribeuri, "%s@%s", p->exten, p->context);
24715          /* Deleted the slow iteration of all sip dialogs to find old subscribes from this peer for exten@context */
24716 
24717       }
24718       if (!p->expiry) {
24719          pvt_set_needdestroy(p, "forcing expiration");
24720       }
24721    }
24722 
24723    if (authpeer) {
24724       unref_peer(authpeer, "unref pointer into (*authpeer)");
24725    }
24726    return 1;
24727 }
24728 
24729 /*! \brief Handle incoming REGISTER request */
24730 static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, const char *e)
24731 {
24732    enum check_auth_result res;
24733 
24734    /* If this is not the intial request, and the initial request isn't
24735     * a register, something screwy happened, so bail */
24736    if (p->initreq.headers && p->initreq.method != SIP_REGISTER) {
24737       ast_log(LOG_WARNING, "Ignoring spurious REGISTER with Call-ID: %s\n", p->callid);
24738       return -1;
24739    }
24740 
24741    /* Use this as the basis */
24742    copy_request(&p->initreq, req);
24743    if (sipdebug)
24744       ast_debug(4, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
24745    check_via(p, req);
24746    if ((res = register_verify(p, addr, req, e)) < 0) {
24747       const char *reason;
24748 
24749       switch (res) {
24750       case AUTH_SECRET_FAILED:
24751          reason = "Wrong password";
24752          break;
24753       case AUTH_USERNAME_MISMATCH:
24754          reason = "Username/auth name mismatch";
24755          break;
24756       case AUTH_NOT_FOUND:
24757          reason = "No matching peer found";
24758          break;
24759       case AUTH_UNKNOWN_DOMAIN:
24760          reason = "Not a local domain";
24761          break;
24762       case AUTH_PEER_NOT_DYNAMIC:
24763          reason = "Peer is not supposed to register";
24764          break;
24765       case AUTH_ACL_FAILED:
24766          reason = "Device does not match ACL";
24767          break;
24768       case AUTH_BAD_TRANSPORT:
24769          reason = "Device not configured to use this transport type";
24770          break;
24771       default:
24772          reason = "Unknown failure";
24773          break;
24774       }
24775       ast_log(LOG_NOTICE, "Registration from '%s' failed for '%s' - %s\n",
24776          get_header(req, "To"), ast_sockaddr_stringify(addr),
24777          reason);
24778       append_history(p, "RegRequest", "Failed : Account %s : %s", get_header(req, "To"), reason);
24779    } else {
24780       req->authenticated = 1;
24781       append_history(p, "RegRequest", "Succeeded : Account %s", get_header(req, "To"));
24782    }
24783 
24784    if (res < 1) {
24785       /* Destroy the session, but keep us around for just a bit in case they don't
24786          get our 200 OK */
24787       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
24788    }
24789    return res;
24790 }
24791 
24792 /*!
24793  * \brief Handle incoming SIP requests (methods)
24794  * \note
24795  * This is where all incoming requests go first.
24796  * \note
24797  * called with p and p->owner locked
24798  */
24799 static int handle_incoming(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, int *recount, int *nounlock)
24800 {
24801    /* Called with p->lock held, as well as p->owner->lock if appropriate, keeping things
24802       relatively static */
24803    const char *cmd;
24804    const char *cseq;
24805    const char *useragent;
24806    const char *via;
24807    const char *callid;
24808    int via_pos = 0;
24809    int seqno;
24810    int len;
24811    int respid;
24812    int res = 0;
24813    int debug = sip_debug_test_pvt(p);
24814    const char *e;
24815    int error = 0;
24816    int oldmethod = p->method;
24817    int acked = 0;
24818 
24819    /* RFC 3261 - 8.1.1 A valid SIP request must contain To, From, CSeq, Call-ID and Via.
24820     * 8.2.6.2 Response must have To, From, Call-ID CSeq, and Via related to the request,
24821     * so we can check to make sure these fields exist for all requests and responses */
24822    cseq = get_header(req, "Cseq");
24823    cmd = REQ_OFFSET_TO_STR(req, header[0]);
24824    /* Save the via_pos so we can check later that responses only have 1 Via header */
24825    via = __get_header(req, "Via", &via_pos);
24826    /* This must exist already because we've called find_call by now */
24827    callid = get_header(req, "Call-ID");
24828 
24829    /* Must have Cseq */
24830    if (ast_strlen_zero(cmd) || ast_strlen_zero(cseq) || ast_strlen_zero(via)) {
24831       ast_log(LOG_ERROR, "Dropping this SIP message with Call-ID '%s', it's incomplete.\n", callid);
24832       error = 1;
24833    }
24834    if (!error && sscanf(cseq, "%30d%n", &seqno, &len) != 1) {
24835       ast_log(LOG_ERROR, "No seqno in '%s'. Dropping incomplete message.\n", cmd);
24836       error = 1;
24837    }
24838    if (error) {
24839       if (!p->initreq.headers) { /* New call */
24840          pvt_set_needdestroy(p, "no headers");
24841       }
24842       return -1;
24843    }
24844    /* Get the command XXX */
24845 
24846    cmd = REQ_OFFSET_TO_STR(req, rlPart1);
24847    e = ast_skip_blanks(REQ_OFFSET_TO_STR(req, rlPart2));
24848 
24849    /* Save useragent of the client */
24850    useragent = get_header(req, "User-Agent");
24851    if (!ast_strlen_zero(useragent))
24852       ast_string_field_set(p, useragent, useragent);
24853 
24854    /* Find out SIP method for incoming request */
24855    if (req->method == SIP_RESPONSE) {  /* Response to our request */
24856       /* ignore means "don't do anything with it" but still have to
24857        * respond appropriately.
24858        * But in this case this is a response already, so we really
24859        * have nothing to do with this message, and even setting the
24860        * ignore flag is pointless.
24861        */
24862       if (ast_strlen_zero(e)) {
24863          return 0;
24864       }
24865       if (sscanf(e, "%30d %n", &respid, &len) != 1) {
24866          ast_log(LOG_WARNING, "Invalid response: '%s'\n", e);
24867          return 0;
24868       }
24869       if (respid <= 0) {
24870          ast_log(LOG_WARNING, "Invalid SIP response code: '%d'\n", respid);
24871          return 0;
24872       }
24873       /* RFC 3261 - 8.1.3.3 If more than one Via header field value is present in a reponse
24874        * the UAC SHOULD discard the message. This is not perfect, as it will not catch multiple
24875        * headers joined with a comma. Fixing that would pretty much involve writing a new parser */
24876       if (!ast_strlen_zero(__get_header(req, "via", &via_pos))) {
24877          ast_log(LOG_WARNING, "Misrouted SIP response '%s' with Call-ID '%s', too many vias\n", e, callid);
24878          return 0;
24879       }
24880       if (p->ocseq && (p->ocseq < seqno)) {
24881          ast_debug(1, "Ignoring out of order response %d (expecting %d)\n", seqno, p->ocseq);
24882          return -1;
24883       } else {
24884          char causevar[256], causeval[256];
24885 
24886          if ((respid == 200) || ((respid >= 300) && (respid <= 399))) {
24887             extract_uri(p, req);
24888          }
24889 
24890          handle_response(p, respid, e + len, req, seqno);
24891 
24892          if (global_store_sip_cause && p->owner) {
24893             struct ast_channel *owner = p->owner;
24894 
24895             snprintf(causevar, sizeof(causevar), "MASTER_CHANNEL(HASH(SIP_CAUSE,%s))", owner->name);
24896             snprintf(causeval, sizeof(causeval), "SIP %s", REQ_OFFSET_TO_STR(req, rlPart2));
24897 
24898             ast_channel_ref(owner);
24899             sip_pvt_unlock(p);
24900             ast_channel_unlock(owner);
24901             *nounlock = 1;
24902             pbx_builtin_setvar_helper(owner, causevar, causeval);
24903             ast_channel_unref(owner);
24904             sip_pvt_lock(p);
24905          }
24906       }
24907       return 0;
24908    }
24909 
24910    /* New SIP request coming in
24911       (could be new request in existing SIP dialog as well...)
24912     */         
24913    
24914    p->method = req->method;   /* Find out which SIP method they are using */
24915    ast_debug(4, "**** Received %s (%d) - Command in SIP %s\n", sip_methods[p->method].text, sip_methods[p->method].id, cmd);
24916 
24917    if (p->icseq && (p->icseq > seqno) ) {
24918       if (p->pendinginvite && seqno == p->pendinginvite && (req->method == SIP_ACK || req->method == SIP_CANCEL)) {
24919          ast_debug(2, "Got CANCEL or ACK on INVITE with transactions in between.\n");
24920       } else {
24921          ast_debug(1, "Ignoring too old SIP packet packet %d (expecting >= %d)\n", seqno, p->icseq);
24922          if (req->method == SIP_INVITE) {
24923             unsigned int ran = (ast_random() % 10) + 1;
24924             char seconds[4];
24925             snprintf(seconds, sizeof(seconds), "%u", ran);
24926             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 */
24927          } else if (req->method != SIP_ACK) {
24928             transmit_response(p, "500 Server error", req);  /* We must respond according to RFC 3261 sec 12.2 */
24929          }
24930          return -1;
24931       }
24932    } else if (p->icseq &&
24933          p->icseq == seqno &&
24934          req->method != SIP_ACK &&
24935          (p->method != SIP_CANCEL || p->alreadygone)) {
24936       /* ignore means "don't do anything with it" but still have to
24937          respond appropriately.  We do this if we receive a repeat of
24938          the last sequence number  */
24939       req->ignore = 1;
24940       ast_debug(3, "Ignoring SIP message because of retransmit (%s Seqno %d, ours %d)\n", sip_methods[p->method].text, p->icseq, seqno);
24941    }
24942 
24943    /* RFC 3261 section 9. "CANCEL has no effect on a request to which a UAS has
24944     * already given a final response." */
24945    if (!p->pendinginvite && (req->method == SIP_CANCEL)) {
24946       transmit_response(p, "481 Call/Transaction Does Not Exist", req);
24947       return res;
24948    }
24949 
24950    if (seqno >= p->icseq)
24951       /* Next should follow monotonically (but not necessarily
24952          incrementally -- thanks again to the genius authors of SIP --
24953          increasing */
24954       p->icseq = seqno;
24955 
24956    /* Find their tag if we haven't got it */
24957    if (ast_strlen_zero(p->theirtag)) {
24958       char tag[128];
24959 
24960       gettag(req, "From", tag, sizeof(tag));
24961       ast_string_field_set(p, theirtag, tag);
24962    }
24963    snprintf(p->lastmsg, sizeof(p->lastmsg), "Rx: %s", cmd);
24964 
24965    if (sip_cfg.pedanticsipchecking) {
24966       /* If this is a request packet without a from tag, it's not
24967          correct according to RFC 3261  */
24968       /* Check if this a new request in a new dialog with a totag already attached to it,
24969          RFC 3261 - section 12.2 - and we don't want to mess with recovery  */
24970       if (!p->initreq.headers && req->has_to_tag) {
24971          /* If this is a first request and it got a to-tag, it is not for us */
24972          if (!req->ignore && req->method == SIP_INVITE) {
24973             transmit_response_reliable(p, "481 Call/Transaction Does Not Exist", req);
24974             /* Will cease to exist after ACK */
24975          } else if (req->method != SIP_ACK) {
24976             transmit_response(p, "481 Call/Transaction Does Not Exist", req);
24977             sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
24978          } else {
24979             ast_debug(1, "Got ACK for unknown dialog... strange.\n");
24980          }
24981          return res;
24982       }
24983    }
24984 
24985    if (!e && (p->method == SIP_INVITE || p->method == SIP_SUBSCRIBE || p->method == SIP_REGISTER || p->method == SIP_NOTIFY || p->method == SIP_PUBLISH)) {
24986       transmit_response(p, "400 Bad request", req);
24987       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
24988       return -1;
24989    }
24990 
24991    /* Handle various incoming SIP methods in requests */
24992    switch (p->method) {
24993    case SIP_OPTIONS:
24994       res = handle_request_options(p, req, addr, e);
24995       break;
24996    case SIP_INVITE:
24997       res = handle_request_invite(p, req, debug, seqno, addr, recount, e, nounlock);
24998       break;
24999    case SIP_REFER:
25000       res = handle_request_refer(p, req, debug, seqno, nounlock);
25001       break;
25002    case SIP_CANCEL:
25003       res = handle_request_cancel(p, req);
25004       break;
25005    case SIP_BYE:
25006       res = handle_request_bye(p, req);
25007       break;
25008    case SIP_MESSAGE:
25009       res = handle_request_message(p, req);
25010       break;
25011    case SIP_PUBLISH:
25012       res = handle_request_publish(p, req, addr, seqno, e);
25013       break;
25014    case SIP_SUBSCRIBE:
25015       res = handle_request_subscribe(p, req, addr, seqno, e);
25016       break;
25017    case SIP_REGISTER:
25018       res = handle_request_register(p, req, addr, e);
25019       break;
25020    case SIP_INFO:
25021       if (req->debug)
25022          ast_verbose("Receiving INFO!\n");
25023       if (!req->ignore)
25024          handle_request_info(p, req);
25025       else  /* if ignoring, transmit response */
25026          transmit_response(p, "200 OK", req);
25027       break;
25028    case SIP_NOTIFY:
25029       res = handle_request_notify(p, req, addr, seqno, e);
25030       break;
25031    case SIP_UPDATE:
25032       res = handle_request_update(p, req);
25033       break;
25034    case SIP_ACK:
25035       /* Make sure we don't ignore this */
25036       if (seqno == p->pendinginvite) {
25037          p->invitestate = INV_TERMINATED;
25038          p->pendinginvite = 0;
25039          acked = __sip_ack(p, seqno, 1 /* response */, 0);
25040          if (find_sdp(req)) {
25041             if (process_sdp(p, req, SDP_T38_NONE))
25042                return -1;
25043          }
25044          check_pendings(p);
25045       } else if (p->glareinvite == seqno) {
25046          /* handle ack for the 491 pending sent for glareinvite */
25047          p->glareinvite = 0;
25048          acked = __sip_ack(p, seqno, 1, 0);
25049       }
25050       if (!acked) {
25051          /* Got an ACK that did not match anything. Ignore
25052           * silently and restore previous method */
25053          p->method = oldmethod;
25054       }
25055       if (!p->lastinvite && ast_strlen_zero(p->randdata)) {
25056          pvt_set_needdestroy(p, "unmatched ACK");
25057       }
25058       break;
25059    default:
25060       transmit_response_with_allow(p, "501 Method Not Implemented", req, 0);
25061       ast_log(LOG_NOTICE, "Unknown SIP command '%s' from '%s'\n",
25062          cmd, ast_sockaddr_stringify(&p->sa));
25063       /* If this is some new method, and we don't have a call, destroy it now */
25064       if (!p->initreq.headers) {
25065          pvt_set_needdestroy(p, "unimplemented method");
25066       }
25067       break;
25068    }
25069    return res;
25070 }
25071 
25072 /*! \brief Read data from SIP UDP socket
25073 \note sipsock_read locks the owner channel while we are processing the SIP message
25074 \return 1 on error, 0 on success
25075 \note Successful messages is connected to SIP call and forwarded to handle_incoming()
25076 */
25077 static int sipsock_read(int *id, int fd, short events, void *ignore)
25078 {
25079    struct sip_request req;
25080    struct ast_sockaddr addr;
25081    int res;
25082    static char readbuf[65535];
25083 
25084    memset(&req, 0, sizeof(req));
25085    res = ast_recvfrom(fd, readbuf, sizeof(readbuf) - 1, 0, &addr);
25086    if (res < 0) {
25087 #if !defined(__FreeBSD__)
25088       if (errno == EAGAIN)
25089          ast_log(LOG_NOTICE, "SIP: Received packet with bad UDP checksum\n");
25090       else
25091 #endif
25092       if (errno != ECONNREFUSED)
25093          ast_log(LOG_WARNING, "Recv error: %s\n", strerror(errno));
25094       return 1;
25095    }
25096 
25097    readbuf[res] = '\0';
25098 
25099    if (!(req.data = ast_str_create(SIP_MIN_PACKET))) {
25100       return 1;
25101    }
25102 
25103    if (ast_str_set(&req.data, 0, "%s", readbuf) == AST_DYNSTR_BUILD_FAILED) {
25104       return -1;
25105    }
25106 
25107    req.socket.fd = sipsock;
25108    set_socket_transport(&req.socket, SIP_TRANSPORT_UDP);
25109    req.socket.tcptls_session  = NULL;
25110    req.socket.port = htons(ast_sockaddr_port(&bindaddr));
25111 
25112    handle_request_do(&req, &addr);
25113    deinit_req(&req);
25114 
25115    return 1;
25116 }
25117 
25118 /*! \brief Handle incoming SIP message - request or response
25119 
25120    This is used for all transports (udp, tcp and tcp/tls)
25121 */
25122 static int handle_request_do(struct sip_request *req, struct ast_sockaddr *addr)
25123 {
25124    struct sip_pvt *p;
25125    struct ast_channel *owner_chan_ref = NULL;
25126    int recount = 0;
25127    int nounlock = 0;
25128 
25129    if (sip_debug_test_addr(addr))   /* Set the debug flag early on packet level */
25130       req->debug = 1;
25131    if (sip_cfg.pedanticsipchecking)
25132       lws2sws(req->data);  /* Fix multiline headers */
25133    if (req->debug) {
25134       ast_verbose("\n<--- SIP read from %s:%s --->\n%s\n<------------->\n",
25135          get_transport(req->socket.type), ast_sockaddr_stringify(addr), req->data->str);
25136    }
25137 
25138    if (parse_request(req) == -1) { /* Bad packet, can't parse */
25139       ast_str_reset(req->data); /* nulling this out is NOT a good idea here. */
25140       return 1;
25141    }
25142    req->method = find_sip_method(REQ_OFFSET_TO_STR(req, rlPart1));
25143 
25144    if (req->debug)
25145       ast_verbose("--- (%d headers %d lines)%s ---\n", req->headers, req->lines, (req->headers + req->lines == 0) ? " Nat keepalive" : "");
25146 
25147    if (req->headers < 2) { /* Must have at least two headers */
25148       ast_str_reset(req->data); /* nulling this out is NOT a good idea here. */
25149       return 1;
25150    }
25151 
25152    /* Process request, with netlock held, and with usual deadlock avoidance */
25153    ast_mutex_lock(&netlock);
25154 
25155    /* Find the active SIP dialog or create a new one */
25156    p = find_call(req, addr, req->method); /* returns p with a reference only. _NOT_ locked*/
25157    if (p == NULL) {
25158       ast_debug(1, "Invalid SIP message - rejected , no callid, len %zu\n", ast_str_strlen(req->data));
25159       ast_mutex_unlock(&netlock);
25160       return 1;
25161    }
25162 
25163    /* Lock both the pvt and the owner if owner is present.  This will
25164     * not fail. */
25165    owner_chan_ref = sip_pvt_lock_full(p);
25166 
25167    copy_socket_data(&p->socket, &req->socket);
25168    ast_sockaddr_copy(&p->recv, addr);
25169 
25170    /* if we have an owner, then this request has been authenticated */
25171    if (p->owner) {
25172       req->authenticated = 1;
25173    }
25174 
25175    if (p->do_history) /* This is a request or response, note what it was for */
25176       append_history(p, "Rx", "%s / %s / %s", req->data->str, get_header(req, "CSeq"), REQ_OFFSET_TO_STR(req, rlPart2));
25177 
25178    if (handle_incoming(p, req, addr, &recount, &nounlock) == -1) {
25179       /* Request failed */
25180       ast_debug(1, "SIP message could not be handled, bad request: %-70.70s\n", p->callid[0] ? p->callid : "<no callid>");
25181    }
25182 
25183    if (recount) {
25184       ast_update_use_count();
25185    }
25186 
25187    if (p->owner && !nounlock) {
25188       ast_channel_unlock(p->owner);
25189    }
25190    if (owner_chan_ref) {
25191       ast_channel_unref(owner_chan_ref);
25192    }
25193    sip_pvt_unlock(p);
25194    ao2_t_ref(p, -1, "throw away dialog ptr from find_call at end of routine"); /* p is gone after the return */
25195    ast_mutex_unlock(&netlock);
25196 
25197    return 1;
25198 }
25199 
25200 /*! \brief Returns the port to use for this socket
25201  *
25202  * \param type The type of transport used
25203  * \param port Port we are checking to see if it's the standard port.
25204  * \note port is expected in host byte order
25205  */
25206 static int sip_standard_port(enum sip_transport type, int port)
25207 {
25208    if (type & SIP_TRANSPORT_TLS)
25209       return port == STANDARD_TLS_PORT;
25210    else
25211       return port == STANDARD_SIP_PORT;
25212 }
25213 
25214 static int threadinfo_locate_cb(void *obj, void *arg, int flags)
25215 {
25216    struct sip_threadinfo *th = obj;
25217    struct ast_sockaddr *s = arg;
25218 
25219    if (!ast_sockaddr_cmp(s, &th->tcptls_session->remote_address)) {
25220       return CMP_MATCH | CMP_STOP;
25221    }
25222 
25223    return 0;
25224 }
25225 
25226 /*!
25227  * \brief Find thread for TCP/TLS session (based on IP/Port
25228  *
25229  * \note This function returns an astobj2 reference
25230  */
25231 static struct ast_tcptls_session_instance *sip_tcp_locate(struct ast_sockaddr *s)
25232 {
25233    struct sip_threadinfo *th;
25234    struct ast_tcptls_session_instance *tcptls_instance = NULL;
25235 
25236    if ((th = ao2_callback(threadt, 0, threadinfo_locate_cb, s))) {
25237       tcptls_instance = (ao2_ref(th->tcptls_session, +1), th->tcptls_session);
25238       ao2_t_ref(th, -1, "decrement ref from callback");
25239    }
25240 
25241    return tcptls_instance;
25242 }
25243 
25244 /*!
25245  * \brief Helper for dns resolution to filter by address family.
25246  *
25247  * \note return 0 if addr is [::] else it returns addr's family.
25248  */
25249 int get_address_family_filter(const struct ast_sockaddr *addr)
25250 {
25251    if (ast_sockaddr_is_ipv6(addr) && ast_sockaddr_is_any(addr)) {
25252       return 0;
25253    }
25254 
25255    return addr->ss.ss_family;
25256 }
25257 
25258 /*! \todo Get socket for dialog, prepare if needed, and return file handle  */
25259 static int sip_prepare_socket(struct sip_pvt *p)
25260 {
25261    struct sip_socket *s = &p->socket;
25262    static const char name[] = "SIP socket";
25263    struct sip_threadinfo *th = NULL;
25264    struct ast_tcptls_session_instance *tcptls_session;
25265    struct ast_tcptls_session_args *ca;
25266    struct ast_sockaddr sa_tmp;
25267 
25268    /* check to see if a socket is already active */
25269    if ((s->fd != -1) && (s->type == SIP_TRANSPORT_UDP)) {
25270       return s->fd;
25271    }
25272    if ((s->type & (SIP_TRANSPORT_TCP | SIP_TRANSPORT_TLS)) &&
25273          (s->tcptls_session) &&
25274          (s->tcptls_session->fd != -1)) {
25275       return s->tcptls_session->fd;
25276    }
25277 
25278    /*! \todo Check this... This might be wrong, depending on the proxy configuration
25279       If proxy is in "force" mode its correct.
25280     */
25281    if (p->outboundproxy && p->outboundproxy->transport) {
25282       s->type = p->outboundproxy->transport;
25283    }
25284 
25285    if (s->type == SIP_TRANSPORT_UDP) {
25286       s->fd = sipsock;
25287       return s->fd;
25288    }
25289 
25290    /* At this point we are dealing with a TCP/TLS connection
25291     * 1. We need to check to see if a connectin thread exists
25292     *    for this address, if so use that.
25293     * 2. If a thread does not exist for this address, but the tcptls_session
25294     *    exists on the socket, the connection was closed.
25295     * 3. If no tcptls_session thread exists for the address, and no tcptls_session
25296     *    already exists on the socket, create a new one and launch a new thread.
25297     */
25298 
25299    /* 1.  check for existing threads */
25300    ast_sockaddr_copy(&sa_tmp, sip_real_dst(p));
25301    if ((tcptls_session = sip_tcp_locate(&sa_tmp))) {
25302       s->fd = tcptls_session->fd;
25303       if (s->tcptls_session) {
25304          ao2_ref(s->tcptls_session, -1);
25305          s->tcptls_session = NULL;
25306       }
25307       s->tcptls_session = tcptls_session;
25308       return s->fd;
25309    /* 2.  Thread not found, if tcptls_session already exists, it once had a thread and is now terminated */
25310    } else if (s->tcptls_session) {
25311       return s->fd; /* XXX whether reconnection is ever necessary here needs to be investigated further */
25312    }
25313 
25314    /* 3.  Create a new TCP/TLS client connection */
25315    /* create new session arguments for the client connection */
25316    if (!(ca = ao2_alloc(sizeof(*ca), sip_tcptls_client_args_destructor)) ||
25317       !(ca->name = ast_strdup(name))) {
25318       goto create_tcptls_session_fail;
25319    }
25320    ca->accept_fd = -1;
25321    ast_sockaddr_copy(&ca->remote_address,sip_real_dst(p));
25322    /* if type is TLS, we need to create a tls cfg for this session arg */
25323    if (s->type == SIP_TRANSPORT_TLS) {
25324       if (!(ca->tls_cfg = ast_calloc(1, sizeof(*ca->tls_cfg)))) {
25325          goto create_tcptls_session_fail;
25326       }
25327       memcpy(ca->tls_cfg, &default_tls_cfg, sizeof(*ca->tls_cfg));
25328 
25329       if (!(ca->tls_cfg->certfile = ast_strdup(default_tls_cfg.certfile)) ||
25330          !(ca->tls_cfg->pvtfile = ast_strdup(default_tls_cfg.pvtfile)) ||
25331          !(ca->tls_cfg->cipher = ast_strdup(default_tls_cfg.cipher)) ||
25332          !(ca->tls_cfg->cafile = ast_strdup(default_tls_cfg.cafile)) ||
25333          !(ca->tls_cfg->capath = ast_strdup(default_tls_cfg.capath))) {
25334 
25335          goto create_tcptls_session_fail;
25336       }
25337 
25338       /* this host is used as the common name in ssl/tls */
25339       if (!ast_strlen_zero(p->tohost)) {
25340          ast_copy_string(ca->hostname, p->tohost, sizeof(ca->hostname));
25341       }
25342    }
25343 
25344    /* Create a client connection for address, this does not start the connection, just sets it up. */
25345    if (!(s->tcptls_session = ast_tcptls_client_create(ca))) {
25346       goto create_tcptls_session_fail;
25347    }
25348 
25349    s->fd = s->tcptls_session->fd;
25350 
25351    /* client connections need to have the sip_threadinfo object created before
25352     * the thread is detached.  This ensures the alert_pipe is up before it will
25353     * be used.  Note that this function links the new threadinfo object into the
25354     * threadt container. */
25355    if (!(th = sip_threadinfo_create(s->tcptls_session, s->type))) {
25356       goto create_tcptls_session_fail;
25357    }
25358 
25359    /* Give the new thread a reference to the tcptls_session */
25360    ao2_ref(s->tcptls_session, +1);
25361 
25362    if (ast_pthread_create_background(&ca->master, NULL, sip_tcp_worker_fn, s->tcptls_session)) {
25363       ast_debug(1, "Unable to launch '%s'.", ca->name);
25364       ao2_ref(s->tcptls_session, -1); /* take away the thread ref we just gave it */
25365       goto create_tcptls_session_fail;
25366    }
25367 
25368    return s->fd;
25369 
25370 create_tcptls_session_fail:
25371    if (ca) {
25372       ao2_t_ref(ca, -1, "failed to create client, getting rid of client tcptls_session arguments");
25373    }
25374    if (s->tcptls_session) {
25375       ast_tcptls_close_session_file(tcptls_session);
25376       s->fd = -1;
25377       ao2_ref(s->tcptls_session, -1);
25378       s->tcptls_session = NULL;
25379    }
25380    if (th) {
25381       ao2_t_unlink(threadt, th, "Removing tcptls thread info object, thread failed to open");
25382    }
25383 
25384    return -1;
25385 }
25386 
25387 /*!
25388  * \brief Get cached MWI info
25389  * \return TRUE if found MWI in cache
25390  */
25391 static int get_cached_mwi(struct sip_peer *peer, int *new, int *old)
25392 {
25393    struct sip_mailbox *mailbox;
25394    int in_cache;
25395 
25396    in_cache = 0;
25397    AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
25398       struct ast_event *event;
25399       event = ast_event_get_cached(AST_EVENT_MWI,
25400          AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, mailbox->mailbox,
25401          AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, S_OR(mailbox->context, "default"),
25402          AST_EVENT_IE_END);
25403       if (!event)
25404          continue;
25405       *new += ast_event_get_ie_uint(event, AST_EVENT_IE_NEWMSGS);
25406       *old += ast_event_get_ie_uint(event, AST_EVENT_IE_OLDMSGS);
25407       ast_event_destroy(event);
25408       in_cache = 1;
25409    }
25410 
25411    return in_cache;
25412 }
25413 
25414 /*! \brief Send message waiting indication to alert peer that they've got voicemail
25415  *  \note Both peer and associated sip_pvt must be unlocked prior to calling this function
25416 */
25417 static int sip_send_mwi_to_peer(struct sip_peer *peer, int cache_only)
25418 {
25419    /* Called with peer lock, but releases it */
25420    struct sip_pvt *p;
25421    int newmsgs = 0, oldmsgs = 0;
25422    const char *vmexten = NULL;
25423 
25424    ao2_lock(peer);
25425 
25426    if (peer->vmexten) {
25427       vmexten = ast_strdupa(peer->vmexten);
25428    }
25429 
25430    if (ast_test_flag((&peer->flags[1]), SIP_PAGE2_SUBSCRIBEMWIONLY) && !peer->mwipvt) {
25431       ao2_unlock(peer);
25432       return 0;
25433    }
25434 
25435    /* Do we have an IP address? If not, skip this peer */
25436    if (ast_sockaddr_isnull(&peer->addr) && ast_sockaddr_isnull(&peer->defaddr)) {
25437       ao2_unlock(peer);
25438       return 0;
25439    }
25440 
25441    /* Attempt to use cached mwi to get message counts. */
25442    if (!get_cached_mwi(peer, &newmsgs, &oldmsgs) && !cache_only) {
25443       /* Fall back to manually checking the mailbox if not cache_only and get_cached_mwi failed */
25444       struct ast_str *mailbox_str = ast_str_alloca(512);
25445       peer_mailboxes_to_str(&mailbox_str, peer);
25446       ao2_unlock(peer);
25447       ast_app_inboxcount(mailbox_str->str, &newmsgs, &oldmsgs);
25448       ao2_lock(peer);
25449    }
25450 
25451    if (peer->mwipvt) {
25452       /* Base message on subscription */
25453       p = dialog_ref(peer->mwipvt, "sip_send_mwi_to_peer: Setting dialog ptr p from peer->mwipvt");
25454       ao2_unlock(peer);
25455    } else {
25456       ao2_unlock(peer);
25457       /* Build temporary dialog for this message */
25458       if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY, NULL))) {
25459          return -1;
25460       }
25461 
25462       /* If we don't set the socket type to 0, then create_addr_from_peer will fail immediately if the peer
25463        * uses any transport other than UDP. We set the type to 0 here and then let create_addr_from_peer copy
25464        * the peer's socket information to the sip_pvt we just allocated
25465        */
25466       set_socket_transport(&p->socket, 0);
25467       if (create_addr_from_peer(p, peer)) {
25468          /* Maybe they're not registered, etc. */
25469          dialog_unlink_all(p);
25470          dialog_unref(p, "unref dialog p just created via sip_alloc");
25471          /* sip_destroy(p); */
25472          return 0;
25473       }
25474       /* Recalculate our side, and recalculate Call ID */
25475       ast_sip_ouraddrfor(&p->sa, &p->ourip, p);
25476       build_via(p);
25477 
25478       ao2_lock(peer);
25479       if (!ast_strlen_zero(peer->mwi_from)) {
25480          ast_string_field_set(p, mwi_from, peer->mwi_from);
25481       } else if (!ast_strlen_zero(default_mwi_from)) {
25482          ast_string_field_set(p, mwi_from, default_mwi_from);
25483       }
25484       ao2_unlock(peer);
25485 
25486       /* Change the dialog callid. */
25487       change_callid_pvt(p, NULL);
25488 
25489       /* Destroy this session after 32 secs */
25490       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
25491    }
25492 
25493    /* 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,
25494       we really need to have a lock on it */
25495    sip_pvt_lock(p);
25496 
25497    /* Send MWI */
25498    ast_set_flag(&p->flags[0], SIP_OUTGOING);
25499    /* the following will decrement the refcount on p as it finishes */
25500    transmit_notify_with_mwi(p, newmsgs, oldmsgs, vmexten);
25501    sip_pvt_unlock(p);
25502    dialog_unref(p, "unref dialog ptr p just before it goes out of scope at the end of sip_send_mwi_to_peer.");
25503 
25504    return 0;
25505 }
25506 
25507 /*! \brief helper function for the monitoring thread -- seems to be called with the assumption that the dialog is locked */
25508 static void check_rtp_timeout(struct sip_pvt *dialog, time_t t)
25509 {
25510    /* If we have no RTP or no active owner, no need to check timers */
25511    if (!dialog->rtp || !dialog->owner)
25512       return;
25513    /* If the call is not in UP state or redirected outside Asterisk, no need to check timers */
25514 
25515    if (dialog->owner->_state != AST_STATE_UP || !ast_sockaddr_isnull(&dialog->redirip))
25516       return;
25517 
25518    /* If the call is involved in a T38 fax session do not check RTP timeout */
25519    if (dialog->t38.state == T38_ENABLED)
25520       return;
25521 
25522    /* If we have no timers set, return now */
25523    if (!ast_rtp_instance_get_keepalive(dialog->rtp) && !ast_rtp_instance_get_timeout(dialog->rtp) && !ast_rtp_instance_get_hold_timeout(dialog->rtp)) {
25524       return;
25525    }
25526 
25527    /* Check AUDIO RTP keepalives */
25528    if (dialog->lastrtptx && ast_rtp_instance_get_keepalive(dialog->rtp) &&
25529           (t > dialog->lastrtptx + ast_rtp_instance_get_keepalive(dialog->rtp))) {
25530       /* Need to send an empty RTP packet */
25531       dialog->lastrtptx = time(NULL);
25532       ast_rtp_instance_sendcng(dialog->rtp, 0);
25533    }
25534 
25535    /*! \todo Check video RTP keepalives
25536 
25537       Do we need to move the lastrtptx to the RTP structure to have one for audio and one
25538       for video? It really does belong to the RTP structure.
25539    */
25540 
25541    /* Check AUDIO RTP timers */
25542    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))) {
25543       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)))) {
25544          /* Needs a hangup */
25545          if (ast_rtp_instance_get_timeout(dialog->rtp)) {
25546             if (!dialog->owner || ast_channel_trylock(dialog->owner)) {
25547                /*
25548                 * Don't block, just try again later.
25549                 * If there was no owner, the call is dead already.
25550                 */
25551                return;
25552             }
25553             ast_log(LOG_NOTICE, "Disconnecting call '%s' for lack of RTP activity in %ld seconds\n",
25554                dialog->owner->name, (long) (t - dialog->lastrtprx));
25555             /* Issue a softhangup */
25556             ast_softhangup_nolock(dialog->owner, AST_SOFTHANGUP_DEV);
25557             ast_channel_unlock(dialog->owner);
25558             /* forget the timeouts for this call, since a hangup
25559                has already been requested and we don't want to
25560                repeatedly request hangups
25561             */
25562             ast_rtp_instance_set_timeout(dialog->rtp, 0);
25563             ast_rtp_instance_set_hold_timeout(dialog->rtp, 0);
25564             if (dialog->vrtp) {
25565                ast_rtp_instance_set_timeout(dialog->vrtp, 0);
25566                ast_rtp_instance_set_hold_timeout(dialog->vrtp, 0);
25567             }
25568          }
25569       }
25570    }
25571 }
25572 
25573 /*! \brief The SIP monitoring thread
25574 \note This thread monitors all the SIP sessions and peers that needs notification of mwi
25575    (and thus do not have a separate thread) indefinitely
25576 */
25577 static void *do_monitor(void *data)
25578 {
25579    int res;
25580    time_t t;
25581    int reloading;
25582 
25583    /* Add an I/O event to our SIP UDP socket */
25584    if (sipsock > -1)
25585       sipsock_read_id = ast_io_add(io, sipsock, sipsock_read, AST_IO_IN, NULL);
25586 
25587    /* From here on out, we die whenever asked */
25588    for(;;) {
25589       /* Check for a reload request */
25590       ast_mutex_lock(&sip_reload_lock);
25591       reloading = sip_reloading;
25592       sip_reloading = FALSE;
25593       ast_mutex_unlock(&sip_reload_lock);
25594       if (reloading) {
25595          ast_verb(1, "Reloading SIP\n");
25596          sip_do_reload(sip_reloadreason);
25597 
25598          /* Change the I/O fd of our UDP socket */
25599          if (sipsock > -1) {
25600             if (sipsock_read_id)
25601                sipsock_read_id = ast_io_change(io, sipsock_read_id, sipsock, NULL, 0, NULL);
25602             else
25603                sipsock_read_id = ast_io_add(io, sipsock, sipsock_read, AST_IO_IN, NULL);
25604          } else if (sipsock_read_id) {
25605             ast_io_remove(io, sipsock_read_id);
25606             sipsock_read_id = NULL;
25607          }
25608       }
25609 
25610       /* Check for dialogs needing to be killed */
25611       t = time(NULL);
25612       /* don't scan the dialogs list if it hasn't been a reasonable period
25613          of time since the last time we did it (when MWI is being sent, we can
25614          get back to this point every millisecond or less)
25615       */
25616       /*
25617        * We cannot hold the dialogs container lock when we destroy a
25618        * dialog because of potential deadlocks.  Instead we link the
25619        * doomed dialog into dialogs_to_destroy and then iterate over
25620        * that container destroying the dialogs.
25621        */
25622       ao2_t_callback(dialogs, OBJ_NODATA | OBJ_MULTIPLE, dialog_needdestroy, &t,
25623          "callback to monitor dialog status");
25624       if (ao2_container_count(dialogs_to_destroy)) {
25625          /* Now destroy the found dialogs that need to be destroyed. */
25626          ao2_t_callback(dialogs_to_destroy, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE,
25627             dialog_unlink_callback, NULL, "callback to dialog_unlink_all");
25628       }
25629 
25630       /* XXX TODO The scheduler usage in this module does not have sufficient
25631        * synchronization being done between running the scheduler and places
25632        * scheduling tasks.  As it is written, any scheduled item may not run
25633        * any sooner than about  1 second, regardless of whether a sooner time
25634        * was asked for. */
25635 
25636       pthread_testcancel();
25637       /* Wait for sched or io */
25638       res = ast_sched_wait(sched);
25639       if ((res < 0) || (res > 1000))
25640          res = 1000;
25641       res = ast_io_wait(io, res);
25642       if (res > 20)
25643          ast_debug(1, "chan_sip: ast_io_wait ran %d all at once\n", res);
25644       ast_mutex_lock(&monlock);
25645       res = ast_sched_runq(sched);
25646       if (res >= 20)
25647          ast_debug(1, "chan_sip: ast_sched_runq ran %d all at once\n", res);
25648       if (global_store_sip_cause && res >= 100)
25649          ast_log(LOG_WARNING, "scheduler delays detected, setting 'storesipcause' to 'no' in %s will improve performance\n", config);
25650       ast_mutex_unlock(&monlock);
25651    }
25652 
25653    /* Never reached */
25654    return NULL;
25655 }
25656 
25657 /*! \brief Start the channel monitor thread */
25658 static int restart_monitor(void)
25659 {
25660    /* If we're supposed to be stopped -- stay stopped */
25661    if (monitor_thread == AST_PTHREADT_STOP)
25662       return 0;
25663    ast_mutex_lock(&monlock);
25664    if (monitor_thread == pthread_self()) {
25665       ast_mutex_unlock(&monlock);
25666       ast_log(LOG_WARNING, "Cannot kill myself\n");
25667       return -1;
25668    }
25669    if (monitor_thread != AST_PTHREADT_NULL) {
25670       /* Wake up the thread */
25671       pthread_kill(monitor_thread, SIGURG);
25672    } else {
25673       /* Start a new monitor */
25674       if (ast_pthread_create_background(&monitor_thread, NULL, do_monitor, NULL) < 0) {
25675          ast_mutex_unlock(&monlock);
25676          ast_log(LOG_ERROR, "Unable to start monitor thread.\n");
25677          return -1;
25678       }
25679    }
25680    ast_mutex_unlock(&monlock);
25681    return 0;
25682 }
25683 
25684 
25685 /*! \brief Session-Timers: Restart session timer */
25686 static void restart_session_timer(struct sip_pvt *p)
25687 {
25688    if (!p->stimer) {
25689       ast_log(LOG_WARNING, "Null stimer in restart_session_timer - %s\n", p->callid);
25690       return;
25691    }
25692 
25693    if (p->stimer->st_active == TRUE) {
25694       ast_debug(2, "Session timer stopped: %d - %s\n", p->stimer->st_schedid, p->callid);
25695       AST_SCHED_DEL_UNREF(sched, p->stimer->st_schedid,
25696             dialog_unref(p, "Removing session timer ref"));
25697       start_session_timer(p);
25698    }
25699 }
25700 
25701 
25702 /*! \brief Session-Timers: Stop session timer */
25703 static void stop_session_timer(struct sip_pvt *p)
25704 {
25705    if (!p->stimer) {
25706       ast_log(LOG_WARNING, "Null stimer in stop_session_timer - %s\n", p->callid);
25707       return;
25708    }
25709 
25710    if (p->stimer->st_active == TRUE) {
25711       p->stimer->st_active = FALSE;
25712       ast_debug(2, "Session timer stopped: %d - %s\n", p->stimer->st_schedid, p->callid);
25713       AST_SCHED_DEL_UNREF(sched, p->stimer->st_schedid,
25714             dialog_unref(p, "removing session timer ref"));
25715    }
25716 }
25717 
25718 
25719 /*! \brief Session-Timers: Start session timer */
25720 static void start_session_timer(struct sip_pvt *p)
25721 {
25722    if (!p->stimer) {
25723       ast_log(LOG_WARNING, "Null stimer in start_session_timer - %s\n", p->callid);
25724       return;
25725    }
25726 
25727    if (p->stimer->st_schedid > -1) {
25728       /* in the event a timer is already going, stop it */
25729       ast_debug(2, "Session timer stopped: %d - %s\n", p->stimer->st_schedid, p->callid);
25730       AST_SCHED_DEL_UNREF(sched, p->stimer->st_schedid,
25731          dialog_unref(p, "unref stimer->st_schedid from dialog"));
25732    }
25733 
25734    p->stimer->st_schedid  = ast_sched_add(sched, p->stimer->st_interval * 1000 / 2, proc_session_timer, 
25735          dialog_ref(p, "adding session timer ref"));
25736    if (p->stimer->st_schedid < 0) {
25737       dialog_unref(p, "removing session timer ref");
25738       ast_log(LOG_ERROR, "ast_sched_add failed - %s\n", p->callid);
25739    } else {
25740       p->stimer->st_active = TRUE;
25741       ast_debug(2, "Session timer started: %d - %s\n", p->stimer->st_schedid, p->callid);
25742    }
25743 }
25744 
25745 
25746 /*! \brief Session-Timers: Process session refresh timeout event */
25747 static int proc_session_timer(const void *vp)
25748 {
25749    struct sip_pvt *p = (struct sip_pvt *) vp;
25750    int sendreinv = FALSE;
25751    int res = 0;
25752 
25753    if (!p->stimer) {
25754       ast_log(LOG_WARNING, "Null stimer in proc_session_timer - %s\n", p->callid);
25755       goto return_unref;
25756    }
25757 
25758    ast_debug(2, "Session timer expired: %d - %s\n", p->stimer->st_schedid, p->callid);
25759 
25760    if (!p->owner) {
25761       goto return_unref;
25762    }
25763 
25764    if ((p->stimer->st_active != TRUE) || (p->owner->_state != AST_STATE_UP)) {
25765       goto return_unref;
25766    }
25767 
25768    switch (p->stimer->st_ref) {
25769    case SESSION_TIMER_REFRESHER_UAC:
25770       if (p->outgoing_call == TRUE) {
25771          sendreinv = TRUE;
25772       }
25773       break;
25774    case SESSION_TIMER_REFRESHER_UAS:
25775       if (p->outgoing_call != TRUE) {
25776          sendreinv = TRUE;
25777       }
25778       break;
25779    default:
25780       ast_log(LOG_ERROR, "Unknown session refresher %d\n", p->stimer->st_ref);
25781       goto return_unref;
25782    }
25783 
25784    if (sendreinv == TRUE) {
25785       res = 1;
25786       transmit_reinvite_with_sdp(p, FALSE, TRUE);
25787    } else {
25788       p->stimer->st_expirys++;
25789       if (p->stimer->st_expirys >= 2) {
25790          if (p->stimer->quit_flag) {
25791             goto return_unref;
25792          }
25793          ast_log(LOG_WARNING, "Session-Timer expired - %s\n", p->callid);
25794          sip_pvt_lock(p);
25795          while (p->owner && ast_channel_trylock(p->owner)) {
25796             sip_pvt_unlock(p);
25797             usleep(1);
25798             if (p->stimer && p->stimer->quit_flag) {
25799                goto return_unref;
25800             }
25801             sip_pvt_lock(p);
25802          }
25803 
25804          ast_softhangup_nolock(p->owner, AST_SOFTHANGUP_DEV);
25805          ast_channel_unlock(p->owner);
25806          sip_pvt_unlock(p);
25807       }
25808    }
25809 
25810 return_unref:
25811    if (!res) {
25812       /* An error occurred.  Stop session timer processing */
25813       if (p->stimer) {
25814          ast_debug(2, "Session timer stopped: %d - %s\n", p->stimer->st_schedid, p->callid);
25815          p->stimer->st_schedid = -1;
25816          stop_session_timer(p);
25817       }
25818 
25819       /* If we are not asking to be rescheduled, then we need to release our
25820        * reference to the dialog. */
25821       dialog_unref(p, "removing session timer ref");
25822    }
25823 
25824    return res;
25825 }
25826 
25827 
25828 /*! \brief Session-Timers: Function for parsing Min-SE header */
25829 int parse_minse (const char *p_hdrval, int *const p_interval)
25830 {
25831    if (ast_strlen_zero(p_hdrval)) {
25832       ast_log(LOG_WARNING, "Null Min-SE header\n");
25833       return -1;
25834    }
25835 
25836    *p_interval = 0;
25837    p_hdrval = ast_skip_blanks(p_hdrval);
25838    if (!sscanf(p_hdrval, "%30d", p_interval)) {
25839       ast_log(LOG_WARNING, "Parsing of Min-SE header failed %s\n", p_hdrval);
25840       return -1;
25841    }
25842 
25843    ast_debug(2, "Received Min-SE: %d\n", *p_interval);
25844    return 0;
25845 }
25846 
25847 
25848 /*! \brief Session-Timers: Function for parsing Session-Expires header */
25849 int parse_session_expires(const char *p_hdrval, int *const p_interval, enum st_refresher *const p_ref)
25850 {
25851    char *p_token;
25852    int  ref_idx;
25853    char *p_se_hdr;
25854 
25855    if (ast_strlen_zero(p_hdrval)) {
25856       ast_log(LOG_WARNING, "Null Session-Expires header\n");
25857       return -1;
25858    }
25859 
25860    *p_ref = SESSION_TIMER_REFRESHER_AUTO;
25861    *p_interval = 0;
25862 
25863    p_se_hdr = ast_strdupa(p_hdrval);
25864    p_se_hdr = ast_skip_blanks(p_se_hdr);
25865 
25866    while ((p_token = strsep(&p_se_hdr, ";"))) {
25867       p_token = ast_skip_blanks(p_token);
25868       if (!sscanf(p_token, "%30d", p_interval)) {
25869          ast_log(LOG_WARNING, "Parsing of Session-Expires failed\n");
25870          return -1;
25871       }
25872 
25873       ast_debug(2, "Session-Expires: %d\n", *p_interval);
25874 
25875       if (!p_se_hdr)
25876          continue;
25877 
25878       p_se_hdr = ast_skip_blanks(p_se_hdr);
25879       ref_idx = strlen("refresher=");
25880       if (!strncasecmp(p_se_hdr, "refresher=", ref_idx)) {
25881          p_se_hdr += ref_idx;
25882          p_se_hdr = ast_skip_blanks(p_se_hdr);
25883 
25884          if (!strncasecmp(p_se_hdr, "uac", strlen("uac"))) {
25885             *p_ref = SESSION_TIMER_REFRESHER_UAC;
25886             ast_debug(2, "Refresher: UAC\n");
25887          } else if (!strncasecmp(p_se_hdr, "uas", strlen("uas"))) {
25888             *p_ref = SESSION_TIMER_REFRESHER_UAS;
25889             ast_debug(2, "Refresher: UAS\n");
25890          } else {
25891             ast_log(LOG_WARNING, "Invalid refresher value %s\n", p_se_hdr);
25892             return -1;
25893          }
25894          break;
25895       }
25896    }
25897    return 0;
25898 }
25899 
25900 
25901 /*! \brief Handle 422 response to INVITE with session-timer requested
25902 
25903    Session-Timers:   An INVITE originated by Asterisk that asks for session-timers support
25904    from the UAS can result into a 422 response. This is how a UAS or an intermediary proxy
25905    server tells Asterisk that the session refresh interval offered by Asterisk is too low
25906    for them.  The proc_422_rsp() function handles a 422 response.  It extracts the Min-SE
25907    header that comes back in 422 and sends a new INVITE accordingly. */
25908 static void proc_422_rsp(struct sip_pvt *p, struct sip_request *rsp)
25909 {
25910    int rtn;
25911    const char *p_hdrval;
25912    int minse;
25913 
25914    p_hdrval = get_header(rsp, "Min-SE");
25915    if (ast_strlen_zero(p_hdrval)) {
25916       ast_log(LOG_WARNING, "422 response without a Min-SE header %s\n", p_hdrval);
25917       return;
25918    }
25919    rtn = parse_minse(p_hdrval, &minse);
25920    if (rtn != 0) {
25921       ast_log(LOG_WARNING, "Parsing of Min-SE header failed %s\n", p_hdrval);
25922       return;
25923    }
25924    p->stimer->st_interval = minse;
25925    transmit_invite(p, SIP_INVITE, 1, 2, NULL);
25926 }
25927 
25928 
25929 /*! \brief Get Max or Min SE (session timer expiry)
25930  * \param p pointer to the SIP dialog
25931  * \param max if true, get max se, otherwise min se
25932 */
25933 int st_get_se(struct sip_pvt *p, int max)
25934 {
25935    if (max == TRUE) {
25936       if (p->stimer->st_cached_max_se) {
25937          return  p->stimer->st_cached_max_se;
25938       }
25939       if (p->relatedpeer) {
25940          p->stimer->st_cached_max_se = p->relatedpeer->stimer.st_max_se;
25941          return (p->stimer->st_cached_max_se);
25942       }
25943       p->stimer->st_cached_max_se = global_max_se;
25944       return (p->stimer->st_cached_max_se);
25945    } 
25946    /* Find Min SE timer */
25947    if (p->stimer->st_cached_min_se) {
25948       return p->stimer->st_cached_min_se;
25949    } 
25950    if (p->relatedpeer) {
25951       p->stimer->st_cached_min_se = p->relatedpeer->stimer.st_min_se;
25952       return (p->stimer->st_cached_min_se);
25953    }
25954    p->stimer->st_cached_min_se = global_min_se;
25955    return (p->stimer->st_cached_min_se);
25956 }
25957 
25958 
25959 /*! \brief Get the entity (UAC or UAS) that's acting as the session-timer refresher
25960  * \param p pointer to the SIP dialog
25961 */
25962 enum st_refresher st_get_refresher(struct sip_pvt *p)
25963 {
25964    if (p->stimer->st_cached_ref != SESSION_TIMER_REFRESHER_AUTO)
25965       return p->stimer->st_cached_ref;
25966 
25967    if (p->relatedpeer) {
25968       p->stimer->st_cached_ref = p->relatedpeer->stimer.st_ref;
25969       return p->stimer->st_cached_ref;
25970    }
25971    
25972    p->stimer->st_cached_ref = global_st_refresher;
25973    return global_st_refresher;
25974 }
25975 
25976 
25977 /*!
25978  * \brief Get the session-timer mode 
25979  * \param p pointer to the SIP dialog 
25980  * \param no_cached, set this to true in order to force a peername lookup on
25981  *        the session timer mode.
25982 */
25983 enum st_mode st_get_mode(struct sip_pvt *p, int no_cached)
25984 {
25985    if (!p->stimer)
25986       sip_st_alloc(p);
25987 
25988    if (!no_cached && p->stimer->st_cached_mode != SESSION_TIMER_MODE_INVALID)
25989       return p->stimer->st_cached_mode;
25990 
25991    if (p->relatedpeer) {
25992       p->stimer->st_cached_mode = p->relatedpeer->stimer.st_mode_oper;
25993       return p->stimer->st_cached_mode;
25994    }
25995 
25996    p->stimer->st_cached_mode = global_st_mode;
25997    return global_st_mode;
25998 }
25999 
26000 
26001 /*! \brief React to lack of answer to Qualify poke */
26002 static int sip_poke_noanswer(const void *data)
26003 {
26004    struct sip_peer *peer = (struct sip_peer *)data;
26005 
26006    peer->pokeexpire = -1;
26007 
26008    if (peer->lastms > -1) {
26009       ast_log(LOG_NOTICE, "Peer '%s' is now UNREACHABLE!  Last qualify: %d\n", peer->name, peer->lastms);
26010       if (sip_cfg.peer_rtupdate) {
26011          ast_update_realtime(ast_check_realtime("sipregs") ? "sipregs" : "sippeers", "name", peer->name, "lastms", "-1", SENTINEL);
26012       }
26013       manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: Unreachable\r\nTime: %d\r\n", peer->name, -1);
26014       if (sip_cfg.regextenonqualify) {
26015          register_peer_exten(peer, FALSE);
26016       }
26017    }
26018 
26019    if (peer->call) {
26020       dialog_unlink_all(peer->call);
26021       peer->call = dialog_unref(peer->call, "unref dialog peer->call");
26022       /* peer->call = sip_destroy(peer->call);*/
26023    }
26024 
26025    /* Don't send a devstate change if nothing changed. */
26026    if (peer->lastms > -1) {
26027       peer->lastms = -1;
26028       ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", peer->name);
26029    }
26030 
26031    /* Try again quickly */
26032    AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched,
26033          DEFAULT_FREQ_NOTOK, sip_poke_peer_s, peer,
26034          unref_peer(_data, "removing poke peer ref"),
26035          unref_peer(peer, "removing poke peer ref"),
26036          ref_peer(peer, "adding poke peer ref"));
26037 
26038    /* Release the ref held by the running scheduler entry */
26039    unref_peer(peer, "release peer poke noanswer ref");
26040 
26041    return 0;
26042 }
26043 
26044 /*! \brief Check availability of peer, also keep NAT open
26045 \note This is done with 60 seconds between each ping,
26046    unless forced by cli or manager. If peer is unreachable,
26047    we check every 10th second by default.
26048 */
26049 static int sip_poke_peer(struct sip_peer *peer, int force)
26050 {
26051    struct sip_pvt *p;
26052    int xmitres = 0;
26053    
26054    if ((!peer->maxms && !force) || ast_sockaddr_isnull(&peer->addr)) {
26055       /* IF we have no IP, or this isn't to be monitored, return
26056         immediately after clearing things out */
26057       AST_SCHED_DEL_UNREF(sched, peer->pokeexpire,
26058             unref_peer(peer, "removing poke peer ref"));
26059       
26060       peer->lastms = 0;
26061       if (peer->call) {
26062          peer->call = dialog_unref(peer->call, "unref dialog peer->call");
26063       }
26064       return 0;
26065    }
26066    if (peer->call) {
26067       if (sipdebug) {
26068          ast_log(LOG_NOTICE, "Still have a QUALIFY dialog active, deleting\n");
26069       }
26070       dialog_unlink_all(peer->call);
26071       peer->call = dialog_unref(peer->call, "unref dialog peer->call");
26072       /* peer->call = sip_destroy(peer->call); */
26073    }
26074    if (!(p = sip_alloc(NULL, NULL, 0, SIP_OPTIONS, NULL))) {
26075       return -1;
26076    }
26077    peer->call = dialog_ref(p, "copy sip alloc from p to peer->call");
26078 
26079    p->sa = peer->addr;
26080    p->recv = peer->addr;
26081    copy_socket_data(&p->socket, &peer->socket);
26082    ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
26083    ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
26084    ast_copy_flags(&p->flags[2], &peer->flags[2], SIP_PAGE3_FLAGS_TO_COPY);
26085 
26086    /* Send OPTIONs to peer's fullcontact */
26087    if (!ast_strlen_zero(peer->fullcontact)) {
26088       ast_string_field_set(p, fullcontact, peer->fullcontact);
26089    }
26090 
26091    if (!ast_strlen_zero(peer->fromuser)) {
26092       ast_string_field_set(p, fromuser, peer->fromuser);
26093    }
26094 
26095    if (!ast_strlen_zero(peer->tohost)) {
26096       ast_string_field_set(p, tohost, peer->tohost);
26097    } else {
26098       ast_string_field_set(p, tohost, ast_sockaddr_stringify_host_remote(&peer->addr));
26099    }
26100 
26101    /* Recalculate our side, and recalculate Call ID */
26102    ast_sip_ouraddrfor(&p->sa, &p->ourip, p);
26103    build_via(p);
26104 
26105    /* Change the dialog callid. */
26106    change_callid_pvt(p, NULL);
26107 
26108    AST_SCHED_DEL_UNREF(sched, peer->pokeexpire,
26109          unref_peer(peer, "removing poke peer ref"));
26110    
26111    if (p->relatedpeer)
26112       p->relatedpeer = unref_peer(p->relatedpeer,"unsetting the relatedpeer field in the dialog, before it is set to something else.");
26113    p->relatedpeer = ref_peer(peer, "setting the relatedpeer field in the dialog");
26114    ast_set_flag(&p->flags[0], SIP_OUTGOING);
26115 #ifdef VOCAL_DATA_HACK
26116    ast_copy_string(p->username, "__VOCAL_DATA_SHOULD_READ_THE_SIP_SPEC__", sizeof(p->username));
26117    xmitres = transmit_invite(p, SIP_INVITE, 0, 2, NULL); /* sinks the p refcount */
26118 #else
26119    xmitres = transmit_invite(p, SIP_OPTIONS, 0, 2, NULL); /* sinks the p refcount */
26120 #endif
26121    peer->ps = ast_tvnow();
26122    if (xmitres == XMIT_ERROR) {
26123       /* Immediately unreachable, network problems */
26124       sip_poke_noanswer(ref_peer(peer, "add ref for peerexpire (fake, for sip_poke_noanswer to remove)"));
26125    } else if (!force) {
26126       AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched, peer->maxms * 2, sip_poke_noanswer, peer,
26127             unref_peer(_data, "removing poke peer ref"),
26128             unref_peer(peer, "removing poke peer ref"),
26129             ref_peer(peer, "adding poke peer ref"));
26130    }
26131    dialog_unref(p, "unref dialog at end of sip_poke_peer, obtained from sip_alloc, just before it goes out of scope");
26132    return 0;
26133 }
26134 
26135 /*! \brief Part of PBX channel interface
26136 \note
26137 \par  Return values:---
26138 
26139    If we have qualify on and the device is not reachable, regardless of registration
26140    state we return AST_DEVICE_UNAVAILABLE
26141 
26142    For peers with call limit:
26143       - not registered        AST_DEVICE_UNAVAILABLE
26144       - registered, no call         AST_DEVICE_NOT_INUSE
26145       - registered, active calls    AST_DEVICE_INUSE
26146       - registered, call limit reached AST_DEVICE_BUSY
26147       - registered, onhold       AST_DEVICE_ONHOLD
26148       - registered, ringing         AST_DEVICE_RINGING
26149 
26150    For peers without call limit:
26151       - not registered        AST_DEVICE_UNAVAILABLE
26152       - registered            AST_DEVICE_NOT_INUSE
26153       - fixed IP (!dynamic)         AST_DEVICE_NOT_INUSE
26154    
26155    Peers that does not have a known call and can't be reached by OPTIONS
26156       - unreachable           AST_DEVICE_UNAVAILABLE
26157 
26158    If we return AST_DEVICE_UNKNOWN, the device state engine will try to find
26159    out a state by walking the channel list.
26160 
26161    The queue system (\ref app_queue.c) treats a member as "active"
26162    if devicestate is != AST_DEVICE_UNAVAILBALE && != AST_DEVICE_INVALID
26163 
26164    When placing a call to the queue member, queue system sets a member to busy if
26165    != AST_DEVICE_NOT_INUSE and != AST_DEVICE_UNKNOWN
26166 
26167 */
26168 static int sip_devicestate(void *data)
26169 {
26170    char *host;
26171    char *tmp;
26172    struct sip_peer *p;
26173 
26174    int res = AST_DEVICE_INVALID;
26175 
26176    /* make sure data is not null. Maybe unnecessary, but better be safe */
26177    host = ast_strdupa(data ? data : "");
26178    if ((tmp = strchr(host, '@')))
26179       host = tmp + 1;
26180 
26181    ast_debug(3, "Checking device state for peer %s\n", host);
26182 
26183    /* If find_peer asks for a realtime peer, then this breaks rtautoclear.  This
26184     * is because when a peer tries to autoexpire, the last thing it does is to
26185     * queue up an event telling the system that the devicestate has changed
26186     * (presumably to unavailable).  If we ask for a realtime peer here, this would
26187     * load it BACK into memory, thus defeating the point of trying to clear dead
26188     * hosts out of memory.
26189     */
26190    if ((p = find_peer(host, NULL, FALSE, FINDALLDEVICES, TRUE, 0))) {
26191       if (!(ast_sockaddr_isnull(&p->addr) && ast_sockaddr_isnull(&p->defaddr))) {
26192          /* we have an address for the peer */
26193       
26194          /* Check status in this order
26195             - Hold
26196             - Ringing
26197             - Busy (enforced only by call limit)
26198             - Inuse (we have a call)
26199             - Unreachable (qualify)
26200             If we don't find any of these state, report AST_DEVICE_NOT_INUSE
26201             for registered devices */
26202 
26203          if (p->onHold)
26204             /* First check for hold or ring states */
26205             res = AST_DEVICE_ONHOLD;
26206          else if (p->inRinging) {
26207             if (p->inRinging == p->inUse)
26208                res = AST_DEVICE_RINGING;
26209             else
26210                res = AST_DEVICE_RINGINUSE;
26211          } else if (p->call_limit && (p->inUse == p->call_limit))
26212             /* check call limit */
26213             res = AST_DEVICE_BUSY;
26214          else if (p->call_limit && p->busy_level && p->inUse >= p->busy_level)
26215             /* We're forcing busy before we've reached the call limit */
26216             res = AST_DEVICE_BUSY;
26217          else if (p->call_limit && p->inUse)
26218             /* Not busy, but we do have a call */
26219             res = AST_DEVICE_INUSE;
26220          else if (p->maxms && ((p->lastms > p->maxms) || (p->lastms < 0)))
26221             /* We don't have a call. Are we reachable at all? Requires qualify= */
26222             res = AST_DEVICE_UNAVAILABLE;
26223          else  /* Default reply if we're registered and have no other data */
26224             res = AST_DEVICE_NOT_INUSE;
26225       } else {
26226          /* there is no address, it's unavailable */
26227          res = AST_DEVICE_UNAVAILABLE;
26228       }
26229       unref_peer(p, "unref_peer, from sip_devicestate, release ref from find_peer");
26230    } else {
26231       res = AST_DEVICE_UNKNOWN;
26232    }
26233 
26234    return res;
26235 }
26236 
26237 /*! \brief PBX interface function -build SIP pvt structure
26238  * SIP calls initiated by the PBX arrive here.
26239  *
26240  * \verbatim   
26241  *    SIP Dial string syntax
26242  *    SIP/exten@host!dnid
26243  * or SIP/host/exten!dnid
26244  * or SIP/host!dnid
26245  * \endverbatim
26246 */
26247 static struct ast_channel *sip_request_call(const char *type, format_t format, const struct ast_channel *requestor, void *data, int *cause)
26248 {
26249    struct sip_pvt *p;
26250    struct ast_channel *tmpc = NULL;
26251    char *ext = NULL, *host;
26252    char tmp[256];
26253    char *dest = data;
26254    char *dnid;
26255    char *secret = NULL;
26256    char *md5secret = NULL;
26257    char *authname = NULL;
26258    char *trans = NULL;
26259    char dialstring[256];
26260    char *remote_address;
26261    enum sip_transport transport = 0;
26262    struct ast_sockaddr remote_address_sa = { {0,} };
26263    format_t oldformat = format;
26264    AST_DECLARE_APP_ARGS(args,
26265       AST_APP_ARG(peerorhost);
26266       AST_APP_ARG(exten);
26267       AST_APP_ARG(remote_address);
26268    );
26269 
26270    /* mask request with some set of allowed formats.
26271     * XXX this needs to be fixed.
26272     * The original code uses AST_FORMAT_AUDIO_MASK, but it is
26273     * unclear what to use here. We have global_capabilities, which is
26274     * configured from sip.conf, and sip_tech.capabilities, which is
26275     * hardwired to all audio formats.
26276     */
26277    format &= AST_FORMAT_AUDIO_MASK;
26278    if (!format) {
26279       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));
26280       *cause = AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;   /* Can't find codec to connect to host */
26281       return NULL;
26282    }
26283    ast_debug(1, "Asked to create a SIP channel with formats: %s\n", ast_getformatname_multiple(tmp, sizeof(tmp), oldformat));
26284 
26285    if (ast_strlen_zero(dest)) {
26286       ast_log(LOG_ERROR, "Unable to create channel with empty destination.\n");
26287       *cause = AST_CAUSE_CHANNEL_UNACCEPTABLE;
26288       return NULL;
26289    }
26290 
26291    if (!(p = sip_alloc(NULL, NULL, 0, SIP_INVITE, NULL))) {
26292       ast_log(LOG_ERROR, "Unable to build sip pvt data for '%s' (Out of memory or socket error)\n", dest);
26293       *cause = AST_CAUSE_SWITCH_CONGESTION;
26294       return NULL;
26295    }
26296 
26297    p->outgoing_call = TRUE;
26298 
26299    snprintf(dialstring, sizeof(dialstring), "%s/%s", type, dest);
26300    ast_string_field_set(p, dialstring, dialstring);
26301 
26302    if (!(p->options = ast_calloc(1, sizeof(*p->options)))) {
26303       dialog_unlink_all(p);
26304       dialog_unref(p, "unref dialog p from mem fail");
26305       /* sip_destroy(p); */
26306       ast_log(LOG_ERROR, "Unable to build option SIP data structure - Out of memory\n");
26307       *cause = AST_CAUSE_SWITCH_CONGESTION;
26308       return NULL;
26309    }
26310 
26311    /* Save the destination, the SIP dial string */
26312    ast_copy_string(tmp, dest, sizeof(tmp));
26313 
26314    /* Find DNID and take it away */
26315    dnid = strchr(tmp, '!');
26316    if (dnid != NULL) {
26317       *dnid++ = '\0';
26318       ast_string_field_set(p, todnid, dnid);
26319    }
26320 
26321    /* Divvy up the items separated by slashes */
26322    AST_NONSTANDARD_APP_ARGS(args, tmp, '/');
26323 
26324    /* Find at sign - @ */
26325    host = strchr(args.peerorhost, '@');
26326    if (host) {
26327       *host++ = '\0';
26328       ext = args.peerorhost;
26329       secret = strchr(ext, ':');
26330    }
26331    if (secret) {
26332       *secret++ = '\0';
26333       md5secret = strchr(secret, ':');
26334    }
26335    if (md5secret) {
26336       *md5secret++ = '\0';
26337       authname = strchr(md5secret, ':');
26338    }
26339    if (authname) {
26340       *authname++ = '\0';
26341       trans = strchr(authname, ':');
26342    }
26343    if (trans) {
26344       *trans++ = '\0';
26345       if (!strcasecmp(trans, "tcp"))
26346          transport = SIP_TRANSPORT_TCP;
26347       else if (!strcasecmp(trans, "tls"))
26348          transport = SIP_TRANSPORT_TLS;
26349       else {
26350          if (strcasecmp(trans, "udp"))
26351             ast_log(LOG_WARNING, "'%s' is not a valid transport option to Dial() for SIP calls, using udp by default.\n", trans);
26352          transport = SIP_TRANSPORT_UDP;
26353       }
26354    } else { /* use default */
26355       transport = SIP_TRANSPORT_UDP;
26356    }
26357 
26358    if (!host) {
26359       ext = args.exten;
26360       host = args.peerorhost;
26361       remote_address = args.remote_address;
26362    } else {
26363       remote_address = args.remote_address;
26364       if (!ast_strlen_zero(args.exten)) {
26365          ast_log(LOG_NOTICE, "Conflicting extension values given. Using '%s' and not '%s'\n", ext, args.exten);
26366       }
26367    }
26368 
26369    if (!ast_strlen_zero(remote_address)) {
26370       if (ast_sockaddr_resolve_first(&remote_address_sa, remote_address, 0)) {
26371          ast_log(LOG_WARNING, "Unable to find IP address for host %s. We will not use this remote IP address\n", remote_address);
26372       } else {
26373          if (!ast_sockaddr_port(&remote_address_sa)) {
26374             ast_sockaddr_set_port(&remote_address_sa,
26375                         transport & SIP_TRANSPORT_TLS ?
26376                         STANDARD_TLS_PORT :
26377                         STANDARD_SIP_PORT);
26378          }
26379       }
26380    }
26381 
26382    set_socket_transport(&p->socket, transport);
26383 
26384    /* We now have
26385       host = peer name, DNS host name or DNS domain (for SRV)
26386       ext = extension (user part of URI)
26387       dnid = destination of the call (applies to the To: header)
26388    */
26389    if (create_addr(p, host, NULL, 1, &remote_address_sa)) {
26390       *cause = AST_CAUSE_UNREGISTERED;
26391       ast_debug(3, "Cant create SIP call - target device not registered\n");
26392       dialog_unlink_all(p);
26393       dialog_unref(p, "unref dialog p UNREGISTERED");
26394       /* sip_destroy(p); */
26395       return NULL;
26396    }
26397    if (ast_strlen_zero(p->peername) && ext)
26398       ast_string_field_set(p, peername, ext);
26399    /* Recalculate our side, and recalculate Call ID */
26400    ast_sip_ouraddrfor(&p->sa, &p->ourip, p);
26401    build_via(p);
26402 
26403    /* Change the dialog callid. */
26404    change_callid_pvt(p, NULL);
26405 
26406    /* We have an extension to call, don't use the full contact here */
26407    /* This to enable dialing registered peers with extension dialling,
26408       like SIP/peername/extension   
26409       SIP/peername will still use the full contact
26410     */
26411    if (ext) {
26412       ast_string_field_set(p, username, ext);
26413       ast_string_field_set(p, fullcontact, NULL);
26414    }
26415    if (secret && !ast_strlen_zero(secret))
26416       ast_string_field_set(p, peersecret, secret);
26417 
26418    if (md5secret && !ast_strlen_zero(md5secret))
26419       ast_string_field_set(p, peermd5secret, md5secret);
26420 
26421    if (authname && !ast_strlen_zero(authname))
26422       ast_string_field_set(p, authname, authname);
26423 #if 0
26424    printf("Setting up to call extension '%s' at '%s'\n", ext ? ext : "<none>", host);
26425 #endif
26426    p->prefcodec = oldformat;           /* Format for this call */
26427    p->jointcapability = oldformat & p->capability;
26428    sip_pvt_lock(p);
26429    tmpc = sip_new(p, AST_STATE_DOWN, host, requestor ? requestor->linkedid : NULL); /* Place the call */
26430    if (sip_cfg.callevents)
26431       manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
26432          "Channel: %s\r\nChanneltype: %s\r\nSIPcallid: %s\r\nSIPfullcontact: %s\r\nPeername: %s\r\n",
26433          p->owner? p->owner->name : "", "SIP", p->callid, p->fullcontact, p->peername);
26434    sip_pvt_unlock(p);
26435    if (!tmpc) {
26436       dialog_unlink_all(p);
26437       /* sip_destroy(p); */
26438    } else {
26439       ast_channel_unlock(tmpc);
26440    }
26441    dialog_unref(p, "toss pvt ptr at end of sip_request_call");
26442    ast_update_use_count();
26443    restart_monitor();
26444    return tmpc;
26445 }
26446 
26447 /*! \brief Parse insecure= setting in sip.conf and set flags according to setting */
26448 static void set_insecure_flags (struct ast_flags *flags, const char *value, int lineno)
26449 {
26450    if (ast_strlen_zero(value))
26451       return;
26452 
26453    if (!ast_false(value)) {
26454       char buf[64];
26455       char *word, *next;
26456 
26457       ast_copy_string(buf, value, sizeof(buf));
26458       next = buf;
26459       while ((word = strsep(&next, ","))) {
26460          if (!strcasecmp(word, "port"))
26461             ast_set_flag(&flags[0], SIP_INSECURE_PORT);
26462          else if (!strcasecmp(word, "invite"))
26463             ast_set_flag(&flags[0], SIP_INSECURE_INVITE);
26464          else
26465             ast_log(LOG_WARNING, "Unknown insecure mode '%s' on line %d\n", value, lineno);
26466       }
26467    }
26468 }
26469 
26470 /*!
26471   \brief Handle T.38 configuration options common to users and peers
26472   \returns non-zero if any config options were handled, zero otherwise
26473 */
26474 static int handle_t38_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v,
26475                int *maxdatagram)
26476 {
26477    int res = 1;
26478 
26479    if (!strcasecmp(v->name, "t38pt_udptl")) {
26480       char *buf = ast_strdupa(v->value);
26481       char *word, *next = buf;
26482 
26483       ast_set_flag(&mask[1], SIP_PAGE2_T38SUPPORT);
26484 
26485       while ((word = strsep(&next, ","))) {
26486          if (ast_true(word) || !strcasecmp(word, "fec")) {
26487             ast_clear_flag(&flags[1], SIP_PAGE2_T38SUPPORT);
26488             ast_set_flag(&flags[1], SIP_PAGE2_T38SUPPORT_UDPTL_FEC);
26489          } else if (!strcasecmp(word, "redundancy")) {
26490             ast_clear_flag(&flags[1], SIP_PAGE2_T38SUPPORT);
26491             ast_set_flag(&flags[1], SIP_PAGE2_T38SUPPORT_UDPTL_REDUNDANCY);
26492          } else if (!strcasecmp(word, "none")) {
26493             ast_clear_flag(&flags[1], SIP_PAGE2_T38SUPPORT);
26494             ast_set_flag(&flags[1], SIP_PAGE2_T38SUPPORT_UDPTL);
26495          } else if (!strncasecmp(word, "maxdatagram=", 12)) {
26496             if (sscanf(&word[12], "%30u", maxdatagram) != 1) {
26497                ast_log(LOG_WARNING, "Invalid maxdatagram '%s' at line %d of %s\n", v->value, v->lineno, config);
26498                *maxdatagram = global_t38_maxdatagram;
26499             }
26500          }
26501       }
26502    } else if (!strcasecmp(v->name, "t38pt_usertpsource")) {
26503       ast_set_flag(&mask[1], SIP_PAGE2_UDPTL_DESTINATION);
26504       ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_UDPTL_DESTINATION);
26505    } else {
26506       res = 0;
26507    }
26508 
26509    return res;
26510 }
26511 
26512 /*!
26513   \brief Handle flag-type options common to configuration of devices - peers
26514   \param flags array of two struct ast_flags
26515   \param mask array of two struct ast_flags
26516   \param v linked list of config variables to process
26517   \returns non-zero if any config options were handled, zero otherwise
26518 */
26519 static int handle_common_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v)
26520 {
26521    int res = 1;
26522 
26523    if (!strcasecmp(v->name, "trustrpid")) {
26524       ast_set_flag(&mask[0], SIP_TRUSTRPID);
26525       ast_set2_flag(&flags[0], ast_true(v->value), SIP_TRUSTRPID);
26526    } else if (!strcasecmp(v->name, "sendrpid")) {
26527       ast_set_flag(&mask[0], SIP_SENDRPID);
26528       if (!strcasecmp(v->value, "pai")) {
26529          ast_set_flag(&flags[0], SIP_SENDRPID_PAI);
26530       } else if (!strcasecmp(v->value, "rpid")) {
26531          ast_set_flag(&flags[0], SIP_SENDRPID_RPID);
26532       } else if (ast_true(v->value)) {
26533          ast_set_flag(&flags[0], SIP_SENDRPID_RPID);
26534       }
26535    } else if (!strcasecmp(v->name, "rpid_update")) {
26536       ast_set_flag(&mask[1], SIP_PAGE2_RPID_UPDATE);
26537       ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_RPID_UPDATE);
26538    } else if (!strcasecmp(v->name, "rpid_immediate")) {
26539       ast_set_flag(&mask[1], SIP_PAGE2_RPID_IMMEDIATE);
26540       ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_RPID_IMMEDIATE);
26541    } else if (!strcasecmp(v->name, "g726nonstandard")) {
26542       ast_set_flag(&mask[0], SIP_G726_NONSTANDARD);
26543       ast_set2_flag(&flags[0], ast_true(v->value), SIP_G726_NONSTANDARD);
26544    } else if (!strcasecmp(v->name, "useclientcode")) {
26545       ast_set_flag(&mask[0], SIP_USECLIENTCODE);
26546       ast_set2_flag(&flags[0], ast_true(v->value), SIP_USECLIENTCODE);
26547    } else if (!strcasecmp(v->name, "dtmfmode")) {
26548       ast_set_flag(&mask[0], SIP_DTMF);
26549       ast_clear_flag(&flags[0], SIP_DTMF);
26550       if (!strcasecmp(v->value, "inband"))
26551          ast_set_flag(&flags[0], SIP_DTMF_INBAND);
26552       else if (!strcasecmp(v->value, "rfc2833"))
26553          ast_set_flag(&flags[0], SIP_DTMF_RFC2833);
26554       else if (!strcasecmp(v->value, "info"))
26555          ast_set_flag(&flags[0], SIP_DTMF_INFO);
26556       else if (!strcasecmp(v->value, "shortinfo"))
26557          ast_set_flag(&flags[0], SIP_DTMF_SHORTINFO);
26558       else if (!strcasecmp(v->value, "auto"))
26559          ast_set_flag(&flags[0], SIP_DTMF_AUTO);
26560       else {
26561          ast_log(LOG_WARNING, "Unknown dtmf mode '%s' on line %d, using rfc2833\n", v->value, v->lineno);
26562          ast_set_flag(&flags[0], SIP_DTMF_RFC2833);
26563       }
26564    } else if (!strcasecmp(v->name, "nat")) {
26565       ast_set_flag(&mask[0], SIP_NAT_FORCE_RPORT);
26566       ast_set_flag(&flags[0], SIP_NAT_FORCE_RPORT); /* Default to "force_rport" */
26567       if (!strcasecmp(v->value, "no")) {
26568          ast_clear_flag(&flags[0], SIP_NAT_FORCE_RPORT);
26569       } else if (!strcasecmp(v->value, "yes")) {
26570          /* We've already defaulted to force_rport */
26571          ast_set_flag(&mask[1], SIP_PAGE2_SYMMETRICRTP);
26572          ast_set_flag(&flags[1], SIP_PAGE2_SYMMETRICRTP);
26573       } else if (!strcasecmp(v->value, "comedia")) {
26574          ast_clear_flag(&flags[0], SIP_NAT_FORCE_RPORT);
26575          ast_set_flag(&mask[1], SIP_PAGE2_SYMMETRICRTP);
26576          ast_set_flag(&flags[1], SIP_PAGE2_SYMMETRICRTP);
26577       }
26578    } else if (!strcasecmp(v->name, "directmedia") || !strcasecmp(v->name, "canreinvite")) {
26579       ast_set_flag(&mask[0], SIP_REINVITE);
26580       ast_clear_flag(&flags[0], SIP_REINVITE);
26581       if (ast_true(v->value)) {
26582          ast_set_flag(&flags[0], SIP_DIRECT_MEDIA | SIP_DIRECT_MEDIA_NAT);
26583       } else if (!ast_false(v->value)) {
26584          char buf[64];
26585          char *word, *next = buf;
26586 
26587          ast_copy_string(buf, v->value, sizeof(buf));
26588          while ((word = strsep(&next, ","))) {
26589             if (!strcasecmp(word, "update")) {
26590                ast_set_flag(&flags[0], SIP_REINVITE_UPDATE | SIP_DIRECT_MEDIA);
26591             } else if (!strcasecmp(word, "nonat")) {
26592                ast_set_flag(&flags[0], SIP_DIRECT_MEDIA);
26593                ast_clear_flag(&flags[0], SIP_DIRECT_MEDIA_NAT);
26594             } else {
26595                ast_log(LOG_WARNING, "Unknown directmedia mode '%s' on line %d\n", v->value, v->lineno);
26596             }
26597          }
26598       }
26599    } else if (!strcasecmp(v->name, "insecure")) {
26600       ast_set_flag(&mask[0], SIP_INSECURE);
26601       ast_clear_flag(&flags[0], SIP_INSECURE);
26602       set_insecure_flags(&flags[0], v->value, v->lineno);   
26603    } else if (!strcasecmp(v->name, "progressinband")) {
26604       ast_set_flag(&mask[0], SIP_PROG_INBAND);
26605       ast_clear_flag(&flags[0], SIP_PROG_INBAND);
26606       if (ast_true(v->value))
26607          ast_set_flag(&flags[0], SIP_PROG_INBAND_YES);
26608       else if (strcasecmp(v->value, "never"))
26609          ast_set_flag(&flags[0], SIP_PROG_INBAND_NO);
26610    } else if (!strcasecmp(v->name, "promiscredir")) {
26611       ast_set_flag(&mask[0], SIP_PROMISCREDIR);
26612       ast_set2_flag(&flags[0], ast_true(v->value), SIP_PROMISCREDIR);
26613    } else if (!strcasecmp(v->name, "videosupport")) {
26614       if (!strcasecmp(v->value, "always")) {
26615          ast_set_flag(&mask[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS);
26616          ast_set_flag(&flags[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS);
26617       } else {
26618          ast_set_flag(&mask[1], SIP_PAGE2_VIDEOSUPPORT);
26619          ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_VIDEOSUPPORT);
26620       }
26621    } else if (!strcasecmp(v->name, "textsupport")) {
26622       ast_set_flag(&mask[1], SIP_PAGE2_TEXTSUPPORT);
26623       ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_TEXTSUPPORT);
26624       res = 1;
26625    } else if (!strcasecmp(v->name, "allowoverlap")) {
26626       ast_set_flag(&mask[1], SIP_PAGE2_ALLOWOVERLAP);
26627       ast_clear_flag(&flags[1], SIP_PAGE2_ALLOWOVERLAP);
26628       if (ast_true(v->value)) {
26629          ast_set_flag(&flags[1], SIP_PAGE2_ALLOWOVERLAP_YES);
26630       } else if (!strcasecmp(v->value, "dtmf")){
26631          ast_set_flag(&flags[1], SIP_PAGE2_ALLOWOVERLAP_DTMF);
26632       }
26633    } else if (!strcasecmp(v->name, "allowsubscribe")) {
26634       ast_set_flag(&mask[1], SIP_PAGE2_ALLOWSUBSCRIBE);
26635       ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_ALLOWSUBSCRIBE);
26636    } else if (!strcasecmp(v->name, "ignoresdpversion")) {
26637       ast_set_flag(&mask[1], SIP_PAGE2_IGNORESDPVERSION);
26638       ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_IGNORESDPVERSION);
26639    } else if (!strcasecmp(v->name, "faxdetect")) {
26640       ast_set_flag(&mask[1], SIP_PAGE2_FAX_DETECT);
26641       if (ast_true(v->value)) {
26642          ast_set_flag(&flags[1], SIP_PAGE2_FAX_DETECT_BOTH);
26643       } else if (ast_false(v->value)) {
26644          ast_clear_flag(&flags[1], SIP_PAGE2_FAX_DETECT_BOTH);
26645       } else {
26646          char *buf = ast_strdupa(v->value);
26647          char *word, *next = buf;
26648 
26649          while ((word = strsep(&next, ","))) {
26650             if (!strcasecmp(word, "cng")) {
26651                ast_set_flag(&flags[1], SIP_PAGE2_FAX_DETECT_CNG);
26652             } else if (!strcasecmp(word, "t38")) {
26653                ast_set_flag(&flags[1], SIP_PAGE2_FAX_DETECT_T38);
26654             } else {
26655                ast_log(LOG_WARNING, "Unknown faxdetect mode '%s' on line %d.\n", word, v->lineno);
26656             }
26657          }
26658       }
26659    } else if (!strcasecmp(v->name, "rfc2833compensate")) {
26660       ast_set_flag(&mask[1], SIP_PAGE2_RFC2833_COMPENSATE);
26661       ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_RFC2833_COMPENSATE);
26662    } else if (!strcasecmp(v->name, "buggymwi")) {
26663       ast_set_flag(&mask[1], SIP_PAGE2_BUGGY_MWI);
26664       ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_BUGGY_MWI);
26665    } else
26666       res = 0;
26667 
26668    return res;
26669 }
26670 
26671 /*! \brief Add SIP domain to list of domains we are responsible for */
26672 static int add_sip_domain(const char *domain, const enum domain_mode mode, const char *context)
26673 {
26674    struct domain *d;
26675 
26676    if (ast_strlen_zero(domain)) {
26677       ast_log(LOG_WARNING, "Zero length domain.\n");
26678       return 1;
26679    }
26680 
26681    if (!(d = ast_calloc(1, sizeof(*d))))
26682       return 0;
26683 
26684    ast_copy_string(d->domain, domain, sizeof(d->domain));
26685 
26686    if (!ast_strlen_zero(context))
26687       ast_copy_string(d->context, context, sizeof(d->context));
26688 
26689    d->mode = mode;
26690 
26691    AST_LIST_LOCK(&domain_list);
26692    AST_LIST_INSERT_TAIL(&domain_list, d, list);
26693    AST_LIST_UNLOCK(&domain_list);
26694 
26695    if (sipdebug)  
26696       ast_debug(1, "Added local SIP domain '%s'\n", domain);
26697 
26698    return 1;
26699 }
26700 
26701 /*! \brief  check_sip_domain: Check if domain part of uri is local to our server */
26702 static int check_sip_domain(const char *domain, char *context, size_t len)
26703 {
26704    struct domain *d;
26705    int result = 0;
26706 
26707    AST_LIST_LOCK(&domain_list);
26708    AST_LIST_TRAVERSE(&domain_list, d, list) {
26709       if (strcasecmp(d->domain, domain)) {
26710          continue;
26711       }
26712 
26713       if (len && !ast_strlen_zero(d->context))
26714          ast_copy_string(context, d->context, len);
26715       
26716       result = 1;
26717       break;
26718    }
26719    AST_LIST_UNLOCK(&domain_list);
26720 
26721    return result;
26722 }
26723 
26724 /*! \brief Clear our domain list (at reload) */
26725 static void clear_sip_domains(void)
26726 {
26727    struct domain *d;
26728 
26729    AST_LIST_LOCK(&domain_list);
26730    while ((d = AST_LIST_REMOVE_HEAD(&domain_list, list)))
26731       ast_free(d);
26732    AST_LIST_UNLOCK(&domain_list);
26733 }
26734 
26735 /*!
26736  * \internal
26737  * \brief Realm authentication container destructor.
26738  *
26739  * \param obj Container object to destroy.
26740  *
26741  * \return Nothing
26742  */
26743 static void destroy_realm_authentication(void *obj)
26744 {
26745    struct sip_auth_container *credentials = obj;
26746    struct sip_auth *auth;
26747 
26748    while ((auth = AST_LIST_REMOVE_HEAD(&credentials->list, node))) {
26749       ast_free(auth);
26750    }
26751 }
26752 
26753 /*!
26754  * \internal
26755  * \brief Add realm authentication to credentials.
26756  *
26757  * \param credentials Realm authentication container to create/add authentication credentials.
26758  * \param configuration Credential configuration value.
26759  * \param lineno Line number in config file.
26760  *
26761  * \return Nothing
26762  */
26763 static void add_realm_authentication(struct sip_auth_container **credentials, const char *configuration, int lineno)
26764 {
26765    char *authcopy;
26766    char *username=NULL, *realm=NULL, *secret=NULL, *md5secret=NULL;
26767    struct sip_auth *auth;
26768 
26769    if (ast_strlen_zero(configuration)) {
26770       /* Nothing to add */
26771       return;
26772    }
26773 
26774    ast_debug(1, "Auth config ::  %s\n", configuration);
26775 
26776    authcopy = ast_strdupa(configuration);
26777    username = authcopy;
26778 
26779    /* split user[:secret] and relm */
26780    realm = strrchr(username, '@');
26781    if (realm)
26782       *realm++ = '\0';
26783    if (ast_strlen_zero(username) || ast_strlen_zero(realm)) {
26784       ast_log(LOG_WARNING, "Format for authentication entry is user[:secret]@realm at line %d\n", lineno);
26785       return;
26786    }
26787 
26788    /* parse username at ':' for secret, or '#" for md5secret */
26789    if ((secret = strchr(username, ':'))) {
26790       *secret++ = '\0';
26791    } else if ((md5secret = strchr(username, '#'))) {
26792       *md5secret++ = '\0';
26793    }
26794 
26795    /* Create the continer if needed. */
26796    if (!*credentials) {
26797       *credentials = ao2_t_alloc(sizeof(**credentials), destroy_realm_authentication,
26798          "Create realm auth container.");
26799       if (!*credentials) {
26800          /* Failed to create the credentials container. */
26801          return;
26802       }
26803    }
26804 
26805    /* Create the authentication credential entry. */
26806    auth = ast_calloc(1, sizeof(*auth));
26807    if (!auth) {
26808       return;
26809    }
26810    ast_copy_string(auth->realm, realm, sizeof(auth->realm));
26811    ast_copy_string(auth->username, username, sizeof(auth->username));
26812    if (secret)
26813       ast_copy_string(auth->secret, secret, sizeof(auth->secret));
26814    if (md5secret)
26815       ast_copy_string(auth->md5secret, md5secret, sizeof(auth->md5secret));
26816 
26817    /* Add credential to container list. */
26818    AST_LIST_INSERT_TAIL(&(*credentials)->list, auth, node);
26819 
26820    ast_verb(3, "Added authentication for realm %s\n", realm);
26821 }
26822 
26823 /*!
26824  * \internal
26825  * \brief Find authentication for a specific realm.
26826  *
26827  * \param credentials Realm authentication container to search.
26828  * \param realm Authentication realm to find.
26829  *
26830  * \return Found authentication credential or NULL.
26831  */
26832 static struct sip_auth *find_realm_authentication(struct sip_auth_container *credentials, const char *realm)
26833 {
26834    struct sip_auth *auth;
26835 
26836    if (credentials) {
26837       AST_LIST_TRAVERSE(&credentials->list, auth, node) {
26838          if (!strcasecmp(auth->realm, realm)) {
26839             break;
26840          }
26841       }
26842    } else {
26843       auth = NULL;
26844    }
26845 
26846    return auth;
26847 }
26848 
26849 /*! \brief
26850  * implement the setvar config line
26851  */
26852 static struct ast_variable *add_var(const char *buf, struct ast_variable *list)
26853 {
26854    struct ast_variable *tmpvar = NULL;
26855    char *varname = ast_strdupa(buf), *varval = NULL;
26856    
26857    if ((varval = strchr(varname, '='))) {
26858       *varval++ = '\0';
26859       if ((tmpvar = ast_variable_new(varname, varval, ""))) {
26860          tmpvar->next = list;
26861          list = tmpvar;
26862       }
26863    }
26864    return list;
26865 }
26866 
26867 /*! \brief Set peer defaults before configuring specific configurations */
26868 static void set_peer_defaults(struct sip_peer *peer)
26869 {
26870    if (peer->expire == 0) {
26871       /* Don't reset expire or port time during reload
26872          if we have an active registration
26873       */
26874       peer->expire = -1;
26875       peer->pokeexpire = -1;
26876       set_socket_transport(&peer->socket, SIP_TRANSPORT_UDP);
26877    }
26878    peer->type = SIP_TYPE_PEER;
26879    ast_copy_flags(&peer->flags[0], &global_flags[0], SIP_FLAGS_TO_COPY);
26880    ast_copy_flags(&peer->flags[1], &global_flags[1], SIP_PAGE2_FLAGS_TO_COPY);
26881    ast_copy_flags(&peer->flags[2], &global_flags[2], SIP_PAGE3_FLAGS_TO_COPY);
26882    ast_string_field_set(peer, context, sip_cfg.default_context);
26883    ast_string_field_set(peer, subscribecontext, sip_cfg.default_subscribecontext);
26884    ast_string_field_set(peer, language, default_language);
26885    ast_string_field_set(peer, mohinterpret, default_mohinterpret);
26886    ast_string_field_set(peer, mohsuggest, default_mohsuggest);
26887    ast_string_field_set(peer, engine, default_engine);
26888    ast_sockaddr_setnull(&peer->addr);
26889    ast_sockaddr_setnull(&peer->defaddr);
26890    peer->capability = sip_cfg.capability;
26891    peer->maxcallbitrate = default_maxcallbitrate;
26892    peer->rtptimeout = global_rtptimeout;
26893    peer->rtpholdtimeout = global_rtpholdtimeout;
26894    peer->rtpkeepalive = global_rtpkeepalive;
26895    peer->allowtransfer = sip_cfg.allowtransfer;
26896    peer->autoframing = global_autoframing;
26897    peer->t38_maxdatagram = global_t38_maxdatagram;
26898    peer->qualifyfreq = global_qualifyfreq;
26899    if (global_callcounter)
26900       peer->call_limit=INT_MAX;
26901    ast_string_field_set(peer, vmexten, default_vmexten);
26902    ast_string_field_set(peer, secret, "");
26903    ast_string_field_set(peer, remotesecret, "");
26904    ast_string_field_set(peer, md5secret, "");
26905    ast_string_field_set(peer, cid_num, "");
26906    ast_string_field_set(peer, cid_name, "");
26907    ast_string_field_set(peer, cid_tag, "");
26908    ast_string_field_set(peer, fromdomain, "");
26909    ast_string_field_set(peer, fromuser, "");
26910    ast_string_field_set(peer, regexten, "");
26911    peer->callgroup = 0;
26912    peer->pickupgroup = 0;
26913    peer->maxms = default_qualify;
26914    peer->prefs = default_prefs;
26915    peer->stimer.st_mode_oper = global_st_mode;  /* Session-Timers */
26916    peer->stimer.st_ref = global_st_refresher;
26917    peer->stimer.st_min_se = global_min_se;
26918    peer->stimer.st_max_se = global_max_se;
26919    peer->timer_t1 = global_t1;
26920    peer->timer_b = global_timer_b;
26921    clear_peer_mailboxes(peer);
26922    peer->disallowed_methods = sip_cfg.disallowed_methods;
26923    peer->transports = default_transports;
26924    peer->default_outbound_transport = default_primary_transport;
26925 }
26926 
26927 /*! \brief Create temporary peer (used in autocreatepeer mode) */
26928 static struct sip_peer *temp_peer(const char *name)
26929 {
26930    struct sip_peer *peer;
26931 
26932    if (!(peer = ao2_t_alloc(sizeof(*peer), sip_destroy_peer_fn, "allocate a peer struct")))
26933       return NULL;
26934 
26935    if (ast_string_field_init(peer, 512)) {
26936       ao2_t_ref(peer, -1, "failed to string_field_init, drop peer");
26937       return NULL;
26938    }
26939    
26940    if (!(peer->cc_params = ast_cc_config_params_init())) {
26941       ao2_t_ref(peer, -1, "failed to allocate cc_params for peer");
26942       return NULL;
26943    }
26944 
26945    ast_atomic_fetchadd_int(&apeerobjs, 1);
26946    set_peer_defaults(peer);
26947 
26948    ast_copy_string(peer->name, name, sizeof(peer->name));
26949 
26950    peer->selfdestruct = TRUE;
26951    peer->host_dynamic = TRUE;
26952    peer->prefs = default_prefs;
26953    reg_source_db(peer);
26954 
26955    return peer;
26956 }
26957 
26958 /*! \todo document this function */
26959 static void add_peer_mailboxes(struct sip_peer *peer, const char *value)
26960 {
26961    char *next, *mbox, *context;
26962 
26963    next = ast_strdupa(value);
26964 
26965    while ((mbox = context = strsep(&next, ","))) {
26966       struct sip_mailbox *mailbox;
26967       int duplicate = 0;
26968       /* remove leading/trailing whitespace from mailbox string */
26969       mbox = ast_strip(mbox);
26970       strsep(&context, "@");
26971 
26972       if (ast_strlen_zero(mbox)) {
26973          continue;
26974       }
26975 
26976       /* Check whether the mailbox is already in the list */
26977       AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
26978          if (!strcmp(mailbox->mailbox, mbox) && !strcmp(S_OR(mailbox->context, ""), S_OR(context, ""))) {
26979             duplicate = 1;
26980             break;
26981          }
26982       }
26983       if (duplicate) {
26984          continue;
26985       }
26986 
26987       if (!(mailbox = ast_calloc(1, sizeof(*mailbox) + strlen(mbox) + strlen(S_OR(context, ""))))) {
26988          continue;
26989       }
26990 
26991       if (!ast_strlen_zero(context)) {
26992          mailbox->context = mailbox->mailbox + strlen(mbox) + 1;
26993          strcpy(mailbox->context, context); /* SAFE */
26994       }
26995       strcpy(mailbox->mailbox, mbox); /* SAFE */
26996 
26997       AST_LIST_INSERT_TAIL(&peer->mailboxes, mailbox, entry);
26998    }
26999 }
27000 
27001 /*! \brief Build peer from configuration (file or realtime static/dynamic) */
27002 static struct sip_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime, int devstate_only)
27003 {
27004    struct sip_peer *peer = NULL;
27005    struct ast_ha *oldha = NULL;
27006    struct ast_ha *olddirectmediaha = NULL;
27007    int found = 0;
27008    int firstpass = 1;
27009    uint16_t port = 0;
27010    int format = 0;      /* Ama flags */
27011    int timerb_set = 0, timert1_set = 0;
27012    time_t regseconds = 0;
27013    struct ast_flags peerflags[3] = {{(0)}};
27014    struct ast_flags mask[3] = {{(0)}};
27015    char callback[256] = "";
27016    struct sip_peer tmp_peer;
27017    const char *srvlookup = NULL;
27018    static int deprecation_warning = 1;
27019    int alt_fullcontact = alt ? 1 : 0, headercount = 0;
27020    struct ast_str *fullcontact = ast_str_alloca(512);
27021 
27022    if (!realtime || ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
27023       /* Note we do NOT use find_peer here, to avoid realtime recursion */
27024       /* We also use a case-sensitive comparison (unlike find_peer) so
27025          that case changes made to the peer name will be properly handled
27026          during reload
27027       */
27028       ast_copy_string(tmp_peer.name, name, sizeof(tmp_peer.name));
27029       peer = ao2_t_find(peers, &tmp_peer, OBJ_POINTER | OBJ_UNLINK, "find and unlink peer from peers table");
27030    }
27031 
27032    if (peer) {
27033       /* Already in the list, remove it and it will be added back (or FREE'd)  */
27034       found++;
27035       /* we've unlinked the peer from the peers container but not unlinked from the peers_by_ip container yet
27036         this leads to a wrong refcounter and the peer object is never destroyed */
27037       if (!ast_sockaddr_isnull(&peer->addr)) {
27038          ao2_t_unlink(peers_by_ip, peer, "ao2_unlink peer from peers_by_ip table");
27039       }
27040       if (!(peer->the_mark))
27041          firstpass = 0;
27042    } else {
27043       if (!(peer = ao2_t_alloc(sizeof(*peer), sip_destroy_peer_fn, "allocate a peer struct")))
27044          return NULL;
27045 
27046       if (ast_string_field_init(peer, 512)) {
27047          ao2_t_ref(peer, -1, "failed to string_field_init, drop peer");
27048          return NULL;
27049       }
27050 
27051       if (!(peer->cc_params = ast_cc_config_params_init())) {
27052          ao2_t_ref(peer, -1, "failed to allocate cc_params for peer");
27053          return NULL;
27054       }
27055 
27056       if (realtime && !ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
27057          ast_atomic_fetchadd_int(&rpeerobjs, 1);
27058          ast_debug(3, "-REALTIME- peer built. Name: %s. Peer objects: %d\n", name, rpeerobjs);
27059       } else
27060          ast_atomic_fetchadd_int(&speerobjs, 1);
27061    }
27062 
27063    /* Note that our peer HAS had its reference count increased */
27064    if (firstpass) {
27065       peer->lastmsgssent = -1;
27066       oldha = peer->ha;
27067       peer->ha = NULL;
27068       olddirectmediaha = peer->directmediaha;
27069       peer->directmediaha = NULL;
27070       set_peer_defaults(peer);   /* Set peer defaults */
27071       peer->type = 0;
27072    }
27073 
27074    /* in case the case of the peer name has changed, update the name */
27075    ast_copy_string(peer->name, name, sizeof(peer->name));
27076 
27077    /* If we have channel variables, remove them (reload) */
27078    if (peer->chanvars) {
27079       ast_variables_destroy(peer->chanvars);
27080       peer->chanvars = NULL;
27081       /* XXX should unregister ? */
27082    }
27083 
27084    if (found)
27085       peer->portinuri = 0;
27086 
27087    /* If we have realm authentication information, remove them (reload) */
27088    ao2_lock(peer);
27089    if (peer->auth) {
27090       ao2_t_ref(peer->auth, -1, "Removing old peer authentication");
27091       peer->auth = NULL;
27092    }
27093    ao2_unlock(peer);
27094 
27095    /* clear the transport information.  We will detect if a default value is required after parsing the config */
27096    peer->default_outbound_transport = 0;
27097    peer->transports = 0;
27098 
27099    if (!devstate_only) {
27100       struct sip_mailbox *mailbox;
27101       AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
27102          mailbox->delme = 1;
27103       }
27104    }
27105 
27106    for (; v || ((v = alt) && !(alt=NULL)); v = v->next) {
27107       if (!devstate_only) {
27108          if (handle_common_options(&peerflags[0], &mask[0], v)) {
27109             continue;
27110          }
27111          if (handle_t38_options(&peerflags[0], &mask[0], v, &peer->t38_maxdatagram)) {
27112             continue;
27113          }
27114          if (!strcasecmp(v->name, "transport") && !ast_strlen_zero(v->value)) {
27115             char *val = ast_strdupa(v->value);
27116             char *trans;
27117 
27118             while ((trans = strsep(&val, ","))) {
27119                trans = ast_skip_blanks(trans);
27120 
27121                if (!strncasecmp(trans, "udp", 3)) {
27122                   peer->transports |= SIP_TRANSPORT_UDP;
27123                } else if (sip_cfg.tcp_enabled && !strncasecmp(trans, "tcp", 3)) {
27124                   peer->transports |= SIP_TRANSPORT_TCP;
27125                } else if (default_tls_cfg.enabled && !strncasecmp(trans, "tls", 3)) {
27126                   peer->transports |= SIP_TRANSPORT_TLS;
27127                } else if (!strncasecmp(trans, "tcp", 3) || !strncasecmp(trans, "tls", 3)) {
27128                   ast_log(LOG_WARNING, "'%.3s' is not a valid transport type when %.3senabled=no. If no other is specified, the defaults from general will be used.\n", trans, trans);
27129                } else {
27130                   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);
27131                }
27132 
27133                if (!peer->default_outbound_transport) { /*!< The first transport listed should be default outbound */
27134                   peer->default_outbound_transport = peer->transports;
27135                }
27136             }
27137          } else if (realtime && !strcasecmp(v->name, "regseconds")) {
27138             ast_get_time_t(v->value, &regseconds, 0, NULL);
27139          } else if (realtime && !strcasecmp(v->name, "name")) {
27140             ast_copy_string(peer->name, v->value, sizeof(peer->name));
27141          } else if (realtime && !strcasecmp(v->name, "useragent")) {
27142             ast_string_field_set(peer, useragent, v->value);
27143          } else if (!strcasecmp(v->name, "type")) {
27144             if (!strcasecmp(v->value, "peer")) {
27145                peer->type |= SIP_TYPE_PEER;
27146             } else if (!strcasecmp(v->value, "user")) {
27147                peer->type |= SIP_TYPE_USER;
27148             } else if (!strcasecmp(v->value, "friend")) {
27149                peer->type = SIP_TYPE_USER | SIP_TYPE_PEER;
27150             }
27151          } else if (!strcasecmp(v->name, "remotesecret")) {
27152             ast_string_field_set(peer, remotesecret, v->value);
27153          } else if (!strcasecmp(v->name, "secret")) {
27154             ast_string_field_set(peer, secret, v->value);
27155          } else if (!strcasecmp(v->name, "md5secret")) {
27156             ast_string_field_set(peer, md5secret, v->value);
27157          } else if (!strcasecmp(v->name, "auth")) {
27158             add_realm_authentication(&peer->auth, v->value, v->lineno);
27159          } else if (!strcasecmp(v->name, "callerid")) {
27160             char cid_name[80] = { '\0' }, cid_num[80] = { '\0' };
27161 
27162             ast_callerid_split(v->value, cid_name, sizeof(cid_name), cid_num, sizeof(cid_num));
27163             ast_string_field_set(peer, cid_name, cid_name);
27164             ast_string_field_set(peer, cid_num, cid_num);
27165          } else if (!strcasecmp(v->name, "mwi_from")) {
27166             ast_string_field_set(peer, mwi_from, v->value);
27167          } else if (!strcasecmp(v->name, "fullname")) {
27168             ast_string_field_set(peer, cid_name, v->value);
27169          } else if (!strcasecmp(v->name, "trunkname")) {
27170             /* This is actually for a trunk, so we don't want to override callerid */
27171             ast_string_field_set(peer, cid_name, "");
27172          } else if (!strcasecmp(v->name, "cid_number")) {
27173             ast_string_field_set(peer, cid_num, v->value);
27174          } else if (!strcasecmp(v->name, "cid_tag")) {
27175             ast_string_field_set(peer, cid_tag, v->value);
27176          } else if (!strcasecmp(v->name, "context")) {
27177             ast_string_field_set(peer, context, v->value);
27178             ast_set_flag(&peer->flags[1], SIP_PAGE2_HAVEPEERCONTEXT);
27179          } else if (!strcasecmp(v->name, "subscribecontext")) {
27180             ast_string_field_set(peer, subscribecontext, v->value);
27181          } else if (!strcasecmp(v->name, "fromdomain")) {
27182             char *fromdomainport;
27183             ast_string_field_set(peer, fromdomain, v->value);
27184             if ((fromdomainport = strchr(peer->fromdomain, ':'))) {
27185                *fromdomainport++ = '\0';
27186                if (!(peer->fromdomainport = port_str2int(fromdomainport, 0))) {
27187                   ast_log(LOG_NOTICE, "'%s' is not a valid port number for fromdomain.\n",fromdomainport);
27188                }
27189             } else {
27190                peer->fromdomainport = STANDARD_SIP_PORT;
27191             }
27192          } else if (!strcasecmp(v->name, "usereqphone")) {
27193             ast_set2_flag(&peer->flags[0], ast_true(v->value), SIP_USEREQPHONE);
27194          } else if (!strcasecmp(v->name, "fromuser")) {
27195             ast_string_field_set(peer, fromuser, v->value);
27196          } else if (!strcasecmp(v->name, "outboundproxy")) {
27197             char *tok, *proxyname;
27198 
27199             if (ast_strlen_zero(v->value)) {
27200                ast_log(LOG_WARNING, "no value given for outbound proxy on line %d of sip.conf.", v->lineno);
27201                continue;
27202             }
27203 
27204             peer->outboundproxy =
27205                 ao2_alloc(sizeof(*peer->outboundproxy), NULL);
27206 
27207             tok = ast_skip_blanks(strtok(ast_strdupa(v->value), ","));
27208 
27209             sip_parse_host(tok, v->lineno, &proxyname,
27210                       &peer->outboundproxy->port,
27211                       &peer->outboundproxy->transport);
27212 
27213             tok = ast_skip_blanks(strtok(ast_strdupa(v->value), ","));
27214 
27215             if ((tok = strtok(NULL, ","))) {
27216                peer->outboundproxy->force = !strncasecmp(ast_skip_blanks(tok), "force", 5);
27217             } else {
27218                peer->outboundproxy->force = FALSE;
27219             }
27220 
27221             if (ast_strlen_zero(proxyname)) {
27222                ast_log(LOG_WARNING, "you must specify a name for the outboundproxy on line %d of sip.conf.", v->lineno);
27223                sip_cfg.outboundproxy.name[0] = '\0';
27224                continue;
27225             }
27226 
27227             ast_copy_string(peer->outboundproxy->name, proxyname, sizeof(peer->outboundproxy->name));
27228 
27229             proxy_update(peer->outboundproxy);
27230          } else if (!strcasecmp(v->name, "host")) {
27231             if (!strcasecmp(v->value, "dynamic")) {
27232                /* They'll register with us */
27233                if (!found || !peer->host_dynamic) {
27234                   /* Initialize stuff if this is a new peer, or if it used to
27235                    * not be dynamic before the reload. */
27236                   ast_sockaddr_setnull(&peer->addr);
27237                }
27238                peer->host_dynamic = TRUE;
27239             } else {
27240                /* Non-dynamic.  Make sure we become that way if we're not */
27241                AST_SCHED_DEL_UNREF(sched, peer->expire,
27242                      unref_peer(peer, "removing register expire ref"));
27243                peer->host_dynamic = FALSE;
27244                srvlookup = v->value;
27245             }
27246          } else if (!strcasecmp(v->name, "defaultip")) {
27247             if (!ast_strlen_zero(v->value) && ast_get_ip(&peer->defaddr, v->value)) {
27248                unref_peer(peer, "unref_peer: from build_peer defaultip");
27249                return NULL;
27250             }
27251          } else if (!strcasecmp(v->name, "permit") || !strcasecmp(v->name, "deny")) {
27252             int ha_error = 0;
27253             if (!ast_strlen_zero(v->value)) {
27254                peer->ha = ast_append_ha(v->name, v->value, peer->ha, &ha_error);
27255             }
27256             if (ha_error) {
27257                ast_log(LOG_ERROR, "Bad ACL entry in configuration line %d : %s\n", v->lineno, v->value);
27258             }
27259          } else if (!strcasecmp(v->name, "contactpermit") || !strcasecmp(v->name, "contactdeny")) {
27260             int ha_error = 0;
27261             if (!ast_strlen_zero(v->value)) {
27262                peer->contactha = ast_append_ha(v->name + 7, v->value, peer->contactha, &ha_error);
27263             }
27264             if (ha_error) {
27265                ast_log(LOG_ERROR, "Bad ACL entry in configuration line %d : %s\n", v->lineno, v->value);
27266             }
27267          } else if (!strcasecmp(v->name, "directmediapermit") || !strcasecmp(v->name, "directmediadeny")) {
27268             int ha_error = 0;
27269             peer->directmediaha = ast_append_ha(v->name + 11, v->value, peer->directmediaha, &ha_error);
27270             if (ha_error) {
27271                ast_log(LOG_ERROR, "Bad directmedia ACL entry in configuration line %d : %s\n", v->lineno, v->value);
27272             }
27273          } else if (!strcasecmp(v->name, "port")) {
27274             peer->portinuri = 1;
27275             if (!(port = port_str2int(v->value, 0))) {
27276                if (realtime) {
27277                   /* If stored as integer, could be 0 for some DBs (notably MySQL) */
27278                   peer->portinuri = 0;
27279                } else {
27280                   ast_log(LOG_WARNING, "Invalid peer port configuration at line %d : %s\n", v->lineno, v->value);
27281                }
27282             }
27283          } else if (!strcasecmp(v->name, "callingpres")) {
27284             peer->callingpres = ast_parse_caller_presentation(v->value);
27285             if (peer->callingpres == -1) {
27286                peer->callingpres = atoi(v->value);
27287             }
27288          } else if (!strcasecmp(v->name, "username") || !strcmp(v->name, "defaultuser")) {   /* "username" is deprecated */
27289             ast_string_field_set(peer, username, v->value);
27290             if (!strcasecmp(v->name, "username")) {
27291                if (deprecation_warning) {
27292                   ast_log(LOG_NOTICE, "The 'username' field for sip peers has been deprecated in favor of the term 'defaultuser'\n");
27293                   deprecation_warning = 0;
27294                }
27295                peer->deprecated_username = 1;
27296             }
27297          } else if (!strcasecmp(v->name, "language")) {
27298             ast_string_field_set(peer, language, v->value);
27299          } else if (!strcasecmp(v->name, "regexten")) {
27300             ast_string_field_set(peer, regexten, v->value);
27301          } else if (!strcasecmp(v->name, "callbackextension")) {
27302             ast_copy_string(callback, v->value, sizeof(callback));
27303          } else if (!strcasecmp(v->name, "amaflags")) {
27304             format = ast_cdr_amaflags2int(v->value);
27305             if (format < 0) {
27306                ast_log(LOG_WARNING, "Invalid AMA Flags for peer: %s at line %d\n", v->value, v->lineno);
27307             } else {
27308                peer->amaflags = format;
27309             }
27310          } else if (!strcasecmp(v->name, "maxforwards")) {
27311             if (sscanf(v->value, "%30d", &peer->maxforwards) != 1
27312                || peer->maxforwards < 1 || 255 < peer->maxforwards) {
27313                ast_log(LOG_WARNING, "'%s' is not a valid maxforwards value at line %d.  Using default.\n", v->value, v->lineno);
27314                peer->maxforwards = sip_cfg.default_max_forwards;
27315             }
27316          } else if (!strcasecmp(v->name, "accountcode")) {
27317             ast_string_field_set(peer, accountcode, v->value);
27318          } else if (!strcasecmp(v->name, "mohinterpret")) {
27319             ast_string_field_set(peer, mohinterpret, v->value);
27320          } else if (!strcasecmp(v->name, "mohsuggest")) {
27321             ast_string_field_set(peer, mohsuggest, v->value);
27322          } else if (!strcasecmp(v->name, "parkinglot")) {
27323             ast_string_field_set(peer, parkinglot, v->value);
27324          } else if (!strcasecmp(v->name, "rtp_engine")) {
27325             ast_string_field_set(peer, engine, v->value);
27326          } else if (!strcasecmp(v->name, "mailbox")) {
27327             add_peer_mailboxes(peer, v->value);
27328          } else if (!strcasecmp(v->name, "hasvoicemail")) {
27329             /* People expect that if 'hasvoicemail' is set, that the mailbox will
27330              * be also set, even if not explicitly specified. */
27331             if (ast_true(v->value) && AST_LIST_EMPTY(&peer->mailboxes)) {
27332                add_peer_mailboxes(peer, name);
27333             }
27334          } else if (!strcasecmp(v->name, "subscribemwi")) {
27335             ast_set2_flag(&peer->flags[1], ast_true(v->value), SIP_PAGE2_SUBSCRIBEMWIONLY);
27336          } else if (!strcasecmp(v->name, "vmexten")) {
27337             ast_string_field_set(peer, vmexten, v->value);
27338          } else if (!strcasecmp(v->name, "callgroup")) {
27339             peer->callgroup = ast_get_group(v->value);
27340          } else if (!strcasecmp(v->name, "allowtransfer")) {
27341             peer->allowtransfer = ast_true(v->value) ? TRANSFER_OPENFORALL : TRANSFER_CLOSED;
27342          } else if (!strcasecmp(v->name, "pickupgroup")) {
27343             peer->pickupgroup = ast_get_group(v->value);
27344          } else if (!strcasecmp(v->name, "allow")) {
27345             int error =  ast_parse_allow_disallow(&peer->prefs, &peer->capability, v->value, TRUE);
27346             if (error) {
27347                ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
27348             }
27349          } else if (!strcasecmp(v->name, "disallow")) {
27350             int error =  ast_parse_allow_disallow(&peer->prefs, &peer->capability, v->value, FALSE);
27351             if (error) {
27352                ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
27353             }
27354          } else if (!strcasecmp(v->name, "preferred_codec_only")) {
27355             ast_set2_flag(&peer->flags[1], ast_true(v->value), SIP_PAGE2_PREFERRED_CODEC);
27356          } else if (!strcasecmp(v->name, "autoframing")) {
27357             peer->autoframing = ast_true(v->value);
27358          } else if (!strcasecmp(v->name, "rtptimeout")) {
27359             if ((sscanf(v->value, "%30d", &peer->rtptimeout) != 1) || (peer->rtptimeout < 0)) {
27360                ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d.  Using default.\n", v->value, v->lineno);
27361                peer->rtptimeout = global_rtptimeout;
27362             }
27363          } else if (!strcasecmp(v->name, "rtpholdtimeout")) {
27364             if ((sscanf(v->value, "%30d", &peer->rtpholdtimeout) != 1) || (peer->rtpholdtimeout < 0)) {
27365                ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d.  Using default.\n", v->value, v->lineno);
27366                peer->rtpholdtimeout = global_rtpholdtimeout;
27367             }
27368          } else if (!strcasecmp(v->name, "rtpkeepalive")) {
27369             if ((sscanf(v->value, "%30d", &peer->rtpkeepalive) != 1) || (peer->rtpkeepalive < 0)) {
27370                ast_log(LOG_WARNING, "'%s' is not a valid RTP keepalive time at line %d.  Using default.\n", v->value, v->lineno);
27371                peer->rtpkeepalive = global_rtpkeepalive;
27372             }
27373          } else if (!strcasecmp(v->name, "timert1")) {
27374             if ((sscanf(v->value, "%30d", &peer->timer_t1) != 1) || (peer->timer_t1 < 200) || (peer->timer_t1 < global_t1min)) {
27375                ast_log(LOG_WARNING, "'%s' is not a valid T1 time at line %d.  Using default.\n", v->value, v->lineno);
27376                peer->timer_t1 = global_t1min;
27377             }
27378             timert1_set = 1;
27379          } else if (!strcasecmp(v->name, "timerb")) {
27380             if ((sscanf(v->value, "%30d", &peer->timer_b) != 1) || (peer->timer_b < 200)) {
27381                ast_log(LOG_WARNING, "'%s' is not a valid Timer B time at line %d.  Using default.\n", v->value, v->lineno);
27382                peer->timer_b = global_timer_b;
27383             }
27384             timerb_set = 1;
27385          } else if (!strcasecmp(v->name, "setvar")) {
27386             peer->chanvars = add_var(v->value, peer->chanvars);
27387          } else if (!strcasecmp(v->name, "header")) {
27388             char tmp[4096];
27389             snprintf(tmp, sizeof(tmp), "__SIPADDHEADERpre%2d=%s", ++headercount, v->value);
27390             peer->chanvars = add_var(tmp, peer->chanvars);
27391          } else if (!strcasecmp(v->name, "qualifyfreq")) {
27392             int i;
27393             if (sscanf(v->value, "%30d", &i) == 1) {
27394                peer->qualifyfreq = i * 1000;
27395             } else {
27396                ast_log(LOG_WARNING, "Invalid qualifyfreq number '%s' at line %d of %s\n", v->value, v->lineno, config);
27397                peer->qualifyfreq = global_qualifyfreq;
27398             }
27399          } else if (!strcasecmp(v->name, "maxcallbitrate")) {
27400             peer->maxcallbitrate = atoi(v->value);
27401             if (peer->maxcallbitrate < 0) {
27402                peer->maxcallbitrate = default_maxcallbitrate;
27403             }
27404          } else if (!strcasecmp(v->name, "session-timers")) {
27405             int i = (int) str2stmode(v->value);
27406             if (i < 0) {
27407                ast_log(LOG_WARNING, "Invalid session-timers '%s' at line %d of %s\n", v->value, v->lineno, config);
27408                peer->stimer.st_mode_oper = global_st_mode;
27409             } else {
27410                peer->stimer.st_mode_oper = i;
27411             }
27412          } else if (!strcasecmp(v->name, "session-expires")) {
27413             if (sscanf(v->value, "%30d", &peer->stimer.st_max_se) != 1) {
27414                ast_log(LOG_WARNING, "Invalid session-expires '%s' at line %d of %s\n", v->value, v->lineno, config);
27415                peer->stimer.st_max_se = global_max_se;
27416             }
27417          } else if (!strcasecmp(v->name, "session-minse")) {
27418             if (sscanf(v->value, "%30d", &peer->stimer.st_min_se) != 1) {
27419                ast_log(LOG_WARNING, "Invalid session-minse '%s' at line %d of %s\n", v->value, v->lineno, config);
27420                peer->stimer.st_min_se = global_min_se;
27421             }
27422             if (peer->stimer.st_min_se < 90) {
27423                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);
27424                peer->stimer.st_min_se = global_min_se;
27425             }
27426          } else if (!strcasecmp(v->name, "session-refresher")) {
27427             int i = (int) str2strefresher(v->value);
27428             if (i < 0) {
27429                ast_log(LOG_WARNING, "Invalid session-refresher '%s' at line %d of %s\n", v->value, v->lineno, config);
27430                peer->stimer.st_ref = global_st_refresher;
27431             } else {
27432                peer->stimer.st_ref = i;
27433             }
27434          } else if (!strcasecmp(v->name, "disallowed_methods")) {
27435             char *disallow = ast_strdupa(v->value);
27436             mark_parsed_methods(&peer->disallowed_methods, disallow);
27437          } else if (!strcasecmp(v->name, "unsolicited_mailbox")) {
27438             ast_string_field_set(peer, unsolicited_mailbox, v->value);
27439          } else if (!strcasecmp(v->name, "use_q850_reason")) {
27440             ast_set2_flag(&peer->flags[1], ast_true(v->value), SIP_PAGE2_Q850_REASON);
27441          } else if (!strcasecmp(v->name, "encryption")) {
27442             ast_set2_flag(&peer->flags[1], ast_true(v->value), SIP_PAGE2_USE_SRTP);
27443          } else if (!strcasecmp(v->name, "snom_aoc_enabled")) {
27444             ast_set2_flag(&peer->flags[2], ast_true(v->value), SIP_PAGE3_SNOM_AOC);
27445          }
27446       }
27447 
27448       /* These apply to devstate lookups */
27449       if (realtime && !strcasecmp(v->name, "lastms")) {
27450          sscanf(v->value, "%30d", &peer->lastms);
27451       } else if (realtime && !strcasecmp(v->name, "ipaddr") && !ast_strlen_zero(v->value) ) {
27452          ast_sockaddr_parse(&peer->addr, v->value, PARSE_PORT_FORBID);
27453       } else if (realtime && !strcasecmp(v->name, "fullcontact")) {
27454          if (alt_fullcontact && !alt) {
27455             /* Reset, because the alternate also has a fullcontact and we
27456              * do NOT want the field value to be doubled. It might be
27457              * tempting to skip this, but the first table might not have
27458              * fullcontact and since we're here, we know that the alternate
27459              * absolutely does. */
27460             alt_fullcontact = 0;
27461             ast_str_reset(fullcontact);
27462          }
27463          /* Reconstruct field, because realtime separates our value at the ';' */
27464          if (fullcontact->used > 0) {
27465             ast_str_append(&fullcontact, 0, ";%s", v->value);
27466          } else {
27467             ast_str_set(&fullcontact, 0, "%s", v->value);
27468          }
27469       } else if (!strcasecmp(v->name, "qualify")) {
27470          if (!strcasecmp(v->value, "no")) {
27471             peer->maxms = 0;
27472          } else if (!strcasecmp(v->value, "yes")) {
27473             peer->maxms = default_qualify ? default_qualify : DEFAULT_MAXMS;
27474          } else if (sscanf(v->value, "%30d", &peer->maxms) != 1) {
27475             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);
27476             peer->maxms = 0;
27477          }
27478          if (realtime && !ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) && peer->maxms > 0) {
27479             /* This would otherwise cause a network storm, where the
27480              * qualify response refreshes the peer from the database,
27481              * which in turn causes another qualify to be sent, ad
27482              * infinitum. */
27483             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);
27484             peer->maxms = 0;
27485          }
27486       } else if (!strcasecmp(v->name, "callcounter")) {
27487          peer->call_limit = ast_true(v->value) ? INT_MAX : 0;
27488       } else if (!strcasecmp(v->name, "call-limit")) {
27489          peer->call_limit = atoi(v->value);
27490          if (peer->call_limit < 0) {
27491             peer->call_limit = 0;
27492          }
27493       } else if (!strcasecmp(v->name, "busylevel")) {
27494          peer->busy_level = atoi(v->value);
27495          if (peer->busy_level < 0) {
27496             peer->busy_level = 0;
27497          }
27498       } else if (ast_cc_is_config_param(v->name)) {
27499          ast_cc_set_param(peer->cc_params, v->name, v->value);
27500       }
27501    }
27502 
27503    if (!devstate_only) {
27504       struct sip_mailbox *mailbox;
27505       AST_LIST_TRAVERSE_SAFE_BEGIN(&peer->mailboxes, mailbox, entry) {
27506          if (mailbox->delme) {
27507             AST_LIST_REMOVE_CURRENT(entry);
27508             destroy_mailbox(mailbox);
27509          }
27510       }
27511       AST_LIST_TRAVERSE_SAFE_END;
27512    }
27513 
27514    if (!can_parse_xml && (ast_get_cc_agent_policy(peer->cc_params) == AST_CC_AGENT_NATIVE)) {
27515       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);
27516       ast_set_cc_agent_policy(peer->cc_params, AST_CC_AGENT_NEVER);
27517    }
27518 
27519    /* Note that Timer B is dependent upon T1 and MUST NOT be lower
27520     * than T1 * 64, according to RFC 3261, Section 17.1.1.2 */
27521    if (peer->timer_b < peer->timer_t1 * 64) {
27522       if (timerb_set && timert1_set) {
27523          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);
27524       } else if (timerb_set) {
27525          if ((peer->timer_t1 = peer->timer_b / 64) < global_t1min) {
27526             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);
27527             peer->timer_t1 = global_t1min;
27528             peer->timer_b = peer->timer_t1 * 64;
27529          }
27530          peer->timer_t1 = peer->timer_b / 64;
27531       } else {
27532          peer->timer_b = peer->timer_t1 * 64;
27533       }
27534    }
27535 
27536    if (!peer->default_outbound_transport) {
27537       /* Set default set of transports */
27538       peer->transports = default_transports;
27539       /* Set default primary transport */
27540       peer->default_outbound_transport = default_primary_transport;
27541    }
27542 
27543    /* The default transport type set during build_peer should only replace the socket.type when...
27544     * 1. Registration is not present and the socket.type and default transport types are different.
27545     * 2. The socket.type is not an acceptable transport type after rebuilding peer.
27546     * 3. The socket.type is not set yet. */
27547    if (((peer->socket.type != peer->default_outbound_transport) && (peer->expire == -1)) ||
27548       !(peer->socket.type & peer->transports) || !(peer->socket.type)) {
27549 
27550       set_socket_transport(&peer->socket, peer->default_outbound_transport);
27551    }
27552 
27553    if (ast_str_strlen(fullcontact)) {
27554       ast_string_field_set(peer, fullcontact, ast_str_buffer(fullcontact));
27555       peer->rt_fromcontact = TRUE;
27556       /* We have a hostname in the fullcontact, but if we don't have an
27557        * address listed on the entry (or if it's 'dynamic'), then we need to
27558        * parse the entry to obtain the IP address, so a dynamic host can be
27559        * contacted immediately after reload (as opposed to waiting for it to
27560        * register once again). But if we have an address for this peer and NAT was
27561        * specified, use that address instead. */
27562       /* XXX May need to revisit the final argument; does the realtime DB store whether
27563        * the original contact was over TLS or not? XXX */
27564       if (!ast_test_flag(&peer->flags[0], SIP_NAT_FORCE_RPORT) || ast_sockaddr_isnull(&peer->addr)) {
27565          __set_address_from_contact(fullcontact->str, &peer->addr, 0);
27566       }
27567    }
27568 
27569    if (srvlookup && peer->dnsmgr == NULL) {
27570       char transport[MAXHOSTNAMELEN];
27571       char _srvlookup[MAXHOSTNAMELEN];
27572       char *params;
27573 
27574       ast_copy_string(_srvlookup, srvlookup, sizeof(_srvlookup));
27575       if ((params = strchr(_srvlookup, ';'))) {
27576          *params++ = '\0';
27577       }
27578 
27579       snprintf(transport, sizeof(transport), "_%s._%s", get_srv_service(peer->socket.type), get_srv_protocol(peer->socket.type));
27580 
27581       peer->addr.ss.ss_family = get_address_family_filter(&bindaddr); /* Filter address family */
27582       if (ast_dnsmgr_lookup(_srvlookup, &peer->addr, &peer->dnsmgr, sip_cfg.srvlookup && !peer->portinuri ? transport : NULL)) {
27583          ast_log(LOG_ERROR, "srvlookup failed for host: %s, on peer %s, removing peer\n", _srvlookup, peer->name);
27584          unref_peer(peer, "getting rid of a peer pointer");
27585          return NULL;
27586       }
27587 
27588       ast_string_field_set(peer, tohost, srvlookup);
27589 
27590       if (global_dynamic_exclude_static) {
27591          int ha_error = 0;
27592          sip_cfg.contact_ha = ast_append_ha("deny", ast_sockaddr_stringify_addr(&peer->addr), 
27593                      sip_cfg.contact_ha, &ha_error);
27594          if (ha_error) {
27595             ast_log(LOG_ERROR, "Bad or unresolved host/IP entry in configuration for peer %s, cannot add to contact ACL\n", peer->name);
27596          }
27597       }
27598    } else if (peer->dnsmgr && !peer->host_dynamic) {
27599       /* force a refresh here on reload if dnsmgr already exists and host is set. */
27600       ast_dnsmgr_refresh(peer->dnsmgr);
27601    }
27602 
27603    if (port && !realtime && peer->host_dynamic) {
27604       ast_sockaddr_set_port(&peer->defaddr, port);
27605    } else if (port) {
27606       ast_sockaddr_set_port(&peer->addr, port);
27607    }
27608 
27609    if (ast_sockaddr_port(&peer->addr) == 0) {
27610       ast_sockaddr_set_port(&peer->addr,
27611                   (peer->socket.type & SIP_TRANSPORT_TLS) ?
27612                   STANDARD_TLS_PORT : STANDARD_SIP_PORT);
27613    }
27614    if (ast_sockaddr_port(&peer->defaddr) == 0) {
27615       ast_sockaddr_set_port(&peer->defaddr,
27616                   (peer->socket.type & SIP_TRANSPORT_TLS) ?
27617                   STANDARD_TLS_PORT : STANDARD_SIP_PORT);
27618    }
27619    if (!peer->socket.port) {
27620       peer->socket.port = htons(((peer->socket.type & SIP_TRANSPORT_TLS) ? STANDARD_TLS_PORT : STANDARD_SIP_PORT));
27621    }
27622 
27623    if (!sip_cfg.ignore_regexpire && peer->host_dynamic && realtime) {
27624       time_t nowtime = time(NULL);
27625 
27626       if ((nowtime - regseconds) > 0) {
27627          destroy_association(peer);
27628          memset(&peer->addr, 0, sizeof(peer->addr));
27629          peer->lastms = -1;
27630          ast_debug(1, "Bah, we're expired (%d/%d/%d)!\n", (int)(nowtime - regseconds), (int)regseconds, (int)nowtime);
27631       }
27632    }
27633 
27634    /* Startup regular pokes */
27635    if (!devstate_only && realtime && peer->lastms > 0) {
27636       ref_peer(peer, "schedule qualify");
27637       sip_poke_peer(peer, 0);
27638    }
27639 
27640    ast_copy_flags(&peer->flags[0], &peerflags[0], mask[0].flags);
27641    ast_copy_flags(&peer->flags[1], &peerflags[1], mask[1].flags);
27642    ast_copy_flags(&peer->flags[2], &peerflags[2], mask[2].flags);
27643    if (ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)) {
27644       sip_cfg.allowsubscribe = TRUE;   /* No global ban any more */
27645    }
27646    /* If read-only RT backend, then refresh from local DB cache */
27647    if (peer->host_dynamic && (!peer->is_realtime || !sip_cfg.peer_rtupdate)) {
27648       reg_source_db(peer);
27649    }
27650 
27651    /* If they didn't request that MWI is sent *only* on subscribe, go ahead and
27652     * subscribe to it now. */
27653    if (!devstate_only && !ast_test_flag(&peer->flags[1], SIP_PAGE2_SUBSCRIBEMWIONLY) &&
27654       !AST_LIST_EMPTY(&peer->mailboxes)) {
27655       add_peer_mwi_subs(peer);
27656       /* Send MWI from the event cache only.  This is so we can send initial
27657        * MWI if app_voicemail got loaded before chan_sip.  If it is the other
27658        * way, then we will get events when app_voicemail gets loaded. */
27659       sip_send_mwi_to_peer(peer, 1);
27660    }
27661 
27662    peer->the_mark = 0;
27663 
27664    ast_free_ha(oldha);
27665    ast_free_ha(olddirectmediaha);
27666    if (!ast_strlen_zero(callback)) { /* build string from peer info */
27667       char *reg_string;
27668       if (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) {
27669          ast_log(LOG_WARNING, "asprintf() failed: %s\n", strerror(errno));
27670       } else if (reg_string) {
27671          sip_register(reg_string, 0); /* XXX TODO: count in registry_count */
27672          ast_free(reg_string);
27673       }
27674    }
27675    return peer;
27676 }
27677 
27678 static int peer_markall_func(void *device, void *arg, int flags)
27679 {
27680    struct sip_peer *peer = device;
27681    peer->the_mark = 1;
27682    return 0;
27683 }
27684 
27685 static void display_nat_warning(const char *cat, int reason, struct ast_flags *flags) {
27686    int global_nat, specific_nat;
27687 
27688    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))) {
27689       ast_log(LOG_WARNING, "!!! PLEASE NOTE: Setting 'nat' for a peer/user that differs from the  global setting can make\n");
27690       ast_log(LOG_WARNING, "!!! the name of that peer/user discoverable by an attacker. Replies for non-existent peers/users\n");
27691       ast_log(LOG_WARNING, "!!! will be sent to a different port than replies for an existing peer/user. If at all possible,\n");
27692       ast_log(LOG_WARNING, "!!! use the global 'nat' setting and do not set 'nat' per peer/user.\n");
27693       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));
27694    }
27695 }
27696 
27697 /*! \brief Re-read SIP.conf config file
27698 \note This function reloads all config data, except for
27699    active peers (with registrations). They will only
27700    change configuration data at restart, not at reload.
27701    SIP debug and recordhistory state will not change
27702  */
27703 static int reload_config(enum channelreloadreason reason)
27704 {
27705    struct ast_config *cfg, *ucfg;
27706    struct ast_variable *v;
27707    struct sip_peer *peer;
27708    char *cat, *stringp, *context, *oldregcontext;
27709    char newcontexts[AST_MAX_CONTEXT], oldcontexts[AST_MAX_CONTEXT];
27710    struct ast_flags dummy[2];
27711    struct ast_flags config_flags = { reason == CHANNEL_MODULE_LOAD ? 0 : ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) ? 0 : CONFIG_FLAG_FILEUNCHANGED };
27712    int auto_sip_domains = FALSE;
27713    struct ast_sockaddr old_bindaddr = bindaddr;
27714    int registry_count = 0, peer_count = 0, timerb_set = 0, timert1_set = 0;
27715    int subscribe_network_change = 1;
27716    time_t run_start, run_end;
27717    int bindport = 0;
27718 
27719    run_start = time(0);
27720    ast_unload_realtime("sipregs");
27721    ast_unload_realtime("sippeers");
27722    cfg = ast_config_load(config, config_flags);
27723 
27724    /* We *must* have a config file otherwise stop immediately */
27725    if (!cfg) {
27726       ast_log(LOG_NOTICE, "Unable to load config %s\n", config);
27727       return -1;
27728    } else if (cfg == CONFIG_STATUS_FILEUNCHANGED) {
27729       ucfg = ast_config_load("users.conf", config_flags);
27730       if (ucfg == CONFIG_STATUS_FILEUNCHANGED) {
27731          return 1;
27732       } else if (ucfg == CONFIG_STATUS_FILEINVALID) {
27733          ast_log(LOG_ERROR, "Contents of users.conf are invalid and cannot be parsed\n");
27734          return 1;
27735       }
27736       /* Must reread both files, because one changed */
27737       ast_clear_flag(&config_flags, CONFIG_FLAG_FILEUNCHANGED);
27738       if ((cfg = ast_config_load(config, config_flags)) == CONFIG_STATUS_FILEINVALID) {
27739          ast_log(LOG_ERROR, "Contents of %s are invalid and cannot be parsed\n", config);
27740          ast_config_destroy(ucfg);
27741          return 1;
27742       }
27743    } else if (cfg == CONFIG_STATUS_FILEINVALID) {
27744       ast_log(LOG_ERROR, "Contents of %s are invalid and cannot be parsed\n", config);
27745       return 1;
27746    } else {
27747       ast_clear_flag(&config_flags, CONFIG_FLAG_FILEUNCHANGED);
27748       if ((ucfg = ast_config_load("users.conf", config_flags)) == CONFIG_STATUS_FILEINVALID) {
27749          ast_log(LOG_ERROR, "Contents of users.conf are invalid and cannot be parsed\n");
27750          ast_config_destroy(cfg);
27751          return 1;
27752       }
27753    }
27754 
27755    ast_free_ha(sip_cfg.contact_ha);
27756    sip_cfg.contact_ha = NULL;
27757 
27758    default_tls_cfg.enabled = FALSE;    /* Default: Disable TLS */
27759 
27760    if (reason != CHANNEL_MODULE_LOAD) {
27761       ast_debug(4, "--------------- SIP reload started\n");
27762 
27763       clear_sip_domains();
27764       ast_mutex_lock(&authl_lock);
27765       if (authl) {
27766          ao2_t_ref(authl, -1, "Removing old global authentication");
27767          authl = NULL;
27768       }
27769       ast_mutex_unlock(&authl_lock);
27770 
27771       /* First, destroy all outstanding registry calls */
27772       /* This is needed, since otherwise active registry entries will not be destroyed */
27773       ASTOBJ_CONTAINER_TRAVERSE(&regl, 1, do {  /* regl is locked */
27774 
27775             ASTOBJ_RDLOCK(iterator); /* now regl is locked, and the object is also locked */
27776             if (iterator->call) {
27777                ast_debug(3, "Destroying active SIP dialog for registry %s@%s\n", iterator->username, iterator->hostname);
27778                /* This will also remove references to the registry */
27779                dialog_unlink_all(iterator->call);
27780                iterator->call = dialog_unref(iterator->call, "remove iterator->call from registry traversal");
27781             }
27782             if (iterator->expire > -1) {
27783                AST_SCHED_DEL_UNREF(sched, iterator->expire, registry_unref(iterator, "reg ptr unref from reload config"));
27784             }
27785             if (iterator->timeout > -1) {
27786                AST_SCHED_DEL_UNREF(sched, iterator->timeout, registry_unref(iterator, "reg ptr unref from reload config"));
27787             }
27788             ASTOBJ_UNLOCK(iterator);
27789       } while(0));
27790 
27791       /* Then, actually destroy users and registry */
27792       ASTOBJ_CONTAINER_DESTROYALL(&regl, sip_registry_destroy);
27793       ast_debug(4, "--------------- Done destroying registry list\n");
27794       ao2_t_callback(peers, OBJ_NODATA, peer_markall_func, NULL, "callback to mark all peers");
27795    }
27796 
27797    /* Reset certificate handling for TLS sessions */
27798    if (reason != CHANNEL_MODULE_LOAD) {
27799       ast_free(default_tls_cfg.certfile);
27800       ast_free(default_tls_cfg.pvtfile);
27801       ast_free(default_tls_cfg.cipher);
27802       ast_free(default_tls_cfg.cafile);
27803       ast_free(default_tls_cfg.capath);
27804    }
27805    default_tls_cfg.certfile = ast_strdup(AST_CERTFILE); /*XXX Not sure if this is useful */
27806    default_tls_cfg.pvtfile = ast_strdup("");
27807    default_tls_cfg.cipher = ast_strdup("");
27808    default_tls_cfg.cafile = ast_strdup("");
27809    default_tls_cfg.capath = ast_strdup("");
27810 
27811    /* Initialize copy of current sip_cfg.regcontext for later use in removing stale contexts */
27812    ast_copy_string(oldcontexts, sip_cfg.regcontext, sizeof(oldcontexts));
27813    oldregcontext = oldcontexts;
27814 
27815    /* Clear all flags before setting default values */
27816    /* Preserve debugging settings for console */
27817    sipdebug &= sip_debug_console;
27818    ast_clear_flag(&global_flags[0], AST_FLAGS_ALL);
27819    ast_clear_flag(&global_flags[1], AST_FLAGS_ALL);
27820    ast_clear_flag(&global_flags[2], AST_FLAGS_ALL);
27821 
27822    /* Reset IP addresses  */
27823    ast_sockaddr_parse(&bindaddr, "0.0.0.0:0", 0);
27824    memset(&internip, 0, sizeof(internip));
27825 
27826    /* Free memory for local network address mask */
27827    ast_free_ha(localaddr);
27828    memset(&localaddr, 0, sizeof(localaddr));
27829    memset(&externaddr, 0, sizeof(externaddr));
27830    memset(&media_address, 0, sizeof(media_address));
27831    memset(&default_prefs, 0 , sizeof(default_prefs));
27832    memset(&sip_cfg.outboundproxy, 0, sizeof(struct sip_proxy));
27833    sip_cfg.outboundproxy.force = FALSE;      /*!< Don't force proxy usage, use route: headers */
27834    default_transports = 0;          /*!< Reset default transport to zero here, default value later on */
27835    default_primary_transport = 0;         /*!< Reset default primary transport to zero here, default value later on */
27836    ourport_tcp = STANDARD_SIP_PORT;
27837    ourport_tls = STANDARD_TLS_PORT;
27838    externtcpport = STANDARD_SIP_PORT;
27839    externtlsport = STANDARD_TLS_PORT;
27840    sip_cfg.srvlookup = DEFAULT_SRVLOOKUP;
27841    global_tos_sip = DEFAULT_TOS_SIP;
27842    global_tos_audio = DEFAULT_TOS_AUDIO;
27843    global_tos_video = DEFAULT_TOS_VIDEO;
27844    global_tos_text = DEFAULT_TOS_TEXT;
27845    global_cos_sip = DEFAULT_COS_SIP;
27846    global_cos_audio = DEFAULT_COS_AUDIO;
27847    global_cos_video = DEFAULT_COS_VIDEO;
27848    global_cos_text = DEFAULT_COS_TEXT;
27849 
27850    externhost[0] = '\0';         /* External host name (for behind NAT DynDNS support) */
27851    externexpire = 0;       /* Expiration for DNS re-issuing */
27852    externrefresh = 10;
27853 
27854    /* Reset channel settings to default before re-configuring */
27855    sip_cfg.allow_external_domains = DEFAULT_ALLOW_EXT_DOM;           /* Allow external invites */
27856    sip_cfg.regcontext[0] = '\0';
27857    sip_cfg.capability = DEFAULT_CAPABILITY;
27858    sip_cfg.regextenonqualify = DEFAULT_REGEXTENONQUALIFY;
27859    sip_cfg.legacy_useroption_parsing = DEFAULT_LEGACY_USEROPTION_PARSING;
27860    sip_cfg.notifyringing = DEFAULT_NOTIFYRINGING;
27861    sip_cfg.notifycid = DEFAULT_NOTIFYCID;
27862    sip_cfg.notifyhold = FALSE;      /*!< Keep track of hold status for a peer */
27863    sip_cfg.directrtpsetup = FALSE;     /* Experimental feature, disabled by default */
27864    sip_cfg.alwaysauthreject = DEFAULT_ALWAYSAUTHREJECT;
27865    sip_cfg.auth_options_requests = DEFAULT_AUTH_OPTIONS;
27866    sip_cfg.allowsubscribe = FALSE;
27867    sip_cfg.disallowed_methods = SIP_UNKNOWN;
27868    sip_cfg.contact_ha = NULL;    /* Reset the contact ACL */
27869    snprintf(global_useragent, sizeof(global_useragent), "%s %s", DEFAULT_USERAGENT, ast_get_version());
27870    snprintf(global_sdpsession, sizeof(global_sdpsession), "%s %s", DEFAULT_SDPSESSION, ast_get_version());
27871    snprintf(global_sdpowner, sizeof(global_sdpowner), "%s", DEFAULT_SDPOWNER);
27872    global_prematuremediafilter = TRUE;
27873    ast_copy_string(default_notifymime, DEFAULT_NOTIFYMIME, sizeof(default_notifymime));
27874    ast_copy_string(sip_cfg.realm, S_OR(ast_config_AST_SYSTEM_NAME, DEFAULT_REALM), sizeof(sip_cfg.realm));
27875    sip_cfg.domainsasrealm = DEFAULT_DOMAINSASREALM;
27876    ast_copy_string(default_callerid, DEFAULT_CALLERID, sizeof(default_callerid));
27877    ast_copy_string(default_mwi_from, DEFAULT_MWI_FROM, sizeof(default_mwi_from));
27878    sip_cfg.compactheaders = DEFAULT_COMPACTHEADERS;
27879    global_reg_timeout = DEFAULT_REGISTRATION_TIMEOUT;
27880    global_regattempts_max = 0;
27881    sip_cfg.pedanticsipchecking = DEFAULT_PEDANTIC;
27882    sip_cfg.autocreatepeer = DEFAULT_AUTOCREATEPEER;
27883    global_autoframing = 0;
27884    sip_cfg.allowguest = DEFAULT_ALLOWGUEST;
27885    global_callcounter = DEFAULT_CALLCOUNTER;
27886    global_match_auth_username = FALSE;    /*!< Match auth username if available instead of From: Default off. */
27887    global_rtptimeout = 0;
27888    global_rtpholdtimeout = 0;
27889    global_rtpkeepalive = DEFAULT_RTPKEEPALIVE;
27890    sip_cfg.allowtransfer = TRANSFER_OPENFORALL; /* Merrily accept all transfers by default */
27891    sip_cfg.rtautoclear = 120;
27892    ast_set_flag(&global_flags[1], SIP_PAGE2_ALLOWSUBSCRIBE);   /* Default for all devices: TRUE */
27893    ast_set_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP_YES); /* Default for all devices: Yes */
27894    sip_cfg.peer_rtupdate = TRUE;
27895    global_dynamic_exclude_static = 0;  /* Exclude static peers */
27896    sip_cfg.tcp_enabled = FALSE;
27897 
27898    /* Session-Timers */
27899    global_st_mode = SESSION_TIMER_MODE_ACCEPT;
27900    global_st_refresher = SESSION_TIMER_REFRESHER_UAS;
27901    global_min_se  = DEFAULT_MIN_SE;
27902    global_max_se  = DEFAULT_MAX_SE;
27903 
27904    /* Peer poking settings */
27905    global_qualify_gap = DEFAULT_QUALIFY_GAP;
27906    global_qualify_peers = DEFAULT_QUALIFY_PEERS;
27907 
27908    /* Initialize some reasonable defaults at SIP reload (used both for channel and as default for devices */
27909    ast_copy_string(sip_cfg.default_context, DEFAULT_CONTEXT, sizeof(sip_cfg.default_context));
27910    sip_cfg.default_subscribecontext[0] = '\0';
27911    sip_cfg.default_max_forwards = DEFAULT_MAX_FORWARDS;
27912    default_language[0] = '\0';
27913    default_fromdomain[0] = '\0';
27914    default_fromdomainport = 0;
27915    default_qualify = DEFAULT_QUALIFY;
27916    default_maxcallbitrate = DEFAULT_MAX_CALL_BITRATE;
27917    ast_copy_string(default_mohinterpret, DEFAULT_MOHINTERPRET, sizeof(default_mohinterpret));
27918    ast_copy_string(default_mohsuggest, DEFAULT_MOHSUGGEST, sizeof(default_mohsuggest));
27919    ast_copy_string(default_vmexten, DEFAULT_VMEXTEN, sizeof(default_vmexten));
27920    ast_set_flag(&global_flags[0], SIP_DTMF_RFC2833);    /*!< Default DTMF setting: RFC2833 */
27921    ast_set_flag(&global_flags[0], SIP_DIRECT_MEDIA);    /*!< Allow re-invites */
27922    ast_set_flag(&global_flags[0], SIP_NAT_FORCE_RPORT); /*!< Default to nat=force_rport */
27923    ast_copy_string(default_engine, DEFAULT_ENGINE, sizeof(default_engine));
27924    ast_copy_string(default_parkinglot, DEFAULT_PARKINGLOT, sizeof(default_parkinglot));
27925 
27926    /* Debugging settings, always default to off */
27927    dumphistory = FALSE;
27928    recordhistory = FALSE;
27929    sipdebug &= ~sip_debug_config;
27930 
27931    /* Misc settings for the channel */
27932    global_relaxdtmf = FALSE;
27933    sip_cfg.callevents = DEFAULT_CALLEVENTS;
27934    global_authfailureevents = FALSE;
27935    global_t1 = DEFAULT_TIMER_T1;
27936    global_timer_b = 64 * DEFAULT_TIMER_T1;
27937    global_t1min = DEFAULT_T1MIN;
27938    global_qualifyfreq = DEFAULT_QUALIFYFREQ;
27939    global_t38_maxdatagram = -1;
27940    global_shrinkcallerid = 1;
27941    authlimit = DEFAULT_AUTHLIMIT;
27942    authtimeout = DEFAULT_AUTHTIMEOUT;
27943    global_store_sip_cause = DEFAULT_STORE_SIP_CAUSE;
27944 
27945    sip_cfg.matchexternaddrlocally = DEFAULT_MATCHEXTERNADDRLOCALLY;
27946 
27947    /* Copy the default jb config over global_jbconf */
27948    memcpy(&global_jbconf, &default_jbconf, sizeof(struct ast_jb_conf));
27949 
27950    ast_clear_flag(&global_flags[1], SIP_PAGE2_FAX_DETECT);
27951    ast_clear_flag(&global_flags[1], SIP_PAGE2_VIDEOSUPPORT | SIP_PAGE2_VIDEOSUPPORT_ALWAYS);
27952    ast_clear_flag(&global_flags[1], SIP_PAGE2_TEXTSUPPORT);
27953    ast_clear_flag(&global_flags[1], SIP_PAGE2_IGNORESDPVERSION);
27954 
27955 
27956    /* Read the [general] config section of sip.conf (or from realtime config) */
27957    for (v = ast_variable_browse(cfg, "general"); v; v = v->next) {
27958       if (handle_common_options(&global_flags[0], &dummy[0], v)) {
27959          continue;
27960       }
27961       if (handle_t38_options(&global_flags[0], &dummy[0], v, &global_t38_maxdatagram)) {
27962          continue;
27963       }
27964       /* handle jb conf */
27965       if (!ast_jb_read_conf(&global_jbconf, v->name, v->value))
27966          continue;
27967 
27968       /* handle tls conf */
27969       if (!ast_tls_read_conf(&default_tls_cfg, &sip_tls_desc, v->name, v->value)) {
27970          continue;
27971       }
27972 
27973       if (!strcasecmp(v->name, "context")) {
27974          ast_copy_string(sip_cfg.default_context, v->value, sizeof(sip_cfg.default_context));
27975       } else if (!strcasecmp(v->name, "subscribecontext")) {
27976          ast_copy_string(sip_cfg.default_subscribecontext, v->value, sizeof(sip_cfg.default_subscribecontext));
27977       } else if (!strcasecmp(v->name, "callcounter")) {
27978          global_callcounter = ast_true(v->value) ? 1 : 0;
27979       } else if (!strcasecmp(v->name, "allowguest")) {
27980          sip_cfg.allowguest = ast_true(v->value) ? 1 : 0;
27981       } else if (!strcasecmp(v->name, "realm")) {
27982          ast_copy_string(sip_cfg.realm, v->value, sizeof(sip_cfg.realm));
27983       } else if (!strcasecmp(v->name, "domainsasrealm")) {
27984          sip_cfg.domainsasrealm = ast_true(v->value);
27985       } else if (!strcasecmp(v->name, "useragent")) {
27986          ast_copy_string(global_useragent, v->value, sizeof(global_useragent));
27987          ast_debug(1, "Setting SIP channel User-Agent Name to %s\n", global_useragent);
27988       } else if (!strcasecmp(v->name, "sdpsession")) {
27989          ast_copy_string(global_sdpsession, v->value, sizeof(global_sdpsession));
27990       } else if (!strcasecmp(v->name, "sdpowner")) {
27991          /* Field cannot contain spaces */
27992          if (!strstr(v->value, " ")) {
27993             ast_copy_string(global_sdpowner, v->value, sizeof(global_sdpowner));
27994          } else {
27995             ast_log(LOG_WARNING, "'%s' must not contain spaces at line %d.  Using default.\n", v->value, v->lineno);
27996          }
27997       } else if (!strcasecmp(v->name, "allowtransfer")) {
27998          sip_cfg.allowtransfer = ast_true(v->value) ? TRANSFER_OPENFORALL : TRANSFER_CLOSED;
27999       } else if (!strcasecmp(v->name, "rtcachefriends")) {
28000          ast_set2_flag(&global_flags[1], ast_true(v->value), SIP_PAGE2_RTCACHEFRIENDS);
28001       } else if (!strcasecmp(v->name, "rtsavesysname")) {
28002          sip_cfg.rtsave_sysname = ast_true(v->value);
28003       } else if (!strcasecmp(v->name, "rtupdate")) {
28004          sip_cfg.peer_rtupdate = ast_true(v->value);
28005       } else if (!strcasecmp(v->name, "ignoreregexpire")) {
28006          sip_cfg.ignore_regexpire = ast_true(v->value);
28007       } else if (!strcasecmp(v->name, "timert1")) {
28008          /* Defaults to 500ms, but RFC 3261 states that it is recommended
28009           * for the value to be set higher, though a lower value is only
28010           * allowed on private networks unconnected to the Internet. */
28011          global_t1 = atoi(v->value);
28012       } else if (!strcasecmp(v->name, "timerb")) {
28013          int tmp = atoi(v->value);
28014          if (tmp < 500) {
28015             global_timer_b = global_t1 * 64;
28016             ast_log(LOG_WARNING, "Invalid value for timerb ('%s').  Setting to default ('%d').\n", v->value, global_timer_b);
28017          }
28018          timerb_set = 1;
28019       } else if (!strcasecmp(v->name, "t1min")) {
28020          global_t1min = atoi(v->value);
28021       } else if (!strcasecmp(v->name, "transport") && !ast_strlen_zero(v->value)) {
28022          char *val = ast_strdupa(v->value);
28023          char *trans;
28024 
28025          while ((trans = strsep(&val, ","))) {
28026             trans = ast_skip_blanks(trans);
28027 
28028             if (!strncasecmp(trans, "udp", 3)) {
28029                default_transports |= SIP_TRANSPORT_UDP;
28030             } else if (!strncasecmp(trans, "tcp", 3)) {
28031                default_transports |= SIP_TRANSPORT_TCP;
28032             } else if (!strncasecmp(trans, "tls", 3)) {
28033                default_transports |= SIP_TRANSPORT_TLS;
28034             } else {
28035                ast_log(LOG_NOTICE, "'%s' is not a valid transport type. if no other is specified, udp will be used.\n", trans);
28036             }
28037             if (default_primary_transport == 0) {
28038                default_primary_transport = default_transports;
28039             }
28040          }
28041       } else if (!strcasecmp(v->name, "tcpenable")) {
28042          if (!ast_false(v->value)) {
28043             ast_debug(2, "Enabling TCP socket for listening\n");
28044             sip_cfg.tcp_enabled = TRUE;
28045          }
28046       } else if (!strcasecmp(v->name, "tcpbindaddr")) {
28047          if (ast_parse_arg(v->value, PARSE_ADDR,
28048                  &sip_tcp_desc.local_address)) {
28049             ast_log(LOG_WARNING, "Invalid %s '%s' at line %d of %s\n",
28050                v->name, v->value, v->lineno, config);
28051          }
28052          ast_debug(2, "Setting TCP socket address to %s\n",
28053               ast_sockaddr_stringify(&sip_tcp_desc.local_address));
28054       } else if (!strcasecmp(v->name, "dynamic_exclude_static") || !strcasecmp(v->name, "dynamic_excludes_static")) {
28055          global_dynamic_exclude_static = ast_true(v->value);
28056       } else if (!strcasecmp(v->name, "contactpermit") || !strcasecmp(v->name, "contactdeny")) {
28057          int ha_error = 0;
28058          sip_cfg.contact_ha = ast_append_ha(v->name + 7, v->value, sip_cfg.contact_ha, &ha_error);
28059          if (ha_error) {
28060             ast_log(LOG_ERROR, "Bad ACL entry in configuration line %d : %s\n", v->lineno, v->value);
28061          }
28062       } else if (!strcasecmp(v->name, "rtautoclear")) {
28063          int i = atoi(v->value);
28064          if (i > 0) {
28065             sip_cfg.rtautoclear = i;
28066          } else {
28067             i = 0;
28068          }
28069          ast_set2_flag(&global_flags[1], i || ast_true(v->value), SIP_PAGE2_RTAUTOCLEAR);
28070       } else if (!strcasecmp(v->name, "usereqphone")) {
28071          ast_set2_flag(&global_flags[0], ast_true(v->value), SIP_USEREQPHONE);
28072       } else if (!strcasecmp(v->name, "prematuremedia")) {
28073          global_prematuremediafilter = ast_true(v->value);
28074       } else if (!strcasecmp(v->name, "relaxdtmf")) {
28075          global_relaxdtmf = ast_true(v->value);
28076       } else if (!strcasecmp(v->name, "vmexten")) {
28077          ast_copy_string(default_vmexten, v->value, sizeof(default_vmexten));
28078       } else if (!strcasecmp(v->name, "rtptimeout")) {
28079          if ((sscanf(v->value, "%30d", &global_rtptimeout) != 1) || (global_rtptimeout < 0)) {
28080             ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d.  Using default.\n", v->value, v->lineno);
28081             global_rtptimeout = 0;
28082          }
28083       } else if (!strcasecmp(v->name, "rtpholdtimeout")) {
28084          if ((sscanf(v->value, "%30d", &global_rtpholdtimeout) != 1) || (global_rtpholdtimeout < 0)) {
28085             ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d.  Using default.\n", v->value, v->lineno);
28086             global_rtpholdtimeout = 0;
28087          }
28088       } else if (!strcasecmp(v->name, "rtpkeepalive")) {
28089          if ((sscanf(v->value, "%30d", &global_rtpkeepalive) != 1) || (global_rtpkeepalive < 0)) {
28090             ast_log(LOG_WARNING, "'%s' is not a valid RTP keepalive time at line %d.  Using default.\n", v->value, v->lineno);
28091             global_rtpkeepalive = DEFAULT_RTPKEEPALIVE;
28092          }
28093       } else if (!strcasecmp(v->name, "compactheaders")) {
28094          sip_cfg.compactheaders = ast_true(v->value);
28095       } else if (!strcasecmp(v->name, "notifymimetype")) {
28096          ast_copy_string(default_notifymime, v->value, sizeof(default_notifymime));
28097       } else if (!strcasecmp(v->name, "directrtpsetup")) {
28098          sip_cfg.directrtpsetup = ast_true(v->value);
28099       } else if (!strcasecmp(v->name, "notifyringing")) {
28100          sip_cfg.notifyringing = ast_true(v->value);
28101       } else if (!strcasecmp(v->name, "notifyhold")) {
28102          sip_cfg.notifyhold = ast_true(v->value);
28103       } else if (!strcasecmp(v->name, "notifycid")) {
28104          if (!strcasecmp(v->value, "ignore-context")) {
28105             sip_cfg.notifycid = IGNORE_CONTEXT;
28106          } else {
28107             sip_cfg.notifycid = ast_true(v->value);
28108          }
28109       } else if (!strcasecmp(v->name, "alwaysauthreject")) {
28110          sip_cfg.alwaysauthreject = ast_true(v->value);
28111       } else if (!strcasecmp(v->name, "auth_options_requests")) {
28112          if (ast_true(v->value)) {
28113             sip_cfg.auth_options_requests = 1;
28114          }
28115       } else if (!strcasecmp(v->name, "mohinterpret")) {
28116          ast_copy_string(default_mohinterpret, v->value, sizeof(default_mohinterpret));
28117       } else if (!strcasecmp(v->name, "mohsuggest")) {
28118          ast_copy_string(default_mohsuggest, v->value, sizeof(default_mohsuggest));
28119       } else if (!strcasecmp(v->name, "language")) {
28120          ast_copy_string(default_language, v->value, sizeof(default_language));
28121       } else if (!strcasecmp(v->name, "regcontext")) {
28122          ast_copy_string(newcontexts, v->value, sizeof(newcontexts));
28123          stringp = newcontexts;
28124          /* Let's remove any contexts that are no longer defined in regcontext */
28125          cleanup_stale_contexts(stringp, oldregcontext);
28126          /* Create contexts if they don't exist already */
28127          while ((context = strsep(&stringp, "&"))) {
28128             ast_copy_string(used_context, context, sizeof(used_context));
28129             ast_context_find_or_create(NULL, NULL, context, "SIP");
28130          }
28131          ast_copy_string(sip_cfg.regcontext, v->value, sizeof(sip_cfg.regcontext));
28132       } else if (!strcasecmp(v->name, "regextenonqualify")) {
28133          sip_cfg.regextenonqualify = ast_true(v->value);
28134       } else if (!strcasecmp(v->name, "legacy_useroption_parsing")) {
28135          sip_cfg.legacy_useroption_parsing = ast_true(v->value);
28136       } else if (!strcasecmp(v->name, "callerid")) {
28137          ast_copy_string(default_callerid, v->value, sizeof(default_callerid));
28138       } else if (!strcasecmp(v->name, "mwi_from")) {
28139          ast_copy_string(default_mwi_from, v->value, sizeof(default_mwi_from));
28140       } else if (!strcasecmp(v->name, "fromdomain")) {
28141          char *fromdomainport;
28142          ast_copy_string(default_fromdomain, v->value, sizeof(default_fromdomain));
28143          if ((fromdomainport = strchr(default_fromdomain, ':'))) {
28144             *fromdomainport++ = '\0';
28145             if (!(default_fromdomainport = port_str2int(fromdomainport, 0))) {
28146                ast_log(LOG_NOTICE, "'%s' is not a valid port number for fromdomain.\n",fromdomainport);
28147             }
28148          } else {
28149             default_fromdomainport = STANDARD_SIP_PORT;
28150          }
28151       } else if (!strcasecmp(v->name, "outboundproxy")) {
28152          char *tok, *proxyname;
28153 
28154          if (ast_strlen_zero(v->value)) {
28155             ast_log(LOG_WARNING, "no value given for outbound proxy on line %d of sip.conf.", v->lineno);
28156             continue;
28157          }
28158 
28159          tok = ast_skip_blanks(strtok(ast_strdupa(v->value), ","));
28160 
28161          sip_parse_host(tok, v->lineno, &proxyname,
28162                    &sip_cfg.outboundproxy.port,
28163                    &sip_cfg.outboundproxy.transport);
28164 
28165          if ((tok = strtok(NULL, ","))) {
28166             sip_cfg.outboundproxy.force = !strncasecmp(ast_skip_blanks(tok), "force", 5);
28167          } else {
28168             sip_cfg.outboundproxy.force = FALSE;
28169          }
28170 
28171          if (ast_strlen_zero(proxyname)) {
28172             ast_log(LOG_WARNING, "you must specify a name for the outboundproxy on line %d of sip.conf.", v->lineno);
28173             sip_cfg.outboundproxy.name[0] = '\0';
28174             continue;
28175          }
28176 
28177          ast_copy_string(sip_cfg.outboundproxy.name, proxyname, sizeof(sip_cfg.outboundproxy.name));
28178 
28179          proxy_update(&sip_cfg.outboundproxy);
28180       } else if (!strcasecmp(v->name, "autocreatepeer")) {
28181          sip_cfg.autocreatepeer = ast_true(v->value);
28182       } else if (!strcasecmp(v->name, "match_auth_username")) {
28183          global_match_auth_username = ast_true(v->value);
28184       } else if (!strcasecmp(v->name, "srvlookup")) {
28185          sip_cfg.srvlookup = ast_true(v->value);
28186       } else if (!strcasecmp(v->name, "pedantic")) {
28187          sip_cfg.pedanticsipchecking = ast_true(v->value);
28188       } else if (!strcasecmp(v->name, "maxexpirey") || !strcasecmp(v->name, "maxexpiry")) {
28189          max_expiry = atoi(v->value);
28190          if (max_expiry < 1) {
28191             max_expiry = DEFAULT_MAX_EXPIRY;
28192          }
28193       } else if (!strcasecmp(v->name, "minexpirey") || !strcasecmp(v->name, "minexpiry")) {
28194          min_expiry = atoi(v->value);
28195          if (min_expiry < 1) {
28196             min_expiry = DEFAULT_MIN_EXPIRY;
28197          }
28198       } else if (!strcasecmp(v->name, "defaultexpiry") || !strcasecmp(v->name, "defaultexpirey")) {
28199          default_expiry = atoi(v->value);
28200          if (default_expiry < 1) {
28201             default_expiry = DEFAULT_DEFAULT_EXPIRY;
28202          }
28203       } else if (!strcasecmp(v->name, "mwiexpiry") || !strcasecmp(v->name, "mwiexpirey")) {
28204          mwi_expiry = atoi(v->value);
28205          if (mwi_expiry < 1) {
28206             mwi_expiry = DEFAULT_MWI_EXPIRY;
28207          }
28208       } else if (!strcasecmp(v->name, "tcpauthtimeout")) {
28209          if (ast_parse_arg(v->value, PARSE_INT32|PARSE_DEFAULT|PARSE_IN_RANGE,
28210                  &authtimeout, DEFAULT_AUTHTIMEOUT, 1, INT_MAX)) {
28211             ast_log(LOG_WARNING, "Invalid %s '%s' at line %d of %s\n",
28212                v->name, v->value, v->lineno, config);
28213          }
28214       } else if (!strcasecmp(v->name, "tcpauthlimit")) {
28215          if (ast_parse_arg(v->value, PARSE_INT32|PARSE_DEFAULT|PARSE_IN_RANGE,
28216                  &authlimit, DEFAULT_AUTHLIMIT, 1, INT_MAX)) {
28217             ast_log(LOG_WARNING, "Invalid %s '%s' at line %d of %s\n",
28218                v->name, v->value, v->lineno, config);
28219          }
28220       } else if (!strcasecmp(v->name, "sipdebug")) {
28221          if (ast_true(v->value))
28222             sipdebug |= sip_debug_config;
28223       } else if (!strcasecmp(v->name, "dumphistory")) {
28224          dumphistory = ast_true(v->value);
28225       } else if (!strcasecmp(v->name, "recordhistory")) {
28226          recordhistory = ast_true(v->value);
28227       } else if (!strcasecmp(v->name, "registertimeout")) {
28228          global_reg_timeout = atoi(v->value);
28229          if (global_reg_timeout < 1) {
28230             global_reg_timeout = DEFAULT_REGISTRATION_TIMEOUT;
28231          }
28232       } else if (!strcasecmp(v->name, "registerattempts")) {
28233          global_regattempts_max = atoi(v->value);
28234       } else if (!strcasecmp(v->name, "bindaddr") || !strcasecmp(v->name, "udpbindaddr")) {
28235          if (ast_parse_arg(v->value, PARSE_ADDR, &bindaddr)) {
28236             ast_log(LOG_WARNING, "Invalid address: %s\n", v->value);
28237          }
28238       } else if (!strcasecmp(v->name, "localnet")) {
28239          struct ast_ha *na;
28240          int ha_error = 0;
28241 
28242          if (!(na = ast_append_ha("d", v->value, localaddr, &ha_error))) {
28243             ast_log(LOG_WARNING, "Invalid localnet value: %s\n", v->value);
28244          } else {
28245             localaddr = na;
28246          }
28247          if (ha_error) {
28248             ast_log(LOG_ERROR, "Bad localnet configuration value line %d : %s\n", v->lineno, v->value);
28249          }
28250       } else if (!strcasecmp(v->name, "media_address")) {
28251          if (ast_parse_arg(v->value, PARSE_ADDR, &media_address))
28252             ast_log(LOG_WARNING, "Invalid address for media_address keyword: %s\n", v->value);
28253       } else if (!strcasecmp(v->name, "externaddr") || !strcasecmp(v->name, "externip")) {
28254          if (ast_parse_arg(v->value, PARSE_ADDR, &externaddr)) {
28255             ast_log(LOG_WARNING,
28256                "Invalid address for externaddr keyword: %s\n",
28257                v->value);
28258          }
28259          externexpire = 0;
28260       } else if (!strcasecmp(v->name, "externhost")) {
28261          ast_copy_string(externhost, v->value, sizeof(externhost));
28262          if (ast_sockaddr_resolve_first(&externaddr, externhost, 0)) {
28263             ast_log(LOG_WARNING, "Invalid address for externhost keyword: %s\n", externhost);
28264          }
28265          externexpire = time(NULL);
28266       } else if (!strcasecmp(v->name, "externrefresh")) {
28267          if (sscanf(v->value, "%30d", &externrefresh) != 1) {
28268             ast_log(LOG_WARNING, "Invalid externrefresh value '%s', must be an integer >0 at line %d\n", v->value, v->lineno);
28269             externrefresh = 10;
28270          }
28271       } else if (!strcasecmp(v->name, "externtcpport")) {
28272          if (!(externtcpport = port_str2int(v->value, 0))) {
28273             ast_log(LOG_WARNING, "Invalid externtcpport value, must be a positive integer between 1 and 65535 at line %d\n", v->lineno);
28274             externtcpport = 0;
28275          }
28276       } else if (!strcasecmp(v->name, "externtlsport")) {
28277          if (!(externtlsport = port_str2int(v->value, STANDARD_TLS_PORT))) {
28278             ast_log(LOG_WARNING, "Invalid externtlsport value, must be a positive integer between 1 and 65535 at line %d\n", v->lineno);
28279          }
28280       } else if (!strcasecmp(v->name, "allow")) {
28281          int error =  ast_parse_allow_disallow(&default_prefs, &sip_cfg.capability, v->value, TRUE);
28282          if (error) {
28283             ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
28284          }
28285       } else if (!strcasecmp(v->name, "disallow")) {
28286          int error =  ast_parse_allow_disallow(&default_prefs, &sip_cfg.capability, v->value, FALSE);
28287          if (error) {
28288             ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
28289          }
28290       } else if (!strcasecmp(v->name, "preferred_codec_only")) {
28291          ast_set2_flag(&global_flags[1], ast_true(v->value), SIP_PAGE2_PREFERRED_CODEC);
28292       } else if (!strcasecmp(v->name, "autoframing")) {
28293          global_autoframing = ast_true(v->value);
28294       } else if (!strcasecmp(v->name, "allowexternaldomains")) {
28295          sip_cfg.allow_external_domains = ast_true(v->value);
28296       } else if (!strcasecmp(v->name, "autodomain")) {
28297          auto_sip_domains = ast_true(v->value);
28298       } else if (!strcasecmp(v->name, "domain")) {
28299          char *domain = ast_strdupa(v->value);
28300          char *cntx = strchr(domain, ',');
28301 
28302          if (cntx) {
28303             *cntx++ = '\0';
28304          }
28305 
28306          if (ast_strlen_zero(cntx)) {
28307             ast_debug(1, "No context specified at line %d for domain '%s'\n", v->lineno, domain);
28308          }
28309          if (ast_strlen_zero(domain)) {
28310             ast_log(LOG_WARNING, "Empty domain specified at line %d\n", v->lineno);
28311          } else {
28312             add_sip_domain(ast_strip(domain), SIP_DOMAIN_CONFIG, cntx ? ast_strip(cntx) : "");
28313          }
28314       } else if (!strcasecmp(v->name, "register")) {
28315          if (sip_register(v->value, v->lineno) == 0) {
28316             registry_count++;
28317          }
28318       } else if (!strcasecmp(v->name, "mwi")) {
28319          sip_subscribe_mwi(v->value, v->lineno);
28320       } else if (!strcasecmp(v->name, "tos_sip")) {
28321          if (ast_str2tos(v->value, &global_tos_sip)) {
28322             ast_log(LOG_WARNING, "Invalid tos_sip value at line %d, refer to QoS documentation\n", v->lineno);
28323          }
28324       } else if (!strcasecmp(v->name, "tos_audio")) {
28325          if (ast_str2tos(v->value, &global_tos_audio)) {
28326             ast_log(LOG_WARNING, "Invalid tos_audio value at line %d, refer to QoS documentation\n", v->lineno);
28327          }
28328       } else if (!strcasecmp(v->name, "tos_video")) {
28329          if (ast_str2tos(v->value, &global_tos_video)) {
28330             ast_log(LOG_WARNING, "Invalid tos_video value at line %d, refer to QoS documentation\n", v->lineno);
28331          }
28332       } else if (!strcasecmp(v->name, "tos_text")) {
28333          if (ast_str2tos(v->value, &global_tos_text)) {
28334             ast_log(LOG_WARNING, "Invalid tos_text value at line %d, refer to QoS documentation\n", v->lineno);
28335          }
28336       } else if (!strcasecmp(v->name, "cos_sip")) {
28337          if (ast_str2cos(v->value, &global_cos_sip)) {
28338             ast_log(LOG_WARNING, "Invalid cos_sip value at line %d, refer to QoS documentation\n", v->lineno);
28339          }
28340       } else if (!strcasecmp(v->name, "cos_audio")) {
28341          if (ast_str2cos(v->value, &global_cos_audio)) {
28342             ast_log(LOG_WARNING, "Invalid cos_audio value at line %d, refer to QoS documentation\n", v->lineno);
28343          }
28344       } else if (!strcasecmp(v->name, "cos_video")) {
28345          if (ast_str2cos(v->value, &global_cos_video)) {
28346             ast_log(LOG_WARNING, "Invalid cos_video value at line %d, refer to QoS documentation\n", v->lineno);
28347          }
28348       } else if (!strcasecmp(v->name, "cos_text")) {
28349          if (ast_str2cos(v->value, &global_cos_text)) {
28350             ast_log(LOG_WARNING, "Invalid cos_text value at line %d, refer to QoS documentation\n", v->lineno);
28351          }
28352       } else if (!strcasecmp(v->name, "bindport")) {
28353          if (sscanf(v->value, "%5d", &bindport) != 1) {
28354             ast_log(LOG_WARNING, "Invalid port number '%s' at line %d of %s\n", v->value, v->lineno, config);
28355          }
28356       } else if (!strcasecmp(v->name, "qualify")) {
28357          if (!strcasecmp(v->value, "no")) {
28358             default_qualify = 0;
28359          } else if (!strcasecmp(v->value, "yes")) {
28360             default_qualify = DEFAULT_MAXMS;
28361          } else if (sscanf(v->value, "%30d", &default_qualify) != 1) {
28362             ast_log(LOG_WARNING, "Qualification default should be 'yes', 'no', or a number of milliseconds at line %d of sip.conf\n", v->lineno);
28363             default_qualify = 0;
28364          }
28365       } else if (!strcasecmp(v->name, "qualifyfreq")) {
28366          int i;
28367          if (sscanf(v->value, "%30d", &i) == 1) {
28368             global_qualifyfreq = i * 1000;
28369          } else {
28370             ast_log(LOG_WARNING, "Invalid qualifyfreq number '%s' at line %d of %s\n", v->value, v->lineno, config);
28371             global_qualifyfreq = DEFAULT_QUALIFYFREQ;
28372          }
28373       } else if (!strcasecmp(v->name, "callevents")) {
28374          sip_cfg.callevents = ast_true(v->value);
28375       } else if (!strcasecmp(v->name, "authfailureevents")) {
28376          global_authfailureevents = ast_true(v->value);
28377       } else if (!strcasecmp(v->name, "maxcallbitrate")) {
28378          default_maxcallbitrate = atoi(v->value);
28379          if (default_maxcallbitrate < 0)
28380             default_maxcallbitrate = DEFAULT_MAX_CALL_BITRATE;
28381       } else if (!strcasecmp(v->name, "matchexternaddrlocally") || !strcasecmp(v->name, "matchexterniplocally")) {
28382          sip_cfg.matchexternaddrlocally = ast_true(v->value);
28383       } else if (!strcasecmp(v->name, "session-timers")) {
28384          int i = (int) str2stmode(v->value);
28385          if (i < 0) {
28386             ast_log(LOG_WARNING, "Invalid session-timers '%s' at line %d of %s\n", v->value, v->lineno, config);
28387             global_st_mode = SESSION_TIMER_MODE_ACCEPT;
28388          } else {
28389             global_st_mode = i;
28390          }
28391       } else if (!strcasecmp(v->name, "session-expires")) {
28392          if (sscanf(v->value, "%30d", &global_max_se) != 1) {
28393             ast_log(LOG_WARNING, "Invalid session-expires '%s' at line %d of %s\n", v->value, v->lineno, config);
28394             global_max_se = DEFAULT_MAX_SE;
28395          }
28396       } else if (!strcasecmp(v->name, "session-minse")) {
28397          if (sscanf(v->value, "%30d", &global_min_se) != 1) {
28398             ast_log(LOG_WARNING, "Invalid session-minse '%s' at line %d of %s\n", v->value, v->lineno, config);
28399             global_min_se = DEFAULT_MIN_SE;
28400          }
28401          if (global_min_se < 90) {
28402             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);
28403             global_min_se = DEFAULT_MIN_SE;
28404          }
28405       } else if (!strcasecmp(v->name, "session-refresher")) {
28406          int i = (int) str2strefresher(v->value);
28407          if (i < 0) {
28408             ast_log(LOG_WARNING, "Invalid session-refresher '%s' at line %d of %s\n", v->value, v->lineno, config);
28409             global_st_refresher = SESSION_TIMER_REFRESHER_UAS;
28410          } else {
28411             global_st_refresher = i;
28412          }
28413       } else if (!strcasecmp(v->name, "storesipcause")) {
28414          global_store_sip_cause = ast_true(v->value);
28415       } else if (!strcasecmp(v->name, "qualifygap")) {
28416          if (sscanf(v->value, "%30d", &global_qualify_gap) != 1) {
28417             ast_log(LOG_WARNING, "Invalid qualifygap '%s' at line %d of %s\n", v->value, v->lineno, config);
28418             global_qualify_gap = DEFAULT_QUALIFY_GAP;
28419          }
28420       } else if (!strcasecmp(v->name, "qualifypeers")) {
28421          if (sscanf(v->value, "%30d", &global_qualify_peers) != 1) {
28422             ast_log(LOG_WARNING, "Invalid pokepeers '%s' at line %d of %s\n", v->value, v->lineno, config);
28423             global_qualify_peers = DEFAULT_QUALIFY_PEERS;
28424          }
28425       } else if (!strcasecmp(v->name, "disallowed_methods")) {
28426          char *disallow = ast_strdupa(v->value);
28427          mark_parsed_methods(&sip_cfg.disallowed_methods, disallow);
28428       } else if (!strcasecmp(v->name, "shrinkcallerid")) {
28429          if (ast_true(v->value)) {
28430             global_shrinkcallerid = 1;
28431          } else if (ast_false(v->value)) {
28432             global_shrinkcallerid = 0;
28433          } else {
28434             ast_log(LOG_WARNING, "shrinkcallerid value %s is not valid at line %d.\n", v->value, v->lineno);
28435          }
28436       } else if (!strcasecmp(v->name, "use_q850_reason")) {
28437          ast_set2_flag(&global_flags[1], ast_true(v->value), SIP_PAGE2_Q850_REASON);
28438       } else if (!strcasecmp(v->name, "maxforwards")) {
28439          if ((sscanf(v->value, "%30d", &sip_cfg.default_max_forwards) != 1) || (sip_cfg.default_max_forwards < 1)) {
28440             ast_log(LOG_WARNING, "'%s' is not a valid maxforwards value at line %d.  Using default.\n", v->value, v->lineno);
28441             sip_cfg.default_max_forwards = DEFAULT_MAX_FORWARDS;
28442          }
28443       } else if (!strcasecmp(v->name, "subscribe_network_change_event")) {
28444          if (ast_true(v->value)) {
28445             subscribe_network_change = 1;
28446          } else if (ast_false(v->value)) {
28447             subscribe_network_change = 0;
28448          } else {
28449             ast_log(LOG_WARNING, "subscribe_network_change_event value %s is not valid at line %d.\n", v->value, v->lineno);
28450          }
28451       } else if (!strcasecmp(v->name, "snom_aoc_enabled")) {
28452          ast_set2_flag(&global_flags[2], ast_true(v->value), SIP_PAGE3_SNOM_AOC);
28453       } else if (!strcasecmp(v->name, "parkinglot")) {
28454          ast_copy_string(default_parkinglot, v->value, sizeof(default_parkinglot));
28455       }
28456    }
28457 
28458    if (subscribe_network_change) {
28459       network_change_event_subscribe();
28460    } else {
28461       network_change_event_unsubscribe();
28462    }
28463 
28464    if (global_t1 < global_t1min) {
28465       ast_log(LOG_WARNING, "'t1min' (%d) cannot be greater than 't1timer' (%d).  Resetting 't1timer' to the value of 't1min'\n", global_t1min, global_t1);
28466       global_t1 = global_t1min;
28467    }
28468 
28469    if (global_timer_b < global_t1 * 64) {
28470       if (timerb_set && timert1_set) {
28471          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);
28472       } else if (timerb_set) {
28473          if ((global_t1 = global_timer_b / 64) < global_t1min) {
28474             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);
28475             global_t1 = global_t1min;
28476             global_timer_b = global_t1 * 64;
28477          }
28478       } else {
28479          global_timer_b = global_t1 * 64;
28480       }
28481    }
28482    if (!sip_cfg.allow_external_domains && AST_LIST_EMPTY(&domain_list)) {
28483       ast_log(LOG_WARNING, "To disallow external domains, you need to configure local SIP domains.\n");
28484       sip_cfg.allow_external_domains = 1;
28485    }
28486    /* If not or badly configured, set default transports */
28487    if (!sip_cfg.tcp_enabled && (default_transports & SIP_TRANSPORT_TCP)) {
28488       ast_log(LOG_WARNING, "Cannot use 'tcp' transport with tcpenable=no. Removing from available transports.\n");
28489       default_primary_transport &= ~SIP_TRANSPORT_TCP;
28490       default_transports &= ~SIP_TRANSPORT_TCP;
28491    }
28492    if (!default_tls_cfg.enabled && (default_transports & SIP_TRANSPORT_TLS)) {
28493       ast_log(LOG_WARNING, "Cannot use 'tls' transport with tlsenable=no. Removing from available transports.\n");
28494       default_primary_transport &= ~SIP_TRANSPORT_TLS;
28495       default_transports &= ~SIP_TRANSPORT_TLS;
28496    }
28497    if (!default_transports) {
28498       ast_log(LOG_WARNING, "No valid transports available, falling back to 'udp'.\n");
28499       default_transports = default_primary_transport = SIP_TRANSPORT_UDP;
28500    } else if (!default_primary_transport) {
28501       ast_log(LOG_WARNING, "No valid default transport. Selecting 'udp' as default.\n");
28502       default_primary_transport = SIP_TRANSPORT_UDP;
28503    }
28504 
28505    /* Build list of authentication to various SIP realms, i.e. service providers */
28506    for (v = ast_variable_browse(cfg, "authentication"); v ; v = v->next) {
28507       /* Format for authentication is auth = username:password@realm */
28508       if (!strcasecmp(v->name, "auth")) {
28509          add_realm_authentication(&authl, v->value, v->lineno);
28510       }
28511    }
28512 
28513    if (bindport) {
28514       if (ast_sockaddr_port(&bindaddr)) {
28515          ast_log(LOG_WARNING, "bindport is also specified in bindaddr. "
28516             "Using %d.\n", bindport);
28517       }
28518       ast_sockaddr_set_port(&bindaddr, bindport);
28519    }
28520 
28521    if (!ast_sockaddr_port(&bindaddr)) {
28522       ast_sockaddr_set_port(&bindaddr, STANDARD_SIP_PORT);
28523    }
28524 
28525    /* Set UDP address and open socket */
28526    ast_sockaddr_copy(&internip, &bindaddr);
28527    if (ast_find_ourip(&internip, &bindaddr, 0)) {
28528       ast_log(LOG_WARNING, "Unable to get own IP address, SIP disabled\n");
28529       ast_config_destroy(cfg);
28530       return 0;
28531    }
28532 
28533    ast_mutex_lock(&netlock);
28534    if ((sipsock > -1) && (ast_sockaddr_cmp(&old_bindaddr, &bindaddr))) {
28535       close(sipsock);
28536       sipsock = -1;
28537    }
28538    if (sipsock < 0) {
28539       sipsock = socket(ast_sockaddr_is_ipv6(&bindaddr) ?
28540              AF_INET6 : AF_INET, SOCK_DGRAM, 0);
28541       if (sipsock < 0) {
28542          ast_log(LOG_WARNING, "Unable to create SIP socket: %s\n", strerror(errno));
28543          ast_config_destroy(cfg);
28544          ast_mutex_unlock(&netlock);
28545          return -1;
28546       } else {
28547          /* Allow SIP clients on the same host to access us: */
28548          const int reuseFlag = 1;
28549 
28550          setsockopt(sipsock, SOL_SOCKET, SO_REUSEADDR,
28551                (const char*)&reuseFlag,
28552                sizeof reuseFlag);
28553 
28554          ast_enable_packet_fragmentation(sipsock);
28555 
28556          if (ast_bind(sipsock, &bindaddr) < 0) {
28557             ast_log(LOG_WARNING, "Failed to bind to %s: %s\n",
28558                ast_sockaddr_stringify(&bindaddr), strerror(errno));
28559             close(sipsock);
28560             sipsock = -1;
28561          } else {
28562             ast_verb(2, "SIP Listening on %s\n", ast_sockaddr_stringify(&bindaddr));
28563             ast_set_qos(sipsock, global_tos_sip, global_cos_sip, "SIP");
28564          }
28565       }
28566    } else {
28567       ast_set_qos(sipsock, global_tos_sip, global_cos_sip, "SIP");
28568    }
28569    ast_mutex_unlock(&netlock);
28570 
28571    /* Start TCP server */
28572    if (sip_cfg.tcp_enabled) {
28573       if (ast_sockaddr_isnull(&sip_tcp_desc.local_address)) {
28574          ast_sockaddr_copy(&sip_tcp_desc.local_address, &bindaddr);
28575       }
28576       if (!ast_sockaddr_port(&sip_tcp_desc.local_address)) {
28577          ast_sockaddr_set_port(&sip_tcp_desc.local_address, STANDARD_SIP_PORT);
28578       }
28579    } else {
28580       ast_sockaddr_setnull(&sip_tcp_desc.local_address);
28581    }
28582    ast_tcptls_server_start(&sip_tcp_desc);
28583    if (sip_cfg.tcp_enabled && sip_tcp_desc.accept_fd == -1) {
28584       /* TCP server start failed. Tell the admin */
28585       ast_log(LOG_ERROR, "SIP TCP Server start failed. Not listening on TCP socket.\n");
28586    } else {
28587       ast_debug(2, "SIP TCP server started\n");
28588    }
28589 
28590    /* Start TLS server if needed */
28591    memcpy(sip_tls_desc.tls_cfg, &default_tls_cfg, sizeof(default_tls_cfg));
28592 
28593    if (ast_ssl_setup(sip_tls_desc.tls_cfg)) {
28594       if (ast_sockaddr_isnull(&sip_tls_desc.local_address)) {
28595          ast_sockaddr_copy(&sip_tls_desc.local_address, &bindaddr);
28596          ast_sockaddr_set_port(&sip_tls_desc.local_address,
28597                      STANDARD_TLS_PORT);
28598       }
28599       if (!ast_sockaddr_port(&sip_tls_desc.local_address)) {
28600          ast_sockaddr_set_port(&sip_tls_desc.local_address,
28601                      STANDARD_TLS_PORT);
28602       }
28603       ast_tcptls_server_start(&sip_tls_desc);
28604       if (default_tls_cfg.enabled && sip_tls_desc.accept_fd == -1) {
28605          ast_log(LOG_ERROR, "TLS Server start failed. Not listening on TLS socket.\n");
28606          sip_tls_desc.tls_cfg = NULL;
28607       }
28608    } else if (sip_tls_desc.tls_cfg->enabled) {
28609       sip_tls_desc.tls_cfg = NULL;
28610       ast_log(LOG_WARNING, "SIP TLS server did not load because of errors.\n");
28611    }
28612 
28613    if (ucfg) {
28614       struct ast_variable *gen;
28615       int genhassip, genregistersip;
28616       const char *hassip, *registersip;
28617       
28618       genhassip = ast_true(ast_variable_retrieve(ucfg, "general", "hassip"));
28619       genregistersip = ast_true(ast_variable_retrieve(ucfg, "general", "registersip"));
28620       gen = ast_variable_browse(ucfg, "general");
28621       cat = ast_category_browse(ucfg, NULL);
28622       while (cat) {
28623          if (strcasecmp(cat, "general")) {
28624             hassip = ast_variable_retrieve(ucfg, cat, "hassip");
28625             registersip = ast_variable_retrieve(ucfg, cat, "registersip");
28626             if (ast_true(hassip) || (!hassip && genhassip)) {
28627                peer = build_peer(cat, gen, ast_variable_browse(ucfg, cat), 0, 0);
28628                if (peer) {
28629                   /* user.conf entries are always of type friend */
28630                   peer->type = SIP_TYPE_USER | SIP_TYPE_PEER;
28631                   ao2_t_link(peers, peer, "link peer into peer table");
28632                   if ((peer->type & SIP_TYPE_PEER) && !ast_sockaddr_isnull(&peer->addr)) {
28633                      ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
28634                   }
28635                   
28636                   unref_peer(peer, "unref_peer: from reload_config");
28637                   peer_count++;
28638                }
28639             }
28640             if (ast_true(registersip) || (!registersip && genregistersip)) {
28641                char tmp[256];
28642                const char *host = ast_variable_retrieve(ucfg, cat, "host");
28643                const char *username = ast_variable_retrieve(ucfg, cat, "username");
28644                const char *secret = ast_variable_retrieve(ucfg, cat, "secret");
28645                const char *contact = ast_variable_retrieve(ucfg, cat, "contact");
28646                const char *authuser = ast_variable_retrieve(ucfg, cat, "authuser");
28647                if (!host) {
28648                   host = ast_variable_retrieve(ucfg, "general", "host");
28649                }
28650                if (!username) {
28651                   username = ast_variable_retrieve(ucfg, "general", "username");
28652                }
28653                if (!secret) {
28654                   secret = ast_variable_retrieve(ucfg, "general", "secret");
28655                }
28656                if (!contact) {
28657                   contact = "s";
28658                }
28659                if (!ast_strlen_zero(username) && !ast_strlen_zero(host)) {
28660                   if (!ast_strlen_zero(secret)) {
28661                      if (!ast_strlen_zero(authuser)) {
28662                         snprintf(tmp, sizeof(tmp), "%s?%s:%s:%s@%s/%s", cat, username, secret, authuser, host, contact);
28663                      } else {
28664                         snprintf(tmp, sizeof(tmp), "%s?%s:%s@%s/%s", cat, username, secret, host, contact);
28665                      }
28666                   } else if (!ast_strlen_zero(authuser)) {
28667                      snprintf(tmp, sizeof(tmp), "%s?%s::%s@%s/%s", cat, username, authuser, host, contact);
28668                   } else {
28669                      snprintf(tmp, sizeof(tmp), "%s?%s@%s/%s", cat, username, host, contact);
28670                   }
28671                   if (sip_register(tmp, 0) == 0) {
28672                      registry_count++;
28673                   }
28674                }
28675             }
28676          }
28677          cat = ast_category_browse(ucfg, cat);
28678       }
28679       ast_config_destroy(ucfg);
28680    }
28681 
28682    /* Load peers, users and friends */
28683    cat = NULL;
28684    while ( (cat = ast_category_browse(cfg, cat)) ) {
28685       const char *utype;
28686       if (!strcasecmp(cat, "general") || !strcasecmp(cat, "authentication"))
28687          continue;
28688       utype = ast_variable_retrieve(cfg, cat, "type");
28689       if (!utype) {
28690          ast_log(LOG_WARNING, "Section '%s' lacks type\n", cat);
28691          continue;
28692       } else {
28693          if (!strcasecmp(utype, "user")) {
28694             ;
28695          } else if (!strcasecmp(utype, "friend")) {
28696             ;
28697          } else if (!strcasecmp(utype, "peer")) {
28698             ;
28699          } else {
28700             ast_log(LOG_WARNING, "Unknown type '%s' for '%s' in %s\n", utype, cat, "sip.conf");
28701             continue;
28702          }
28703          peer = build_peer(cat, ast_variable_browse(cfg, cat), NULL, 0, 0);
28704          if (peer) {
28705             display_nat_warning(cat, reason, &peer->flags[0]);
28706             ao2_t_link(peers, peer, "link peer into peers table");
28707             if ((peer->type & SIP_TYPE_PEER) && !ast_sockaddr_isnull(&peer->addr)) {
28708                ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
28709             }
28710             unref_peer(peer, "unref the result of the build_peer call. Now, the links from the tables are the only ones left.");
28711             peer_count++;
28712          }
28713       }
28714    }
28715 
28716    /* Add default domains - host name, IP address and IP:port
28717     * Only do this if user added any sip domain with "localdomains"
28718     * In order to *not* break backwards compatibility
28719     *    Some phones address us at IP only, some with additional port number
28720     */
28721    if (auto_sip_domains) {
28722       char temp[MAXHOSTNAMELEN];
28723 
28724       /* First our default IP address */
28725       if (!ast_sockaddr_isnull(&bindaddr) && !ast_sockaddr_is_any(&bindaddr)) {
28726          add_sip_domain(ast_sockaddr_stringify_addr(&bindaddr),
28727                    SIP_DOMAIN_AUTO, NULL);
28728       } else if (!ast_sockaddr_isnull(&internip) && !ast_sockaddr_is_any(&internip)) {
28729       /* Our internal IP address, if configured */
28730          add_sip_domain(ast_sockaddr_stringify_addr(&internip),
28731                    SIP_DOMAIN_AUTO, NULL);
28732       } else {
28733          ast_log(LOG_NOTICE, "Can't add wildcard IP address to domain list, please add IP address to domain manually.\n");
28734       }
28735 
28736       /* If TCP is running on a different IP than UDP, then add it too */
28737       if (!ast_sockaddr_isnull(&sip_tcp_desc.local_address) &&
28738           !ast_sockaddr_cmp(&bindaddr, &sip_tcp_desc.local_address)) {
28739          add_sip_domain(ast_sockaddr_stringify_addr(&sip_tcp_desc.local_address),
28740                    SIP_DOMAIN_AUTO, NULL);
28741       }
28742 
28743       /* If TLS is running on a different IP than UDP and TCP, then add that too */
28744       if (!ast_sockaddr_isnull(&sip_tls_desc.local_address) &&
28745           !ast_sockaddr_cmp(&bindaddr, &sip_tls_desc.local_address) &&
28746           !ast_sockaddr_cmp(&sip_tcp_desc.local_address,
28747                   &sip_tls_desc.local_address)) {
28748          add_sip_domain(ast_sockaddr_stringify_addr(&sip_tcp_desc.local_address),
28749                    SIP_DOMAIN_AUTO, NULL);
28750       }
28751 
28752       /* Our extern IP address, if configured */
28753       if (!ast_sockaddr_isnull(&externaddr)) {
28754          add_sip_domain(ast_sockaddr_stringify_addr(&externaddr),
28755                    SIP_DOMAIN_AUTO, NULL);
28756       }
28757 
28758       /* Extern host name (NAT traversal support) */
28759       if (!ast_strlen_zero(externhost)) {
28760          add_sip_domain(externhost, SIP_DOMAIN_AUTO, NULL);
28761       }
28762       
28763       /* Our host name */
28764       if (!gethostname(temp, sizeof(temp))) {
28765          add_sip_domain(temp, SIP_DOMAIN_AUTO, NULL);
28766       }
28767    }
28768 
28769    /* Release configuration from memory */
28770    ast_config_destroy(cfg);
28771 
28772    /* Load the list of manual NOTIFY types to support */
28773    if (notify_types)
28774       ast_config_destroy(notify_types);
28775    if ((notify_types = ast_config_load(notify_config, config_flags)) == CONFIG_STATUS_FILEINVALID) {
28776       ast_log(LOG_ERROR, "Contents of %s are invalid and cannot be parsed.\n", notify_config);
28777       notify_types = NULL;
28778    }
28779 
28780    /* Done, tell the manager */
28781    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);
28782    run_end = time(0);
28783    ast_debug(4, "SIP reload_config done...Runtime= %d sec\n", (int)(run_end-run_start));
28784 
28785    return 0;
28786 }
28787 
28788 static int apply_directmedia_ha(struct sip_pvt *p, const char *op)
28789 {
28790    struct ast_sockaddr us = { { 0, }, }, them = { { 0, }, };
28791    int res = AST_SENSE_ALLOW;
28792 
28793    ast_rtp_instance_get_remote_address(p->rtp, &them);
28794    ast_rtp_instance_get_local_address(p->rtp, &us);
28795 
28796    if ((res = ast_apply_ha(p->directmediaha, &them)) == AST_SENSE_DENY) {
28797       const char *us_addr = ast_strdupa(ast_sockaddr_stringify(&us));
28798       const char *them_addr = ast_strdupa(ast_sockaddr_stringify(&them));
28799 
28800       ast_debug(3, "Reinvite %s to %s denied by directmedia ACL on %s\n",
28801          op, them_addr, us_addr);
28802    }
28803 
28804    return res;
28805 }
28806 
28807 static struct ast_udptl *sip_get_udptl_peer(struct ast_channel *chan)
28808 {
28809    struct sip_pvt *p;
28810    struct ast_udptl *udptl = NULL;
28811    
28812    p = chan->tech_pvt;
28813    if (!p) {
28814       return NULL;
28815    }
28816    
28817    sip_pvt_lock(p);
28818    if (p->udptl && ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA)) {
28819       if (apply_directmedia_ha(p, "UDPTL T.38 data")) {
28820          udptl = p->udptl;
28821       }
28822    }
28823    sip_pvt_unlock(p);
28824    return udptl;
28825 }
28826 
28827 static int sip_set_udptl_peer(struct ast_channel *chan, struct ast_udptl *udptl)
28828 {
28829    struct sip_pvt *p;
28830 
28831    /* Lock the channel and the private safely. */
28832    ast_channel_lock(chan);
28833    p = chan->tech_pvt;
28834    if (!p) {
28835       ast_channel_unlock(chan);
28836       return -1;
28837    }
28838    sip_pvt_lock(p);
28839    if (p->owner != chan) {
28840       /* I suppose it could be argued that if this happens it is a bug. */
28841       ast_debug(1, "The private is not owned by channel %s anymore.\n", chan->name);
28842       sip_pvt_unlock(p);
28843       ast_channel_unlock(chan);
28844       return 0;
28845    }
28846 
28847    if (udptl) {
28848       ast_udptl_get_peer(udptl, &p->udptlredirip);
28849    } else {
28850       memset(&p->udptlredirip, 0, sizeof(p->udptlredirip));
28851    }
28852    if (!ast_test_flag(&p->flags[0], SIP_GOTREFER)) {
28853       if (!p->pendinginvite) {
28854          ast_debug(3, "Sending reinvite on SIP '%s' - It's UDPTL soon redirected to IP %s\n",
28855                p->callid, ast_sockaddr_stringify(udptl ? &p->udptlredirip : &p->ourip));
28856          transmit_reinvite_with_sdp(p, TRUE, FALSE);
28857       } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
28858          ast_debug(3, "Deferring reinvite on SIP '%s' - It's UDPTL will be redirected to IP %s\n",
28859                p->callid, ast_sockaddr_stringify(udptl ? &p->udptlredirip : &p->ourip));
28860          ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
28861       }
28862    }
28863    /* Reset lastrtprx timer */
28864    p->lastrtprx = p->lastrtptx = time(NULL);
28865    sip_pvt_unlock(p);
28866    ast_channel_unlock(chan);
28867    return 0;
28868 }
28869 
28870 static enum ast_rtp_glue_result sip_get_rtp_peer(struct ast_channel *chan, struct ast_rtp_instance **instance)
28871 {
28872    struct sip_pvt *p = NULL;
28873    enum ast_rtp_glue_result res = AST_RTP_GLUE_RESULT_LOCAL;
28874 
28875    if (!(p = chan->tech_pvt)) {
28876       return AST_RTP_GLUE_RESULT_FORBID;
28877    }
28878 
28879    sip_pvt_lock(p);
28880    if (!(p->rtp)) {
28881       sip_pvt_unlock(p);
28882       return AST_RTP_GLUE_RESULT_FORBID;
28883    }
28884 
28885    ao2_ref(p->rtp, +1);
28886    *instance = p->rtp;
28887 
28888    if (ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA)) {
28889       res = AST_RTP_GLUE_RESULT_REMOTE;
28890       if (!apply_directmedia_ha(p, "audio")) {
28891          res = AST_RTP_GLUE_RESULT_FORBID;
28892       }
28893    } else if (ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA_NAT)) {
28894       res = AST_RTP_GLUE_RESULT_REMOTE;
28895    } else if (ast_test_flag(&global_jbconf, AST_JB_FORCED)) {
28896       res = AST_RTP_GLUE_RESULT_FORBID;
28897    }
28898 
28899    if (p->srtp) {
28900       res = AST_RTP_GLUE_RESULT_FORBID;
28901    }
28902 
28903    sip_pvt_unlock(p);
28904 
28905    return res;
28906 }
28907 
28908 static enum ast_rtp_glue_result sip_get_vrtp_peer(struct ast_channel *chan, struct ast_rtp_instance **instance)
28909 {
28910    struct sip_pvt *p = NULL;
28911    enum ast_rtp_glue_result res = AST_RTP_GLUE_RESULT_FORBID;
28912 
28913    if (!(p = chan->tech_pvt)) {
28914       return AST_RTP_GLUE_RESULT_FORBID;
28915    }
28916 
28917    sip_pvt_lock(p);
28918    if (!(p->vrtp)) {
28919       sip_pvt_unlock(p);
28920       return AST_RTP_GLUE_RESULT_FORBID;
28921    }
28922 
28923    ao2_ref(p->vrtp, +1);
28924    *instance = p->vrtp;
28925 
28926    if (ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA)) {
28927       res = AST_RTP_GLUE_RESULT_REMOTE;
28928       if (!apply_directmedia_ha(p, "video")) {
28929          res = AST_RTP_GLUE_RESULT_FORBID;
28930       }
28931    }
28932 
28933    sip_pvt_unlock(p);
28934 
28935    return res;
28936 }
28937 
28938 static enum ast_rtp_glue_result sip_get_trtp_peer(struct ast_channel *chan, struct ast_rtp_instance **instance)
28939 {
28940    struct sip_pvt *p = NULL;
28941    enum ast_rtp_glue_result res = AST_RTP_GLUE_RESULT_FORBID;
28942 
28943    if (!(p = chan->tech_pvt)) {
28944       return AST_RTP_GLUE_RESULT_FORBID;
28945    }
28946 
28947    sip_pvt_lock(p);
28948    if (!(p->trtp)) {
28949       sip_pvt_unlock(p);
28950       return AST_RTP_GLUE_RESULT_FORBID;
28951    }
28952 
28953    ao2_ref(p->trtp, +1);
28954    *instance = p->trtp;
28955 
28956    if (ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA)) {
28957       res = AST_RTP_GLUE_RESULT_REMOTE;
28958       if (!apply_directmedia_ha(p, "text")) {
28959          res = AST_RTP_GLUE_RESULT_FORBID;
28960       }
28961    }
28962 
28963    sip_pvt_unlock(p);
28964 
28965    return res;
28966 }
28967 
28968 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)
28969 {
28970    struct sip_pvt *p;
28971    int changed = 0;
28972 
28973    /* Lock the channel and the private safely. */
28974    ast_channel_lock(chan);
28975    p = chan->tech_pvt;
28976    if (!p) {
28977       ast_channel_unlock(chan);
28978       return -1;
28979    }
28980    sip_pvt_lock(p);
28981    if (p->owner != chan) {
28982       /* I suppose it could be argued that if this happens it is a bug. */
28983       ast_debug(1, "The private is not owned by channel %s anymore.\n", chan->name);
28984       sip_pvt_unlock(p);
28985       ast_channel_unlock(chan);
28986       return 0;
28987    }
28988 
28989    /* Disable early RTP bridge  */
28990    if ((instance || vinstance || tinstance) &&
28991       !ast_bridged_channel(chan) &&
28992       !sip_cfg.directrtpsetup) {
28993       sip_pvt_unlock(p);
28994       ast_channel_unlock(chan);
28995       return 0;
28996    }
28997 
28998    if (p->alreadygone) {
28999       /* If we're destroyed, don't bother */
29000       sip_pvt_unlock(p);
29001       ast_channel_unlock(chan);
29002       return 0;
29003    }
29004 
29005    /* if this peer cannot handle reinvites of the media stream to devices
29006       that are known to be behind a NAT, then stop the process now
29007    */
29008    if (nat_active && !ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA_NAT)) {
29009       sip_pvt_unlock(p);
29010       ast_channel_unlock(chan);
29011       return 0;
29012    }
29013 
29014    if (instance) {
29015       changed |= ast_rtp_instance_get_and_cmp_remote_address(instance, &p->redirip);
29016    } else if (!ast_sockaddr_isnull(&p->redirip)) {
29017       memset(&p->redirip, 0, sizeof(p->redirip));
29018       changed = 1;
29019    }
29020    if (vinstance) {
29021       changed |= ast_rtp_instance_get_and_cmp_remote_address(vinstance, &p->vredirip);
29022    } else if (!ast_sockaddr_isnull(&p->vredirip)) {
29023       memset(&p->vredirip, 0, sizeof(p->vredirip));
29024       changed = 1;
29025    }
29026    if (tinstance) {
29027       changed |= ast_rtp_instance_get_and_cmp_remote_address(tinstance, &p->tredirip);
29028    } else if (!ast_sockaddr_isnull(&p->tredirip)) {
29029       memset(&p->tredirip, 0, sizeof(p->tredirip));
29030       changed = 1;
29031    }
29032    if (codecs && (p->redircodecs != codecs)) {
29033       p->redircodecs = codecs;
29034       changed = 1;
29035    }
29036    if (changed && !ast_test_flag(&p->flags[0], SIP_GOTREFER) && !ast_test_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER)) {
29037       if (chan->_state != AST_STATE_UP) {     /* We are in early state */
29038          if (p->do_history)
29039             append_history(p, "ExtInv", "Initial invite sent with remote bridge proposal.");
29040          ast_debug(1, "Early remote bridge setting SIP '%s' - Sending media to %s\n", p->callid, ast_sockaddr_stringify(instance ? &p->redirip : &p->ourip));
29041       } else if (!p->pendinginvite) {   /* We are up, and have no outstanding invite */
29042          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));
29043          transmit_reinvite_with_sdp(p, FALSE, FALSE);
29044       } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
29045          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));
29046          /* We have a pending Invite. Send re-invite when we're done with the invite */
29047          ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
29048       }
29049    }
29050    /* Reset lastrtprx timer */
29051    p->lastrtprx = p->lastrtptx = time(NULL);
29052    sip_pvt_unlock(p);
29053    ast_channel_unlock(chan);
29054    return 0;
29055 }
29056 
29057 static format_t sip_get_codec(struct ast_channel *chan)
29058 {
29059    struct sip_pvt *p = chan->tech_pvt;
29060    return p->peercapability ? p->peercapability : p->capability;
29061 }
29062 
29063 static struct ast_rtp_glue sip_rtp_glue = {
29064    .type = "SIP",
29065    .get_rtp_info = sip_get_rtp_peer,
29066    .get_vrtp_info = sip_get_vrtp_peer,
29067    .get_trtp_info = sip_get_trtp_peer,
29068    .update_peer = sip_set_rtp_peer,
29069    .get_codec = sip_get_codec,
29070 };
29071 
29072 static char *app_dtmfmode = "SIPDtmfMode";
29073 static char *app_sipaddheader = "SIPAddHeader";
29074 static char *app_sipremoveheader = "SIPRemoveHeader";
29075 
29076 /*! \brief Set the DTMFmode for an outbound SIP call (application) */
29077 static int sip_dtmfmode(struct ast_channel *chan, const char *data)
29078 {
29079    struct sip_pvt *p;
29080    const char *mode = data;
29081 
29082    if (!data) {
29083       ast_log(LOG_WARNING, "This application requires the argument: info, inband, rfc2833\n");
29084       return 0;
29085    }
29086    ast_channel_lock(chan);
29087    if (!IS_SIP_TECH(chan->tech)) {
29088       ast_log(LOG_WARNING, "Call this application only on SIP incoming calls\n");
29089       ast_channel_unlock(chan);
29090       return 0;
29091    }
29092    p = chan->tech_pvt;
29093    if (!p) {
29094       ast_channel_unlock(chan);
29095       return 0;
29096    }
29097    sip_pvt_lock(p);
29098    if (!strcasecmp(mode, "info")) {
29099       ast_clear_flag(&p->flags[0], SIP_DTMF);
29100       ast_set_flag(&p->flags[0], SIP_DTMF_INFO);
29101       p->jointnoncodeccapability &= ~AST_RTP_DTMF;
29102    } else if (!strcasecmp(mode, "shortinfo")) {
29103       ast_clear_flag(&p->flags[0], SIP_DTMF);
29104       ast_set_flag(&p->flags[0], SIP_DTMF_SHORTINFO);
29105       p->jointnoncodeccapability &= ~AST_RTP_DTMF;
29106    } else if (!strcasecmp(mode, "rfc2833")) {
29107       ast_clear_flag(&p->flags[0], SIP_DTMF);
29108       ast_set_flag(&p->flags[0], SIP_DTMF_RFC2833);
29109       p->jointnoncodeccapability |= AST_RTP_DTMF;
29110    } else if (!strcasecmp(mode, "inband")) {
29111       ast_clear_flag(&p->flags[0], SIP_DTMF);
29112       ast_set_flag(&p->flags[0], SIP_DTMF_INBAND);
29113       p->jointnoncodeccapability &= ~AST_RTP_DTMF;
29114    } else {
29115       ast_log(LOG_WARNING, "I don't know about this dtmf mode: %s\n", mode);
29116    }
29117    if (p->rtp)
29118       ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_DTMF, ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
29119    if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) ||
29120        (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO)) {
29121       enable_dsp_detect(p);
29122    } else {
29123       disable_dsp_detect(p);
29124    }
29125    sip_pvt_unlock(p);
29126    ast_channel_unlock(chan);
29127    return 0;
29128 }
29129 
29130 /*! \brief Add a SIP header to an outbound INVITE */
29131 static int sip_addheader(struct ast_channel *chan, const char *data)
29132 {
29133    int no = 0;
29134    int ok = FALSE;
29135    char varbuf[30];
29136    const char *inbuf = data;
29137    char *subbuf;
29138    
29139    if (ast_strlen_zero(inbuf)) {
29140       ast_log(LOG_WARNING, "This application requires the argument: Header\n");
29141       return 0;
29142    }
29143    ast_channel_lock(chan);
29144 
29145    /* Check for headers */
29146    while (!ok && no <= 50) {
29147       no++;
29148       snprintf(varbuf, sizeof(varbuf), "__SIPADDHEADER%.2d", no);
29149 
29150       /* Compare without the leading underscores */
29151       if ((pbx_builtin_getvar_helper(chan, (const char *) varbuf + 2) == (const char *) NULL)) {
29152          ok = TRUE;
29153       }
29154    }
29155    if (ok) {
29156       size_t len = strlen(inbuf);
29157       subbuf = alloca(len + 1);
29158       ast_get_encoded_str(inbuf, subbuf, len + 1);
29159       pbx_builtin_setvar_helper(chan, varbuf, subbuf);
29160       if (sipdebug) {
29161          ast_debug(1, "SIP Header added \"%s\" as %s\n", inbuf, varbuf);
29162       }
29163    } else {
29164       ast_log(LOG_WARNING, "Too many SIP headers added, max 50\n");
29165    }
29166    ast_channel_unlock(chan);
29167    return 0;
29168 }
29169 
29170 /*! \brief Remove SIP headers added previously with SipAddHeader application */
29171 static int sip_removeheader(struct ast_channel *chan, const char *data)
29172 {
29173    struct ast_var_t *newvariable;
29174    struct varshead *headp;
29175    int removeall = 0;
29176    char *inbuf = (char *) data;
29177 
29178    if (ast_strlen_zero(inbuf)) {
29179       removeall = 1;
29180    }
29181    ast_channel_lock(chan);
29182 
29183    headp=&chan->varshead;
29184    AST_LIST_TRAVERSE_SAFE_BEGIN (headp, newvariable, entries) {
29185       if (strncasecmp(ast_var_name(newvariable), "SIPADDHEADER", strlen("SIPADDHEADER")) == 0) {
29186          if (removeall || (!strncasecmp(ast_var_value(newvariable),inbuf,strlen(inbuf)))) {
29187             if (sipdebug)
29188                ast_debug(1,"removing SIP Header \"%s\" as %s\n",
29189                   ast_var_value(newvariable),
29190                   ast_var_name(newvariable));
29191             AST_LIST_REMOVE_CURRENT(entries);
29192             ast_var_delete(newvariable);
29193          }
29194       }
29195    }
29196    AST_LIST_TRAVERSE_SAFE_END;
29197 
29198    ast_channel_unlock(chan);
29199    return 0;
29200 }
29201 
29202 /*! \brief Transfer call before connect with a 302 redirect
29203 \note Called by the transfer() dialplan application through the sip_transfer()
29204    pbx interface function if the call is in ringing state
29205 \todo Fix this function so that we wait for reply to the REFER and
29206    react to errors, denials or other issues the other end might have.
29207  */
29208 static int sip_sipredirect(struct sip_pvt *p, const char *dest)
29209 {
29210    char *cdest;
29211    char *extension, *domain;
29212 
29213    cdest = ast_strdupa(dest);
29214    
29215    extension = strsep(&cdest, "@");
29216    domain = strsep(&cdest, ":");
29217    if (ast_strlen_zero(extension)) {
29218       ast_log(LOG_ERROR, "Missing mandatory argument: extension\n");
29219       return 0;
29220    }
29221 
29222    /* we'll issue the redirect message here */
29223    if (!domain) {
29224       char *local_to_header;
29225       char to_header[256];
29226 
29227       ast_copy_string(to_header, get_header(&p->initreq, "To"), sizeof(to_header));
29228       if (ast_strlen_zero(to_header)) {
29229          ast_log(LOG_ERROR, "Cannot retrieve the 'To' header from the original SIP request!\n");
29230          return 0;
29231       }
29232       if (((local_to_header = strcasestr(to_header, "sip:")) || (local_to_header = strcasestr(to_header, "sips:")))
29233          && (local_to_header = strchr(local_to_header, '@'))) {
29234          char ldomain[256];
29235 
29236          memset(ldomain, 0, sizeof(ldomain));
29237          local_to_header++;
29238          /* This is okey because lhost and lport are as big as tmp */
29239          sscanf(local_to_header, "%256[^<>; ]", ldomain);
29240          if (ast_strlen_zero(ldomain)) {
29241             ast_log(LOG_ERROR, "Can't find the host address\n");
29242             return 0;
29243          }
29244          domain = ast_strdupa(ldomain);
29245       }
29246    }
29247 
29248    ast_string_field_build(p, our_contact, "Transfer <sip:%s@%s>", extension, domain);
29249    transmit_response_reliable(p, "302 Moved Temporarily", &p->initreq);
29250 
29251    sip_scheddestroy(p, SIP_TRANS_TIMEOUT);   /* Make sure we stop send this reply. */
29252    sip_alreadygone(p);
29253 
29254    if (p->owner) {
29255       enum ast_control_transfer message = AST_TRANSFER_SUCCESS;
29256       ast_queue_control_data(p->owner, AST_CONTROL_TRANSFER, &message, sizeof(message));
29257    }
29258    /* hangup here */
29259    return 0;
29260 }
29261 
29262 static int sip_is_xml_parsable(void)
29263 {
29264 #ifdef HAVE_LIBXML2
29265    return TRUE;
29266 #else
29267    return FALSE;
29268 #endif
29269 }
29270 
29271 /*! \brief Send a poke to all known peers */
29272 static void sip_poke_all_peers(void)
29273 {
29274    int ms = 0, num = 0;
29275    struct ao2_iterator i;
29276    struct sip_peer *peer;
29277 
29278    if (!speerobjs) { /* No peers, just give up */
29279       return;
29280    }
29281 
29282    i = ao2_iterator_init(peers, 0);
29283    while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
29284       ao2_lock(peer);
29285       if (num == global_qualify_peers) {
29286          ms += global_qualify_gap;
29287          num = 0;
29288       } else {
29289          num++;
29290       }
29291       AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched, ms, sip_poke_peer_s, peer,
29292             unref_peer(_data, "removing poke peer ref"),
29293             unref_peer(peer, "removing poke peer ref"),
29294             ref_peer(peer, "adding poke peer ref"));
29295       ao2_unlock(peer);
29296       unref_peer(peer, "toss iterator peer ptr");
29297    }
29298    ao2_iterator_destroy(&i);
29299 }
29300 
29301 /*! \brief Send all known registrations */
29302 static void sip_send_all_registers(void)
29303 {
29304    int ms;
29305    int regspacing;
29306    if (!regobjs)
29307       return;
29308    regspacing = default_expiry * 1000/regobjs;
29309    if (regspacing > 100) {
29310       regspacing = 100;
29311    }
29312    ms = regspacing;
29313    ASTOBJ_CONTAINER_TRAVERSE(&regl, 1, do {
29314       ASTOBJ_WRLOCK(iterator);
29315       ms += regspacing;
29316       AST_SCHED_REPLACE_UNREF(iterator->expire, sched, ms, sip_reregister, iterator,
29317                         registry_unref(_data, "REPLACE sched del decs the refcount"),
29318                         registry_unref(iterator, "REPLACE sched add failure decs the refcount"),
29319                         registry_addref(iterator, "REPLACE sched add incs the refcount"));
29320       ASTOBJ_UNLOCK(iterator);
29321    } while (0)
29322    );
29323 }
29324 
29325 /*! \brief Send all MWI subscriptions */
29326 static void sip_send_all_mwi_subscriptions(void)
29327 {
29328    ASTOBJ_CONTAINER_TRAVERSE(&submwil, 1, do {
29329       ASTOBJ_WRLOCK(iterator);
29330       AST_SCHED_DEL(sched, iterator->resub);
29331       if ((iterator->resub = ast_sched_add(sched, 1, sip_subscribe_mwi_do, ASTOBJ_REF(iterator))) < 0) {
29332          ASTOBJ_UNREF(iterator, sip_subscribe_mwi_destroy);
29333       }
29334       ASTOBJ_UNLOCK(iterator);
29335    } while (0));
29336 }
29337 
29338 /* SRTP */
29339 static int setup_srtp(struct sip_srtp **srtp)
29340 {
29341    if (!ast_rtp_engine_srtp_is_registered()) {
29342       ast_log(LOG_ERROR, "No SRTP module loaded, can't setup SRTP session.\n");
29343       return -1;
29344    }
29345 
29346    if (!(*srtp = sip_srtp_alloc())) { /* Allocate SRTP data structure */
29347       return -1;
29348    }
29349 
29350    return 0;
29351 }
29352 
29353 static int process_crypto(struct sip_pvt *p, struct ast_rtp_instance *rtp, struct sip_srtp **srtp, const char *a)
29354 {
29355    /* If no RTP instance exists for this media stream don't bother processing the crypto line */
29356    if (!rtp) {
29357       ast_debug(3, "Received offer with crypto line for media stream that is not enabled\n");
29358       return FALSE;
29359    }
29360 
29361    if (strncasecmp(a, "crypto:", 7)) {
29362       return FALSE;
29363    }
29364    if (!*srtp) {
29365       if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
29366          ast_log(LOG_WARNING, "Ignoring unexpected crypto attribute in SDP answer\n");
29367          return FALSE;
29368       }
29369 
29370       if (setup_srtp(srtp) < 0) {
29371          return FALSE;
29372       }
29373    }
29374 
29375    /* For now, when we receive an INVITE just take the first successful crypto line */
29376    if ((*srtp)->crypto && !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
29377       ast_debug(3, "We've already processed a crypto attribute, skipping '%s'\n", a);
29378       return FALSE;
29379    }
29380 
29381    if (!(*srtp)->crypto && !((*srtp)->crypto = sdp_crypto_setup())) {
29382       return FALSE;
29383    }
29384 
29385    if (sdp_crypto_process((*srtp)->crypto, a, rtp) < 0) {
29386       return FALSE;
29387    }
29388 
29389    ast_set_flag(*srtp, SRTP_CRYPTO_OFFER_OK);
29390 
29391    return TRUE;
29392 }
29393 
29394 /*! \brief Reload module */
29395 static int sip_do_reload(enum channelreloadreason reason)
29396 {
29397    time_t start_poke, end_poke;
29398    
29399    reload_config(reason);
29400    ast_sched_dump(sched);
29401 
29402    start_poke = time(0);
29403    /* Prune peers who still are supposed to be deleted */
29404    unlink_marked_peers_from_tables();
29405 
29406    ast_debug(4, "--------------- Done destroying pruned peers\n");
29407 
29408    /* Send qualify (OPTIONS) to all peers */
29409    sip_poke_all_peers();
29410 
29411    /* Register with all services */
29412    sip_send_all_registers();
29413 
29414    sip_send_all_mwi_subscriptions();
29415 
29416    end_poke = time(0);
29417    
29418    ast_debug(4, "do_reload finished. peer poke/prune reg contact time = %d sec.\n", (int)(end_poke-start_poke));
29419 
29420    ast_debug(4, "--------------- SIP reload done\n");
29421 
29422    return 0;
29423 }
29424 
29425 /*! \brief Force reload of module from cli */
29426 static char *sip_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
29427 {
29428    
29429    switch (cmd) {
29430    case CLI_INIT:
29431       e->command = "sip reload";
29432       e->usage =
29433          "Usage: sip reload\n"
29434          "       Reloads SIP configuration from sip.conf\n";
29435       return NULL;
29436    case CLI_GENERATE:
29437       return NULL;
29438    }
29439 
29440    ast_mutex_lock(&sip_reload_lock);
29441    if (sip_reloading) {
29442       ast_verbose("Previous SIP reload not yet done\n");
29443    } else {
29444       sip_reloading = TRUE;
29445       sip_reloadreason = (a && a->fd) ? CHANNEL_CLI_RELOAD : CHANNEL_MODULE_RELOAD;
29446    }
29447    ast_mutex_unlock(&sip_reload_lock);
29448    restart_monitor();
29449 
29450    return CLI_SUCCESS;
29451 }
29452 
29453 /*! \brief  Part of Asterisk module interface */
29454 static int reload(void)
29455 {
29456    if (sip_reload(0, 0, NULL))
29457       return 0;
29458    return 1;
29459 }
29460 
29461 /*! \brief  Return the first entry from ast_sockaddr_resolve filtered by address family
29462  *
29463  * \warn Using this function probably means you have a faulty design.
29464  */
29465 static int ast_sockaddr_resolve_first_af(struct ast_sockaddr *addr,
29466                   const char* name, int flag, int family)
29467 {
29468    struct ast_sockaddr *addrs;
29469    int addrs_cnt;
29470 
29471    addrs_cnt = ast_sockaddr_resolve(&addrs, name, flag, family);
29472    if (addrs_cnt <= 0) {
29473       return 1;
29474    }
29475    if (addrs_cnt > 1) {
29476       ast_debug(1, "Multiple addresses, using the first one only\n");
29477    }
29478 
29479    ast_sockaddr_copy(addr, &addrs[0]);
29480 
29481    ast_free(addrs);
29482    return 0;
29483 }
29484 
29485 /*! \brief  Return the first entry from ast_sockaddr_resolve filtered by family of binddaddr
29486  *
29487  * \warn Using this function probably means you have a faulty design.
29488  */
29489 static int ast_sockaddr_resolve_first(struct ast_sockaddr *addr,
29490                   const char* name, int flag)
29491 {
29492    return ast_sockaddr_resolve_first_af(addr, name, flag, get_address_family_filter(&bindaddr));
29493 }
29494 
29495 /*! \brief
29496  * \note The only member of the peer used here is the name field
29497  */
29498 static int peer_hash_cb(const void *obj, const int flags)
29499 {
29500    const struct sip_peer *peer = obj;
29501 
29502    return ast_str_case_hash(peer->name);
29503 }
29504 
29505 /*!
29506  * \note The only member of the peer used here is the name field
29507  */
29508 static int peer_cmp_cb(void *obj, void *arg, int flags)
29509 {
29510    struct sip_peer *peer = obj, *peer2 = arg;
29511 
29512    return !strcasecmp(peer->name, peer2->name) ? CMP_MATCH | CMP_STOP : 0;
29513 }
29514 
29515 /*!
29516  * Hash function based on the the peer's ip address.  For IPv6, we use the end
29517  * of the address.
29518  * \todo Find a better hashing function
29519  */
29520 static int peer_iphash_cb(const void *obj, const int flags)
29521 {
29522    const struct sip_peer *peer = obj;
29523    int ret = 0;
29524 
29525    if (ast_sockaddr_isnull(&peer->addr)) {
29526       ast_log(LOG_ERROR, "Empty address\n");
29527    }
29528 
29529    ret = ast_sockaddr_hash(&peer->addr);
29530 
29531    if (ret < 0) {
29532       ret = -ret;
29533    }
29534 
29535    return ret;
29536 }
29537 
29538 /*!
29539  * Match Peers by IP and Port number.
29540  *
29541  * This function has two modes.
29542  *  - If the peer arg does not have INSECURE_PORT set, then we will only return
29543  *    a match for a peer that matches both the IP and port.
29544  *  - If the peer arg does have the INSECURE_PORT flag set, then we will only
29545  *    return a match for a peer that matches the IP and has insecure=port
29546  *    in its configuration.
29547  *
29548  * This callback will be used twice when doing peer matching.  There is a first
29549  * pass for full IP+port matching, and a second pass in case there is a match
29550  * that meets the insecure=port criteria.
29551  *
29552  * \note Connections coming in over TCP or TLS should never be matched by port.
29553  *
29554  * \note the peer's addr struct provides to fields combined to make a key: the sin_addr.s_addr and sin_port fields.
29555  */
29556 static int peer_ipcmp_cb(void *obj, void *arg, int flags)
29557 {
29558    struct sip_peer *peer = obj, *peer2 = arg;
29559 
29560    if (ast_sockaddr_cmp_addr(&peer->addr, &peer2->addr)) {
29561       /* IP doesn't match */
29562       return 0;
29563    }
29564 
29565    /* We matched the IP, check to see if we need to match by port as well. */
29566    if ((peer->transports & peer2->transports) & (SIP_TRANSPORT_TLS | SIP_TRANSPORT_TCP)) {
29567       /* peer matching on port is not possible with TCP/TLS */
29568       return CMP_MATCH | CMP_STOP;
29569    } else if (ast_test_flag(&peer2->flags[0], SIP_INSECURE_PORT)) {
29570       /* We are allowing match without port for peers configured that
29571        * way in this pass through the peers. */
29572       return ast_test_flag(&peer->flags[0], SIP_INSECURE_PORT) ?
29573             (CMP_MATCH | CMP_STOP) : 0;
29574    }
29575 
29576    /* Now only return a match if the port matches, as well. */
29577    return ast_sockaddr_port(&peer->addr) == ast_sockaddr_port(&peer2->addr) ?
29578          (CMP_MATCH | CMP_STOP) : 0;
29579 }
29580 
29581 
29582 static int threadt_hash_cb(const void *obj, const int flags)
29583 {
29584    const struct sip_threadinfo *th = obj;
29585 
29586    return ast_sockaddr_hash(&th->tcptls_session->remote_address);
29587 }
29588 
29589 static int threadt_cmp_cb(void *obj, void *arg, int flags)
29590 {
29591    struct sip_threadinfo *th = obj, *th2 = arg;
29592 
29593    return (th->tcptls_session == th2->tcptls_session) ? CMP_MATCH | CMP_STOP : 0;
29594 }
29595 
29596 /*!
29597  * \note The only member of the dialog used here callid string
29598  */
29599 static int dialog_hash_cb(const void *obj, const int flags)
29600 {
29601    const struct sip_pvt *pvt = obj;
29602 
29603    return ast_str_case_hash(pvt->callid);
29604 }
29605 
29606 /*!
29607  * \note Same as dialog_cmp_cb, except without the CMP_STOP on match
29608  */
29609 static int dialog_find_multiple(void *obj, void *arg, int flags)
29610 {
29611    struct sip_pvt *pvt = obj, *pvt2 = arg;
29612 
29613    return !strcasecmp(pvt->callid, pvt2->callid) ? CMP_MATCH : 0;
29614 }
29615 
29616 /*!
29617  * \note The only member of the dialog used here callid string
29618  */
29619 static int dialog_cmp_cb(void *obj, void *arg, int flags)
29620 {
29621    struct sip_pvt *pvt = obj, *pvt2 = arg;
29622 
29623    return !strcasecmp(pvt->callid, pvt2->callid) ? CMP_MATCH | CMP_STOP : 0;
29624 }
29625 
29626 /*! \brief SIP Cli commands definition */
29627 static struct ast_cli_entry cli_sip[] = {
29628    AST_CLI_DEFINE(sip_show_channels, "List active SIP channels or subscriptions"),
29629    AST_CLI_DEFINE(sip_show_channelstats, "List statistics for active SIP channels"),
29630    AST_CLI_DEFINE(sip_show_domains, "List our local SIP domains"),
29631    AST_CLI_DEFINE(sip_show_inuse, "List all inuse/limits"),
29632    AST_CLI_DEFINE(sip_show_objects, "List all SIP object allocations"),
29633    AST_CLI_DEFINE(sip_show_peers, "List defined SIP peers"),
29634    AST_CLI_DEFINE(sip_show_registry, "List SIP registration status"),
29635    AST_CLI_DEFINE(sip_unregister, "Unregister (force expiration) a SIP peer from the registry"),
29636    AST_CLI_DEFINE(sip_show_settings, "Show SIP global settings"),
29637    AST_CLI_DEFINE(sip_show_mwi, "Show MWI subscriptions"),
29638    AST_CLI_DEFINE(sip_cli_notify, "Send a notify packet to a SIP peer"),
29639    AST_CLI_DEFINE(sip_show_channel, "Show detailed SIP channel info"),
29640    AST_CLI_DEFINE(sip_show_history, "Show SIP dialog history"),
29641    AST_CLI_DEFINE(sip_show_peer, "Show details on specific SIP peer"),
29642    AST_CLI_DEFINE(sip_show_users, "List defined SIP users"),
29643    AST_CLI_DEFINE(sip_show_user, "Show details on specific SIP user"),
29644    AST_CLI_DEFINE(sip_qualify_peer, "Send an OPTIONS packet to a peer"),
29645    AST_CLI_DEFINE(sip_show_sched, "Present a report on the status of the scheduler queue"),
29646    AST_CLI_DEFINE(sip_prune_realtime, "Prune cached Realtime users/peers"),
29647    AST_CLI_DEFINE(sip_do_debug, "Enable/Disable SIP debugging"),
29648    AST_CLI_DEFINE(sip_set_history, "Enable/Disable SIP history"),
29649    AST_CLI_DEFINE(sip_reload, "Reload SIP configuration"),
29650    AST_CLI_DEFINE(sip_show_tcp, "List TCP Connections")
29651 };
29652 
29653 /*! \brief SIP test registration */
29654 static void sip_register_tests(void)
29655 {
29656    sip_config_parser_register_tests();
29657    sip_request_parser_register_tests();
29658    sip_dialplan_function_register_tests();
29659 }
29660 
29661 /*! \brief SIP test registration */
29662 static void sip_unregister_tests(void)
29663 {
29664    sip_config_parser_unregister_tests();
29665    sip_request_parser_unregister_tests();
29666    sip_dialplan_function_unregister_tests();
29667 }
29668 
29669 #ifdef TEST_FRAMEWORK
29670 AST_TEST_DEFINE(test_sip_mwi_subscribe_parse)
29671 {
29672    int found = 0;
29673    enum ast_test_result_state res = AST_TEST_PASS;
29674    const char *mwi1 = "1234@mysipprovider.com/1234";
29675    const char *mwi2 = "1234:password@mysipprovider.com/1234";
29676    const char *mwi3 = "1234:password@mysipprovider.com:5061/1234";
29677    const char *mwi4 = "1234:password:authuser@mysipprovider.com/1234";
29678    const char *mwi5 = "1234:password:authuser@mysipprovider.com:5061/1234";
29679    const char *mwi6 = "1234:password";
29680 
29681    switch (cmd) {
29682    case TEST_INIT:
29683       info->name = "sip_mwi_subscribe_parse_test";
29684       info->category = "/channels/chan_sip/";
29685       info->summary = "SIP MWI subscribe line parse unit test";
29686       info->description =
29687          "Tests the parsing of mwi subscription lines (e.g., mwi => from sip.conf)";
29688       return AST_TEST_NOT_RUN;
29689    case TEST_EXECUTE:
29690       break;
29691    }
29692 
29693    if (sip_subscribe_mwi(mwi1, 1)) {
29694       res = AST_TEST_FAIL;
29695    } else {
29696       found = 0;
29697       res = AST_TEST_FAIL;
29698       ASTOBJ_CONTAINER_TRAVERSE(&submwil, 1, do {
29699          ASTOBJ_WRLOCK(iterator);
29700          if (
29701             !strcmp(iterator->hostname, "mysipprovider.com") &&
29702             !strcmp(iterator->username, "1234") &&
29703             !strcmp(iterator->secret, "") &&
29704             !strcmp(iterator->authuser, "") &&
29705             !strcmp(iterator->mailbox, "1234") &&
29706             iterator->portno == 0) {
29707             found = 1;
29708             res = AST_TEST_PASS;
29709          }
29710          ASTOBJ_UNLOCK(iterator);
29711       } while(0));
29712       if (!found) {
29713          ast_test_status_update(test, "sip_subscribe_mwi test 1 failed\n");
29714       }
29715    }
29716 
29717    if (sip_subscribe_mwi(mwi2, 1)) {
29718       res = AST_TEST_FAIL;
29719    } else {
29720       found = 0;
29721       res = AST_TEST_FAIL;
29722       ASTOBJ_CONTAINER_TRAVERSE(&submwil, 1, do {
29723          ASTOBJ_WRLOCK(iterator);
29724          if (
29725             !strcmp(iterator->hostname, "mysipprovider.com") &&
29726             !strcmp(iterator->username, "1234") &&
29727             !strcmp(iterator->secret, "password") &&
29728             !strcmp(iterator->authuser, "") &&
29729             !strcmp(iterator->mailbox, "1234") &&
29730             iterator->portno == 0) {
29731             found = 1;
29732             res = AST_TEST_PASS;
29733          }
29734          ASTOBJ_UNLOCK(iterator);
29735       } while(0));
29736       if (!found) {
29737          ast_test_status_update(test, "sip_subscribe_mwi test 2 failed\n");
29738       }
29739    }
29740 
29741    if (sip_subscribe_mwi(mwi3, 1)) {
29742       res = AST_TEST_FAIL;
29743    } else {
29744       found = 0;
29745       res = AST_TEST_FAIL;
29746       ASTOBJ_CONTAINER_TRAVERSE(&submwil, 1, do {
29747          ASTOBJ_WRLOCK(iterator);
29748          if (
29749             !strcmp(iterator->hostname, "mysipprovider.com") &&
29750             !strcmp(iterator->username, "1234") &&
29751             !strcmp(iterator->secret, "password") &&
29752             !strcmp(iterator->authuser, "") &&
29753             !strcmp(iterator->mailbox, "1234") &&
29754             iterator->portno == 5061) {
29755             found = 1;
29756             res = AST_TEST_PASS;
29757          }
29758          ASTOBJ_UNLOCK(iterator);
29759       } while(0));
29760       if (!found) {
29761          ast_test_status_update(test, "sip_subscribe_mwi test 3 failed\n");
29762       }
29763    }
29764 
29765    if (sip_subscribe_mwi(mwi4, 1)) {
29766       res = AST_TEST_FAIL;
29767    } else {
29768       found = 0;
29769       res = AST_TEST_FAIL;
29770       ASTOBJ_CONTAINER_TRAVERSE(&submwil, 1, do {
29771          ASTOBJ_WRLOCK(iterator);
29772          if (
29773             !strcmp(iterator->hostname, "mysipprovider.com") &&
29774             !strcmp(iterator->username, "1234") &&
29775             !strcmp(iterator->secret, "password") &&
29776             !strcmp(iterator->authuser, "authuser") &&
29777             !strcmp(iterator->mailbox, "1234") &&
29778             iterator->portno == 0) {
29779             found = 1;
29780             res = AST_TEST_PASS;
29781          }
29782          ASTOBJ_UNLOCK(iterator);
29783       } while(0));
29784       if (!found) {
29785          ast_test_status_update(test, "sip_subscribe_mwi test 4 failed\n");
29786       }
29787    }
29788 
29789    if (sip_subscribe_mwi(mwi5, 1)) {
29790       res = AST_TEST_FAIL;
29791    } else {
29792       found = 0;
29793       res = AST_TEST_FAIL;
29794       ASTOBJ_CONTAINER_TRAVERSE(&submwil, 1, do {
29795          ASTOBJ_WRLOCK(iterator);
29796          if (
29797             !strcmp(iterator->hostname, "mysipprovider.com") &&
29798             !strcmp(iterator->username, "1234") &&
29799             !strcmp(iterator->secret, "password") &&
29800             !strcmp(iterator->authuser, "authuser") &&
29801             !strcmp(iterator->mailbox, "1234") &&
29802             iterator->portno == 5061) {
29803             found = 1;
29804             res = AST_TEST_PASS;
29805          }
29806          ASTOBJ_UNLOCK(iterator);
29807       } while(0));
29808       if (!found) {
29809          ast_test_status_update(test, "sip_subscribe_mwi test 5 failed\n");
29810       }
29811    }
29812    
29813    if (sip_subscribe_mwi(mwi6, 1)) {
29814       res = AST_TEST_PASS;
29815    } else {
29816       res = AST_TEST_FAIL;
29817    }
29818    return res;
29819 }
29820 
29821 AST_TEST_DEFINE(test_sip_peers_get)
29822 {
29823    struct sip_peer *peer;
29824    struct ast_data *node;
29825    struct ast_data_query query = {
29826       .path = "/asterisk/channel/sip/peers",
29827       .search = "peers/peer/name=test_peer_data_provider"
29828    };
29829 
29830    switch (cmd) {
29831       case TEST_INIT:
29832          info->name = "sip_peers_get_data_test";
29833          info->category = "/main/data/sip/peers/";
29834          info->summary = "SIP peers data providers unit test";
29835          info->description =
29836             "Tests whether the SIP peers data provider implementation works as expected.";
29837          return AST_TEST_NOT_RUN;
29838       case TEST_EXECUTE:
29839          break;
29840    }
29841 
29842    /* Create the peer that we will retrieve. */
29843    peer = build_peer("test_peer_data_provider", NULL, NULL, 0, 0);
29844    if (!peer) {
29845       return AST_TEST_FAIL;
29846    }
29847    peer->type = SIP_TYPE_USER;
29848    peer->call_limit = 10;
29849    ao2_link(peers, peer);
29850 
29851    /* retrieve the chan_sip/peers tree and check the created peer. */
29852    node = ast_data_get(&query);
29853    if (!node) {
29854       ao2_unlink(peers, peer);
29855       ao2_ref(peer, -1);
29856       return AST_TEST_FAIL;
29857    }
29858 
29859    /* compare item. */
29860    if (strcmp(ast_data_retrieve_string(node, "peer/name"), "test_peer_data_provider")) {
29861       ao2_unlink(peers, peer);
29862       ao2_ref(peer, -1);
29863       ast_data_free(node);
29864       return AST_TEST_FAIL;
29865    }
29866 
29867    if (strcmp(ast_data_retrieve_string(node, "peer/type"), "user")) {
29868       ao2_unlink(peers, peer);
29869       ao2_ref(peer, -1);
29870       ast_data_free(node);
29871       return AST_TEST_FAIL;
29872    }
29873 
29874    if (ast_data_retrieve_int(node, "peer/call_limit") != 10) {
29875       ao2_unlink(peers, peer);
29876       ao2_ref(peer, -1);
29877       ast_data_free(node);
29878       return AST_TEST_FAIL;
29879    }
29880 
29881    /* release resources */
29882    ast_data_free(node);
29883 
29884    ao2_unlink(peers, peer);
29885    ao2_ref(peer, -1);
29886 
29887    return AST_TEST_PASS;
29888 }
29889 
29890 #endif
29891 
29892 #define DATA_EXPORT_SIP_PEER(MEMBER)            \
29893    MEMBER(sip_peer, name, AST_DATA_STRING)         \
29894    MEMBER(sip_peer, secret, AST_DATA_PASSWORD)     \
29895    MEMBER(sip_peer, md5secret, AST_DATA_PASSWORD)     \
29896    MEMBER(sip_peer, remotesecret, AST_DATA_PASSWORD)  \
29897    MEMBER(sip_peer, context, AST_DATA_STRING)      \
29898    MEMBER(sip_peer, subscribecontext, AST_DATA_STRING)   \
29899    MEMBER(sip_peer, username, AST_DATA_STRING)     \
29900    MEMBER(sip_peer, accountcode, AST_DATA_STRING)     \
29901    MEMBER(sip_peer, tohost, AST_DATA_STRING)    \
29902    MEMBER(sip_peer, regexten, AST_DATA_STRING)     \
29903    MEMBER(sip_peer, fromuser, AST_DATA_STRING)     \
29904    MEMBER(sip_peer, fromdomain, AST_DATA_STRING)      \
29905    MEMBER(sip_peer, fullcontact, AST_DATA_STRING)     \
29906    MEMBER(sip_peer, cid_num, AST_DATA_STRING)      \
29907    MEMBER(sip_peer, cid_name, AST_DATA_STRING)     \
29908    MEMBER(sip_peer, vmexten, AST_DATA_STRING)      \
29909    MEMBER(sip_peer, language, AST_DATA_STRING)     \
29910    MEMBER(sip_peer, mohinterpret, AST_DATA_STRING)    \
29911    MEMBER(sip_peer, mohsuggest, AST_DATA_STRING)      \
29912    MEMBER(sip_peer, parkinglot, AST_DATA_STRING)      \
29913    MEMBER(sip_peer, useragent, AST_DATA_STRING)    \
29914    MEMBER(sip_peer, mwi_from, AST_DATA_STRING)     \
29915    MEMBER(sip_peer, engine, AST_DATA_STRING)    \
29916    MEMBER(sip_peer, unsolicited_mailbox, AST_DATA_STRING)   \
29917    MEMBER(sip_peer, is_realtime, AST_DATA_BOOLEAN)    \
29918    MEMBER(sip_peer, host_dynamic, AST_DATA_BOOLEAN)   \
29919    MEMBER(sip_peer, autoframing, AST_DATA_BOOLEAN)    \
29920    MEMBER(sip_peer, inUse, AST_DATA_INTEGER)    \
29921    MEMBER(sip_peer, inRinging, AST_DATA_INTEGER)      \
29922    MEMBER(sip_peer, onHold, AST_DATA_INTEGER)      \
29923    MEMBER(sip_peer, call_limit, AST_DATA_INTEGER)     \
29924    MEMBER(sip_peer, t38_maxdatagram, AST_DATA_INTEGER)   \
29925    MEMBER(sip_peer, maxcallbitrate, AST_DATA_INTEGER) \
29926    MEMBER(sip_peer, rtptimeout, AST_DATA_SECONDS)     \
29927    MEMBER(sip_peer, rtpholdtimeout, AST_DATA_SECONDS) \
29928    MEMBER(sip_peer, rtpkeepalive, AST_DATA_SECONDS)   \
29929    MEMBER(sip_peer, lastms, AST_DATA_MILLISECONDS)    \
29930    MEMBER(sip_peer, maxms, AST_DATA_MILLISECONDS)     \
29931    MEMBER(sip_peer, qualifyfreq, AST_DATA_MILLISECONDS)  \
29932    MEMBER(sip_peer, timer_t1, AST_DATA_MILLISECONDS)  \
29933    MEMBER(sip_peer, timer_b, AST_DATA_MILLISECONDS)
29934 
29935 AST_DATA_STRUCTURE(sip_peer, DATA_EXPORT_SIP_PEER);
29936 
29937 static int peers_data_provider_get(const struct ast_data_search *search,
29938    struct ast_data *data_root)
29939 {
29940    struct sip_peer *peer;
29941    struct ao2_iterator i;
29942    struct ast_data *data_peer, *data_peer_mailboxes = NULL, *data_peer_mailbox, *enum_node;
29943    struct ast_data *data_sip_options;
29944    int total_mailboxes, x;
29945    struct sip_mailbox *mailbox;
29946 
29947    i = ao2_iterator_init(peers, 0);
29948    while ((peer = ao2_iterator_next(&i))) {
29949       ao2_lock(peer);
29950 
29951       data_peer = ast_data_add_node(data_root, "peer");
29952       if (!data_peer) {
29953          ao2_unlock(peer);
29954          ao2_ref(peer, -1);
29955          continue;
29956       }
29957 
29958       ast_data_add_structure(sip_peer, data_peer, peer);
29959 
29960       /* transfer mode */
29961       enum_node = ast_data_add_node(data_peer, "allowtransfer");
29962       if (!enum_node) {
29963          continue;
29964       }
29965       ast_data_add_str(enum_node, "text", transfermode2str(peer->allowtransfer));
29966       ast_data_add_int(enum_node, "value", peer->allowtransfer);
29967 
29968       /* transports */
29969       ast_data_add_str(data_peer, "transports", get_transport_list(peer->transports));
29970 
29971       /* peer type */
29972       if ((peer->type & SIP_TYPE_USER) && (peer->type & SIP_TYPE_PEER)) {
29973          ast_data_add_str(data_peer, "type", "friend");
29974       } else if (peer->type & SIP_TYPE_PEER) {
29975          ast_data_add_str(data_peer, "type", "peer");
29976       } else if (peer->type & SIP_TYPE_USER) {
29977          ast_data_add_str(data_peer, "type", "user");
29978       }
29979 
29980       /* mailboxes */
29981       total_mailboxes = 0;
29982       AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
29983          if (!total_mailboxes) {
29984             data_peer_mailboxes = ast_data_add_node(data_peer, "mailboxes");
29985             if (!data_peer_mailboxes) {
29986                break;
29987             }
29988             total_mailboxes++;
29989          }
29990 
29991          data_peer_mailbox = ast_data_add_node(data_peer_mailboxes, "mailbox");
29992          if (!data_peer_mailbox) {
29993             continue;
29994          }
29995          ast_data_add_str(data_peer_mailbox, "mailbox", mailbox->mailbox);
29996          ast_data_add_str(data_peer_mailbox, "context", mailbox->context);
29997       }
29998 
29999       /* amaflags */
30000       enum_node = ast_data_add_node(data_peer, "amaflags");
30001       if (!enum_node) {
30002          continue;
30003       }
30004       ast_data_add_int(enum_node, "value", peer->amaflags);
30005       ast_data_add_str(enum_node, "text", ast_cdr_flags2str(peer->amaflags));
30006 
30007       /* sip options */
30008       data_sip_options = ast_data_add_node(data_peer, "sipoptions");
30009       if (!data_sip_options) {
30010          continue;
30011       }
30012       for (x = 0 ; x < ARRAY_LEN(sip_options); x++) {
30013          ast_data_add_bool(data_sip_options, sip_options[x].text, peer->sipoptions & sip_options[x].id);
30014       }
30015 
30016       /* callingpres */
30017       enum_node = ast_data_add_node(data_peer, "callingpres");
30018       if (!enum_node) {
30019          continue;
30020       }
30021       ast_data_add_int(enum_node, "value", peer->callingpres);
30022       ast_data_add_str(enum_node, "text", ast_describe_caller_presentation(peer->callingpres));
30023 
30024       /* codecs */
30025       ast_data_add_codecs(data_peer, "codecs", peer->capability);
30026 
30027       if (!ast_data_search_match(search, data_peer)) {
30028          ast_data_remove_node(data_root, data_peer);
30029       }
30030 
30031       ao2_unlock(peer);
30032       ao2_ref(peer, -1);
30033    }
30034    ao2_iterator_destroy(&i);
30035 
30036    return 0;
30037 }
30038 
30039 static const struct ast_data_handler peers_data_provider = {
30040    .version = AST_DATA_HANDLER_VERSION,
30041    .get = peers_data_provider_get
30042 };
30043 
30044 static const struct ast_data_entry sip_data_providers[] = {
30045    AST_DATA_ENTRY("asterisk/channel/sip/peers", &peers_data_provider),
30046 };
30047 
30048 /*! \brief PBX load module - initialization */
30049 static int load_module(void)
30050 {
30051    ast_verbose("SIP channel loading...\n");
30052 
30053    /* the fact that ao2_containers can't resize automatically is a major worry! */
30054    /* if the number of objects gets above MAX_XXX_BUCKETS, things will slow down */
30055    peers = ao2_t_container_alloc(HASH_PEER_SIZE, peer_hash_cb, peer_cmp_cb, "allocate peers");
30056    peers_by_ip = ao2_t_container_alloc(HASH_PEER_SIZE, peer_iphash_cb, peer_ipcmp_cb, "allocate peers_by_ip");
30057    dialogs = ao2_t_container_alloc(HASH_DIALOG_SIZE, dialog_hash_cb, dialog_cmp_cb, "allocate dialogs");
30058    dialogs_to_destroy = ao2_t_container_alloc(1, NULL, NULL, "allocate dialogs_to_destroy");
30059    threadt = ao2_t_container_alloc(HASH_DIALOG_SIZE, threadt_hash_cb, threadt_cmp_cb, "allocate threadt table");
30060    if (!peers || !peers_by_ip || !dialogs || !dialogs_to_destroy || !threadt) {
30061       ast_log(LOG_ERROR, "Unable to create primary SIP container(s)\n");
30062       return AST_MODULE_LOAD_FAILURE;
30063    }
30064 
30065    ASTOBJ_CONTAINER_INIT(&regl); /* Registry object list -- not searched for anything */
30066    ASTOBJ_CONTAINER_INIT(&submwil); /* MWI subscription object list */
30067 
30068    if (!(sched = sched_context_create())) {
30069       ast_log(LOG_ERROR, "Unable to create scheduler context\n");
30070       return AST_MODULE_LOAD_FAILURE;
30071    }
30072 
30073    if (!(io = io_context_create())) {
30074       ast_log(LOG_ERROR, "Unable to create I/O context\n");
30075       sched_context_destroy(sched);
30076       return AST_MODULE_LOAD_FAILURE;
30077    }
30078 
30079    sip_reloadreason = CHANNEL_MODULE_LOAD;
30080 
30081    can_parse_xml = sip_is_xml_parsable();
30082    if (reload_config(sip_reloadreason)) { /* Load the configuration from sip.conf */
30083       return AST_MODULE_LOAD_DECLINE;
30084    }
30085 
30086    /* Prepare the version that does not require DTMF BEGIN frames.
30087     * We need to use tricks such as memcpy and casts because the variable
30088     * has const fields.
30089     */
30090    memcpy(&sip_tech_info, &sip_tech, sizeof(sip_tech));
30091    memset((void *) &sip_tech_info.send_digit_begin, 0, sizeof(sip_tech_info.send_digit_begin));
30092 
30093    /* Make sure we can register our sip channel type */
30094    if (ast_channel_register(&sip_tech)) {
30095       ast_log(LOG_ERROR, "Unable to register channel type 'SIP'\n");
30096       io_context_destroy(io);
30097       sched_context_destroy(sched);
30098       return AST_MODULE_LOAD_FAILURE;
30099    }
30100 
30101 #ifdef TEST_FRAMEWORK
30102    AST_TEST_REGISTER(test_sip_peers_get);
30103    AST_TEST_REGISTER(test_sip_mwi_subscribe_parse);
30104 #endif
30105 
30106    /* Register AstData providers */
30107    ast_data_register_multiple(sip_data_providers, ARRAY_LEN(sip_data_providers));
30108 
30109    /* Register all CLI functions for SIP */
30110    ast_cli_register_multiple(cli_sip, ARRAY_LEN(cli_sip));
30111 
30112    /* Tell the UDPTL subdriver that we're here */
30113    ast_udptl_proto_register(&sip_udptl);
30114 
30115    /* Tell the RTP engine about our RTP glue */
30116    ast_rtp_glue_register(&sip_rtp_glue);
30117 
30118    /* Register dialplan applications */
30119    ast_register_application_xml(app_dtmfmode, sip_dtmfmode);
30120    ast_register_application_xml(app_sipaddheader, sip_addheader);
30121    ast_register_application_xml(app_sipremoveheader, sip_removeheader);
30122 
30123    /* Register dialplan functions */
30124    ast_custom_function_register(&sip_header_function);
30125    ast_custom_function_register(&sippeer_function);
30126    ast_custom_function_register(&sipchaninfo_function);
30127    ast_custom_function_register(&checksipdomain_function);
30128 
30129    /* Register manager commands */
30130    ast_manager_register_xml("SIPpeers", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_sip_show_peers);
30131    ast_manager_register_xml("SIPshowpeer", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_sip_show_peer);
30132    ast_manager_register_xml("SIPqualifypeer", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_sip_qualify_peer);
30133    ast_manager_register_xml("SIPshowregistry", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_show_registry);
30134    ast_manager_register_xml("SIPnotify", EVENT_FLAG_SYSTEM, manager_sipnotify);
30135    sip_poke_all_peers();   
30136    sip_send_all_registers();
30137    sip_send_all_mwi_subscriptions();
30138    initialize_escs();
30139 
30140    if (sip_epa_register(&cc_epa_static_data)) {
30141       return AST_MODULE_LOAD_DECLINE;
30142    }
30143 
30144    if (sip_reqresp_parser_init() == -1) {
30145       ast_log(LOG_ERROR, "Unable to initialize the SIP request and response parser\n");
30146       return AST_MODULE_LOAD_DECLINE;
30147    }
30148 
30149    if (can_parse_xml) {
30150       /* SIP CC agents require the ability to parse XML PIDF bodies
30151        * in incoming PUBLISH requests
30152        */
30153       if (ast_cc_agent_register(&sip_cc_agent_callbacks)) {
30154          return AST_MODULE_LOAD_DECLINE;
30155       }
30156    }
30157    if (ast_cc_monitor_register(&sip_cc_monitor_callbacks)) {
30158       return AST_MODULE_LOAD_DECLINE;
30159    }
30160    if (!(sip_monitor_instances = ao2_container_alloc(37, sip_monitor_instance_hash_fn, sip_monitor_instance_cmp_fn))) {
30161       return AST_MODULE_LOAD_DECLINE;
30162    }
30163 
30164    /* And start the monitor for the first time */
30165    restart_monitor();
30166 
30167    ast_realtime_require_field(ast_check_realtime("sipregs") ? "sipregs" : "sippeers",
30168       "name", RQ_CHAR, 10,
30169       "ipaddr", RQ_CHAR, INET6_ADDRSTRLEN - 1,
30170       "port", RQ_UINTEGER2, 5,
30171       "regseconds", RQ_INTEGER4, 11,
30172       "defaultuser", RQ_CHAR, 10,
30173       "fullcontact", RQ_CHAR, 35,
30174       "regserver", RQ_CHAR, 20,
30175       "useragent", RQ_CHAR, 20,
30176       "lastms", RQ_INTEGER4, 11,
30177       SENTINEL);
30178 
30179 
30180    sip_register_tests();
30181    network_change_event_subscribe();
30182 
30183    return AST_MODULE_LOAD_SUCCESS;
30184 }
30185 
30186 /*! \brief PBX unload module API */
30187 static int unload_module(void)
30188 {
30189    struct sip_pvt *p;
30190    struct sip_threadinfo *th;
30191    struct ast_context *con;
30192    struct ao2_iterator i;
30193 
30194    network_change_event_unsubscribe();
30195 
30196    ast_sched_dump(sched);
30197    
30198    /* First, take us out of the channel type list */
30199    ast_channel_unregister(&sip_tech);
30200 
30201    /* Unregister dial plan functions */
30202    ast_custom_function_unregister(&sipchaninfo_function);
30203    ast_custom_function_unregister(&sippeer_function);
30204    ast_custom_function_unregister(&sip_header_function);
30205    ast_custom_function_unregister(&checksipdomain_function);
30206 
30207    /* Unregister dial plan applications */
30208    ast_unregister_application(app_dtmfmode);
30209    ast_unregister_application(app_sipaddheader);
30210    ast_unregister_application(app_sipremoveheader);
30211 
30212 #ifdef TEST_FRAMEWORK
30213    AST_TEST_UNREGISTER(test_sip_peers_get);
30214    AST_TEST_UNREGISTER(test_sip_mwi_subscribe_parse);
30215 #endif
30216    /* Unregister all the AstData providers */
30217    ast_data_unregister(NULL);
30218 
30219    /* Unregister CLI commands */
30220    ast_cli_unregister_multiple(cli_sip, ARRAY_LEN(cli_sip));
30221 
30222    /* Disconnect from UDPTL */
30223    ast_udptl_proto_unregister(&sip_udptl);
30224 
30225    /* Disconnect from RTP engine */
30226    ast_rtp_glue_unregister(&sip_rtp_glue);
30227 
30228    /* Unregister AMI actions */
30229    ast_manager_unregister("SIPpeers");
30230    ast_manager_unregister("SIPshowpeer");
30231    ast_manager_unregister("SIPqualifypeer");
30232    ast_manager_unregister("SIPshowregistry");
30233    ast_manager_unregister("SIPnotify");
30234    
30235    /* Kill TCP/TLS server threads */
30236    if (sip_tcp_desc.master) {
30237       ast_tcptls_server_stop(&sip_tcp_desc);
30238    }
30239    if (sip_tls_desc.master) {
30240       ast_tcptls_server_stop(&sip_tls_desc);
30241    }
30242 
30243    /* Kill all existing TCP/TLS threads */
30244    i = ao2_iterator_init(threadt, 0);
30245    while ((th = ao2_t_iterator_next(&i, "iterate through tcp threads for 'sip show tcp'"))) {
30246       pthread_t thread = th->threadid;
30247       th->stop = 1;
30248       pthread_kill(thread, SIGURG);
30249       pthread_join(thread, NULL);
30250       ao2_t_ref(th, -1, "decrement ref from iterator");
30251    }
30252    ao2_iterator_destroy(&i);
30253 
30254    /* Hangup all dialogs if they have an owner */
30255    i = ao2_iterator_init(dialogs, 0);
30256    while ((p = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
30257       if (p->owner)
30258          ast_softhangup(p->owner, AST_SOFTHANGUP_APPUNLOAD);
30259       ao2_t_ref(p, -1, "toss dialog ptr from iterator_next");
30260    }
30261    ao2_iterator_destroy(&i);
30262 
30263    unlink_all_peers_from_tables();
30264 
30265    ast_mutex_lock(&monlock);
30266    if (monitor_thread && (monitor_thread != AST_PTHREADT_STOP) && (monitor_thread != AST_PTHREADT_NULL)) {
30267       pthread_cancel(monitor_thread);
30268       pthread_kill(monitor_thread, SIGURG);
30269       pthread_join(monitor_thread, NULL);
30270    }
30271    monitor_thread = AST_PTHREADT_STOP;
30272    ast_mutex_unlock(&monlock);
30273 
30274    /* Destroy all the dialogs and free their memory */
30275    i = ao2_iterator_init(dialogs, 0);
30276    while ((p = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
30277       dialog_unlink_all(p);
30278       ao2_t_ref(p, -1, "throw away iterator result");
30279    }
30280    ao2_iterator_destroy(&i);
30281 
30282    /* Free memory for local network address mask */
30283    ast_free_ha(localaddr);
30284 
30285    ast_mutex_lock(&authl_lock);
30286    if (authl) {
30287       ao2_t_ref(authl, -1, "Removing global authentication");
30288       authl = NULL;
30289    }
30290    ast_mutex_unlock(&authl_lock);
30291 
30292    destroy_escs();
30293 
30294    if (default_tls_cfg.certfile) {
30295       ast_free(default_tls_cfg.certfile);
30296    }
30297    if (default_tls_cfg.pvtfile) {
30298       ast_free(default_tls_cfg.pvtfile);
30299    }
30300    if (default_tls_cfg.cipher) {
30301       ast_free(default_tls_cfg.cipher);
30302    }
30303    if (default_tls_cfg.cafile) {
30304       ast_free(default_tls_cfg.cafile);
30305    }
30306    if (default_tls_cfg.capath) {
30307       ast_free(default_tls_cfg.capath);
30308    }
30309 
30310    ASTOBJ_CONTAINER_DESTROYALL(&regl, sip_registry_destroy);
30311    ASTOBJ_CONTAINER_DESTROY(&regl);
30312    ASTOBJ_CONTAINER_DESTROYALL(&submwil, sip_subscribe_mwi_destroy);
30313    ASTOBJ_CONTAINER_DESTROY(&submwil);
30314 
30315    ao2_t_ref(peers, -1, "unref the peers table");
30316    ao2_t_ref(peers_by_ip, -1, "unref the peers_by_ip table");
30317    ao2_t_ref(dialogs, -1, "unref the dialogs table");
30318    ao2_t_ref(dialogs_to_destroy, -1, "unref dialogs_to_destroy");
30319    ao2_t_ref(threadt, -1, "unref the thread table");
30320    ao2_t_ref(sip_monitor_instances, -1, "unref the sip_monitor_instances table");
30321 
30322    clear_sip_domains();
30323    ast_free_ha(sip_cfg.contact_ha);
30324    close(sipsock);
30325    sched_context_destroy(sched);
30326    con = ast_context_find(used_context);
30327    if (con) {
30328       ast_context_destroy(con, "SIP");
30329    }
30330    ast_unload_realtime("sipregs");
30331    ast_unload_realtime("sippeers");
30332    ast_cc_monitor_unregister(&sip_cc_monitor_callbacks);
30333    ast_cc_agent_unregister(&sip_cc_agent_callbacks);
30334 
30335    sip_reqresp_parser_exit();
30336    sip_unregister_tests();
30337 
30338    return 0;
30339 }
30340 
30341 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "Session Initiation Protocol (SIP)",
30342       .load = load_module,
30343       .unload = unload_module,
30344       .reload = reload,
30345       .load_pri = AST_MODPRI_CHANNEL_DRIVER,
30346       .nonoptreq = "res_crypto,chan_local",
30347           );