Fri Apr 29 2011 07:54:10

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  ***/
00168 
00169 /*!  \page sip_session_timers SIP Session Timers in Asterisk Chan_sip
00170 
00171    The SIP Session-Timers is an extension of the SIP protocol that allows end-points and proxies to
00172    refresh a session periodically. The sessions are kept alive by sending a RE-INVITE or UPDATE
00173    request at a negotiated interval. If a session refresh fails then all the entities that support Session-
00174    Timers clear their internal session state. In addition, UAs generate a BYE request in order to clear
00175    the state in the proxies and the remote UA (this is done for the benefit of SIP entities in the path
00176    that do not support Session-Timers).
00177 
00178    The Session-Timers can be configured on a system-wide, per-user, or per-peer basis. The peruser/
00179    per-peer settings override the global settings. The following new parameters have been
00180    added to the sip.conf file.
00181       session-timers=["accept", "originate", "refuse"]
00182       session-expires=[integer]
00183       session-minse=[integer]
00184       session-refresher=["uas", "uac"]
00185 
00186    The session-timers parameter in sip.conf defines the mode of operation of SIP session-timers feature in
00187    Asterisk. The Asterisk can be configured in one of the following three modes:
00188 
00189    1. Accept :: In the "accept" mode, the Asterisk server honors session-timers requests
00190       made by remote end-points. A remote end-point can request Asterisk to engage
00191       session-timers by either sending it an INVITE request with a "Supported: timer"
00192       header in it or by responding to Asterisk's INVITE with a 200 OK that contains
00193       Session-Expires: header in it. In this mode, the Asterisk server does not
00194       request session-timers from remote end-points. This is the default mode.
00195    2. Originate :: In the "originate" mode, the Asterisk server requests the remote
00196       end-points to activate session-timers in addition to honoring such requests
00197       made by the remote end-pints. In order to get as much protection as possible
00198       against hanging SIP channels due to network or end-point failures, Asterisk
00199       resends periodic re-INVITEs even if a remote end-point does not support
00200       the session-timers feature.
00201    3. Refuse :: In the "refuse" mode, Asterisk acts as if it does not support session-
00202       timers for inbound or outbound requests. If a remote end-point requests
00203       session-timers in a dialog, then Asterisk ignores that request unless it's
00204       noted as a requirement (Require: header), in which case the INVITE is
00205       rejected with a 420 Bad Extension response.
00206 
00207 */
00208 
00209 #include "asterisk.h"
00210 
00211 ASTERISK_FILE_VERSION(__FILE__, "$Revision: 314723 $")
00212 
00213 #include <signal.h>
00214 #include <sys/signal.h>
00215 #include <regex.h>
00216 #include <inttypes.h>
00217 
00218 #include "asterisk/network.h"
00219 #include "asterisk/paths.h"   /* need ast_config_AST_SYSTEM_NAME */
00220 /*
00221    Uncomment the define below,  if you are having refcount related memory leaks.
00222    With this uncommented, this module will generate a file, /tmp/refs, which contains
00223    a history of the ao2_ref() calls. To be useful, all calls to ao2_* functions should
00224    be modified to ao2_t_* calls, and include a tag describing what is happening with
00225    enough detail, to make pairing up a reference count increment with its corresponding decrement.
00226    The refcounter program in utils/ can be invaluable in highlighting objects that are not
00227    balanced, along with the complete history for that object.
00228    In normal operation, the macros defined will throw away the tags, so they do not
00229    affect the speed of the program at all. They can be considered to be documentation.
00230 */
00231 /* #define  REF_DEBUG 1 */
00232 #include "asterisk/lock.h"
00233 #include "asterisk/config.h"
00234 #include "asterisk/module.h"
00235 #include "asterisk/pbx.h"
00236 #include "asterisk/sched.h"
00237 #include "asterisk/io.h"
00238 #include "asterisk/rtp_engine.h"
00239 #include "asterisk/udptl.h"
00240 #include "asterisk/acl.h"
00241 #include "asterisk/manager.h"
00242 #include "asterisk/callerid.h"
00243 #include "asterisk/cli.h"
00244 #include "asterisk/musiconhold.h"
00245 #include "asterisk/dsp.h"
00246 #include "asterisk/features.h"
00247 #include "asterisk/srv.h"
00248 #include "asterisk/astdb.h"
00249 #include "asterisk/causes.h"
00250 #include "asterisk/utils.h"
00251 #include "asterisk/file.h"
00252 #include "asterisk/astobj2.h"
00253 #include "asterisk/dnsmgr.h"
00254 #include "asterisk/devicestate.h"
00255 #include "asterisk/monitor.h"
00256 #include "asterisk/netsock2.h"
00257 #include "asterisk/localtime.h"
00258 #include "asterisk/abstract_jb.h"
00259 #include "asterisk/threadstorage.h"
00260 #include "asterisk/translate.h"
00261 #include "asterisk/ast_version.h"
00262 #include "asterisk/event.h"
00263 #include "asterisk/cel.h"
00264 #include "asterisk/data.h"
00265 #include "asterisk/aoc.h"
00266 #include "sip/include/sip.h"
00267 #include "sip/include/globals.h"
00268 #include "sip/include/config_parser.h"
00269 #include "sip/include/reqresp_parser.h"
00270 #include "sip/include/sip_utils.h"
00271 #include "sip/include/srtp.h"
00272 #include "sip/include/sdp_crypto.h"
00273 #include "asterisk/ccss.h"
00274 #include "asterisk/xml.h"
00275 #include "sip/include/dialog.h"
00276 #include "sip/include/dialplan_functions.h"
00277 
00278 
00279 /*** DOCUMENTATION
00280    <application name="SIPDtmfMode" language="en_US">
00281       <synopsis>
00282          Change the dtmfmode for a SIP call.
00283       </synopsis>
00284       <syntax>
00285          <parameter name="mode" required="true">
00286             <enumlist>
00287                <enum name="inband" />
00288                <enum name="info" />
00289                <enum name="rfc2833" />
00290             </enumlist>
00291          </parameter>
00292       </syntax>
00293       <description>
00294          <para>Changes the dtmfmode for a SIP call.</para>
00295       </description>
00296    </application>
00297    <application name="SIPAddHeader" language="en_US">
00298       <synopsis>
00299          Add a SIP header to the outbound call.
00300       </synopsis>
00301       <syntax argsep=":">
00302          <parameter name="Header" required="true" />
00303          <parameter name="Content" required="true" />
00304       </syntax>
00305       <description>
00306          <para>Adds a header to a SIP call placed with DIAL.</para>
00307          <para>Remember to use the X-header if you are adding non-standard SIP
00308          headers, like <literal>X-Asterisk-Accountcode:</literal>. Use this with care.
00309          Adding the wrong headers may jeopardize the SIP dialog.</para>
00310          <para>Always returns <literal>0</literal>.</para>
00311       </description>
00312    </application>
00313    <application name="SIPRemoveHeader" language="en_US">
00314       <synopsis>
00315          Remove SIP headers previously added with SIPAddHeader
00316       </synopsis>
00317       <syntax>
00318          <parameter name="Header" required="false" />
00319       </syntax>
00320       <description>
00321          <para>SIPRemoveHeader() allows you to remove headers which were previously
00322          added with SIPAddHeader(). If no parameter is supplied, all previously added
00323          headers will be removed. If a parameter is supplied, only the matching headers
00324          will be removed.</para>
00325          <para>For example you have added these 2 headers:</para>
00326          <para>SIPAddHeader(P-Asserted-Identity: sip:foo@bar);</para>
00327          <para>SIPAddHeader(P-Preferred-Identity: sip:bar@foo);</para>
00328          <para></para>
00329          <para>// remove all headers</para>
00330          <para>SIPRemoveHeader();</para>
00331          <para>// remove all P- headers</para>
00332          <para>SIPRemoveHeader(P-);</para>
00333          <para>// remove only the PAI header (note the : at the end)</para>
00334          <para>SIPRemoveHeader(P-Asserted-Identity:);</para>
00335          <para></para>
00336          <para>Always returns <literal>0</literal>.</para>
00337       </description>
00338    </application>
00339    <function name="SIP_HEADER" language="en_US">
00340       <synopsis>
00341          Gets the specified SIP header.
00342       </synopsis>
00343       <syntax>
00344          <parameter name="name" required="true" />
00345          <parameter name="number">
00346             <para>If not specified, defaults to <literal>1</literal>.</para>
00347          </parameter>
00348       </syntax>
00349       <description>
00350          <para>Since there are several headers (such as Via) which can occur multiple
00351          times, SIP_HEADER takes an optional second argument to specify which header with
00352          that name to retrieve. Headers start at offset <literal>1</literal>.</para>
00353       </description>
00354    </function>
00355    <function name="SIPPEER" language="en_US">
00356       <synopsis>
00357          Gets SIP peer information.
00358       </synopsis>
00359       <syntax>
00360          <parameter name="peername" required="true" />
00361          <parameter name="item">
00362             <enumlist>
00363                <enum name="ip">
00364                   <para>(default) The ip address.</para>
00365                </enum>
00366                <enum name="port">
00367                   <para>The port number.</para>
00368                </enum>
00369                <enum name="mailbox">
00370                   <para>The configured mailbox.</para>
00371                </enum>
00372                <enum name="context">
00373                   <para>The configured context.</para>
00374                </enum>
00375                <enum name="expire">
00376                   <para>The epoch time of the next expire.</para>
00377                </enum>
00378                <enum name="dynamic">
00379                   <para>Is it dynamic? (yes/no).</para>
00380                </enum>
00381                <enum name="callerid_name">
00382                   <para>The configured Caller ID name.</para>
00383                </enum>
00384                <enum name="callerid_num">
00385                   <para>The configured Caller ID number.</para>
00386                </enum>
00387                <enum name="callgroup">
00388                   <para>The configured Callgroup.</para>
00389                </enum>
00390                <enum name="pickupgroup">
00391                   <para>The configured Pickupgroup.</para>
00392                </enum>
00393                <enum name="codecs">
00394                   <para>The configured codecs.</para>
00395                </enum>
00396                <enum name="status">
00397                   <para>Status (if qualify=yes).</para>
00398                </enum>
00399                <enum name="regexten">
00400                   <para>Registration extension.</para>
00401                </enum>
00402                <enum name="limit">
00403                   <para>Call limit (call-limit).</para>
00404                </enum>
00405                <enum name="busylevel">
00406                   <para>Configured call level for signalling busy.</para>
00407                </enum>
00408                <enum name="curcalls">
00409                   <para>Current amount of calls. Only available if call-limit is set.</para>
00410                </enum>
00411                <enum name="language">
00412                   <para>Default language for peer.</para>
00413                </enum>
00414                <enum name="accountcode">
00415                   <para>Account code for this peer.</para>
00416                </enum>
00417                <enum name="useragent">
00418                   <para>Current user agent id for peer.</para>
00419                </enum>
00420                <enum name="maxforwards">
00421                   <para>The value used for SIP loop prevention in outbound requests</para>
00422                </enum>
00423                <enum name="chanvar[name]">
00424                   <para>A channel variable configured with setvar for this peer.</para>
00425                </enum>
00426                <enum name="codec[x]">
00427                   <para>Preferred codec index number <replaceable>x</replaceable> (beginning with zero).</para>
00428                </enum>
00429             </enumlist>
00430          </parameter>
00431       </syntax>
00432       <description></description>
00433    </function>
00434    <function name="SIPCHANINFO" language="en_US">
00435       <synopsis>
00436          Gets the specified SIP parameter from the current channel.
00437       </synopsis>
00438       <syntax>
00439          <parameter name="item" required="true">
00440             <enumlist>
00441                <enum name="peerip">
00442                   <para>The IP address of the peer.</para>
00443                </enum>
00444                <enum name="recvip">
00445                   <para>The source IP address of the peer.</para>
00446                </enum>
00447                <enum name="from">
00448                   <para>The URI from the <literal>From:</literal> header.</para>
00449                </enum>
00450                <enum name="uri">
00451                   <para>The URI from the <literal>Contact:</literal> header.</para>
00452                </enum>
00453                <enum name="useragent">
00454                   <para>The useragent.</para>
00455                </enum>
00456                <enum name="peername">
00457                   <para>The name of the peer.</para>
00458                </enum>
00459                <enum name="t38passthrough">
00460                   <para><literal>1</literal> if T38 is offered or enabled in this channel,
00461                   otherwise <literal>0</literal>.</para>
00462                </enum>
00463             </enumlist>
00464          </parameter>
00465       </syntax>
00466       <description></description>
00467    </function>
00468    <function name="CHECKSIPDOMAIN" language="en_US">
00469       <synopsis>
00470          Checks if domain is a local domain.
00471       </synopsis>
00472       <syntax>
00473          <parameter name="domain" required="true" />
00474       </syntax>
00475       <description>
00476          <para>This function checks if the <replaceable>domain</replaceable> in the argument is configured
00477          as a local SIP domain that this Asterisk server is configured to handle.
00478          Returns the domain name if it is locally handled, otherwise an empty string.
00479          Check the <literal>domain=</literal> configuration in <filename>sip.conf</filename>.</para>
00480       </description>
00481    </function>
00482    <manager name="SIPpeers" language="en_US">
00483       <synopsis>
00484          List SIP peers (text format).
00485       </synopsis>
00486       <syntax>
00487          <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
00488       </syntax>
00489       <description>
00490          <para>Lists SIP peers in text format with details on current status.
00491          Peerlist will follow as separate events, followed by a final event called
00492          PeerlistComplete.</para>
00493       </description>
00494    </manager>
00495    <manager name="SIPshowpeer" language="en_US">
00496       <synopsis>
00497          show SIP peer (text format).
00498       </synopsis>
00499       <syntax>
00500          <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
00501          <parameter name="Peer" required="true">
00502             <para>The peer name you want to check.</para>
00503          </parameter>
00504       </syntax>
00505       <description>
00506          <para>Show one SIP peer with details on current status.</para>
00507       </description>
00508    </manager>
00509    <manager name="SIPqualifypeer" language="en_US">
00510       <synopsis>
00511          Qualify SIP peers.
00512       </synopsis>
00513       <syntax>
00514          <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
00515          <parameter name="Peer" required="true">
00516             <para>The peer name you want to qualify.</para>
00517          </parameter>
00518       </syntax>
00519       <description>
00520          <para>Qualify a SIP peer.</para>
00521       </description>
00522    </manager>
00523    <manager name="SIPshowregistry" language="en_US">
00524       <synopsis>
00525          Show SIP registrations (text format).
00526       </synopsis>
00527       <syntax>
00528          <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
00529       </syntax>
00530       <description>
00531          <para>Lists all registration requests and status. Registrations will follow as separate
00532          events. followed by a final event called RegistrationsComplete.</para>
00533       </description>
00534    </manager>
00535    <manager name="SIPnotify" language="en_US">
00536       <synopsis>
00537          Send a SIP notify.
00538       </synopsis>
00539       <syntax>
00540          <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
00541          <parameter name="Channel" required="true">
00542             <para>Peer to receive the notify.</para>
00543          </parameter>
00544          <parameter name="Variable" required="true">
00545             <para>At least one variable pair must be specified.
00546             <replaceable>name</replaceable>=<replaceable>value</replaceable></para>
00547          </parameter>
00548       </syntax>
00549       <description>
00550          <para>Sends a SIP Notify event.</para>
00551          <para>All parameters for this event must be specified in the body of this request
00552          via multiple Variable: name=value sequences.</para>
00553       </description>
00554    </manager>
00555  ***/
00556 
00557 static int min_expiry = DEFAULT_MIN_EXPIRY;        /*!< Minimum accepted registration time */
00558 static int max_expiry = DEFAULT_MAX_EXPIRY;        /*!< Maximum accepted registration time */
00559 static int default_expiry = DEFAULT_DEFAULT_EXPIRY;
00560 static int mwi_expiry = DEFAULT_MWI_EXPIRY;
00561 
00562 static int unauth_sessions = 0;
00563 static int authlimit = DEFAULT_AUTHLIMIT;
00564 static int authtimeout = DEFAULT_AUTHTIMEOUT;
00565 
00566 /*! \brief Global jitterbuffer configuration - by default, jb is disabled */
00567 static struct ast_jb_conf default_jbconf =
00568 {
00569    .flags = 0,
00570    .max_size = -1,
00571    .resync_threshold = -1,
00572    .impl = "",
00573    .target_extra = -1,
00574 };
00575 static struct ast_jb_conf global_jbconf;                /*!< Global jitterbuffer configuration */
00576 
00577 static const char config[] = "sip.conf";                /*!< Main configuration file */
00578 static const char notify_config[] = "sip_notify.conf";  /*!< Configuration file for sending Notify with CLI commands to reconfigure or reboot phones */
00579 
00580 /*! \brief Readable descriptions of device states.
00581  *  \note Should be aligned to above table as index */
00582 static const struct invstate2stringtable {
00583    const enum invitestates state;
00584    const char *desc;
00585 } invitestate2string[] = {
00586    {INV_NONE,              "None"  },
00587    {INV_CALLING,           "Calling (Trying)"},
00588    {INV_PROCEEDING,        "Proceeding "},
00589    {INV_EARLY_MEDIA,       "Early media"},
00590    {INV_COMPLETED,         "Completed (done)"},
00591    {INV_CONFIRMED,         "Confirmed (up)"},
00592    {INV_TERMINATED,        "Done"},
00593    {INV_CANCELLED,         "Cancelled"}
00594 };
00595 
00596 /*! \brief Subscription types that we support. We support
00597  * - dialoginfo updates (really device status, not dialog info as was the original intent of the standard)
00598  * - SIMPLE presence used for device status
00599  * - Voicemail notification subscriptions
00600  */
00601 static const struct cfsubscription_types {
00602    enum subscriptiontype type;
00603    const char * const event;
00604    const char * const mediatype;
00605    const char * const text;
00606 } subscription_types[] = {
00607    { NONE,        "-",        "unknown",               "unknown" },
00608    /* RFC 4235: SIP Dialog event package */
00609    { DIALOG_INFO_XML, "dialog",   "application/dialog-info+xml", "dialog-info+xml" },
00610    { CPIM_PIDF_XML,   "presence", "application/cpim-pidf+xml",   "cpim-pidf+xml" },  /* RFC 3863 */
00611    { PIDF_XML,        "presence", "application/pidf+xml",        "pidf+xml" },       /* RFC 3863 */
00612    { XPIDF_XML,       "presence", "application/xpidf+xml",       "xpidf+xml" },       /* Pre-RFC 3863 with MS additions */
00613    { MWI_NOTIFICATION,  "message-summary", "application/simple-message-summary", "mwi" } /* RFC 3842: Mailbox notification */
00614 };
00615 
00616 /*! \brief The core structure to setup dialogs. We parse incoming messages by using
00617  *  structure and then route the messages according to the type.
00618  *
00619  *  \note Note that sip_methods[i].id == i must hold or the code breaks
00620  */
00621 static const struct  cfsip_methods {
00622    enum sipmethod id;
00623    int need_rtp;     /*!< when this is the 'primary' use for a pvt structure, does it need RTP? */
00624    char * const text;
00625    enum can_create_dialog can_create;
00626 } sip_methods[] = {
00627    { SIP_UNKNOWN,   RTP,    "-UNKNOWN-",CAN_CREATE_DIALOG },
00628    { SIP_RESPONSE,  NO_RTP, "SIP/2.0",  CAN_NOT_CREATE_DIALOG },
00629    { SIP_REGISTER,  NO_RTP, "REGISTER", CAN_CREATE_DIALOG },
00630    { SIP_OPTIONS,   NO_RTP, "OPTIONS",  CAN_CREATE_DIALOG },
00631    { SIP_NOTIFY,    NO_RTP, "NOTIFY",   CAN_CREATE_DIALOG },
00632    { SIP_INVITE,    RTP,    "INVITE",   CAN_CREATE_DIALOG },
00633    { SIP_ACK,       NO_RTP, "ACK",      CAN_NOT_CREATE_DIALOG },
00634    { SIP_PRACK,     NO_RTP, "PRACK",    CAN_NOT_CREATE_DIALOG },
00635    { SIP_BYE,       NO_RTP, "BYE",      CAN_NOT_CREATE_DIALOG },
00636    { SIP_REFER,     NO_RTP, "REFER",    CAN_CREATE_DIALOG },
00637    { SIP_SUBSCRIBE, NO_RTP, "SUBSCRIBE",CAN_CREATE_DIALOG },
00638    { SIP_MESSAGE,   NO_RTP, "MESSAGE",  CAN_CREATE_DIALOG },
00639    { SIP_UPDATE,    NO_RTP, "UPDATE",   CAN_NOT_CREATE_DIALOG },
00640    { SIP_INFO,      NO_RTP, "INFO",     CAN_NOT_CREATE_DIALOG },
00641    { SIP_CANCEL,    NO_RTP, "CANCEL",   CAN_NOT_CREATE_DIALOG },
00642    { SIP_PUBLISH,   NO_RTP, "PUBLISH",  CAN_CREATE_DIALOG },
00643    { SIP_PING,      NO_RTP, "PING",     CAN_CREATE_DIALOG_UNSUPPORTED_METHOD }
00644 };
00645 
00646 /*! \brief Diversion header reasons
00647  *
00648  * The core defines a bunch of constants used to define
00649  * redirecting reasons. This provides a translation table
00650  * between those and the strings which may be present in
00651  * a SIP Diversion header
00652  */
00653 static const struct sip_reasons {
00654    enum AST_REDIRECTING_REASON code;
00655    char * const text;
00656 } sip_reason_table[] = {
00657    { AST_REDIRECTING_REASON_UNKNOWN, "unknown" },
00658    { AST_REDIRECTING_REASON_USER_BUSY, "user-busy" },
00659    { AST_REDIRECTING_REASON_NO_ANSWER, "no-answer" },
00660    { AST_REDIRECTING_REASON_UNAVAILABLE, "unavailable" },
00661    { AST_REDIRECTING_REASON_UNCONDITIONAL, "unconditional" },
00662    { AST_REDIRECTING_REASON_TIME_OF_DAY, "time-of-day" },
00663    { AST_REDIRECTING_REASON_DO_NOT_DISTURB, "do-not-disturb" },
00664    { AST_REDIRECTING_REASON_DEFLECTION, "deflection" },
00665    { AST_REDIRECTING_REASON_FOLLOW_ME, "follow-me" },
00666    { AST_REDIRECTING_REASON_OUT_OF_ORDER, "out-of-service" },
00667    { AST_REDIRECTING_REASON_AWAY, "away" },
00668    { AST_REDIRECTING_REASON_CALL_FWD_DTE, "unknown"}
00669 };
00670 
00671 
00672 /*! \name DefaultSettings
00673    Default setttings are used as a channel setting and as a default when
00674    configuring devices
00675 */
00676 /*@{*/
00677 static char default_language[MAX_LANGUAGE];      /*!< Default language setting for new channels */
00678 static char default_callerid[AST_MAX_EXTENSION]; /*!< Default caller ID for sip messages */
00679 static char default_mwi_from[80];                /*!< Default caller ID for MWI updates */
00680 static char default_fromdomain[AST_MAX_EXTENSION]; /*!< Default domain on outound messages */
00681 static int default_fromdomainport;                 /*!< Default domain port on outbound messages */
00682 static char default_notifymime[AST_MAX_EXTENSION]; /*!< Default MIME media type for MWI notify messages */
00683 static char default_vmexten[AST_MAX_EXTENSION];    /*!< Default From Username on MWI updates */
00684 static int default_qualify;                        /*!< Default Qualify= setting */
00685 static char default_mohinterpret[MAX_MUSICCLASS];  /*!< Global setting for moh class to use when put on hold */
00686 static char default_mohsuggest[MAX_MUSICCLASS];    /*!< Global setting for moh class to suggest when putting
00687                                                     *   a bridged channel on hold */
00688 static char default_parkinglot[AST_MAX_CONTEXT];   /*!< Parkinglot */
00689 static char default_engine[256];                   /*!< Default RTP engine */
00690 static int default_maxcallbitrate;                 /*!< Maximum bitrate for call */
00691 static struct ast_codec_pref default_prefs;        /*!< Default codec prefs */
00692 static unsigned int default_transports;            /*!< Default Transports (enum sip_transport) that are acceptable */
00693 static unsigned int default_primary_transport;     /*!< Default primary Transport (enum sip_transport) for outbound connections to devices */
00694 /*@}*/
00695 
00696 static struct sip_settings sip_cfg;    /*!< SIP configuration data.
00697                \note in the future we could have multiple of these (per domain, per device group etc) */
00698 
00699 /*!< use this macro when ast_uri_decode is dependent on pedantic checking to be on. */
00700 #define SIP_PEDANTIC_DECODE(str) \
00701    if (sip_cfg.pedanticsipchecking && !ast_strlen_zero(str)) { \
00702       ast_uri_decode(str); \
00703    }  \
00704 
00705 static unsigned int chan_idx;       /*!< used in naming sip channel */
00706 static int global_match_auth_username;    /*!< Match auth username if available instead of From: Default off. */
00707 
00708 static int global_relaxdtmf;        /*!< Relax DTMF */
00709 static int global_prematuremediafilter;   /*!< Enable/disable premature frames in a call (causing 183 early media) */
00710 static int global_rtptimeout;       /*!< Time out call if no RTP */
00711 static int global_rtpholdtimeout;   /*!< Time out call if no RTP during hold */
00712 static int global_rtpkeepalive;     /*!< Send RTP keepalives */
00713 static int global_reg_timeout;      /*!< Global time between attempts for outbound registrations */
00714 static int global_regattempts_max;  /*!< Registration attempts before giving up */
00715 static int global_shrinkcallerid;   /*!< enable or disable shrinking of caller id  */
00716 static int global_callcounter;      /*!< Enable call counters for all devices. This is currently enabled by setting the peer
00717                                      *   call-limit to INT_MAX. When we remove the call-limit from the code, we can make it
00718                                      *   with just a boolean flag in the device structure */
00719 static unsigned int global_tos_sip;      /*!< IP type of service for SIP packets */
00720 static unsigned int global_tos_audio;    /*!< IP type of service for audio RTP packets */
00721 static unsigned int global_tos_video;    /*!< IP type of service for video RTP packets */
00722 static unsigned int global_tos_text;     /*!< IP type of service for text RTP packets */
00723 static unsigned int global_cos_sip;      /*!< 802.1p class of service for SIP packets */
00724 static unsigned int global_cos_audio;    /*!< 802.1p class of service for audio RTP packets */
00725 static unsigned int global_cos_video;    /*!< 802.1p class of service for video RTP packets */
00726 static unsigned int global_cos_text;     /*!< 802.1p class of service for text RTP packets */
00727 static unsigned int recordhistory;       /*!< Record SIP history. Off by default */
00728 static unsigned int dumphistory;         /*!< Dump history to verbose before destroying SIP dialog */
00729 static char global_useragent[AST_MAX_EXTENSION];    /*!< Useragent for the SIP channel */
00730 static char global_sdpsession[AST_MAX_EXTENSION];   /*!< SDP session name for the SIP channel */
00731 static char global_sdpowner[AST_MAX_EXTENSION];     /*!< SDP owner name for the SIP channel */
00732 static int global_authfailureevents;     /*!< Whether we send authentication failure manager events or not. Default no. */
00733 static int global_t1;           /*!< T1 time */
00734 static int global_t1min;        /*!< T1 roundtrip time minimum */
00735 static int global_timer_b;      /*!< Timer B - RFC 3261 Section 17.1.1.2 */
00736 static unsigned int global_autoframing; /*!< Turn autoframing on or off. */
00737 static int global_qualifyfreq;          /*!< Qualify frequency */
00738 static int global_qualify_gap;          /*!< Time between our group of peer pokes */
00739 static int global_qualify_peers;        /*!< Number of peers to poke at a given time */
00740 
00741 static enum st_mode global_st_mode;           /*!< Mode of operation for Session-Timers           */
00742 static enum st_refresher global_st_refresher; /*!< Session-Timer refresher                        */
00743 static int global_min_se;                     /*!< Lowest threshold for session refresh interval  */
00744 static int global_max_se;                     /*!< Highest threshold for session refresh interval */
00745 
00746 static int global_dynamic_exclude_static = 0; /*!< Exclude static peers from contact registrations */
00747 /*@}*/
00748 
00749 /*!
00750  * We use libxml2 in order to parse XML that may appear in the body of a SIP message. Currently,
00751  * the only usage is for parsing PIDF bodies of incoming PUBLISH requests in the call-completion
00752  * event package. This variable is set at module load time and may be checked at runtime to determine
00753  * if XML parsing support was found.
00754  */
00755 static int can_parse_xml;
00756 
00757 /*! \name Object counters @{
00758  *  \bug These counters are not handled in a thread-safe way ast_atomic_fetchadd_int()
00759  *  should be used to modify these values. */
00760 static int speerobjs = 0;     /*!< Static peers */
00761 static int rpeerobjs = 0;     /*!< Realtime peers */
00762 static int apeerobjs = 0;     /*!< Autocreated peer objects */
00763 static int regobjs = 0;       /*!< Registry objects */
00764 /* }@ */
00765 
00766 static struct ast_flags global_flags[3] = {{0}};  /*!< global SIP_ flags */
00767 static int global_t38_maxdatagram;                /*!< global T.38 FaxMaxDatagram override */
00768 
00769 static struct ast_event_sub *network_change_event_subscription; /*!< subscription id for network change events */
00770 static int network_change_event_sched_id = -1;
00771 
00772 static char used_context[AST_MAX_CONTEXT];        /*!< name of automatically created context for unloading */
00773 
00774 AST_MUTEX_DEFINE_STATIC(netlock);
00775 
00776 /*! \brief Protect the monitoring thread, so only one process can kill or start it, and not
00777    when it's doing something critical. */
00778 AST_MUTEX_DEFINE_STATIC(monlock);
00779 
00780 AST_MUTEX_DEFINE_STATIC(sip_reload_lock);
00781 
00782 /*! \brief This is the thread for the monitor which checks for input on the channels
00783    which are not currently in use.  */
00784 static pthread_t monitor_thread = AST_PTHREADT_NULL;
00785 
00786 static int sip_reloading = FALSE;                       /*!< Flag for avoiding multiple reloads at the same time */
00787 static enum channelreloadreason sip_reloadreason;       /*!< Reason for last reload/load of configuration */
00788 
00789 struct sched_context *sched;     /*!< The scheduling context */
00790 static struct io_context *io;           /*!< The IO context */
00791 static int *sipsock_read_id;            /*!< ID of IO entry for sipsock FD */
00792 struct sip_pkt;
00793 static AST_LIST_HEAD_STATIC(domain_list, domain);    /*!< The SIP domain list */
00794 
00795 AST_LIST_HEAD_NOLOCK(sip_history_head, sip_history); /*!< history list, entry in sip_pvt */
00796 
00797 static enum sip_debug_e sipdebug;
00798 
00799 /*! \brief extra debugging for 'text' related events.
00800  *  At the moment this is set together with sip_debug_console.
00801  *  \note It should either go away or be implemented properly.
00802  */
00803 static int sipdebug_text;
00804 
00805 static const struct _map_x_s referstatusstrings[] = {
00806    { REFER_IDLE,      "<none>" },
00807    { REFER_SENT,      "Request sent" },
00808    { REFER_RECEIVED,  "Request received" },
00809    { REFER_CONFIRMED, "Confirmed" },
00810    { REFER_ACCEPTED,  "Accepted" },
00811    { REFER_RINGING,   "Target ringing" },
00812    { REFER_200OK,     "Done" },
00813    { REFER_FAILED,    "Failed" },
00814    { REFER_NOAUTH,    "Failed - auth failure" },
00815    { -1,               NULL} /* terminator */
00816 };
00817 
00818 /* --- Hash tables of various objects --------*/
00819 #ifdef LOW_MEMORY
00820 static const int HASH_PEER_SIZE = 17;
00821 static const int HASH_DIALOG_SIZE = 17;
00822 #else
00823 static const int HASH_PEER_SIZE = 563; /*!< Size of peer hash table, prime number preferred! */
00824 static const int HASH_DIALOG_SIZE = 563;
00825 #endif
00826 
00827 static const struct {
00828    enum ast_cc_service_type service;
00829    const char *service_string;
00830 } sip_cc_service_map [] = {
00831    [AST_CC_NONE] = { AST_CC_NONE, "" },
00832    [AST_CC_CCBS] = { AST_CC_CCBS, "BS" },
00833    [AST_CC_CCNR] = { AST_CC_CCNR, "NR" },
00834    [AST_CC_CCNL] = { AST_CC_CCNL, "NL" },
00835 };
00836 
00837 static enum ast_cc_service_type service_string_to_service_type(const char * const service_string)
00838 {
00839    enum ast_cc_service_type service;
00840    for (service = AST_CC_CCBS; service <= AST_CC_CCNL; ++service) {
00841       if (!strcasecmp(service_string, sip_cc_service_map[service].service_string)) {
00842          return service;
00843       }
00844    }
00845    return AST_CC_NONE;
00846 }
00847 
00848 static const struct {
00849    enum sip_cc_notify_state state;
00850    const char *state_string;
00851 } sip_cc_notify_state_map [] = {
00852    [CC_QUEUED] = {CC_QUEUED, "cc-state: queued"},
00853    [CC_READY] = {CC_READY, "cc-state: ready"},
00854 };
00855 
00856 AST_LIST_HEAD_STATIC(epa_static_data_list, epa_backend);
00857 
00858 static int sip_epa_register(const struct epa_static_data *static_data)
00859 {
00860    struct epa_backend *backend = ast_calloc(1, sizeof(*backend));
00861 
00862    if (!backend) {
00863       return -1;
00864    }
00865 
00866    backend->static_data = static_data;
00867 
00868    AST_LIST_LOCK(&epa_static_data_list);
00869    AST_LIST_INSERT_TAIL(&epa_static_data_list, backend, next);
00870    AST_LIST_UNLOCK(&epa_static_data_list);
00871    return 0;
00872 }
00873 
00874 static void cc_handle_publish_error(struct sip_pvt *pvt, const int resp, struct sip_request *req, struct sip_epa_entry *epa_entry);
00875 
00876 static void cc_epa_destructor(void *data)
00877 {
00878    struct sip_epa_entry *epa_entry = data;
00879    struct cc_epa_entry *cc_entry = epa_entry->instance_data;
00880    ast_free(cc_entry);
00881 }
00882 
00883 static const struct epa_static_data cc_epa_static_data  = {
00884    .event = CALL_COMPLETION,
00885    .name = "call-completion",
00886    .handle_error = cc_handle_publish_error,
00887    .destructor = cc_epa_destructor,
00888 };
00889 
00890 static const struct epa_static_data *find_static_data(const char * const event_package)
00891 {
00892    const struct epa_backend *backend = NULL;
00893 
00894    AST_LIST_LOCK(&epa_static_data_list);
00895    AST_LIST_TRAVERSE(&epa_static_data_list, backend, next) {
00896       if (!strcmp(backend->static_data->name, event_package)) {
00897          break;
00898       }
00899    }
00900    AST_LIST_UNLOCK(&epa_static_data_list);
00901    return backend ? backend->static_data : NULL;
00902 }
00903 
00904 static struct sip_epa_entry *create_epa_entry (const char * const event_package, const char * const destination)
00905 {
00906    struct sip_epa_entry *epa_entry;
00907    const struct epa_static_data *static_data;
00908 
00909    if (!(static_data = find_static_data(event_package))) {
00910       return NULL;
00911    }
00912 
00913    if (!(epa_entry = ao2_t_alloc(sizeof(*epa_entry), static_data->destructor, "Allocate new EPA entry"))) {
00914       return NULL;
00915    }
00916 
00917    epa_entry->static_data = static_data;
00918    ast_copy_string(epa_entry->destination, destination, sizeof(epa_entry->destination));
00919    return epa_entry;
00920 }
00921 
00922 /*!
00923  * Used to create new entity IDs by ESCs.
00924  */
00925 static int esc_etag_counter;
00926 static const int DEFAULT_PUBLISH_EXPIRES = 3600;
00927 
00928 #ifdef HAVE_LIBXML2
00929 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);
00930 
00931 static const struct sip_esc_publish_callbacks cc_esc_publish_callbacks = {
00932    .initial_handler = cc_esc_publish_handler,
00933    .modify_handler = cc_esc_publish_handler,
00934 };
00935 #endif
00936 
00937 /*!
00938  * \brief The Event State Compositors
00939  *
00940  * An Event State Compositor is an entity which
00941  * accepts PUBLISH requests and acts appropriately
00942  * based on these requests.
00943  *
00944  * The actual event_state_compositor structure is simply
00945  * an ao2_container of sip_esc_entrys. When an incoming
00946  * PUBLISH is received, we can match the appropriate sip_esc_entry
00947  * using the entity ID of the incoming PUBLISH.
00948  */
00949 static struct event_state_compositor {
00950    enum subscriptiontype event;
00951    const char * name;
00952    const struct sip_esc_publish_callbacks *callbacks;
00953    struct ao2_container *compositor;
00954 } event_state_compositors [] = {
00955 #ifdef HAVE_LIBXML2
00956    {CALL_COMPLETION, "call-completion", &cc_esc_publish_callbacks},
00957 #endif
00958 };
00959 
00960 static const int ESC_MAX_BUCKETS = 37;
00961 
00962 static void esc_entry_destructor(void *obj)
00963 {
00964    struct sip_esc_entry *esc_entry = obj;
00965    if (esc_entry->sched_id > -1) {
00966       AST_SCHED_DEL(sched, esc_entry->sched_id);
00967    }
00968 }
00969 
00970 static int esc_hash_fn(const void *obj, const int flags)
00971 {
00972    const struct sip_esc_entry *entry = obj;
00973    return ast_str_hash(entry->entity_tag);
00974 }
00975 
00976 static int esc_cmp_fn(void *obj, void *arg, int flags)
00977 {
00978    struct sip_esc_entry *entry1 = obj;
00979    struct sip_esc_entry *entry2 = arg;
00980 
00981    return (!strcmp(entry1->entity_tag, entry2->entity_tag)) ? (CMP_MATCH | CMP_STOP) : 0;
00982 }
00983 
00984 static struct event_state_compositor *get_esc(const char * const event_package) {
00985    int i;
00986    for (i = 0; i < ARRAY_LEN(event_state_compositors); i++) {
00987       if (!strcasecmp(event_package, event_state_compositors[i].name)) {
00988          return &event_state_compositors[i];
00989       }
00990    }
00991    return NULL;
00992 }
00993 
00994 static struct sip_esc_entry *get_esc_entry(const char * entity_tag, struct event_state_compositor *esc) {
00995    struct sip_esc_entry *entry;
00996    struct sip_esc_entry finder;
00997 
00998    ast_copy_string(finder.entity_tag, entity_tag, sizeof(finder.entity_tag));
00999 
01000    entry = ao2_find(esc->compositor, &finder, OBJ_POINTER);
01001 
01002    return entry;
01003 }
01004 
01005 static int publish_expire(const void *data)
01006 {
01007    struct sip_esc_entry *esc_entry = (struct sip_esc_entry *) data;
01008    struct event_state_compositor *esc = get_esc(esc_entry->event);
01009 
01010    ast_assert(esc != NULL);
01011 
01012    ao2_unlink(esc->compositor, esc_entry);
01013    ao2_ref(esc_entry, -1);
01014    return 0;
01015 }
01016 
01017 static void create_new_sip_etag(struct sip_esc_entry *esc_entry, int is_linked)
01018 {
01019    int new_etag = ast_atomic_fetchadd_int(&esc_etag_counter, +1);
01020    struct event_state_compositor *esc = get_esc(esc_entry->event);
01021 
01022    ast_assert(esc != NULL);
01023    if (is_linked) {
01024       ao2_unlink(esc->compositor, esc_entry);
01025    }
01026    snprintf(esc_entry->entity_tag, sizeof(esc_entry->entity_tag), "%d", new_etag);
01027    ao2_link(esc->compositor, esc_entry);
01028 }
01029 
01030 static struct sip_esc_entry *create_esc_entry(struct event_state_compositor *esc, struct sip_request *req, const int expires)
01031 {
01032    struct sip_esc_entry *esc_entry;
01033    int expires_ms;
01034 
01035    if (!(esc_entry = ao2_alloc(sizeof(*esc_entry), esc_entry_destructor))) {
01036       return NULL;
01037    }
01038 
01039    esc_entry->event = esc->name;
01040 
01041    expires_ms = expires * 1000;
01042    /* Bump refcount for scheduler */
01043    ao2_ref(esc_entry, +1);
01044    esc_entry->sched_id = ast_sched_add(sched, expires_ms, publish_expire, esc_entry);
01045 
01046    /* Note: This links the esc_entry into the ESC properly */
01047    create_new_sip_etag(esc_entry, 0);
01048 
01049    return esc_entry;
01050 }
01051 
01052 static int initialize_escs(void)
01053 {
01054    int i, res = 0;
01055    for (i = 0; i < ARRAY_LEN(event_state_compositors); i++) {
01056       if (!((event_state_compositors[i].compositor) =
01057                ao2_container_alloc(ESC_MAX_BUCKETS, esc_hash_fn, esc_cmp_fn))) {
01058          res = -1;
01059       }
01060    }
01061    return res;
01062 }
01063 
01064 static void destroy_escs(void)
01065 {
01066    int i;
01067    for (i = 0; i < ARRAY_LEN(event_state_compositors); i++) {
01068       ao2_ref(event_state_compositors[i].compositor, -1);
01069    }
01070 }
01071 
01072 /*! \brief
01073  * Here we implement the container for dialogs (sip_pvt), defining
01074  * generic wrapper functions to ease the transition from the current
01075  * implementation (a single linked list) to a different container.
01076  * In addition to a reference to the container, we need functions to lock/unlock
01077  * the container and individual items, and functions to add/remove
01078  * references to the individual items.
01079  */
01080 static struct ao2_container *dialogs;
01081 #define sip_pvt_lock(x) ao2_lock(x)
01082 #define sip_pvt_trylock(x) ao2_trylock(x)
01083 #define sip_pvt_unlock(x) ao2_unlock(x)
01084 
01085 /*! \brief  The table of TCP threads */
01086 static struct ao2_container *threadt;
01087 
01088 /*! \brief  The peer list: Users, Peers and Friends */
01089 static struct ao2_container *peers;
01090 static struct ao2_container *peers_by_ip;
01091 
01092 /*! \brief  The register list: Other SIP proxies we register with and receive calls from */
01093 static struct ast_register_list {
01094    ASTOBJ_CONTAINER_COMPONENTS(struct sip_registry);
01095    int recheck;
01096 } regl;
01097 
01098 /*! \brief  The MWI subscription list */
01099 static struct ast_subscription_mwi_list {
01100    ASTOBJ_CONTAINER_COMPONENTS(struct sip_subscription_mwi);
01101 } submwil;
01102 static int temp_pvt_init(void *);
01103 static void temp_pvt_cleanup(void *);
01104 
01105 /*! \brief A per-thread temporary pvt structure */
01106 AST_THREADSTORAGE_CUSTOM(ts_temp_pvt, temp_pvt_init, temp_pvt_cleanup);
01107 
01108 /*! \brief Authentication list for realm authentication
01109  * \todo Move the sip_auth list to AST_LIST */
01110 static struct sip_auth *authl = NULL;
01111 
01112 /* --- Sockets and networking --------------*/
01113 
01114 /*! \brief Main socket for UDP SIP communication.
01115  *
01116  * sipsock is shared between the SIP manager thread (which handles reload
01117  * requests), the udp io handler (sipsock_read()) and the user routines that
01118  * issue udp writes (using __sip_xmit()).
01119  * The socket is -1 only when opening fails (this is a permanent condition),
01120  * or when we are handling a reload() that changes its address (this is
01121  * a transient situation during which we might have a harmless race, see
01122  * below). Because the conditions for the race to be possible are extremely
01123  * rare, we don't want to pay the cost of locking on every I/O.
01124  * Rather, we remember that when the race may occur, communication is
01125  * bound to fail anyways, so we just live with this event and let
01126  * the protocol handle this above us.
01127  */
01128 static int sipsock  = -1;
01129 
01130 struct ast_sockaddr bindaddr; /*!< UDP: The address we bind to */
01131 
01132 /*! \brief our (internal) default address/port to put in SIP/SDP messages
01133  *  internip is initialized picking a suitable address from one of the
01134  * interfaces, and the same port number we bind to. It is used as the
01135  * default address/port in SIP messages, and as the default address
01136  * (but not port) in SDP messages.
01137  */
01138 static struct ast_sockaddr internip;
01139 
01140 /*! \brief our external IP address/port for SIP sessions.
01141  * externaddr.sin_addr is only set when we know we might be behind
01142  * a NAT, and this is done using a variety of (mutually exclusive)
01143  * ways from the config file:
01144  *
01145  * + with "externaddr = host[:port]" we specify the address/port explicitly.
01146  *   The address is looked up only once when (re)loading the config file;
01147  *
01148  * + with "externhost = host[:port]" we do a similar thing, but the
01149  *   hostname is stored in externhost, and the hostname->IP mapping
01150  *   is refreshed every 'externrefresh' seconds;
01151  *
01152  * Other variables (externhost, externexpire, externrefresh) are used
01153  * to support the above functions.
01154  */
01155 static struct ast_sockaddr externaddr;      /*!< External IP address if we are behind NAT */
01156 static struct ast_sockaddr media_address; /*!< External RTP IP address if we are behind NAT */
01157 
01158 static char externhost[MAXHOSTNAMELEN];   /*!< External host name */
01159 static time_t externexpire;             /*!< Expiration counter for re-resolving external host name in dynamic DNS */
01160 static int externrefresh = 10;          /*!< Refresh timer for DNS-based external address (dyndns) */
01161 static uint16_t externtcpport;          /*!< external tcp port */ 
01162 static uint16_t externtlsport;          /*!< external tls port */
01163 
01164 /*! \brief  List of local networks
01165  * We store "localnet" addresses from the config file into an access list,
01166  * marked as 'DENY', so the call to ast_apply_ha() will return
01167  * AST_SENSE_DENY for 'local' addresses, and AST_SENSE_ALLOW for 'non local'
01168  * (i.e. presumably public) addresses.
01169  */
01170 static struct ast_ha *localaddr;    /*!< List of local networks, on the same side of NAT as this Asterisk */
01171 
01172 static int ourport_tcp;             /*!< The port used for TCP connections */
01173 static int ourport_tls;             /*!< The port used for TCP/TLS connections */
01174 static struct ast_sockaddr debugaddr;
01175 
01176 static struct ast_config *notify_types = NULL;    /*!< The list of manual NOTIFY types we know how to send */
01177 
01178 /*! some list management macros. */
01179 
01180 #define UNLINK(element, head, prev) do {  \
01181    if (prev)            \
01182       (prev)->next = (element)->next;  \
01183    else              \
01184       (head) = (element)->next;  \
01185    } while (0)
01186 
01187 /*---------------------------- Forward declarations of functions in chan_sip.c */
01188 /* Note: This is added to help splitting up chan_sip.c into several files
01189    in coming releases. */
01190 
01191 /*--- PBX interface functions */
01192 static struct ast_channel *sip_request_call(const char *type, format_t format, const struct ast_channel *requestor, void *data, int *cause);
01193 static int sip_devicestate(void *data);
01194 static int sip_sendtext(struct ast_channel *ast, const char *text);
01195 static int sip_call(struct ast_channel *ast, char *dest, int timeout);
01196 static int sip_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen);
01197 static int sip_hangup(struct ast_channel *ast);
01198 static int sip_answer(struct ast_channel *ast);
01199 static struct ast_frame *sip_read(struct ast_channel *ast);
01200 static int sip_write(struct ast_channel *ast, struct ast_frame *frame);
01201 static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen);
01202 static int sip_transfer(struct ast_channel *ast, const char *dest);
01203 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
01204 static int sip_senddigit_begin(struct ast_channel *ast, char digit);
01205 static int sip_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration);
01206 static int sip_setoption(struct ast_channel *chan, int option, void *data, int datalen);
01207 static int sip_queryoption(struct ast_channel *chan, int option, void *data, int *datalen);
01208 static const char *sip_get_callid(struct ast_channel *chan);
01209 
01210 static int handle_request_do(struct sip_request *req, struct ast_sockaddr *addr);
01211 static int sip_standard_port(enum sip_transport type, int port);
01212 static int sip_prepare_socket(struct sip_pvt *p);
01213 static int get_address_family_filter(const struct ast_sockaddr *addr);
01214 
01215 /*--- Transmitting responses and requests */
01216 static int sipsock_read(int *id, int fd, short events, void *ignore);
01217 static int __sip_xmit(struct sip_pvt *p, struct ast_str *data, int len);
01218 static int __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, struct ast_str *data, int len, int fatal, int sipmethod);
01219 static void add_cc_call_info_to_response(struct sip_pvt *p, struct sip_request *resp);
01220 static int __transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
01221 static int retrans_pkt(const void *data);
01222 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);
01223 static int transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req);
01224 static int transmit_response_reliable(struct sip_pvt *p, const char *msg, const struct sip_request *req);
01225 static int transmit_response_with_date(struct sip_pvt *p, const char *msg, const struct sip_request *req);
01226 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);
01227 static int transmit_response_with_unsupported(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *unsupported);
01228 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);
01229 static int transmit_provisional_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, int with_sdp);
01230 static int transmit_response_with_allow(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
01231 static void transmit_fake_auth_response(struct sip_pvt *p, int sipmethod, struct sip_request *req, enum xmittype reliable);
01232 static int transmit_request(struct sip_pvt *p, int sipmethod, int inc, enum xmittype reliable, int newbranch);
01233 static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, int seqno, enum xmittype reliable, int newbranch);
01234 static int transmit_publish(struct sip_epa_entry *epa_entry, enum sip_publish_type publish_type, const char * const explicit_uri);
01235 static int transmit_invite(struct sip_pvt *p, int sipmethod, int sdp, int init, const char * const explicit_uri);
01236 static int transmit_reinvite_with_sdp(struct sip_pvt *p, int t38version, int oldsdp);
01237 static int transmit_info_with_aoc(struct sip_pvt *p, struct ast_aoc_decoded *decoded);
01238 static int transmit_info_with_digit(struct sip_pvt *p, const char digit, unsigned int duration);
01239 static int transmit_info_with_vidupdate(struct sip_pvt *p);
01240 static int transmit_message_with_text(struct sip_pvt *p, const char *text);
01241 static int transmit_refer(struct sip_pvt *p, const char *dest);
01242 static int transmit_notify_with_mwi(struct sip_pvt *p, int newmsgs, int oldmsgs, const char *vmexten);
01243 static int transmit_notify_with_sipfrag(struct sip_pvt *p, int cseq, char *message, int terminate);
01244 static int transmit_cc_notify(struct ast_cc_agent *agent, struct sip_pvt *subscription, enum sip_cc_notify_state state);
01245 static int transmit_register(struct sip_registry *r, int sipmethod, const char *auth, const char *authheader);
01246 static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno);
01247 static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno);
01248 static void copy_request(struct sip_request *dst, const struct sip_request *src);
01249 static void receive_message(struct sip_pvt *p, struct sip_request *req);
01250 static void parse_moved_contact(struct sip_pvt *p, struct sip_request *req, char **name, char **number, int set_call_forward);
01251 static int sip_send_mwi_to_peer(struct sip_peer *peer, const struct ast_event *event, int cache_only);
01252 
01253 /* Misc dialog routines */
01254 static int __sip_autodestruct(const void *data);
01255 static void *registry_unref(struct sip_registry *reg, char *tag);
01256 static int update_call_counter(struct sip_pvt *fup, int event);
01257 static int auto_congest(const void *arg);
01258 static struct sip_pvt *find_call(struct sip_request *req, struct ast_sockaddr *addr, const int intended_method);
01259 static void free_old_route(struct sip_route *route);
01260 static void list_route(struct sip_route *route);
01261 static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards);
01262 static enum check_auth_result register_verify(struct sip_pvt *p, struct ast_sockaddr *addr,
01263                      struct sip_request *req, const char *uri);
01264 static struct sip_pvt *get_sip_pvt_byid_locked(const char *callid, const char *totag, const char *fromtag);
01265 static void check_pendings(struct sip_pvt *p);
01266 static void *sip_park_thread(void *stuff);
01267 static int sip_park(struct ast_channel *chan1, struct ast_channel *chan2, struct sip_request *req, int seqno, char *parkexten);
01268 static int sip_sipredirect(struct sip_pvt *p, const char *dest);
01269 static int is_method_allowed(unsigned int *allowed_methods, enum sipmethod method);
01270 
01271 /*--- Codec handling / SDP */
01272 static void try_suggested_sip_codec(struct sip_pvt *p);
01273 static const char *get_sdp_iterate(int* start, struct sip_request *req, const char *name);
01274 static char get_sdp_line(int *start, int stop, struct sip_request *req, const char **value);
01275 static int find_sdp(struct sip_request *req);
01276 static int process_sdp(struct sip_pvt *p, struct sip_request *req, int t38action);
01277 static int process_sdp_o(const char *o, struct sip_pvt *p);
01278 static int process_sdp_c(const char *c, struct ast_sockaddr *addr);
01279 static int process_sdp_a_sendonly(const char *a, int *sendonly);
01280 static int process_sdp_a_audio(const char *a, struct sip_pvt *p, struct ast_rtp_codecs *newaudiortp, int *last_rtpmap_codec);
01281 static int process_sdp_a_video(const char *a, struct sip_pvt *p, struct ast_rtp_codecs *newvideortp, int *last_rtpmap_codec);
01282 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);
01283 static int process_sdp_a_image(const char *a, struct sip_pvt *p);
01284 static void add_codec_to_sdp(const struct sip_pvt *p, format_t codec,
01285               struct ast_str **m_buf, struct ast_str **a_buf,
01286               int debug, int *min_packet_size);
01287 static void add_noncodec_to_sdp(const struct sip_pvt *p, int format,
01288             struct ast_str **m_buf, struct ast_str **a_buf,
01289             int debug);
01290 static enum sip_result add_sdp(struct sip_request *resp, struct sip_pvt *p, int oldsdp, int add_audio, int add_t38);
01291 static void do_setnat(struct sip_pvt *p);
01292 static void stop_media_flows(struct sip_pvt *p);
01293 
01294 /*--- Authentication stuff */
01295 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod, char *digest, int digest_len);
01296 static int build_reply_digest(struct sip_pvt *p, int method, char *digest, int digest_len);
01297 static enum check_auth_result check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
01298                 const char *secret, const char *md5secret, int sipmethod,
01299                 const char *uri, enum xmittype reliable, int ignore);
01300 static enum check_auth_result check_user_full(struct sip_pvt *p, struct sip_request *req,
01301                      int sipmethod, const char *uri, enum xmittype reliable,
01302                      struct ast_sockaddr *addr, struct sip_peer **authpeer);
01303 static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, const char *uri, enum xmittype reliable, struct ast_sockaddr *addr);
01304 
01305 /*--- Domain handling */
01306 static int check_sip_domain(const char *domain, char *context, size_t len); /* Check if domain is one of our local domains */
01307 static int add_sip_domain(const char *domain, const enum domain_mode mode, const char *context);
01308 static void clear_sip_domains(void);
01309 
01310 /*--- SIP realm authentication */
01311 static struct sip_auth *add_realm_authentication(struct sip_auth *authlist, const char *configuration, int lineno);
01312 static int clear_realm_authentication(struct sip_auth *authlist); /* Clear realm authentication list (at reload) */
01313 static struct sip_auth *find_realm_authentication(struct sip_auth *authlist, const char *realm);
01314 
01315 /*--- Misc functions */
01316 static void check_rtp_timeout(struct sip_pvt *dialog, time_t t);
01317 static int sip_do_reload(enum channelreloadreason reason);
01318 static int reload_config(enum channelreloadreason reason);
01319 static int expire_register(const void *data);
01320 static void *do_monitor(void *data);
01321 static int restart_monitor(void);
01322 static void peer_mailboxes_to_str(struct ast_str **mailbox_str, struct sip_peer *peer);
01323 static struct ast_variable *copy_vars(struct ast_variable *src);
01324 static int dialog_find_multiple(void *obj, void *arg, int flags);
01325 /* static int sip_addrcmp(char *name, struct sockaddr_in *sin);   Support for peer matching */
01326 static int sip_refer_allocate(struct sip_pvt *p);
01327 static int sip_notify_allocate(struct sip_pvt *p);
01328 static void ast_quiet_chan(struct ast_channel *chan);
01329 static int attempt_transfer(struct sip_dual *transferer, struct sip_dual *target);
01330 static int do_magic_pickup(struct ast_channel *channel, const char *extension, const char *context);
01331 
01332 /*--- Device monitoring and Device/extension state/event handling */
01333 static int cb_extensionstate(char *context, char* exten, int state, void *data);
01334 static int sip_devicestate(void *data);
01335 static int sip_poke_noanswer(const void *data);
01336 static int sip_poke_peer(struct sip_peer *peer, int force);
01337 static void sip_poke_all_peers(void);
01338 static void sip_peer_hold(struct sip_pvt *p, int hold);
01339 static void mwi_event_cb(const struct ast_event *, void *);
01340 static void network_change_event_cb(const struct ast_event *, void *);
01341 
01342 /*--- Applications, functions, CLI and manager command helpers */
01343 static const char *sip_nat_mode(const struct sip_pvt *p);
01344 static char *sip_show_inuse(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01345 static char *transfermode2str(enum transfermodes mode) attribute_const;
01346 static int peer_status(struct sip_peer *peer, char *status, int statuslen);
01347 static char *sip_show_sched(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01348 static char * _sip_show_peers(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char *argv[]);
01349 static char *sip_show_peers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01350 static char *sip_show_objects(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01351 static void  print_group(int fd, ast_group_t group, int crlf);
01352 static const char *dtmfmode2str(int mode) attribute_const;
01353 static int str2dtmfmode(const char *str) attribute_unused;
01354 static const char *insecure2str(int mode) attribute_const;
01355 static void cleanup_stale_contexts(char *new, char *old);
01356 static void print_codec_to_cli(int fd, struct ast_codec_pref *pref);
01357 static const char *domain_mode_to_text(const enum domain_mode mode);
01358 static char *sip_show_domains(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01359 static char *_sip_show_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[]);
01360 static char *sip_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01361 static char *_sip_qualify_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[]);
01362 static char *sip_qualify_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01363 static char *sip_show_registry(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01364 static char *sip_unregister(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01365 static char *sip_show_settings(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01366 static char *sip_show_mwi(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01367 static const char *subscription_type2str(enum subscriptiontype subtype) attribute_pure;
01368 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
01369 static char *complete_sip_peer(const char *word, int state, int flags2);
01370 static char *complete_sip_registered_peer(const char *word, int state, int flags2);
01371 static char *complete_sip_show_history(const char *line, const char *word, int pos, int state);
01372 static char *complete_sip_show_peer(const char *line, const char *word, int pos, int state);
01373 static char *complete_sip_unregister(const char *line, const char *word, int pos, int state);
01374 static char *complete_sipnotify(const char *line, const char *word, int pos, int state);
01375 static char *sip_show_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01376 static char *sip_show_channelstats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01377 static char *sip_show_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01378 static char *sip_do_debug_ip(int fd, const char *arg);
01379 static char *sip_do_debug_peer(int fd, const char *arg);
01380 static char *sip_do_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01381 static char *sip_cli_notify(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01382 static char *sip_set_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01383 static int sip_dtmfmode(struct ast_channel *chan, const char *data);
01384 static int sip_addheader(struct ast_channel *chan, const char *data);
01385 static int sip_do_reload(enum channelreloadreason reason);
01386 static char *sip_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01387 static int ast_sockaddr_resolve_first_af(struct ast_sockaddr *addr,
01388                   const char *name, int flag, int family);
01389 static int ast_sockaddr_resolve_first(struct ast_sockaddr *addr,
01390                   const char *name, int flag);
01391 
01392 /*--- Debugging
01393    Functions for enabling debug per IP or fully, or enabling history logging for
01394    a SIP dialog
01395 */
01396 static void sip_dump_history(struct sip_pvt *dialog); /* Dump history to debuglog at end of dialog, before destroying data */
01397 static inline int sip_debug_test_addr(const struct ast_sockaddr *addr);
01398 static inline int sip_debug_test_pvt(struct sip_pvt *p);
01399 static void append_history_full(struct sip_pvt *p, const char *fmt, ...);
01400 static void sip_dump_history(struct sip_pvt *dialog);
01401 
01402 /*--- Device object handling */
01403 static struct sip_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime, int devstate_only);
01404 static int update_call_counter(struct sip_pvt *fup, int event);
01405 static void sip_destroy_peer(struct sip_peer *peer);
01406 static void sip_destroy_peer_fn(void *peer);
01407 static void set_peer_defaults(struct sip_peer *peer);
01408 static struct sip_peer *temp_peer(const char *name);
01409 static void register_peer_exten(struct sip_peer *peer, int onoff);
01410 static struct sip_peer *find_peer(const char *peer, struct ast_sockaddr *addr, int realtime, int forcenamematch, int devstate_only, int transport);
01411 static int sip_poke_peer_s(const void *data);
01412 static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *p, struct sip_request *req);
01413 static void reg_source_db(struct sip_peer *peer);
01414 static void destroy_association(struct sip_peer *peer);
01415 static void set_insecure_flags(struct ast_flags *flags, const char *value, int lineno);
01416 static int handle_common_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v);
01417 static void set_socket_transport(struct sip_socket *socket, int transport);
01418 
01419 /* Realtime device support */
01420 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);
01421 static void update_peer(struct sip_peer *p, int expire);
01422 static struct ast_variable *get_insecure_variable_from_config(struct ast_config *config);
01423 static const char *get_name_from_variable(struct ast_variable *var, const char *newpeername);
01424 static struct sip_peer *realtime_peer(const char *peername, struct ast_sockaddr *sin, int devstate_only, int which_objects);
01425 static char *sip_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01426 
01427 /*--- Internal UA client handling (outbound registrations) */
01428 static void ast_sip_ouraddrfor(const struct ast_sockaddr *them, struct ast_sockaddr *us, struct sip_pvt *p);
01429 static void sip_registry_destroy(struct sip_registry *reg);
01430 static int sip_register(const char *value, int lineno);
01431 static const char *regstate2str(enum sipregistrystate regstate) attribute_const;
01432 static int sip_reregister(const void *data);
01433 static int __sip_do_register(struct sip_registry *r);
01434 static int sip_reg_timeout(const void *data);
01435 static void sip_send_all_registers(void);
01436 static int sip_reinvite_retry(const void *data);
01437 
01438 /*--- Parsing SIP requests and responses */
01439 static void append_date(struct sip_request *req);  /* Append date to SIP packet */
01440 static int determine_firstline_parts(struct sip_request *req);
01441 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
01442 static const char *gettag(const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize);
01443 static int find_sip_method(const char *msg);
01444 static unsigned int parse_allowed_methods(struct sip_request *req);
01445 static unsigned int set_pvt_allowed_methods(struct sip_pvt *pvt, struct sip_request *req);
01446 static int parse_request(struct sip_request *req);
01447 static const char *get_header(const struct sip_request *req, const char *name);
01448 static const char *referstatus2str(enum referstatus rstatus) attribute_pure;
01449 static int method_match(enum sipmethod id, const char *name);
01450 static void parse_copy(struct sip_request *dst, const struct sip_request *src);
01451 static const char *find_alias(const char *name, const char *_default);
01452 static const char *__get_header(const struct sip_request *req, const char *name, int *start);
01453 static int lws2sws(char *msgbuf, int len);
01454 static void extract_uri(struct sip_pvt *p, struct sip_request *req);
01455 static char *remove_uri_parameters(char *uri);
01456 static int get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req);
01457 static int get_also_info(struct sip_pvt *p, struct sip_request *oreq);
01458 static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req);
01459 static int set_address_from_contact(struct sip_pvt *pvt);
01460 static void check_via(struct sip_pvt *p, struct sip_request *req);
01461 static int get_rpid(struct sip_pvt *p, struct sip_request *oreq);
01462 static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq, char **name, char **number, int *reason);
01463 static enum sip_get_dest_result get_destination(struct sip_pvt *p, struct sip_request *oreq, int *cc_recall_core_id);
01464 static int get_msg_text(char *buf, int len, struct sip_request *req, int addnewline);
01465 static int transmit_state_notify(struct sip_pvt *p, int state, int full, int timeout);
01466 static void update_connectedline(struct sip_pvt *p, const void *data, size_t datalen);
01467 static void update_redirecting(struct sip_pvt *p, const void *data, size_t datalen);
01468 static int get_domain(const char *str, char *domain, int len);
01469 static void get_realm(struct sip_pvt *p, const struct sip_request *req);
01470 
01471 /*-- TCP connection handling ---*/
01472 static void *_sip_tcp_helper_thread(struct sip_pvt *pvt, struct ast_tcptls_session_instance *tcptls_session);
01473 static void *sip_tcp_worker_fn(void *);
01474 
01475 /*--- Constructing requests and responses */
01476 static void initialize_initreq(struct sip_pvt *p, struct sip_request *req);
01477 static int init_req(struct sip_request *req, int sipmethod, const char *recip);
01478 static void deinit_req(struct sip_request *req);
01479 static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, int seqno, int newbranch);
01480 static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, const char * const explicit_uri);
01481 static int init_resp(struct sip_request *resp, const char *msg);
01482 static inline int resp_needs_contact(const char *msg, enum sipmethod method);
01483 static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req);
01484 static const struct ast_sockaddr *sip_real_dst(const struct sip_pvt *p);
01485 static void build_via(struct sip_pvt *p);
01486 static int create_addr_from_peer(struct sip_pvt *r, struct sip_peer *peer);
01487 static int create_addr(struct sip_pvt *dialog, const char *opeer, struct ast_sockaddr *addr, int newdialog, struct ast_sockaddr *remote_address);
01488 static char *generate_random_string(char *buf, size_t size);
01489 static void build_callid_pvt(struct sip_pvt *pvt);
01490 static void build_callid_registry(struct sip_registry *reg, const struct ast_sockaddr *ourip, const char *fromdomain);
01491 static void make_our_tag(char *tagbuf, size_t len);
01492 static int add_header(struct sip_request *req, const char *var, const char *value);
01493 static int add_header_max_forwards(struct sip_pvt *dialog, struct sip_request *req);
01494 static int add_content(struct sip_request *req, const char *line);
01495 static int finalize_content(struct sip_request *req);
01496 static int add_text(struct sip_request *req, const char *text);
01497 static int add_digit(struct sip_request *req, char digit, unsigned int duration, int mode);
01498 static int add_rpid(struct sip_request *req, struct sip_pvt *p);
01499 static int add_vidupdate(struct sip_request *req);
01500 static void add_route(struct sip_request *req, struct sip_route *route);
01501 static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field);
01502 static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field);
01503 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field);
01504 static void set_destination(struct sip_pvt *p, char *uri);
01505 static void append_date(struct sip_request *req);
01506 static void build_contact(struct sip_pvt *p);
01507 
01508 /*------Request handling functions */
01509 static int handle_incoming(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, int *recount, int *nounlock);
01510 static int handle_request_update(struct sip_pvt *p, struct sip_request *req);
01511 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);
01512 static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, int *nounlock);
01513 static int handle_request_bye(struct sip_pvt *p, struct sip_request *req);
01514 static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *sin, const char *e);
01515 static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req);
01516 static int handle_request_message(struct sip_pvt *p, struct sip_request *req);
01517 static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, int seqno, const char *e);
01518 static void handle_request_info(struct sip_pvt *p, struct sip_request *req);
01519 static int handle_request_options(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, const char *e);
01520 static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, struct ast_sockaddr *addr, int *nounlock);
01521 static int handle_request_notify(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, int seqno, const char *e);
01522 static int local_attended_transfer(struct sip_pvt *transferer, struct sip_dual *current, struct sip_request *req, int seqno, int *nounlock);
01523 
01524 /*------Response handling functions */
01525 static void handle_response_publish(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno);
01526 static void handle_response_invite(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno);
01527 static void handle_response_notify(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno);
01528 static void handle_response_refer(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno);
01529 static void handle_response_subscribe(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno);
01530 static int handle_response_register(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno);
01531 static void handle_response(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno);
01532 
01533 /*------ SRTP Support -------- */
01534 static int setup_srtp(struct sip_srtp **srtp);
01535 static int process_crypto(struct sip_pvt *p, struct ast_rtp_instance *rtp, struct sip_srtp **srtp, const char *a);
01536 
01537 /*------ T38 Support --------- */
01538 static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans);
01539 static struct ast_udptl *sip_get_udptl_peer(struct ast_channel *chan);
01540 static int sip_set_udptl_peer(struct ast_channel *chan, struct ast_udptl *udptl);
01541 static void change_t38_state(struct sip_pvt *p, int state);
01542 
01543 /*------ Session-Timers functions --------- */
01544 static void proc_422_rsp(struct sip_pvt *p, struct sip_request *rsp);
01545 static int  proc_session_timer(const void *vp);
01546 static void stop_session_timer(struct sip_pvt *p);
01547 static void start_session_timer(struct sip_pvt *p);
01548 static void restart_session_timer(struct sip_pvt *p);
01549 static const char *strefresher2str(enum st_refresher r);
01550 static int parse_session_expires(const char *p_hdrval, int *const p_interval, enum st_refresher *const p_ref);
01551 static int parse_minse(const char *p_hdrval, int *const p_interval);
01552 static int st_get_se(struct sip_pvt *, int max);
01553 static enum st_refresher st_get_refresher(struct sip_pvt *);
01554 static enum st_mode st_get_mode(struct sip_pvt *);
01555 static struct sip_st_dlg* sip_st_alloc(struct sip_pvt *const p);
01556 
01557 /*------- RTP Glue functions -------- */
01558 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);
01559 
01560 /*!--- SIP MWI Subscription support */
01561 static int sip_subscribe_mwi(const char *value, int lineno);
01562 static void sip_subscribe_mwi_destroy(struct sip_subscription_mwi *mwi);
01563 static void sip_send_all_mwi_subscriptions(void);
01564 static int sip_subscribe_mwi_do(const void *data);
01565 static int __sip_subscribe_mwi_do(struct sip_subscription_mwi *mwi);
01566 
01567 /*! \brief Definition of this channel for PBX channel registration */
01568 const struct ast_channel_tech sip_tech = {
01569    .type = "SIP",
01570    .description = "Session Initiation Protocol (SIP)",
01571    .capabilities = AST_FORMAT_AUDIO_MASK, /* all audio formats */
01572    .properties = AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER,
01573    .requester = sip_request_call,         /* called with chan unlocked */
01574    .devicestate = sip_devicestate,        /* called with chan unlocked (not chan-specific) */
01575    .call = sip_call,       /* called with chan locked */
01576    .send_html = sip_sendhtml,
01577    .hangup = sip_hangup,         /* called with chan locked */
01578    .answer = sip_answer,         /* called with chan locked */
01579    .read = sip_read,       /* called with chan locked */
01580    .write = sip_write,        /* called with chan locked */
01581    .write_video = sip_write,     /* called with chan locked */
01582    .write_text = sip_write,
01583    .indicate = sip_indicate,     /* called with chan locked */
01584    .transfer = sip_transfer,     /* called with chan locked */
01585    .fixup = sip_fixup,        /* called with chan locked */
01586    .send_digit_begin = sip_senddigit_begin,  /* called with chan unlocked */
01587    .send_digit_end = sip_senddigit_end,
01588    .bridge = ast_rtp_instance_bridge,        /* XXX chan unlocked ? */
01589    .early_bridge = ast_rtp_instance_early_bridge,
01590    .send_text = sip_sendtext,    /* called with chan locked */
01591    .func_channel_read = sip_acf_channel_read,
01592    .setoption = sip_setoption,
01593    .queryoption = sip_queryoption,
01594    .get_pvt_uniqueid = sip_get_callid,
01595 };
01596 
01597 /*! \brief This version of the sip channel tech has no send_digit_begin
01598  * callback so that the core knows that the channel does not want
01599  * DTMF BEGIN frames.
01600  * The struct is initialized just before registering the channel driver,
01601  * and is for use with channels using SIP INFO DTMF.
01602  */
01603 struct ast_channel_tech sip_tech_info;
01604 
01605 static int sip_cc_agent_init(struct ast_cc_agent *agent, struct ast_channel *chan);
01606 static int sip_cc_agent_start_offer_timer(struct ast_cc_agent *agent);
01607 static int sip_cc_agent_stop_offer_timer(struct ast_cc_agent *agent);
01608 static void sip_cc_agent_ack(struct ast_cc_agent *agent);
01609 static int sip_cc_agent_status_request(struct ast_cc_agent *agent);
01610 static int sip_cc_agent_start_monitoring(struct ast_cc_agent *agent);
01611 static int sip_cc_agent_recall(struct ast_cc_agent *agent);
01612 static void sip_cc_agent_destructor(struct ast_cc_agent *agent);
01613 
01614 static struct ast_cc_agent_callbacks sip_cc_agent_callbacks = {
01615    .type = "SIP",
01616    .init = sip_cc_agent_init,
01617    .start_offer_timer = sip_cc_agent_start_offer_timer,
01618    .stop_offer_timer = sip_cc_agent_stop_offer_timer,
01619    .ack = sip_cc_agent_ack,
01620    .status_request = sip_cc_agent_status_request,
01621    .start_monitoring = sip_cc_agent_start_monitoring,
01622    .callee_available = sip_cc_agent_recall,
01623    .destructor = sip_cc_agent_destructor,
01624 };
01625 
01626 static int find_by_notify_uri_helper(void *obj, void *arg, int flags)
01627 {
01628    struct ast_cc_agent *agent = obj;
01629    struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01630    const char *uri = arg;
01631 
01632    return !sip_uri_cmp(agent_pvt->notify_uri, uri) ? CMP_MATCH | CMP_STOP : 0;
01633 }
01634 
01635 static struct ast_cc_agent *find_sip_cc_agent_by_notify_uri(const char * const uri)
01636 {
01637    struct ast_cc_agent *agent = ast_cc_agent_callback(0, find_by_notify_uri_helper, (char *)uri, "SIP");
01638    return agent;
01639 }
01640 
01641 static int find_by_subscribe_uri_helper(void *obj, void *arg, int flags)
01642 {
01643    struct ast_cc_agent *agent = obj;
01644    struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01645    const char *uri = arg;
01646 
01647    return !sip_uri_cmp(agent_pvt->subscribe_uri, uri) ? CMP_MATCH | CMP_STOP : 0;
01648 }
01649 
01650 static struct ast_cc_agent *find_sip_cc_agent_by_subscribe_uri(const char * const uri)
01651 {
01652    struct ast_cc_agent *agent = ast_cc_agent_callback(0, find_by_subscribe_uri_helper, (char *)uri, "SIP");
01653    return agent;
01654 }
01655 
01656 static int find_by_callid_helper(void *obj, void *arg, int flags)
01657 {
01658    struct ast_cc_agent *agent = obj;
01659    struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01660    struct sip_pvt *call_pvt = arg;
01661 
01662    return !strcmp(agent_pvt->original_callid, call_pvt->callid) ? CMP_MATCH | CMP_STOP : 0;
01663 }
01664 
01665 static struct ast_cc_agent *find_sip_cc_agent_by_original_callid(struct sip_pvt *pvt)
01666 {
01667    struct ast_cc_agent *agent = ast_cc_agent_callback(0, find_by_callid_helper, pvt, "SIP");
01668    return agent;
01669 }
01670 
01671 static int sip_cc_agent_init(struct ast_cc_agent *agent, struct ast_channel *chan)
01672 {
01673    struct sip_cc_agent_pvt *agent_pvt = ast_calloc(1, sizeof(*agent_pvt));
01674    struct sip_pvt *call_pvt = chan->tech_pvt;
01675 
01676    if (!agent_pvt) {
01677       return -1;
01678    }
01679 
01680    ast_assert(!strcmp(chan->tech->type, "SIP"));
01681 
01682    ast_copy_string(agent_pvt->original_callid, call_pvt->callid, sizeof(agent_pvt->original_callid));
01683    ast_copy_string(agent_pvt->original_exten, call_pvt->exten, sizeof(agent_pvt->original_exten));
01684    agent_pvt->offer_timer_id = -1;
01685    agent->private_data = agent_pvt;
01686    sip_pvt_lock(call_pvt);
01687    ast_set_flag(&call_pvt->flags[0], SIP_OFFER_CC);
01688    sip_pvt_unlock(call_pvt);
01689    return 0;
01690 }
01691 
01692 static int sip_offer_timer_expire(const void *data)
01693 {
01694    struct ast_cc_agent *agent = (struct ast_cc_agent *) data;
01695    struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01696 
01697    agent_pvt->offer_timer_id = -1;
01698 
01699    return ast_cc_failed(agent->core_id, "SIP agent %s's offer timer expired", agent->device_name);
01700 }
01701 
01702 static int sip_cc_agent_start_offer_timer(struct ast_cc_agent *agent)
01703 {
01704    struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01705    int when;
01706 
01707    when = ast_get_cc_offer_timer(agent->cc_params) * 1000;
01708    agent_pvt->offer_timer_id = ast_sched_add(sched, when, sip_offer_timer_expire, agent);
01709    return 0;
01710 }
01711 
01712 static int sip_cc_agent_stop_offer_timer(struct ast_cc_agent *agent)
01713 {
01714    struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01715 
01716    AST_SCHED_DEL(sched, agent_pvt->offer_timer_id);
01717    return 0;
01718 }
01719 
01720 static void sip_cc_agent_ack(struct ast_cc_agent *agent)
01721 {
01722    struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01723 
01724    sip_pvt_lock(agent_pvt->subscribe_pvt);
01725    ast_set_flag(&agent_pvt->subscribe_pvt->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
01726    transmit_response(agent_pvt->subscribe_pvt, "200 OK", &agent_pvt->subscribe_pvt->initreq);
01727    transmit_cc_notify(agent, agent_pvt->subscribe_pvt, CC_QUEUED);
01728    sip_pvt_unlock(agent_pvt->subscribe_pvt);
01729    agent_pvt->is_available = TRUE;
01730 }
01731 
01732 static int sip_cc_agent_status_request(struct ast_cc_agent *agent)
01733 {
01734    struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01735    enum ast_device_state state = agent_pvt->is_available ? AST_DEVICE_NOT_INUSE : AST_DEVICE_INUSE;
01736    return ast_cc_agent_status_response(agent->core_id, state);
01737 }
01738 
01739 static int sip_cc_agent_start_monitoring(struct ast_cc_agent *agent)
01740 {
01741    /* To start monitoring just means to wait for an incoming PUBLISH
01742     * to tell us that the caller has become available again. No special
01743     * action is needed
01744     */
01745    return 0;
01746 }
01747 
01748 static int sip_cc_agent_recall(struct ast_cc_agent *agent)
01749 {
01750    struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01751    /* If we have received a PUBLISH beforehand stating that the caller in question
01752     * is not available, we can save ourself a bit of effort here and just report
01753     * the caller as busy
01754     */
01755    if (!agent_pvt->is_available) {
01756       return ast_cc_agent_caller_busy(agent->core_id, "Caller %s is busy, reporting to the core",
01757             agent->device_name);
01758    }
01759    /* Otherwise, we transmit a NOTIFY to the caller and await either
01760     * a PUBLISH or an INVITE
01761     */
01762    sip_pvt_lock(agent_pvt->subscribe_pvt);
01763    transmit_cc_notify(agent, agent_pvt->subscribe_pvt, CC_READY);
01764    sip_pvt_unlock(agent_pvt->subscribe_pvt);
01765    return 0;
01766 }
01767 
01768 static void sip_cc_agent_destructor(struct ast_cc_agent *agent)
01769 {
01770    struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01771 
01772    if (!agent_pvt) {
01773       /* The agent constructor probably failed. */
01774       return;
01775    }
01776 
01777    sip_cc_agent_stop_offer_timer(agent);
01778    if (agent_pvt->subscribe_pvt) {
01779       sip_pvt_lock(agent_pvt->subscribe_pvt);
01780       if (!ast_test_flag(&agent_pvt->subscribe_pvt->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED)) {
01781          /* If we haven't sent a 200 OK for the SUBSCRIBE dialog yet, then we need to send a response letting
01782           * the subscriber know something went wrong
01783           */
01784          transmit_response(agent_pvt->subscribe_pvt, "500 Internal Server Error", &agent_pvt->subscribe_pvt->initreq);
01785       }
01786       sip_pvt_unlock(agent_pvt->subscribe_pvt);
01787       agent_pvt->subscribe_pvt = dialog_unref(agent_pvt->subscribe_pvt, "SIP CC agent destructor: Remove ref to subscription");
01788    }
01789    ast_free(agent_pvt);
01790 }
01791 
01792 struct ao2_container *sip_monitor_instances;
01793 
01794 static int sip_monitor_instance_hash_fn(const void *obj, const int flags)
01795 {
01796    const struct sip_monitor_instance *monitor_instance = obj;
01797    return monitor_instance->core_id;
01798 }
01799 
01800 static int sip_monitor_instance_cmp_fn(void *obj, void *arg, int flags)
01801 {
01802    struct sip_monitor_instance *monitor_instance1 = obj;
01803    struct sip_monitor_instance *monitor_instance2 = arg;
01804 
01805    return monitor_instance1->core_id == monitor_instance2->core_id ? CMP_MATCH | CMP_STOP : 0;
01806 }
01807 
01808 static void sip_monitor_instance_destructor(void *data)
01809 {
01810    struct sip_monitor_instance *monitor_instance = data;
01811    if (monitor_instance->subscription_pvt) {
01812       sip_pvt_lock(monitor_instance->subscription_pvt);
01813       monitor_instance->subscription_pvt->expiry = 0;
01814       transmit_invite(monitor_instance->subscription_pvt, SIP_SUBSCRIBE, FALSE, 0, monitor_instance->subscribe_uri);
01815       sip_pvt_unlock(monitor_instance->subscription_pvt);
01816       dialog_unref(monitor_instance->subscription_pvt, "Unref monitor instance ref of subscription pvt");
01817    }
01818    if (monitor_instance->suspension_entry) {
01819       monitor_instance->suspension_entry->body[0] = '\0';
01820       transmit_publish(monitor_instance->suspension_entry, SIP_PUBLISH_REMOVE ,monitor_instance->notify_uri);
01821       ao2_t_ref(monitor_instance->suspension_entry, -1, "Decrementing suspension entry refcount in sip_monitor_instance_destructor");
01822    }
01823    ast_string_field_free_memory(monitor_instance);
01824 }
01825 
01826 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)
01827 {
01828    struct sip_monitor_instance *monitor_instance = ao2_alloc(sizeof(*monitor_instance), sip_monitor_instance_destructor);
01829 
01830    if (!monitor_instance) {
01831       return NULL;
01832    }
01833 
01834    if (ast_string_field_init(monitor_instance, 256)) {
01835       ao2_ref(monitor_instance, -1);
01836       return NULL;
01837    }
01838 
01839    ast_string_field_set(monitor_instance, subscribe_uri, subscribe_uri);
01840    ast_string_field_set(monitor_instance, peername, peername);
01841    ast_string_field_set(monitor_instance, device_name, device_name);
01842    monitor_instance->core_id = core_id;
01843    ao2_link(sip_monitor_instances, monitor_instance);
01844    return monitor_instance;
01845 }
01846 
01847 static int find_sip_monitor_instance_by_subscription_pvt(void *obj, void *arg, int flags)
01848 {
01849    struct sip_monitor_instance *monitor_instance = obj;
01850    return monitor_instance->subscription_pvt == arg ? CMP_MATCH | CMP_STOP : 0;
01851 }
01852 
01853 static int find_sip_monitor_instance_by_suspension_entry(void *obj, void *arg, int flags)
01854 {
01855    struct sip_monitor_instance *monitor_instance = obj;
01856    return monitor_instance->suspension_entry == arg ? CMP_MATCH | CMP_STOP : 0;
01857 }
01858 
01859 static int sip_cc_monitor_request_cc(struct ast_cc_monitor *monitor, int *available_timer_id);
01860 static int sip_cc_monitor_suspend(struct ast_cc_monitor *monitor);
01861 static int sip_cc_monitor_unsuspend(struct ast_cc_monitor *monitor);
01862 static int sip_cc_monitor_cancel_available_timer(struct ast_cc_monitor *monitor, int *sched_id);
01863 static void sip_cc_monitor_destructor(void *private_data);
01864 
01865 static struct ast_cc_monitor_callbacks sip_cc_monitor_callbacks = {
01866    .type = "SIP",
01867    .request_cc = sip_cc_monitor_request_cc,
01868    .suspend = sip_cc_monitor_suspend,
01869    .unsuspend = sip_cc_monitor_unsuspend,
01870    .cancel_available_timer = sip_cc_monitor_cancel_available_timer,
01871    .destructor = sip_cc_monitor_destructor,
01872 };
01873 
01874 static int sip_cc_monitor_request_cc(struct ast_cc_monitor *monitor, int *available_timer_id)
01875 {
01876    struct sip_monitor_instance *monitor_instance = monitor->private_data;
01877    enum ast_cc_service_type service = monitor->service_offered;
01878    int when;
01879 
01880    if (!monitor_instance) {
01881       return -1;
01882    }
01883 
01884    if (!(monitor_instance->subscription_pvt = sip_alloc(NULL, NULL, 0, SIP_SUBSCRIBE, NULL))) {
01885       return -1;
01886    }
01887 
01888    when = service == AST_CC_CCBS ? ast_get_ccbs_available_timer(monitor->interface->config_params) :
01889       ast_get_ccnr_available_timer(monitor->interface->config_params);
01890 
01891    sip_pvt_lock(monitor_instance->subscription_pvt);
01892    create_addr(monitor_instance->subscription_pvt, monitor_instance->peername, 0, 1, NULL);
01893    ast_sip_ouraddrfor(&monitor_instance->subscription_pvt->sa, &monitor_instance->subscription_pvt->ourip, monitor_instance->subscription_pvt);
01894    monitor_instance->subscription_pvt->subscribed = CALL_COMPLETION;
01895    monitor_instance->subscription_pvt->expiry = when;
01896 
01897    transmit_invite(monitor_instance->subscription_pvt, SIP_SUBSCRIBE, FALSE, 2, monitor_instance->subscribe_uri);
01898    sip_pvt_unlock(monitor_instance->subscription_pvt);
01899 
01900    ao2_t_ref(monitor, +1, "Adding a ref to the monitor for the scheduler");
01901    *available_timer_id = ast_sched_add(sched, when * 1000, ast_cc_available_timer_expire, monitor);
01902    return 0;
01903 }
01904 
01905 static int construct_pidf_body(enum sip_cc_publish_state state, char *pidf_body, size_t size, const char *presentity)
01906 {
01907    struct ast_str *body = ast_str_alloca(size);
01908    char tuple_id[32];
01909 
01910    generate_random_string(tuple_id, sizeof(tuple_id));
01911 
01912    /* We'll make this a bare-bones pidf body. In state_notify_build_xml, the PIDF
01913     * body gets a lot more extra junk that isn't necessary, so we'll leave it out here.
01914     */
01915    ast_str_append(&body, 0, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
01916    /* XXX The entity attribute is currently set to the peer name associated with the
01917     * dialog. This is because we currently only call this function for call-completion
01918     * PUBLISH bodies. In such cases, the entity is completely disregarded. For other
01919     * event packages, it may be crucial to have a proper URI as the presentity so this
01920     * should be revisited as support is expanded.
01921     */
01922    ast_str_append(&body, 0, "<presence xmlns=\"urn:ietf:params:xml:ns:pidf\" entity=\"%s\">\n", presentity);
01923    ast_str_append(&body, 0, "<tuple id=\"%s\">\n", tuple_id);
01924    ast_str_append(&body, 0, "<status><basic>%s</basic></status>\n", state == CC_OPEN ? "open" : "closed");
01925    ast_str_append(&body, 0, "</tuple>\n");
01926    ast_str_append(&body, 0, "</presence>\n");
01927    ast_copy_string(pidf_body, ast_str_buffer(body), size);
01928    return 0;
01929 }
01930 
01931 static int sip_cc_monitor_suspend(struct ast_cc_monitor *monitor)
01932 {
01933    struct sip_monitor_instance *monitor_instance = monitor->private_data;
01934    enum sip_publish_type publish_type;
01935    struct cc_epa_entry *cc_entry;
01936 
01937    if (!monitor_instance) {
01938       return -1;
01939    }
01940 
01941    if (!monitor_instance->suspension_entry) {
01942       /* We haven't yet allocated the suspension entry, so let's give it a shot */
01943       if (!(monitor_instance->suspension_entry = create_epa_entry("call-completion", monitor_instance->peername))) {
01944          ast_log(LOG_WARNING, "Unable to allocate sip EPA entry for call-completion\n");
01945          ao2_ref(monitor_instance, -1);
01946          return -1;
01947       }
01948       if (!(cc_entry = ast_calloc(1, sizeof(*cc_entry)))) {
01949          ast_log(LOG_WARNING, "Unable to allocate space for instance data of EPA entry for call-completion\n");
01950          ao2_ref(monitor_instance, -1);
01951          return -1;
01952       }
01953       cc_entry->core_id = monitor->core_id;
01954       monitor_instance->suspension_entry->instance_data = cc_entry;
01955       publish_type = SIP_PUBLISH_INITIAL;
01956    } else {
01957       publish_type = SIP_PUBLISH_MODIFY;
01958       cc_entry = monitor_instance->suspension_entry->instance_data;
01959    }
01960 
01961    cc_entry->current_state = CC_CLOSED;
01962 
01963    if (ast_strlen_zero(monitor_instance->notify_uri)) {
01964       /* If we have no set notify_uri, then what this means is that we have
01965        * not received a NOTIFY from this destination stating that he is
01966        * currently available.
01967        *
01968        * This situation can arise when the core calls the suspend callbacks
01969        * of multiple destinations. If one of the other destinations aside
01970        * from this one notified Asterisk that he is available, then there
01971        * is no reason to take any suspension action on this device. Rather,
01972        * we should return now and if we receive a NOTIFY while monitoring
01973        * is still "suspended" then we can immediately respond with the
01974        * proper PUBLISH to let this endpoint know what is going on.
01975        */
01976       return 0;
01977    }
01978    construct_pidf_body(CC_CLOSED, monitor_instance->suspension_entry->body, sizeof(monitor_instance->suspension_entry->body), monitor_instance->peername);
01979    return transmit_publish(monitor_instance->suspension_entry, publish_type, monitor_instance->notify_uri);
01980 }
01981 
01982 static int sip_cc_monitor_unsuspend(struct ast_cc_monitor *monitor)
01983 {
01984    struct sip_monitor_instance *monitor_instance = monitor->private_data;
01985    struct cc_epa_entry *cc_entry;
01986 
01987    if (!monitor_instance) {
01988       return -1;
01989    }
01990 
01991    ast_assert(monitor_instance->suspension_entry != NULL);
01992 
01993    cc_entry = monitor_instance->suspension_entry->instance_data;
01994    cc_entry->current_state = CC_OPEN;
01995    if (ast_strlen_zero(monitor_instance->notify_uri)) {
01996       /* This means we are being asked to unsuspend a call leg we never
01997        * sent a PUBLISH on. As such, there is no reason to send another
01998        * PUBLISH at this point either. We can just return instead.
01999        */
02000       return 0;
02001    }
02002    construct_pidf_body(CC_OPEN, monitor_instance->suspension_entry->body, sizeof(monitor_instance->suspension_entry->body), monitor_instance->peername);
02003    return transmit_publish(monitor_instance->suspension_entry, SIP_PUBLISH_MODIFY, monitor_instance->notify_uri);
02004 }
02005 
02006 static int sip_cc_monitor_cancel_available_timer(struct ast_cc_monitor *monitor, int *sched_id)
02007 {
02008    if (*sched_id != -1) {
02009       AST_SCHED_DEL(sched, *sched_id);
02010       ao2_t_ref(monitor, -1, "Removing scheduler's reference to the monitor");
02011    }
02012    return 0;
02013 }
02014 
02015 static void sip_cc_monitor_destructor(void *private_data)
02016 {
02017    struct sip_monitor_instance *monitor_instance = private_data;
02018    ao2_unlink(sip_monitor_instances, monitor_instance);
02019    ast_module_unref(ast_module_info->self);
02020 }
02021 
02022 static int sip_get_cc_information(struct sip_request *req, char *subscribe_uri, size_t size, enum ast_cc_service_type *service)
02023 {
02024    char *call_info = ast_strdupa(get_header(req, "Call-Info"));
02025    char *uri;
02026    char *purpose;
02027    char *service_str;
02028    static const char cc_purpose[] = "purpose=call-completion";
02029    static const int cc_purpose_len = sizeof(cc_purpose) - 1;
02030 
02031    if (ast_strlen_zero(call_info)) {
02032       /* No Call-Info present. Definitely no CC offer */
02033       return -1;
02034    }
02035 
02036    uri = strsep(&call_info, ";");
02037 
02038    while ((purpose = strsep(&call_info, ";"))) {
02039       if (!strncmp(purpose, cc_purpose, cc_purpose_len)) {
02040          break;
02041       }
02042    }
02043    if (!purpose) {
02044       /* We didn't find the appropriate purpose= parameter. Oh well */
02045       return -1;
02046    }
02047 
02048    /* Okay, call-completion has been offered. Let's figure out what type of service this is */
02049    while ((service_str = strsep(&call_info, ";"))) {
02050       if (!strncmp(service_str, "m=", 2)) {
02051          break;
02052       }
02053    }
02054    if (!service_str) {
02055       /* So they didn't offer a particular service, We'll just go with CCBS since it really
02056        * doesn't matter anyway
02057        */
02058       service_str = "BS";
02059    } else {
02060       /* We already determined that there is an "m=" so no need to check
02061        * the result of this strsep
02062        */
02063       strsep(&service_str, "=");
02064    }
02065 
02066    if ((*service = service_string_to_service_type(service_str)) == AST_CC_NONE) {
02067       /* Invalid service offered */
02068       return -1;
02069    }
02070 
02071    ast_copy_string(subscribe_uri, get_in_brackets(uri), size);
02072 
02073    return 0;
02074 }
02075 
02076 /*
02077  * \brief Determine what, if any, CC has been offered and queue a CC frame if possible
02078  *
02079  * After taking care of some formalities to be sure that this call is eligible for CC,
02080  * we first try to see if we can make use of native CC. We grab the information from
02081  * the passed-in sip_request (which is always a response to an INVITE). If we can
02082  * use native CC monitoring for the call, then so be it.
02083  *
02084  * If native cc monitoring is not possible or not supported, then we will instead attempt
02085  * to use generic monitoring. Falling back to generic from a failed attempt at using native
02086  * monitoring will only work if the monitor policy of the endpoint is "always"
02087  *
02088  * \param pvt The current dialog. Contains CC parameters for the endpoint
02089  * \param req The response to the INVITE we want to inspect
02090  * \param service The service to use if generic monitoring is to be used. For native
02091  * monitoring, we get the service from the SIP response itself
02092  */
02093 static void sip_handle_cc(struct sip_pvt *pvt, struct sip_request *req, enum ast_cc_service_type service)
02094 {
02095    enum ast_cc_monitor_policies monitor_policy = ast_get_cc_monitor_policy(pvt->cc_params);
02096    int core_id;
02097    char interface_name[AST_CHANNEL_NAME];
02098 
02099    if (monitor_policy == AST_CC_MONITOR_NEVER) {
02100       /* Don't bother, just return */
02101       return;
02102    }
02103 
02104    if ((core_id = ast_cc_get_current_core_id(pvt->owner)) == -1) {
02105       /* For some reason, CC is invalid, so don't try it! */
02106       return;
02107    }
02108 
02109    ast_channel_get_device_name(pvt->owner, interface_name, sizeof(interface_name));
02110 
02111    if (monitor_policy == AST_CC_MONITOR_ALWAYS || monitor_policy == AST_CC_MONITOR_NATIVE) {
02112       char subscribe_uri[SIPBUFSIZE];
02113       char device_name[AST_CHANNEL_NAME];
02114       enum ast_cc_service_type offered_service;
02115       struct sip_monitor_instance *monitor_instance;
02116       if (sip_get_cc_information(req, subscribe_uri, sizeof(subscribe_uri), &offered_service)) {
02117          /* If CC isn't being offered to us, or for some reason the CC offer is
02118           * not formatted correctly, then it may still be possible to use generic
02119           * call completion since the monitor policy may be "always"
02120           */
02121          goto generic;
02122       }
02123       ast_channel_get_device_name(pvt->owner, device_name, sizeof(device_name));
02124       if (!(monitor_instance = sip_monitor_instance_init(core_id, subscribe_uri, pvt->peername, device_name))) {
02125          /* Same deal. We can try using generic still */
02126          goto generic;
02127       }
02128       /* We bump the refcount of chan_sip because once we queue this frame, the CC core
02129        * will have a reference to callbacks in this module. We decrement the module
02130        * refcount once the monitor destructor is called
02131        */
02132       ast_module_ref(ast_module_info->self);
02133       ast_queue_cc_frame(pvt->owner, "SIP", pvt->dialstring, offered_service, monitor_instance);
02134       ao2_ref(monitor_instance, -1);
02135       return;
02136    }
02137 
02138 generic:
02139    if (monitor_policy == AST_CC_MONITOR_GENERIC || monitor_policy == AST_CC_MONITOR_ALWAYS) {
02140       ast_queue_cc_frame(pvt->owner, AST_CC_GENERIC_MONITOR_TYPE, interface_name, service, NULL);
02141    }
02142 }
02143 
02144 /*! \brief Working TLS connection configuration */
02145 static struct ast_tls_config sip_tls_cfg;
02146 
02147 /*! \brief Default TLS connection configuration */
02148 static struct ast_tls_config default_tls_cfg;
02149 
02150 /*! \brief The TCP server definition */
02151 static struct ast_tcptls_session_args sip_tcp_desc = {
02152    .accept_fd = -1,
02153    .master = AST_PTHREADT_NULL,
02154    .tls_cfg = NULL,
02155    .poll_timeout = -1,
02156    .name = "SIP TCP server",
02157    .accept_fn = ast_tcptls_server_root,
02158    .worker_fn = sip_tcp_worker_fn,
02159 };
02160 
02161 /*! \brief The TCP/TLS server definition */
02162 static struct ast_tcptls_session_args sip_tls_desc = {
02163    .accept_fd = -1,
02164    .master = AST_PTHREADT_NULL,
02165    .tls_cfg = &sip_tls_cfg,
02166    .poll_timeout = -1,
02167    .name = "SIP TLS server",
02168    .accept_fn = ast_tcptls_server_root,
02169    .worker_fn = sip_tcp_worker_fn,
02170 };
02171 
02172 /*! \brief Append to SIP dialog history
02173    \return Always returns 0 */
02174 #define append_history(p, event, fmt , args... )   append_history_full(p, "%-15s " fmt, event, ## args)
02175 
02176 struct sip_pvt *dialog_ref_debug(struct sip_pvt *p, char *tag, char *file, int line, const char *func)
02177 {
02178    if (p)
02179 #ifdef REF_DEBUG
02180       __ao2_ref_debug(p, 1, tag, file, line, func);
02181 #else
02182       ao2_ref(p, 1);
02183 #endif
02184    else
02185       ast_log(LOG_ERROR, "Attempt to Ref a null pointer\n");
02186    return p;
02187 }
02188 
02189 struct sip_pvt *dialog_unref_debug(struct sip_pvt *p, char *tag, char *file, int line, const char *func)
02190 {
02191    if (p)
02192 #ifdef REF_DEBUG
02193       __ao2_ref_debug(p, -1, tag, file, line, func);
02194 #else
02195       ao2_ref(p, -1);
02196 #endif
02197    return NULL;
02198 }
02199 
02200 /*! \brief map from an integer value to a string.
02201  * If no match is found, return errorstring
02202  */
02203 static const char *map_x_s(const struct _map_x_s *table, int x, const char *errorstring)
02204 {
02205    const struct _map_x_s *cur;
02206 
02207    for (cur = table; cur->s; cur++)
02208       if (cur->x == x)
02209          return cur->s;
02210    return errorstring;
02211 }
02212 
02213 /*! \brief map from a string to an integer value, case insensitive.
02214  * If no match is found, return errorvalue.
02215  */
02216 static int map_s_x(const struct _map_x_s *table, const char *s, int errorvalue)
02217 {
02218    const struct _map_x_s *cur;
02219 
02220    for (cur = table; cur->s; cur++)
02221       if (!strcasecmp(cur->s, s))
02222          return cur->x;
02223    return errorvalue;
02224 }
02225 
02226 static enum AST_REDIRECTING_REASON sip_reason_str_to_code(const char *text)
02227 {
02228    enum AST_REDIRECTING_REASON ast = AST_REDIRECTING_REASON_UNKNOWN;
02229    int i;
02230 
02231    for (i = 0; i < ARRAY_LEN(sip_reason_table); ++i) {
02232       if (!strcasecmp(text, sip_reason_table[i].text)) {
02233          ast = sip_reason_table[i].code;
02234          break;
02235       }
02236    }
02237 
02238    return ast;
02239 }
02240 
02241 static const char *sip_reason_code_to_str(enum AST_REDIRECTING_REASON code)
02242 {
02243    if (code >= 0 && code < ARRAY_LEN(sip_reason_table)) {
02244       return sip_reason_table[code].text;
02245    }
02246 
02247    return "unknown";
02248 }
02249 
02250 /*!
02251  * \brief generic function for determining if a correct transport is being
02252  * used to contact a peer
02253  *
02254  * this is done as a macro so that the "tmpl" var can be passed either a
02255  * sip_request or a sip_peer
02256  */
02257 #define check_request_transport(peer, tmpl) ({ \
02258    int ret = 0; \
02259    if (peer->socket.type == tmpl->socket.type) \
02260       ; \
02261    else if (!(peer->transports & tmpl->socket.type)) {\
02262       ast_log(LOG_ERROR, \
02263          "'%s' is not a valid transport for '%s'. we only use '%s'! ending call.\n", \
02264          get_transport(tmpl->socket.type), peer->name, get_transport_list(peer->transports) \
02265          ); \
02266       ret = 1; \
02267    } else if (peer->socket.type & SIP_TRANSPORT_TLS) { \
02268       ast_log(LOG_WARNING, \
02269          "peer '%s' HAS NOT USED (OR SWITCHED TO) TLS in favor of '%s' (but this was allowed in sip.conf)!\n", \
02270          peer->name, get_transport(tmpl->socket.type) \
02271       ); \
02272    } else { \
02273       ast_debug(1, \
02274          "peer '%s' has contacted us over %s even though we prefer %s.\n", \
02275          peer->name, get_transport(tmpl->socket.type), get_transport(peer->socket.type) \
02276       ); \
02277    }\
02278    (ret); \
02279 })
02280 
02281 /*! \brief
02282  * duplicate a list of channel variables, \return the copy.
02283  */
02284 static struct ast_variable *copy_vars(struct ast_variable *src)
02285 {
02286    struct ast_variable *res = NULL, *tmp, *v = NULL;
02287 
02288    for (v = src ; v ; v = v->next) {
02289       if ((tmp = ast_variable_new(v->name, v->value, v->file))) {
02290          tmp->next = res;
02291          res = tmp;
02292       }
02293    }
02294    return res;
02295 }
02296 
02297 static void tcptls_packet_destructor(void *obj)
02298 {
02299    struct tcptls_packet *packet = obj;
02300 
02301    ast_free(packet->data);
02302 }
02303 
02304 static void sip_tcptls_client_args_destructor(void *obj)
02305 {
02306    struct ast_tcptls_session_args *args = obj;
02307    if (args->tls_cfg) {
02308       ast_free(args->tls_cfg->certfile);
02309       ast_free(args->tls_cfg->pvtfile);
02310       ast_free(args->tls_cfg->cipher);
02311       ast_free(args->tls_cfg->cafile);
02312       ast_free(args->tls_cfg->capath);
02313    }
02314    ast_free(args->tls_cfg);
02315    ast_free((char *) args->name);
02316 }
02317 
02318 static void sip_threadinfo_destructor(void *obj)
02319 {
02320    struct sip_threadinfo *th = obj;
02321    struct tcptls_packet *packet;
02322    if (th->alert_pipe[1] > -1) {
02323       close(th->alert_pipe[0]);
02324    }
02325    if (th->alert_pipe[1] > -1) {
02326       close(th->alert_pipe[1]);
02327    }
02328    th->alert_pipe[0] = th->alert_pipe[1] = -1;
02329 
02330    while ((packet = AST_LIST_REMOVE_HEAD(&th->packet_q, entry))) {
02331       ao2_t_ref(packet, -1, "thread destruction, removing packet from frame queue");
02332    }
02333 
02334    if (th->tcptls_session) {
02335       ao2_t_ref(th->tcptls_session, -1, "remove tcptls_session for sip_threadinfo object");
02336    }
02337 }
02338 
02339 /*! \brief creates a sip_threadinfo object and links it into the threadt table. */
02340 static struct sip_threadinfo *sip_threadinfo_create(struct ast_tcptls_session_instance *tcptls_session, int transport)
02341 {
02342    struct sip_threadinfo *th;
02343 
02344    if (!tcptls_session || !(th = ao2_alloc(sizeof(*th), sip_threadinfo_destructor))) {
02345       return NULL;
02346    }
02347 
02348    th->alert_pipe[0] = th->alert_pipe[1] = -1;
02349 
02350    if (pipe(th->alert_pipe) == -1) {
02351       ao2_t_ref(th, -1, "Failed to open alert pipe on sip_threadinfo");
02352       ast_log(LOG_ERROR, "Could not create sip alert pipe in tcptls thread, error %s\n", strerror(errno));
02353       return NULL;
02354    }
02355    ao2_t_ref(tcptls_session, +1, "tcptls_session ref for sip_threadinfo object");
02356    th->tcptls_session = tcptls_session;
02357    th->type = transport ? transport : (tcptls_session->ssl ? SIP_TRANSPORT_TLS: SIP_TRANSPORT_TCP);
02358    ao2_t_link(threadt, th, "Adding new tcptls helper thread");
02359    ao2_t_ref(th, -1, "Decrementing threadinfo ref from alloc, only table ref remains");
02360    return th;
02361 }
02362 
02363 /*! \brief used to indicate to a tcptls thread that data is ready to be written */
02364 static int sip_tcptls_write(struct ast_tcptls_session_instance *tcptls_session, const void *buf, size_t len)
02365 {
02366    int res = len;
02367    struct sip_threadinfo *th = NULL;
02368    struct tcptls_packet *packet = NULL;
02369    struct sip_threadinfo tmp = {
02370       .tcptls_session = tcptls_session,
02371    };
02372    enum sip_tcptls_alert alert = TCPTLS_ALERT_DATA;
02373 
02374    if (!tcptls_session) {
02375       return XMIT_ERROR;
02376    }
02377 
02378    ast_mutex_lock(&tcptls_session->lock);
02379 
02380    if ((tcptls_session->fd == -1) ||
02381       !(th = ao2_t_find(threadt, &tmp, OBJ_POINTER, "ao2_find, getting sip_threadinfo in tcp helper thread")) ||
02382       !(packet = ao2_alloc(sizeof(*packet), tcptls_packet_destructor)) ||
02383       !(packet->data = ast_str_create(len))) {
02384       goto tcptls_write_setup_error;
02385    }
02386 
02387    /* goto tcptls_write_error should _NOT_ be used beyond this point */
02388    ast_str_set(&packet->data, 0, "%s", (char *) buf);
02389    packet->len = len;
02390 
02391    /* alert tcptls thread handler that there is a packet to be sent.
02392     * must lock the thread info object to guarantee control of the
02393     * packet queue */
02394    ao2_lock(th);
02395    if (write(th->alert_pipe[1], &alert, sizeof(alert)) == -1) {
02396       ast_log(LOG_ERROR, "write() to alert pipe failed: %s\n", strerror(errno));
02397       ao2_t_ref(packet, -1, "could not write to alert pipe, remove packet");
02398       packet = NULL;
02399       res = XMIT_ERROR;
02400    } else { /* it is safe to queue the frame after issuing the alert when we hold the threadinfo lock */
02401       AST_LIST_INSERT_TAIL(&th->packet_q, packet, entry);
02402    }
02403    ao2_unlock(th);
02404 
02405    ast_mutex_unlock(&tcptls_session->lock);
02406    ao2_t_ref(th, -1, "In sip_tcptls_write, unref threadinfo object after finding it");
02407    return res;
02408 
02409 tcptls_write_setup_error:
02410    if (th) {
02411       ao2_t_ref(th, -1, "In sip_tcptls_write, unref threadinfo obj, could not create packet");
02412    }
02413    if (packet) {
02414       ao2_t_ref(packet, -1, "could not allocate packet's data");
02415    }
02416    ast_mutex_unlock(&tcptls_session->lock);
02417 
02418    return XMIT_ERROR;
02419 }
02420 
02421 /*! \brief SIP TCP connection handler */
02422 static void *sip_tcp_worker_fn(void *data)
02423 {
02424    struct ast_tcptls_session_instance *tcptls_session = data;
02425 
02426    return _sip_tcp_helper_thread(NULL, tcptls_session);
02427 }
02428 
02429 /*! \brief Check if the authtimeout has expired.
02430  * \param start the time when the session started
02431  *
02432  * \retval 0 the timeout has expired
02433  * \retval -1 error
02434  * \return the number of milliseconds until the timeout will expire
02435  */
02436 static int sip_check_authtimeout(time_t start)
02437 {
02438    int timeout;
02439    time_t now;
02440    if(time(&now) == -1) {
02441       ast_log(LOG_ERROR, "error executing time(): %s\n", strerror(errno));
02442       return -1;
02443    }
02444 
02445    timeout = (authtimeout - (now - start)) * 1000;
02446    if (timeout < 0) {
02447       /* we have timed out */
02448       return 0;
02449    }
02450 
02451    return timeout;
02452 }
02453 
02454 /*! \brief SIP TCP thread management function
02455    This function reads from the socket, parses the packet into a request
02456 */
02457 static void *_sip_tcp_helper_thread(struct sip_pvt *pvt, struct ast_tcptls_session_instance *tcptls_session)
02458 {
02459    int res, cl, timeout = -1, authenticated = 0, flags;
02460    time_t start;
02461    struct sip_request req = { 0, } , reqcpy = { 0, };
02462    struct sip_threadinfo *me = NULL;
02463    char buf[1024] = "";
02464    struct pollfd fds[2] = { { 0 }, { 0 }, };
02465    struct ast_tcptls_session_args *ca = NULL;
02466 
02467    /* If this is a server session, then the connection has already been
02468     * setup. Check if the authlimit has been reached and if not create the
02469     * threadinfo object so we can access this thread for writing.
02470     *
02471     * if this is a client connection more work must be done.
02472     * 1. We own the parent session args for a client connection.  This pointer needs
02473     *    to be held on to so we can decrement it's ref count on thread destruction.
02474     * 2. The threadinfo object was created before this thread was launched, however
02475     *    it must be found within the threadt table.
02476     * 3. Last, the tcptls_session must be started.
02477     */
02478    if (!tcptls_session->client) {
02479       if (ast_atomic_fetchadd_int(&unauth_sessions, +1) >= authlimit) {
02480          /* unauth_sessions is decremented in the cleanup code */
02481          goto cleanup;
02482       }
02483 
02484       if ((flags = fcntl(tcptls_session->fd, F_GETFL)) == -1) {
02485          ast_log(LOG_ERROR, "error setting socket to non blocking mode, fcntl() failed: %s\n", strerror(errno));
02486          goto cleanup;
02487       }
02488 
02489       flags |= O_NONBLOCK;
02490       if (fcntl(tcptls_session->fd, F_SETFL, flags) == -1) {
02491          ast_log(LOG_ERROR, "error setting socket to non blocking mode, fcntl() failed: %s\n", strerror(errno));
02492          goto cleanup;
02493       }
02494 
02495       if (!(me = sip_threadinfo_create(tcptls_session, tcptls_session->ssl ? SIP_TRANSPORT_TLS : SIP_TRANSPORT_TCP))) {
02496          goto cleanup;
02497       }
02498       ao2_t_ref(me, +1, "Adding threadinfo ref for tcp_helper_thread");
02499    } else {
02500       struct sip_threadinfo tmp = {
02501          .tcptls_session = tcptls_session,
02502       };
02503 
02504       if ((!(ca = tcptls_session->parent)) ||
02505          (!(me = ao2_t_find(threadt, &tmp, OBJ_POINTER, "ao2_find, getting sip_threadinfo in tcp helper thread"))) ||
02506          (!(tcptls_session = ast_tcptls_client_start(tcptls_session)))) {
02507          goto cleanup;
02508       }
02509    }
02510 
02511    me->threadid = pthread_self();
02512    ast_debug(2, "Starting thread for %s server\n", tcptls_session->ssl ? "SSL" : "TCP");
02513 
02514    /* set up pollfd to watch for reads on both the socket and the alert_pipe */
02515    fds[0].fd = tcptls_session->fd;
02516    fds[1].fd = me->alert_pipe[0];
02517    fds[0].events = fds[1].events = POLLIN | POLLPRI;
02518 
02519    if (!(req.data = ast_str_create(SIP_MIN_PACKET))) {
02520       goto cleanup;
02521    }
02522    if (!(reqcpy.data = ast_str_create(SIP_MIN_PACKET))) {
02523       goto cleanup;
02524    }
02525 
02526    if(time(&start) == -1) {
02527       ast_log(LOG_ERROR, "error executing time(): %s\n", strerror(errno));
02528       goto cleanup;
02529    }
02530 
02531    for (;;) {
02532       struct ast_str *str_save;
02533 
02534       if (!tcptls_session->client && req.authenticated && !authenticated) {
02535          authenticated = 1;
02536          ast_atomic_fetchadd_int(&unauth_sessions, -1);
02537       }
02538 
02539       /* calculate the timeout for unauthenticated server sessions */
02540       if (!tcptls_session->client && !authenticated ) {
02541          if ((timeout = sip_check_authtimeout(start)) < 0) {
02542             goto cleanup;
02543          }
02544 
02545          if (timeout == 0) {
02546             ast_debug(2, "SIP %s server timed out\n", tcptls_session->ssl ? "SSL": "TCP");
02547             goto cleanup;
02548          }
02549       } else {
02550          timeout = -1;
02551       }
02552 
02553       res = ast_poll(fds, 2, timeout); /* polls for both socket and alert_pipe */
02554       if (res < 0) {
02555          ast_debug(2, "SIP %s server :: ast_wait_for_input returned %d\n", tcptls_session->ssl ? "SSL": "TCP", res);
02556          goto cleanup;
02557       } else if (res == 0) {
02558          /* timeout */
02559          ast_debug(2, "SIP %s server timed out\n", tcptls_session->ssl ? "SSL": "TCP");
02560          goto cleanup;
02561       }
02562 
02563       /* handle the socket event, check for both reads from the socket fd,
02564        * and writes from alert_pipe fd */
02565       if (fds[0].revents) { /* there is data on the socket to be read */
02566 
02567          fds[0].revents = 0;
02568 
02569          /* clear request structure */
02570          str_save = req.data;
02571          memset(&req, 0, sizeof(req));
02572          req.data = str_save;
02573          ast_str_reset(req.data);
02574 
02575          str_save = reqcpy.data;
02576          memset(&reqcpy, 0, sizeof(reqcpy));
02577          reqcpy.data = str_save;
02578          ast_str_reset(reqcpy.data);
02579 
02580          memset(buf, 0, sizeof(buf));
02581 
02582          if (tcptls_session->ssl) {
02583             set_socket_transport(&req.socket, SIP_TRANSPORT_TLS);
02584             req.socket.port = htons(ourport_tls);
02585          } else {
02586             set_socket_transport(&req.socket, SIP_TRANSPORT_TCP);
02587             req.socket.port = htons(ourport_tcp);
02588          }
02589          req.socket.fd = tcptls_session->fd;
02590 
02591          /* Read in headers one line at a time */
02592          while (req.len < 4 || strncmp(REQ_OFFSET_TO_STR(&req, len - 4), "\r\n\r\n", 4)) {
02593             if (!tcptls_session->client && !authenticated ) {
02594                if ((timeout = sip_check_authtimeout(start)) < 0) {
02595                   goto cleanup;
02596                }
02597 
02598                if (timeout == 0) {
02599                   ast_debug(2, "SIP %s server timed out\n", tcptls_session->ssl ? "SSL": "TCP");
02600                   goto cleanup;
02601                }
02602             } else {
02603                timeout = -1;
02604             }
02605 
02606             res = ast_wait_for_input(tcptls_session->fd, timeout);
02607             if (res < 0) {
02608                ast_debug(2, "SIP %s server :: ast_wait_for_input returned %d\n", tcptls_session->ssl ? "SSL": "TCP", res);
02609                goto cleanup;
02610             } else if (res == 0) {
02611                /* timeout */
02612                ast_debug(2, "SIP %s server timed out\n", tcptls_session->ssl ? "SSL": "TCP");
02613                goto cleanup;
02614             }
02615 
02616             ast_mutex_lock(&tcptls_session->lock);
02617             if (!fgets(buf, sizeof(buf), tcptls_session->f)) {
02618                ast_mutex_unlock(&tcptls_session->lock);
02619                goto cleanup;
02620             }
02621             ast_mutex_unlock(&tcptls_session->lock);
02622             if (me->stop) {
02623                 goto cleanup;
02624             }
02625             ast_str_append(&req.data, 0, "%s", buf);
02626             req.len = req.data->used;
02627          }
02628          copy_request(&reqcpy, &req);
02629          parse_request(&reqcpy);
02630          /* In order to know how much to read, we need the content-length header */
02631          if (sscanf(get_header(&reqcpy, "Content-Length"), "%30d", &cl)) {
02632             while (cl > 0) {
02633                size_t bytes_read;
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", tcptls_session->ssl ? "SSL": "TCP");
02641                      goto cleanup;
02642                   }
02643                } else {
02644                   timeout = -1;
02645                }
02646 
02647                res = ast_wait_for_input(tcptls_session->fd, timeout);
02648                if (res < 0) {
02649                   ast_debug(2, "SIP %s server :: ast_wait_for_input returned %d\n", tcptls_session->ssl ? "SSL": "TCP", res);
02650                   goto cleanup;
02651                } else if (res == 0) {
02652                   /* timeout */
02653                   ast_debug(2, "SIP %s server timed out", tcptls_session->ssl ? "SSL": "TCP");
02654                   goto cleanup;
02655                }
02656 
02657                ast_mutex_lock(&tcptls_session->lock);
02658                if (!(bytes_read = fread(buf, 1, MIN(sizeof(buf) - 1, cl), tcptls_session->f))) {
02659                   ast_mutex_unlock(&tcptls_session->lock);
02660                   goto cleanup;
02661                }
02662                buf[bytes_read] = '\0';
02663                ast_mutex_unlock(&tcptls_session->lock);
02664                if (me->stop) {
02665                   goto cleanup;
02666                }
02667                cl -= strlen(buf);
02668                ast_str_append(&req.data, 0, "%s", buf);
02669                req.len = req.data->used;
02670             }
02671          }
02672          /*! \todo XXX If there's no Content-Length or if the content-length and what
02673                we receive is not the same - we should generate an error */
02674 
02675          req.socket.tcptls_session = tcptls_session;
02676          handle_request_do(&req, &tcptls_session->remote_address);
02677       }
02678 
02679       if (fds[1].revents) { /* alert_pipe indicates there is data in the send queue to be sent */
02680          enum sip_tcptls_alert alert;
02681          struct tcptls_packet *packet;
02682 
02683          fds[1].revents = 0;
02684 
02685          if (read(me->alert_pipe[0], &alert, sizeof(alert)) == -1) {
02686             ast_log(LOG_ERROR, "read() failed: %s\n", strerror(errno));
02687             continue;
02688          }
02689 
02690          switch (alert) {
02691          case TCPTLS_ALERT_STOP:
02692             goto cleanup;
02693          case TCPTLS_ALERT_DATA:
02694             ao2_lock(me);
02695             if (!(packet = AST_LIST_REMOVE_HEAD(&me->packet_q, entry))) {
02696                ast_log(LOG_WARNING, "TCPTLS thread alert_pipe indicated packet should be sent, but frame_q is empty");
02697             } else if (ast_tcptls_server_write(tcptls_session, ast_str_buffer(packet->data), packet->len) == -1) {
02698                ast_log(LOG_WARNING, "Failure to write to tcp/tls socket\n");
02699             }
02700 
02701             if (packet) {
02702                ao2_t_ref(packet, -1, "tcptls packet sent, this is no longer needed");
02703             }
02704             ao2_unlock(me);
02705             break;
02706          default:
02707             ast_log(LOG_ERROR, "Unknown tcptls thread alert '%d'\n", alert);
02708          }
02709       }
02710    }
02711 
02712    ast_debug(2, "Shutting down thread for %s server\n", tcptls_session->ssl ? "SSL" : "TCP");
02713 
02714 cleanup:
02715    if (!tcptls_session->client && !authenticated) {
02716       ast_atomic_fetchadd_int(&unauth_sessions, -1);
02717    }
02718 
02719    if (me) {
02720       ao2_t_unlink(threadt, me, "Removing tcptls helper thread, thread is closing");
02721       ao2_t_ref(me, -1, "Removing tcp_helper_threads threadinfo ref");
02722    }
02723    deinit_req(&reqcpy);
02724    deinit_req(&req);
02725 
02726    /* if client, we own the parent session arguments and must decrement ref */
02727    if (ca) {
02728       ao2_t_ref(ca, -1, "closing tcptls thread, getting rid of client tcptls_session arguments");
02729    }
02730 
02731    if (tcptls_session) {
02732       ast_mutex_lock(&tcptls_session->lock);
02733       if (tcptls_session->f) {
02734          fclose(tcptls_session->f);
02735          tcptls_session->f = NULL;
02736       }
02737       if (tcptls_session->fd != -1) {
02738          close(tcptls_session->fd);
02739          tcptls_session->fd = -1;
02740       }
02741       tcptls_session->parent = NULL;
02742       ast_mutex_unlock(&tcptls_session->lock);
02743 
02744       ao2_ref(tcptls_session, -1);
02745       tcptls_session = NULL;
02746    }
02747    return NULL;
02748 }
02749 
02750 /* this func is used with ao2_callback to unlink/delete all marked
02751    peers */
02752 static int peer_is_marked(void *peerobj, void *arg, int flags)
02753 {
02754    struct sip_peer *peer = peerobj;
02755    if (peer->the_mark && peer->pokeexpire != -1) {
02756       AST_SCHED_DEL(sched, peer->pokeexpire);
02757    }
02758    return peer->the_mark ? CMP_MATCH : 0;
02759 }
02760 
02761 
02762 /* \brief Unlink all marked peers from ao2 containers */
02763 static void unlink_marked_peers_from_tables(void)
02764 {
02765    ao2_t_callback(peers, OBJ_NODATA | OBJ_UNLINK | OBJ_MULTIPLE, peer_is_marked, NULL,
02766                   "initiating callback to remove marked peers");
02767    ao2_t_callback(peers_by_ip, OBJ_NODATA | OBJ_UNLINK | OBJ_MULTIPLE, peer_is_marked, NULL,
02768                   "initiating callback to remove marked peers");
02769 }
02770 
02771 /* \brief Unlink single peer from all ao2 containers */
02772 static void unlink_peer_from_tables(struct sip_peer *peer)
02773 {
02774    ao2_t_unlink(peers, peer, "ao2_unlink of peer from peers table");
02775    if (!ast_sockaddr_isnull(&peer->addr)) {
02776       ao2_t_unlink(peers_by_ip, peer, "ao2_unlink of peer from peers_by_ip table");
02777    }
02778 }
02779 
02780 /*!
02781  * helper functions to unreference various types of objects.
02782  * By handling them this way, we don't have to declare the
02783  * destructor on each call, which removes the chance of errors.
02784  */
02785 static void *unref_peer(struct sip_peer *peer, char *tag)
02786 {
02787    ao2_t_ref(peer, -1, tag);
02788    return NULL;
02789 }
02790 
02791 static struct sip_peer *ref_peer(struct sip_peer *peer, char *tag)
02792 {
02793    ao2_t_ref(peer, 1, tag);
02794    return peer;
02795 }
02796 
02797 /*! \brief maintain proper refcounts for a sip_pvt's outboundproxy
02798  *
02799  * This function sets pvt's outboundproxy pointer to the one referenced
02800  * by the proxy parameter. Because proxy may be a refcounted object, and
02801  * because pvt's old outboundproxy may also be a refcounted object, we need
02802  * to maintain the proper refcounts.
02803  *
02804  * \param pvt The sip_pvt for which we wish to set the outboundproxy
02805  * \param proxy The sip_proxy which we will point pvt towards.
02806  * \return Returns void
02807  */
02808 static void ref_proxy(struct sip_pvt *pvt, struct sip_proxy *proxy)
02809 {
02810    struct sip_proxy *old_obproxy = pvt->outboundproxy;
02811    /* The sip_cfg.outboundproxy is statically allocated, and so
02812     * we don't ever need to adjust refcounts for it
02813     */
02814    if (proxy && proxy != &sip_cfg.outboundproxy) {
02815       ao2_ref(proxy, +1);
02816    }
02817    pvt->outboundproxy = proxy;
02818    if (old_obproxy && old_obproxy != &sip_cfg.outboundproxy) {
02819       ao2_ref(old_obproxy, -1);
02820    }
02821 }
02822 
02823 /*!
02824  * \brief Unlink a dialog from the dialogs container, as well as any other places
02825  * that it may be currently stored.
02826  *
02827  * \note A reference to the dialog must be held before calling this function, and this
02828  * function does not release that reference.
02829  */
02830 void *dialog_unlink_all(struct sip_pvt *dialog, int lockowner, int lockdialoglist)
02831 {
02832    struct sip_pkt *cp;
02833 
02834    dialog_ref(dialog, "Let's bump the count in the unlink so it doesn't accidentally become dead before we are done");
02835 
02836    ao2_t_unlink(dialogs, dialog, "unlinking dialog via ao2_unlink");
02837 
02838    /* Unlink us from the owner (channel) if we have one */
02839    if (dialog->owner) {
02840       if (lockowner)
02841          ast_channel_lock(dialog->owner);
02842       ast_debug(1, "Detaching from channel %s\n", dialog->owner->name);
02843       dialog->owner->tech_pvt = dialog_unref(dialog->owner->tech_pvt, "resetting channel dialog ptr in unlink_all");
02844       if (lockowner) {
02845          ast_channel_unlock(dialog->owner);
02846       }
02847    }
02848    if (dialog->registry) {
02849       if (dialog->registry->call == dialog) {
02850          dialog->registry->call = dialog_unref(dialog->registry->call, "nulling out the registry's call dialog field in unlink_all");
02851       }
02852       dialog->registry = registry_unref(dialog->registry, "delete dialog->registry");
02853    }
02854    if (dialog->stateid > -1) {
02855       ast_extension_state_del(dialog->stateid, NULL);
02856       dialog_unref(dialog, "removing extension_state, should unref the associated dialog ptr that was stored there.");
02857       dialog->stateid = -1; /* shouldn't we 'zero' this out? */
02858    }
02859    /* Remove link from peer to subscription of MWI */
02860    if (dialog->relatedpeer && dialog->relatedpeer->mwipvt == dialog) {
02861       dialog->relatedpeer->mwipvt = dialog_unref(dialog->relatedpeer->mwipvt, "delete ->relatedpeer->mwipvt");
02862    }
02863    if (dialog->relatedpeer && dialog->relatedpeer->call == dialog) {
02864       dialog->relatedpeer->call = dialog_unref(dialog->relatedpeer->call, "unset the relatedpeer->call field in tandem with relatedpeer field itself");
02865    }
02866 
02867    /* remove all current packets in this dialog */
02868    while((cp = dialog->packets)) {
02869       dialog->packets = dialog->packets->next;
02870       AST_SCHED_DEL(sched, cp->retransid);
02871       dialog_unref(cp->owner, "remove all current packets in this dialog, and the pointer to the dialog too as part of __sip_destroy");
02872       if (cp->data) {
02873          ast_free(cp->data);
02874       }
02875       ast_free(cp);
02876    }
02877 
02878    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"));
02879 
02880    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"));
02881    
02882    if (dialog->autokillid > -1) {
02883       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"));
02884    }
02885 
02886    if (dialog->request_queue_sched_id > -1) {
02887       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"));
02888    }
02889 
02890    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"));
02891 
02892    if (dialog->t38id > -1) {
02893       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"));
02894    }
02895 
02896    dialog_unref(dialog, "Let's unbump the count in the unlink so the poor pvt can disappear if it is time");
02897    return NULL;
02898 }
02899 
02900 void *registry_unref(struct sip_registry *reg, char *tag)
02901 {
02902    ast_debug(3, "SIP Registry %s: refcount now %d\n", reg->hostname, reg->refcount - 1);
02903    ASTOBJ_UNREF(reg, sip_registry_destroy);
02904    return NULL;
02905 }
02906 
02907 /*! \brief Add object reference to SIP registry */
02908 static struct sip_registry *registry_addref(struct sip_registry *reg, char *tag)
02909 {
02910    ast_debug(3, "SIP Registry %s: refcount now %d\n", reg->hostname, reg->refcount + 1);
02911    return ASTOBJ_REF(reg); /* Add pointer to registry in packet */
02912 }
02913 
02914 /*! \brief Interface structure with callbacks used to connect to UDPTL module*/
02915 static struct ast_udptl_protocol sip_udptl = {
02916    type: "SIP",
02917    get_udptl_info: sip_get_udptl_peer,
02918    set_udptl_peer: sip_set_udptl_peer,
02919 };
02920 
02921 static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
02922    __attribute__((format(printf, 2, 3)));
02923 
02924 
02925 /*! \brief Convert transfer status to string */
02926 static const char *referstatus2str(enum referstatus rstatus)
02927 {
02928    return map_x_s(referstatusstrings, rstatus, "");
02929 }
02930 
02931 static inline void pvt_set_needdestroy(struct sip_pvt *pvt, const char *reason)
02932 {
02933    if (pvt->final_destruction_scheduled) {
02934       return; /* This is already scheduled for final destruction, let the scheduler take care of it. */
02935    }
02936    append_history(pvt, "NeedDestroy", "Setting needdestroy because %s", reason);
02937    pvt->needdestroy = 1;
02938 }
02939 
02940 /*! \brief Initialize the initital request packet in the pvt structure.
02941    This packet is used for creating replies and future requests in
02942    a dialog */
02943 static void initialize_initreq(struct sip_pvt *p, struct sip_request *req)
02944 {
02945    if (p->initreq.headers) {
02946       ast_debug(1, "Initializing already initialized SIP dialog %s (presumably reinvite)\n", p->callid);
02947    } else {
02948       ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
02949    }
02950    /* Use this as the basis */
02951    copy_request(&p->initreq, req);
02952    parse_request(&p->initreq);
02953    if (req->debug) {
02954       ast_verbose("Initreq: %d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
02955    }
02956 }
02957 
02958 /*! \brief Encapsulate setting of SIP_ALREADYGONE to be able to trace it with debugging */
02959 static void sip_alreadygone(struct sip_pvt *dialog)
02960 {
02961    ast_debug(3, "Setting SIP_ALREADYGONE on dialog %s\n", dialog->callid);
02962    dialog->alreadygone = 1;
02963 }
02964 
02965 /*! Resolve DNS srv name or host name in a sip_proxy structure */
02966 static int proxy_update(struct sip_proxy *proxy)
02967 {
02968    /* if it's actually an IP address and not a name,
02969            there's no need for a managed lookup */
02970    if (!ast_sockaddr_parse(&proxy->ip, proxy->name, 0)) {
02971       /* Ok, not an IP address, then let's check if it's a domain or host */
02972       /* XXX Todo - if we have proxy port, don't do SRV */
02973       proxy->ip.ss.ss_family = get_address_family_filter(&bindaddr); /* Filter address family */
02974       if (ast_get_ip_or_srv(&proxy->ip, proxy->name, sip_cfg.srvlookup ? "_sip._udp" : NULL) < 0) {
02975             ast_log(LOG_WARNING, "Unable to locate host '%s'\n", proxy->name);
02976             return FALSE;
02977       }
02978 
02979    }
02980 
02981    ast_sockaddr_set_port(&proxy->ip, proxy->port);
02982 
02983    proxy->last_dnsupdate = time(NULL);
02984    return TRUE;
02985 }
02986 
02987 /*! \brief converts ascii port to int representation. If no
02988  *  pt buffer is provided or the pt has errors when being converted
02989  *  to an int value, the port provided as the standard is used.
02990  */
02991 unsigned int port_str2int(const char *pt, unsigned int standard)
02992 {
02993    int port = standard;
02994    if (ast_strlen_zero(pt) || (sscanf(pt, "%30d", &port) != 1) || (port < 1) || (port > 65535)) {
02995       port = standard;
02996    }
02997 
02998    return port;
02999 }
03000 
03001 /*! \brief Get default outbound proxy or global proxy */
03002 static struct sip_proxy *obproxy_get(struct sip_pvt *dialog, struct sip_peer *peer)
03003 {
03004    if (peer && peer->outboundproxy) {
03005       if (sipdebug) {
03006          ast_debug(1, "OBPROXY: Applying peer OBproxy to this call\n");
03007       }
03008       append_history(dialog, "OBproxy", "Using peer obproxy %s", peer->outboundproxy->name);
03009       return peer->outboundproxy;
03010    }
03011    if (sip_cfg.outboundproxy.name[0]) {
03012       if (sipdebug) {
03013          ast_debug(1, "OBPROXY: Applying global OBproxy to this call\n");
03014       }
03015       append_history(dialog, "OBproxy", "Using global obproxy %s", sip_cfg.outboundproxy.name);
03016       return &sip_cfg.outboundproxy;
03017    }
03018    if (sipdebug) {
03019       ast_debug(1, "OBPROXY: Not applying OBproxy to this call\n");
03020    }
03021    return NULL;
03022 }
03023 
03024 /*! \brief returns true if 'name' (with optional trailing whitespace)
03025  * matches the sip method 'id'.
03026  * Strictly speaking, SIP methods are case SENSITIVE, but we do
03027  * a case-insensitive comparison to be more tolerant.
03028  * following Jon Postel's rule: Be gentle in what you accept, strict with what you send
03029  */
03030 static int method_match(enum sipmethod id, const char *name)
03031 {
03032    int len = strlen(sip_methods[id].text);
03033    int l_name = name ? strlen(name) : 0;
03034    /* true if the string is long enough, and ends with whitespace, and matches */
03035    return (l_name >= len && name[len] < 33 &&
03036       !strncasecmp(sip_methods[id].text, name, len));
03037 }
03038 
03039 /*! \brief  find_sip_method: Find SIP method from header */
03040 static int find_sip_method(const char *msg)
03041 {
03042    int i, res = 0;
03043    
03044    if (ast_strlen_zero(msg)) {
03045       return 0;
03046    }
03047    for (i = 1; i < ARRAY_LEN(sip_methods) && !res; i++) {
03048       if (method_match(i, msg)) {
03049          res = sip_methods[i].id;
03050       }
03051    }
03052    return res;
03053 }
03054 
03055 /*! \brief See if we pass debug IP filter */
03056 static inline int sip_debug_test_addr(const struct ast_sockaddr *addr)
03057 {
03058    /* Can't debug if sipdebug is not enabled */
03059    if (!sipdebug) {
03060       return 0;
03061    }
03062 
03063    /* A null debug_addr means we'll debug any address */
03064    if (ast_sockaddr_isnull(&debugaddr)) {
03065       return 1;
03066    }
03067 
03068    /* If no port was specified for a debug address, just compare the
03069     * addresses, otherwise compare the address and port
03070     */
03071    if (ast_sockaddr_port(&debugaddr)) {
03072       return !ast_sockaddr_cmp(&debugaddr, addr);
03073    } else {
03074       return !ast_sockaddr_cmp_addr(&debugaddr, addr);
03075    }
03076 }
03077 
03078 /*! \brief The real destination address for a write */
03079 static const struct ast_sockaddr *sip_real_dst(const struct sip_pvt *p)
03080 {
03081    if (p->outboundproxy) {
03082       return &p->outboundproxy->ip;
03083    }
03084 
03085    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;
03086 }
03087 
03088 /*! \brief Display SIP nat mode */
03089 static const char *sip_nat_mode(const struct sip_pvt *p)
03090 {
03091    return ast_test_flag(&p->flags[0], SIP_NAT_FORCE_RPORT) ? "NAT" : "no NAT";
03092 }
03093 
03094 /*! \brief Test PVT for debugging output */
03095 static inline int sip_debug_test_pvt(struct sip_pvt *p)
03096 {
03097    if (!sipdebug) {
03098       return 0;
03099    }
03100    return sip_debug_test_addr(sip_real_dst(p));
03101 }
03102 
03103 /*! \brief Return int representing a bit field of transport types found in const char *transport */
03104 static int get_transport_str2enum(const char *transport)
03105 {
03106    int res = 0;
03107 
03108    if (ast_strlen_zero(transport)) {
03109       return res;
03110    }
03111 
03112    if (!strcasecmp(transport, "udp")) {
03113       res |= SIP_TRANSPORT_UDP;
03114    }
03115    if (!strcasecmp(transport, "tcp")) {
03116       res |= SIP_TRANSPORT_TCP;
03117    }
03118    if (!strcasecmp(transport, "tls")) {
03119       res |= SIP_TRANSPORT_TLS;
03120    }
03121 
03122    return res;
03123 }
03124 
03125 /*! \brief Return configuration of transports for a device */
03126 static inline const char *get_transport_list(unsigned int transports) {
03127    switch (transports) {
03128       case SIP_TRANSPORT_UDP:
03129          return "UDP";
03130       case SIP_TRANSPORT_TCP:
03131          return "TCP";
03132       case SIP_TRANSPORT_TLS:
03133          return "TLS";
03134       case SIP_TRANSPORT_UDP | SIP_TRANSPORT_TCP:
03135          return "TCP,UDP";
03136       case SIP_TRANSPORT_UDP | SIP_TRANSPORT_TLS:
03137          return "TLS,UDP";
03138       case SIP_TRANSPORT_TCP | SIP_TRANSPORT_TLS:
03139          return "TLS,TCP";
03140       default:
03141          return transports ?
03142             "TLS,TCP,UDP" : "UNKNOWN"; 
03143    }
03144 }
03145 
03146 /*! \brief Return transport as string */
03147 static inline const char *get_transport(enum sip_transport t)
03148 {
03149    switch (t) {
03150    case SIP_TRANSPORT_UDP:
03151       return "UDP";
03152    case SIP_TRANSPORT_TCP:
03153       return "TCP";
03154    case SIP_TRANSPORT_TLS:
03155       return "TLS";
03156    }
03157 
03158    return "UNKNOWN";
03159 }
03160 
03161 /*! \brief Return protocol string for srv dns query */
03162 static inline const char *get_srv_protocol(enum sip_transport t)
03163 {
03164    switch (t) {
03165    case SIP_TRANSPORT_UDP:
03166       return "udp";
03167    case SIP_TRANSPORT_TLS:
03168    case SIP_TRANSPORT_TCP:
03169       return "tcp";
03170    }
03171 
03172    return "udp";
03173 }
03174 
03175 /*! \brief Return service string for srv dns query */
03176 static inline const char *get_srv_service(enum sip_transport t)
03177 {
03178    switch (t) {
03179    case SIP_TRANSPORT_TCP:
03180    case SIP_TRANSPORT_UDP:
03181       return "sip";
03182    case SIP_TRANSPORT_TLS:
03183       return "sips";
03184    }
03185    return "sip";
03186 }
03187 
03188 /*! \brief Return transport of dialog.
03189    \note this is based on a false assumption. We don't always use the
03190    outbound proxy for all requests in a dialog. It depends on the
03191    "force" parameter. The FIRST request is always sent to the ob proxy.
03192    \todo Fix this function to work correctly
03193 */
03194 static inline const char *get_transport_pvt(struct sip_pvt *p)
03195 {
03196    if (p->outboundproxy && p->outboundproxy->transport) {
03197       set_socket_transport(&p->socket, p->outboundproxy->transport);
03198    }
03199 
03200    return get_transport(p->socket.type);
03201 }
03202 
03203 /*! \brief Transmit SIP message
03204    Sends a SIP request or response on a given socket (in the pvt)
03205    Called by retrans_pkt, send_request, send_response and
03206    __sip_reliable_xmit
03207    \return length of transmitted message, XMIT_ERROR on known network failures -1 on other failures.
03208 */
03209 static int __sip_xmit(struct sip_pvt *p, struct ast_str *data, int len)
03210 {
03211    int res = 0;
03212    const struct ast_sockaddr *dst = sip_real_dst(p);
03213 
03214    ast_debug(2, "Trying to put '%.11s' onto %s socket destined for %s\n", data->str, get_transport_pvt(p), ast_sockaddr_stringify(dst));
03215 
03216    if (sip_prepare_socket(p) < 0) {
03217       return XMIT_ERROR;
03218    }
03219 
03220    if (p->socket.type == SIP_TRANSPORT_UDP) {
03221       res = ast_sendto(p->socket.fd, data->str, len, 0, dst);
03222    } else if (p->socket.tcptls_session) {
03223       res = sip_tcptls_write(p->socket.tcptls_session, data->str, len);
03224    } else {
03225       ast_debug(2, "Socket type is TCP but no tcptls_session is present to write to\n");
03226       return XMIT_ERROR;
03227    }
03228 
03229    if (res == -1) {
03230       switch (errno) {
03231       case EBADF:       /* Bad file descriptor - seems like this is generated when the host exist, but doesn't accept the UDP packet */
03232       case EHOSTUNREACH:   /* Host can't be reached */
03233       case ENETDOWN:       /* Interface down */
03234       case ENETUNREACH: /* Network failure */
03235       case ECONNREFUSED:      /* ICMP port unreachable */
03236          res = XMIT_ERROR; /* Don't bother with trying to transmit again */
03237       }
03238    }
03239    if (res != len) {
03240       ast_log(LOG_WARNING, "sip_xmit of %p (len %d) to %s returned %d: %s\n", data, len, ast_sockaddr_stringify(dst), res, strerror(errno));
03241    }
03242 
03243    return res;
03244 }
03245 
03246 /*! \brief Build a Via header for a request */
03247 static void build_via(struct sip_pvt *p)
03248 {
03249    /* Work around buggy UNIDEN UIP200 firmware */
03250    const char *rport = (ast_test_flag(&p->flags[0], SIP_NAT_FORCE_RPORT) || ast_test_flag(&p->flags[0], SIP_NAT_RPORT_PRESENT)) ? ";rport" : "";
03251 
03252    /* z9hG4bK is a magic cookie.  See RFC 3261 section 8.1.1.7 */
03253    snprintf(p->via, sizeof(p->via), "SIP/2.0/%s %s;branch=z9hG4bK%08x%s",
03254        get_transport_pvt(p),
03255        ast_sockaddr_stringify(&p->ourip),
03256        (int) p->branch, rport);
03257 }
03258 
03259 /*! \brief NAT fix - decide which IP address to use for Asterisk server?
03260  *
03261  * Using the localaddr structure built up with localnet statements in sip.conf
03262  * apply it to their address to see if we need to substitute our
03263  * externaddr or can get away with our internal bindaddr
03264  * 'us' is always overwritten.
03265  */
03266 static void ast_sip_ouraddrfor(const struct ast_sockaddr *them, struct ast_sockaddr *us, struct sip_pvt *p)
03267 {
03268    struct ast_sockaddr theirs;
03269 
03270    /* Set want_remap to non-zero if we want to remap 'us' to an externally
03271     * reachable IP address and port. This is done if:
03272     * 1. we have a localaddr list (containing 'internal' addresses marked
03273     *    as 'deny', so ast_apply_ha() will return AST_SENSE_DENY on them,
03274     *    and AST_SENSE_ALLOW on 'external' ones);
03275     * 2. externaddr is set, so we know what to use as the
03276     *    externally visible address;
03277     * 3. the remote address, 'them', is external;
03278     * 4. the address returned by ast_ouraddrfor() is 'internal' (AST_SENSE_DENY
03279     *    when passed to ast_apply_ha() so it does need to be remapped.
03280     *    This fourth condition is checked later.
03281     */
03282    int want_remap = 0;
03283 
03284    ast_sockaddr_copy(us, &internip); /* starting guess for the internal address */
03285    /* now ask the system what would it use to talk to 'them' */
03286    ast_ouraddrfor(them, us);
03287    ast_sockaddr_copy(&theirs, them);
03288 
03289    if (ast_sockaddr_is_ipv6(&theirs)) {
03290       if (localaddr && !ast_sockaddr_isnull(&externaddr)) {
03291          ast_log(LOG_WARNING, "Address remapping activated in sip.conf "
03292             "but we're using IPv6, which doesn't need it. Please "
03293             "remove \"localnet\" and/or \"externaddr\" settings.\n");
03294       }
03295    } else {
03296       want_remap = localaddr &&
03297          !ast_sockaddr_isnull(&externaddr) &&
03298          ast_apply_ha(localaddr, &theirs) == AST_SENSE_ALLOW ;
03299    }
03300 
03301    if (want_remap &&
03302        (!sip_cfg.matchexternaddrlocally || !ast_apply_ha(localaddr, us)) ) {
03303       /* if we used externhost, see if it is time to refresh the info */
03304       if (externexpire && time(NULL) >= externexpire) {
03305          if (ast_sockaddr_resolve_first(&externaddr, externhost, 0)) {
03306             ast_log(LOG_NOTICE, "Warning: Re-lookup of '%s' failed!\n", externhost);
03307          }
03308          externexpire = time(NULL) + externrefresh;
03309       }
03310       if (!ast_sockaddr_isnull(&externaddr)) {
03311          ast_sockaddr_copy(us, &externaddr);
03312          switch (p->socket.type) {
03313          case SIP_TRANSPORT_TCP:
03314             if (!externtcpport && ast_sockaddr_port(&externaddr)) {
03315                /* for consistency, default to the externaddr port */
03316                externtcpport = ast_sockaddr_port(&externaddr);
03317             }
03318             ast_sockaddr_set_port(us, externtcpport);
03319             break;
03320          case SIP_TRANSPORT_TLS:
03321             ast_sockaddr_set_port(us, externtlsport);
03322             break;
03323          case SIP_TRANSPORT_UDP:
03324             if (!ast_sockaddr_port(&externaddr)) {
03325                ast_sockaddr_set_port(us, ast_sockaddr_port(&bindaddr));
03326             }
03327             break;
03328          default:
03329             break;
03330          }
03331       }
03332       ast_debug(1, "Target address %s is not local, substituting externaddr\n",
03333            ast_sockaddr_stringify(them));
03334    } else if (p) {
03335       /* no remapping, but we bind to a specific address, so use it. */
03336       switch (p->socket.type) {
03337       case SIP_TRANSPORT_TCP:
03338          if (!ast_sockaddr_is_any(&sip_tcp_desc.local_address)) {
03339             ast_sockaddr_copy(us,
03340                     &sip_tcp_desc.local_address);
03341          } else {
03342             ast_sockaddr_set_port(us,
03343                         ast_sockaddr_port(&sip_tcp_desc.local_address));
03344          }
03345          break;
03346       case SIP_TRANSPORT_TLS:
03347          if (!ast_sockaddr_is_any(&sip_tls_desc.local_address)) {
03348             ast_sockaddr_copy(us,
03349                     &sip_tls_desc.local_address);
03350          } else {
03351             ast_sockaddr_set_port(us,
03352                         ast_sockaddr_port(&sip_tls_desc.local_address));
03353          }
03354          break;
03355       case SIP_TRANSPORT_UDP:
03356          /* fall through on purpose */
03357       default:
03358          if (!ast_sockaddr_is_any(&bindaddr)) {
03359             ast_sockaddr_copy(us, &bindaddr);
03360          }
03361          if (!ast_sockaddr_port(us)) {
03362             ast_sockaddr_set_port(us, ast_sockaddr_port(&bindaddr));
03363          }
03364       }
03365    } else if (!ast_sockaddr_is_any(&bindaddr)) {
03366       ast_sockaddr_copy(us, &bindaddr);
03367    }
03368    ast_debug(3, "Setting SIP_TRANSPORT_%s with address %s\n", get_transport(p->socket.type), ast_sockaddr_stringify(us));
03369 }
03370 
03371 /*! \brief Append to SIP dialog history with arg list  */
03372 static __attribute__((format(printf, 2, 0))) void append_history_va(struct sip_pvt *p, const char *fmt, va_list ap)
03373 {
03374    char buf[80], *c = buf; /* max history length */
03375    struct sip_history *hist;
03376    int l;
03377 
03378    vsnprintf(buf, sizeof(buf), fmt, ap);
03379    strsep(&c, "\r\n"); /* Trim up everything after \r or \n */
03380    l = strlen(buf) + 1;
03381    if (!(hist = ast_calloc(1, sizeof(*hist) + l))) {
03382       return;
03383    }
03384    if (!p->history && !(p->history = ast_calloc(1, sizeof(*p->history)))) {
03385       ast_free(hist);
03386       return;
03387    }
03388    memcpy(hist->event, buf, l);
03389    if (p->history_entries == MAX_HISTORY_ENTRIES) {
03390       struct sip_history *oldest;
03391       oldest = AST_LIST_REMOVE_HEAD(p->history, list);
03392       p->history_entries--;
03393       ast_free(oldest);
03394    }
03395    AST_LIST_INSERT_TAIL(p->history, hist, list);
03396    p->history_entries++;
03397 }
03398 
03399 /*! \brief Append to SIP dialog history with arg list  */
03400 static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
03401 {
03402    va_list ap;
03403 
03404    if (!p) {
03405       return;
03406    }
03407 
03408    if (!p->do_history && !recordhistory && !dumphistory) {
03409       return;
03410    }
03411 
03412    va_start(ap, fmt);
03413    append_history_va(p, fmt, ap);
03414    va_end(ap);
03415 
03416    return;
03417 }
03418 
03419 /*! \brief Retransmit SIP message if no answer (Called from scheduler) */
03420 static int retrans_pkt(const void *data)
03421 {
03422    struct sip_pkt *pkt = (struct sip_pkt *)data, *prev, *cur = NULL;
03423    int reschedule = DEFAULT_RETRANS;
03424    int xmitres = 0;
03425    /* how many ms until retrans timeout is reached */
03426    int64_t diff = pkt->retrans_stop_time - ast_tvdiff_ms(ast_tvnow(), pkt->time_sent);
03427 
03428    /* Do not retransmit if time out is reached. This will be negative if the time between
03429     * the first transmission and now is larger than our timeout period. This is a fail safe
03430     * check in case the scheduler gets behind or the clock is changed. */
03431    if ((diff <= 0) || (diff > pkt->retrans_stop_time)) {
03432       pkt->retrans_stop = 1;
03433    }
03434 
03435    /* Lock channel PVT */
03436    sip_pvt_lock(pkt->owner);
03437 
03438    if (!pkt->retrans_stop) {
03439       pkt->retrans++;
03440       if (!pkt->timer_t1) {   /* Re-schedule using timer_a and timer_t1 */
03441          if (sipdebug) {
03442             ast_debug(4, "SIP TIMER: Not rescheduling id #%d:%s (Method %d) (No timer T1)\n",
03443                pkt->retransid,
03444                sip_methods[pkt->method].text,
03445                pkt->method);
03446          }
03447       } else {
03448          int siptimer_a;
03449 
03450          if (sipdebug) {
03451             ast_debug(4, "SIP TIMER: Rescheduling retransmission #%d (%d) %s - %d\n",
03452                pkt->retransid,
03453                pkt->retrans,
03454                sip_methods[pkt->method].text,
03455                pkt->method);
03456          }
03457          if (!pkt->timer_a) {
03458             pkt->timer_a = 2 ;
03459          } else {
03460             pkt->timer_a = 2 * pkt->timer_a;
03461          }
03462 
03463          /* For non-invites, a maximum of 4 secs */
03464          siptimer_a = pkt->timer_t1 * pkt->timer_a;   /* Double each time */
03465          if (pkt->method != SIP_INVITE && siptimer_a > 4000) {
03466             siptimer_a = 4000;
03467          }
03468 
03469          /* Reschedule re-transmit */
03470          reschedule = siptimer_a;
03471          ast_debug(4, "** SIP timers: Rescheduling retransmission %d to %d ms (t1 %d ms (Retrans id #%d)) \n",
03472             pkt->retrans + 1,
03473             siptimer_a,
03474             pkt->timer_t1,
03475             pkt->retransid);
03476       }
03477 
03478       if (sip_debug_test_pvt(pkt->owner)) {
03479          const struct ast_sockaddr *dst = sip_real_dst(pkt->owner);
03480          ast_verbose("Retransmitting #%d (%s) to %s:\n%s\n---\n",
03481             pkt->retrans, sip_nat_mode(pkt->owner),
03482             ast_sockaddr_stringify(dst),
03483             pkt->data->str);
03484       }
03485 
03486       append_history(pkt->owner, "ReTx", "%d %s", reschedule, pkt->data->str);
03487       xmitres = __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
03488 
03489       /* If there was no error during the network transmission, schedule the next retransmission,
03490        * but if the next retransmission is going to be beyond our timeout period, mark the packet's
03491        * stop_retrans value and set the next retransmit to be the exact time of timeout.  This will
03492        * allow any responses to the packet to be processed before the packet is destroyed on the next
03493        * call to this function by the scheduler. */
03494       if (xmitres != XMIT_ERROR) {
03495          if (reschedule >= diff) {
03496             pkt->retrans_stop = 1;
03497             reschedule = diff;
03498          }
03499          sip_pvt_unlock(pkt->owner);
03500          return  reschedule;
03501       }
03502    }
03503 
03504    /* At this point, either the packet's retransmission timed out, or there was a
03505     * transmission error, either way destroy the scheduler item and this packet. */
03506 
03507    pkt->retransid = -1; /* Kill this scheduler item */
03508 
03509    if (pkt->owner && pkt->method != SIP_OPTIONS && xmitres == 0) {
03510       if (pkt->is_fatal || sipdebug) { /* Tell us if it's critical or if we're debugging */
03511          ast_log(LOG_WARNING, "Retransmission timeout reached on transmission %s for seqno %d (%s %s) -- See doc/sip-retransmit.txt.\n"
03512             "Packet timed out after %dms with no response\n",
03513             pkt->owner->callid,
03514             pkt->seqno,
03515             pkt->is_fatal ? "Critical" : "Non-critical",
03516             pkt->is_resp ? "Response" : "Request",
03517             (int) ast_tvdiff_ms(ast_tvnow(), pkt->time_sent));
03518       }
03519    } else if (pkt->method == SIP_OPTIONS && sipdebug) {
03520       ast_log(LOG_WARNING, "Cancelling retransmit of OPTIONs (call id %s)  -- See doc/sip-retransmit.txt.\n", pkt->owner->callid);
03521    }
03522 
03523    if (xmitres == XMIT_ERROR) {
03524       ast_log(LOG_WARNING, "Transmit error :: Cancelling transmission on Call ID %s\n", pkt->owner->callid);
03525       append_history(pkt->owner, "XmitErr", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
03526    } else {
03527       append_history(pkt->owner, "MaxRetries", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
03528    }
03529 
03530    if (pkt->is_fatal) {
03531       while(pkt->owner->owner && ast_channel_trylock(pkt->owner->owner)) {
03532          sip_pvt_unlock(pkt->owner);   /* SIP_PVT, not channel */
03533          usleep(1);
03534          sip_pvt_lock(pkt->owner);
03535       }
03536       if (pkt->owner->owner && !pkt->owner->owner->hangupcause) {
03537          pkt->owner->owner->hangupcause = AST_CAUSE_NO_USER_RESPONSE;
03538       }
03539       if (pkt->owner->owner) {
03540          ast_log(LOG_WARNING, "Hanging up call %s - no reply to our critical packet (see doc/sip-retransmit.txt).\n", pkt->owner->callid);
03541 
03542          if (pkt->is_resp &&
03543             (pkt->response_code >= 200) &&
03544             (pkt->response_code < 300) &&
03545             pkt->owner->pendinginvite &&
03546             ast_test_flag(&pkt->owner->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED)) {
03547             /* This is a timeout of the 2XX response to a pending INVITE.  In this case terminate the INVITE
03548              * transaction just as if we received the ACK, but immediately hangup with a BYE (sip_hangup
03549              * will send the BYE as long as the dialog is not set as "alreadygone")
03550              * RFC 3261 section 13.3.1.4.
03551              * "If the server retransmits the 2xx response for 64*T1 seconds without receiving
03552              * an ACK, the dialog is confirmed, but the session SHOULD be terminated.  This is
03553              * accomplished with a BYE, as described in Section 15." */
03554             pkt->owner->invitestate = INV_TERMINATED;
03555             pkt->owner->pendinginvite = 0;
03556          } else {
03557             /* there is nothing left to do, mark the dialog as gone */
03558             sip_alreadygone(pkt->owner);
03559          }
03560          ast_queue_hangup_with_cause(pkt->owner->owner, AST_CAUSE_PROTOCOL_ERROR);
03561          ast_channel_unlock(pkt->owner->owner);
03562       } else {
03563          /* If no channel owner, destroy now */
03564 
03565          /* Let the peerpoke system expire packets when the timer expires for poke_noanswer */
03566          if (pkt->method != SIP_OPTIONS && pkt->method != SIP_REGISTER) {
03567             pvt_set_needdestroy(pkt->owner, "no response to critical packet");
03568             sip_alreadygone(pkt->owner);
03569             append_history(pkt->owner, "DialogKill", "Killing this failed dialog immediately");
03570          }
03571       }
03572    }
03573 
03574    if (pkt->method == SIP_BYE) {
03575       /* We're not getting answers on SIP BYE's.  Tear down the call anyway. */
03576       if (pkt->owner->owner) {
03577          ast_channel_unlock(pkt->owner->owner);
03578       }
03579       append_history(pkt->owner, "ByeFailure", "Remote peer doesn't respond to bye. Destroying call anyway.");
03580       pvt_set_needdestroy(pkt->owner, "no response to BYE");
03581    }
03582 
03583    /* Remove the packet */
03584    for (prev = NULL, cur = pkt->owner->packets; cur; prev = cur, cur = cur->next) {
03585       if (cur == pkt) {
03586          UNLINK(cur, pkt->owner->packets, prev);
03587          sip_pvt_unlock(pkt->owner);
03588          if (pkt->owner) {
03589             pkt->owner = dialog_unref(pkt->owner,"pkt is being freed, its dialog ref is dead now");
03590          }
03591          if (pkt->data) {
03592             ast_free(pkt->data);
03593          }
03594          pkt->data = NULL;
03595          ast_free(pkt);
03596          return 0;
03597       }
03598    }
03599    /* error case */
03600    ast_log(LOG_WARNING, "Weird, couldn't find packet owner!\n");
03601    sip_pvt_unlock(pkt->owner);
03602    return 0;
03603 }
03604 
03605 /*! \brief Transmit packet with retransmits
03606    \return 0 on success, -1 on failure to allocate packet
03607 */
03608 static enum sip_result __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, struct ast_str *data, int len, int fatal, int sipmethod)
03609 {
03610    struct sip_pkt *pkt = NULL;
03611    int siptimer_a = DEFAULT_RETRANS;
03612    int xmitres = 0;
03613    int respid;
03614 
03615    if (sipmethod == SIP_INVITE) {
03616       /* Note this is a pending invite */
03617       p->pendinginvite = seqno;
03618    }
03619 
03620    /* If the transport is something reliable (TCP or TLS) then don't really send this reliably */
03621    /* I removed the code from retrans_pkt that does the same thing so it doesn't get loaded into the scheduler */
03622    /*! \todo According to the RFC some packets need to be retransmitted even if its TCP, so this needs to get revisited */
03623    if (!(p->socket.type & SIP_TRANSPORT_UDP)) {
03624       xmitres = __sip_xmit(p, data, len); /* Send packet */
03625       if (xmitres == XMIT_ERROR) {  /* Serious network trouble, no need to try again */
03626          append_history(p, "XmitErr", "%s", fatal ? "(Critical)" : "(Non-critical)");
03627          return AST_FAILURE;
03628       } else {
03629          return AST_SUCCESS;
03630       }
03631    }
03632 
03633    if (!(pkt = ast_calloc(1, sizeof(*pkt) + len + 1))) {
03634       return AST_FAILURE;
03635    }
03636    /* copy data, add a terminator and save length */
03637    if (!(pkt->data = ast_str_create(len))) {
03638       ast_free(pkt);
03639       return AST_FAILURE;
03640    }
03641    ast_str_set(&pkt->data, 0, "%s%s", data->str, "\0");
03642    pkt->packetlen = len;
03643    /* copy other parameters from the caller */
03644    pkt->method = sipmethod;
03645    pkt->seqno = seqno;
03646    pkt->is_resp = resp;
03647    pkt->is_fatal = fatal;
03648    pkt->owner = dialog_ref(p, "__sip_reliable_xmit: setting pkt->owner");
03649    pkt->next = p->packets;
03650    p->packets = pkt; /* Add it to the queue */
03651    if (resp) {
03652       /* Parse out the response code */
03653       if (sscanf(ast_str_buffer(pkt->data), "SIP/2.0 %30u", &respid) == 1) {
03654          pkt->response_code = respid;
03655       }
03656    }
03657    pkt->timer_t1 = p->timer_t1;  /* Set SIP timer T1 */
03658    pkt->retransid = -1;
03659    if (pkt->timer_t1) {
03660       siptimer_a = pkt->timer_t1;
03661    }
03662 
03663    pkt->time_sent = ast_tvnow(); /* time packet was sent */
03664    pkt->retrans_stop_time = 64 * (pkt->timer_t1 ? pkt->timer_t1 : DEFAULT_TIMER_T1); /* time in ms after pkt->time_sent to stop retransmission */
03665 
03666    /* Schedule retransmission */
03667    AST_SCHED_REPLACE_VARIABLE(pkt->retransid, sched, siptimer_a, retrans_pkt, pkt, 1);
03668    if (sipdebug) {
03669       ast_debug(4, "*** SIP TIMER: Initializing retransmit timer on packet: Id  #%d\n", pkt->retransid);
03670    }
03671 
03672    xmitres = __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);   /* Send packet */
03673 
03674    if (xmitres == XMIT_ERROR) {  /* Serious network trouble, no need to try again */
03675       append_history(pkt->owner, "XmitErr", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
03676       ast_log(LOG_ERROR, "Serious Network Trouble; __sip_xmit returns error for pkt data\n");
03677       AST_SCHED_DEL(sched, pkt->retransid);
03678       p->packets = pkt->next;
03679       pkt->owner = dialog_unref(pkt->owner,"pkt is being freed, its dialog ref is dead now");
03680       ast_free(pkt->data);
03681       ast_free(pkt);
03682       return AST_FAILURE;
03683    } else {
03684       /* This is odd, but since the retrans timer starts at 500ms and the do_monitor thread
03685        * only wakes up every 1000ms by default, we have to poke the thread here to make
03686        * sure it successfully detects this must be retransmitted in less time than
03687        * it usually sleeps for. Otherwise it might not retransmit this packet for 1000ms. */
03688       if (monitor_thread != AST_PTHREADT_NULL) {
03689          pthread_kill(monitor_thread, SIGURG);
03690       }
03691       return AST_SUCCESS;
03692    }
03693 }
03694 
03695 /*! \brief Kill a SIP dialog (called only by the scheduler)
03696  * The scheduler has a reference to this dialog when p->autokillid != -1,
03697  * and we are called using that reference. So if the event is not
03698  * rescheduled, we need to call dialog_unref().
03699  */
03700 static int __sip_autodestruct(const void *data)
03701 {
03702    struct sip_pvt *p = (struct sip_pvt *)data;
03703 
03704    /* If this is a subscription, tell the phone that we got a timeout */
03705    if (p->subscribed && p->subscribed != MWI_NOTIFICATION && p->subscribed != CALL_COMPLETION) {
03706       transmit_state_notify(p, AST_EXTENSION_DEACTIVATED, 1, TRUE);  /* Send last notification */
03707       p->subscribed = NONE;
03708       append_history(p, "Subscribestatus", "timeout");
03709       ast_debug(3, "Re-scheduled destruction of SIP subscription %s\n", p->callid ? p->callid : "<unknown>");
03710       return 10000;  /* Reschedule this destruction so that we know that it's gone */
03711    }
03712 
03713    /* If there are packets still waiting for delivery, delay the destruction */
03714    if (p->packets) {
03715       if (!p->needdestroy) {
03716          char method_str[31];
03717          ast_debug(3, "Re-scheduled destruction of SIP call %s\n", p->callid ? p->callid : "<unknown>");
03718          append_history(p, "ReliableXmit", "timeout");
03719          if (sscanf(p->lastmsg, "Tx: %30s", method_str) == 1 || sscanf(p->lastmsg, "Rx: %30s", method_str) == 1) {
03720             if (method_match(SIP_CANCEL, method_str) || method_match(SIP_BYE, method_str)) {
03721                pvt_set_needdestroy(p, "autodestruct");
03722             }
03723          }
03724          return 10000;
03725       } else {
03726          /* They've had their chance to respond. Time to bail */
03727          __sip_pretend_ack(p);
03728       }
03729    }
03730 
03731    /* Reset schedule ID */
03732    p->autokillid = -1;
03733 
03734 
03735    /*
03736     * Lock both the pvt and the channel safely so that we can queue up a frame.
03737     */
03738    sip_pvt_lock(p);
03739    while (p->owner && ast_channel_trylock(p->owner)) {
03740       sip_pvt_unlock(p);
03741       sched_yield();
03742       sip_pvt_lock(p);
03743    }
03744 
03745    if (p->owner) {
03746       ast_log(LOG_WARNING, "Autodestruct on dialog '%s' with owner in place (Method: %s)\n", p->callid, sip_methods[p->method].text);
03747       ast_queue_hangup_with_cause(p->owner, AST_CAUSE_PROTOCOL_ERROR);
03748       ast_channel_unlock(p->owner);
03749    } else if (p->refer && !p->alreadygone) {
03750       ast_debug(3, "Finally hanging up channel after transfer: %s\n", p->callid);
03751       transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
03752       append_history(p, "ReferBYE", "Sending BYE on transferer call leg %s", p->callid);
03753       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
03754    } else {
03755       append_history(p, "AutoDestroy", "%s", p->callid);
03756       ast_debug(3, "Auto destroying SIP dialog '%s'\n", p->callid);
03757       dialog_unlink_all(p, TRUE, TRUE); /* once it's unlinked and unrefd everywhere, it'll be freed automagically */
03758       /* dialog_unref(p, "unref dialog-- no other matching conditions"); -- unlink all now should finish off the dialog's references and free it. */
03759       /* sip_destroy(p); */      /* Go ahead and destroy dialog. All attempts to recover is done */
03760       /* sip_destroy also absorbs the reference */
03761    }
03762 
03763    sip_pvt_unlock(p);
03764 
03765    dialog_unref(p, "The ref to a dialog passed to this sched callback is going out of scope; unref it.");
03766 
03767    return 0;
03768 }
03769 
03770 /*! \brief Schedule final destruction of SIP dialog.  This can not be canceled.
03771  *  This function is used to keep a dialog around for a period of time in order
03772  *  to properly respond to any retransmits. */
03773 void sip_scheddestroy_final(struct sip_pvt *p, int ms)
03774 {
03775    if (p->final_destruction_scheduled) {
03776       return; /* already set final destruction */
03777    }
03778 
03779    sip_scheddestroy(p, ms);
03780    if (p->autokillid != -1) {
03781       p->final_destruction_scheduled = 1;
03782    }
03783 }
03784 
03785 /*! \brief Schedule destruction of SIP dialog */
03786 void sip_scheddestroy(struct sip_pvt *p, int ms)
03787 {
03788    if (p->final_destruction_scheduled) {
03789       return; /* already set final destruction */
03790    }
03791 
03792    if (ms < 0) {
03793       if (p->timer_t1 == 0) {
03794          p->timer_t1 = global_t1;   /* Set timer T1 if not set (RFC 3261) */
03795       }
03796       if (p->timer_b == 0) {
03797          p->timer_b = global_timer_b;  /* Set timer B if not set (RFC 3261) */
03798       }
03799       ms = p->timer_t1 * 64;
03800    }
03801    if (sip_debug_test_pvt(p)) {
03802       ast_verbose("Scheduling destruction of SIP dialog '%s' in %d ms (Method: %s)\n", p->callid, ms, sip_methods[p->method].text);
03803    }
03804    if (sip_cancel_destroy(p)) {
03805       ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
03806    }
03807 
03808    if (p->do_history) {
03809       append_history(p, "SchedDestroy", "%d ms", ms);
03810    }
03811    p->autokillid = ast_sched_add(sched, ms, __sip_autodestruct, dialog_ref(p, "setting ref as passing into ast_sched_add for __sip_autodestruct"));
03812 
03813    if (p->stimer && p->stimer->st_active == TRUE && p->stimer->st_schedid > 0) {
03814       stop_session_timer(p);
03815    }
03816 }
03817 
03818 /*! \brief Cancel destruction of SIP dialog.
03819  * Be careful as this also absorbs the reference - if you call it
03820  * from within the scheduler, this might be the last reference.
03821  */
03822 int sip_cancel_destroy(struct sip_pvt *p)
03823 {
03824    int res = 0;
03825 
03826    if (p->final_destruction_scheduled) {
03827       return res;
03828    }
03829 
03830    if (p->autokillid > -1) {
03831       int res3;
03832 
03833       if (!(res3 = ast_sched_del(sched, p->autokillid))) {
03834          append_history(p, "CancelDestroy", "");
03835          p->autokillid = -1;
03836          dialog_unref(p, "dialog unrefd because autokillid is de-sched'd");
03837       }
03838    }
03839    return res;
03840 }
03841 
03842 /*! \brief Acknowledges receipt of a packet and stops retransmission
03843  * called with p locked*/
03844 int __sip_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod)
03845 {
03846    struct sip_pkt *cur, *prev = NULL;
03847    const char *msg = "Not Found";   /* used only for debugging */
03848    int res = FALSE;
03849 
03850    /* If we have an outbound proxy for this dialog, then delete it now since
03851      the rest of the requests in this dialog needs to follow the routing.
03852      If obforcing is set, we will keep the outbound proxy during the whole
03853      dialog, regardless of what the SIP rfc says
03854    */
03855    if (p->outboundproxy && !p->outboundproxy->force){
03856       ref_proxy(p, NULL);
03857    }
03858 
03859    for (cur = p->packets; cur; prev = cur, cur = cur->next) {
03860       if (cur->seqno != seqno || cur->is_resp != resp) {
03861          continue;
03862       }
03863       if (cur->is_resp || cur->method == sipmethod) {
03864          res = TRUE;
03865          msg = "Found";
03866          if (!resp && (seqno == p->pendinginvite)) {
03867             ast_debug(1, "Acked pending invite %d\n", p->pendinginvite);
03868             p->pendinginvite = 0;
03869          }
03870          if (cur->retransid > -1) {
03871             if (sipdebug)
03872                ast_debug(4, "** SIP TIMER: Cancelling retransmit of packet (reply received) Retransid #%d\n", cur->retransid);
03873          }
03874          /* This odd section is designed to thwart a
03875           * race condition in the packet scheduler. There are
03876           * two conditions under which deleting the packet from the
03877           * scheduler can fail.
03878           *
03879           * 1. The packet has been removed from the scheduler because retransmission
03880           * is being attempted. The problem is that if the packet is currently attempting
03881           * retransmission and we are at this point in the code, then that MUST mean
03882           * that retrans_pkt is waiting on p's lock. Therefore we will relinquish the
03883           * lock temporarily to allow retransmission.
03884           *
03885           * 2. The packet has reached its maximum number of retransmissions and has
03886           * been permanently removed from the packet scheduler. If this is the case, then
03887           * the packet's retransid will be set to -1. The atomicity of the setting and checking
03888           * of the retransid to -1 is ensured since in both cases p's lock is held.
03889           */
03890          while (cur->retransid > -1 && ast_sched_del(sched, cur->retransid)) {
03891             sip_pvt_unlock(p);
03892             usleep(1);
03893             sip_pvt_lock(p);
03894          }
03895          UNLINK(cur, p->packets, prev);
03896          dialog_unref(cur->owner, "unref pkt cur->owner dialog from sip ack before freeing pkt");
03897          if (cur->data) {
03898             ast_free(cur->data);
03899          }
03900          ast_free(cur);
03901          break;
03902       }
03903    }
03904    ast_debug(1, "Stopping retransmission on '%s' of %s %d: Match %s\n",
03905       p->callid, resp ? "Response" : "Request", seqno, msg);
03906    return res;
03907 }
03908 
03909 /*! \brief Pretend to ack all packets
03910  * called with p locked */
03911 void __sip_pretend_ack(struct sip_pvt *p)
03912 {
03913    struct sip_pkt *cur = NULL;
03914 
03915    while (p->packets) {
03916       int method;
03917       if (cur == p->packets) {
03918          ast_log(LOG_WARNING, "Have a packet that doesn't want to give up! %s\n", sip_methods[cur->method].text);
03919          return;
03920       }
03921       cur = p->packets;
03922       method = (cur->method) ? cur->method : find_sip_method(cur->data->str);
03923       __sip_ack(p, cur->seqno, cur->is_resp, method);
03924    }
03925 }
03926 
03927 /*! \brief Acks receipt of packet, keep it around (used for provisional responses) */
03928 int __sip_semi_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod)
03929 {
03930    struct sip_pkt *cur;
03931    int res = FALSE;
03932 
03933    for (cur = p->packets; cur; cur = cur->next) {
03934       if (cur->seqno == seqno && cur->is_resp == resp &&
03935          (cur->is_resp || method_match(sipmethod, cur->data->str))) {
03936          /* this is our baby */
03937          if (cur->retransid > -1) {
03938             if (sipdebug)
03939                ast_debug(4, "*** SIP TIMER: Cancelling retransmission #%d - %s (got response)\n", cur->retransid, sip_methods[sipmethod].text);
03940          }
03941          AST_SCHED_DEL(sched, cur->retransid);
03942          res = TRUE;
03943          break;
03944       }
03945    }
03946    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");
03947    return res;
03948 }
03949 
03950 
03951 /*! \brief Copy SIP request, parse it */
03952 static void parse_copy(struct sip_request *dst, const struct sip_request *src)
03953 {
03954    copy_request(dst, src);
03955    parse_request(dst);
03956 }
03957 
03958 /*! \brief add a blank line if no body */
03959 static void add_blank(struct sip_request *req)
03960 {
03961    if (!req->lines) {
03962       /* Add extra empty return. add_header() reserves 4 bytes so cannot be truncated */
03963       ast_str_append(&req->data, 0, "\r\n");
03964       req->len = ast_str_strlen(req->data);
03965    }
03966 }
03967 
03968 static int send_provisional_keepalive_full(struct sip_pvt *pvt, int with_sdp)
03969 {
03970    const char *msg = NULL;
03971 
03972    if (!pvt->last_provisional || !strncasecmp(pvt->last_provisional, "100", 3)) {
03973       msg = "183 Session Progress";
03974    }
03975 
03976    if (pvt->invitestate < INV_COMPLETED) {
03977       if (with_sdp) {
03978          transmit_response_with_sdp(pvt, S_OR(msg, pvt->last_provisional), &pvt->initreq, XMIT_UNRELIABLE, FALSE, FALSE);
03979       } else {
03980          transmit_response(pvt, S_OR(msg, pvt->last_provisional), &pvt->initreq);
03981       }
03982       return PROVIS_KEEPALIVE_TIMEOUT;
03983    }
03984 
03985    return 0;
03986 }
03987 
03988 static int send_provisional_keepalive(const void *data) {
03989    struct sip_pvt *pvt = (struct sip_pvt *) data;
03990 
03991    return send_provisional_keepalive_full(pvt, 0);
03992 }
03993 
03994 static int send_provisional_keepalive_with_sdp(const void *data) {
03995    struct sip_pvt *pvt = (void *)data;
03996 
03997    return send_provisional_keepalive_full(pvt, 1);
03998 }
03999 
04000 static void update_provisional_keepalive(struct sip_pvt *pvt, int with_sdp)
04001 {
04002    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"));
04003 
04004    pvt->provisional_keepalive_sched_id = ast_sched_add(sched, PROVIS_KEEPALIVE_TIMEOUT,
04005       with_sdp ? send_provisional_keepalive_with_sdp : send_provisional_keepalive, dialog_ref(pvt, "Increment refcount to pass dialog pointer to sched callback"));
04006 }
04007 
04008 /*! \brief Transmit response on SIP request*/
04009 static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno)
04010 {
04011    int res;
04012 
04013    finalize_content(req);
04014    add_blank(req);
04015    if (sip_debug_test_pvt(p)) {
04016       const struct ast_sockaddr *dst = sip_real_dst(p);
04017 
04018       ast_verbose("\n<--- %sTransmitting (%s) to %s --->\n%s\n<------------>\n",
04019          reliable ? "Reliably " : "", sip_nat_mode(p),
04020          ast_sockaddr_stringify(dst),
04021          req->data->str);
04022    }
04023    if (p->do_history) {
04024       struct sip_request tmp = { .rlPart1 = 0, };
04025       parse_copy(&tmp, req);
04026       append_history(p, reliable ? "TxRespRel" : "TxResp", "%s / %s - %s", tmp.data->str, get_header(&tmp, "CSeq"),
04027          (tmp.method == SIP_RESPONSE || tmp.method == SIP_UNKNOWN) ? REQ_OFFSET_TO_STR(&tmp, rlPart2) : sip_methods[tmp.method].text);
04028       deinit_req(&tmp);
04029    }
04030 
04031    /* If we are sending a final response to an INVITE, stop retransmitting provisional responses */
04032    if (p->initreq.method == SIP_INVITE && reliable == XMIT_CRITICAL) {
04033       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"));
04034    }
04035 
04036    res = (reliable) ?
04037        __sip_reliable_xmit(p, seqno, 1, req->data, req->len, (reliable == XMIT_CRITICAL), req->method) :
04038       __sip_xmit(p, req->data, req->len);
04039    deinit_req(req);
04040    if (res > 0) {
04041       return 0;
04042    }
04043    return res;
04044 }
04045 
04046 /*! \brief Send SIP Request to the other part of the dialogue 
04047    \return see \ref __sip_xmit
04048 */
04049 static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno)
04050 {
04051    int res;
04052 
04053    /* If we have an outbound proxy, reset peer address
04054       Only do this once.
04055    */
04056    if (p->outboundproxy) {
04057       p->sa = p->outboundproxy->ip;
04058    }
04059 
04060    finalize_content(req);
04061    add_blank(req);
04062    if (sip_debug_test_pvt(p)) {
04063       if (ast_test_flag(&p->flags[0], SIP_NAT_FORCE_RPORT)) {
04064          ast_verbose("%sTransmitting (NAT) to %s:\n%s\n---\n", reliable ? "Reliably " : "", ast_sockaddr_stringify(&p->recv), req->data->str);
04065       } else {
04066          ast_verbose("%sTransmitting (no NAT) to %s:\n%s\n---\n", reliable ? "Reliably " : "", ast_sockaddr_stringify(&p->sa), req->data->str);
04067       }
04068    }
04069    if (p->do_history) {
04070       struct sip_request tmp = { .rlPart1 = 0, };
04071       parse_copy(&tmp, req);
04072       append_history(p, reliable ? "TxReqRel" : "TxReq", "%s / %s - %s", tmp.data->str, get_header(&tmp, "CSeq"), sip_methods[tmp.method].text);
04073       deinit_req(&tmp);
04074    }
04075    res = (reliable) ?
04076       __sip_reliable_xmit(p, seqno, 0, req->data, req->len, (reliable == XMIT_CRITICAL), req->method) :
04077       __sip_xmit(p, req->data, req->len);
04078    deinit_req(req);
04079    return res;
04080 }
04081 
04082 static void enable_dsp_detect(struct sip_pvt *p)
04083 {
04084    int features = 0;
04085 
04086    if (p->dsp) {
04087       return;
04088    }
04089 
04090    if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) ||
04091             (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO)) {
04092       if (!p->rtp || ast_rtp_instance_dtmf_mode_set(p->rtp, AST_RTP_DTMF_MODE_INBAND)) {
04093          features |= DSP_FEATURE_DIGIT_DETECT;
04094                 }
04095    }
04096 
04097    if (ast_test_flag(&p->flags[1], SIP_PAGE2_FAX_DETECT_CNG)) {
04098       features |= DSP_FEATURE_FAX_DETECT;
04099    }
04100 
04101    if (!features) {
04102       return;
04103    }
04104 
04105    if (!(p->dsp = ast_dsp_new())) {
04106       return;
04107    }
04108 
04109    ast_dsp_set_features(p->dsp, features);
04110    if (global_relaxdtmf) {
04111       ast_dsp_set_digitmode(p->dsp, DSP_DIGITMODE_DTMF | DSP_DIGITMODE_RELAXDTMF);
04112    }
04113 }
04114 
04115 static void disable_dsp_detect(struct sip_pvt *p)
04116 {
04117    if (p->dsp) {
04118       ast_dsp_free(p->dsp);
04119       p->dsp = NULL;
04120    }
04121 }
04122 
04123 /*! \brief Set an option on a SIP dialog */
04124 static int sip_setoption(struct ast_channel *chan, int option, void *data, int datalen)
04125 {
04126    int res = -1;
04127    struct sip_pvt *p = chan->tech_pvt;
04128 
04129    switch (option) {
04130    case AST_OPTION_FORMAT_READ:
04131       res = ast_rtp_instance_set_read_format(p->rtp, *(int *) data);
04132       break;
04133    case AST_OPTION_FORMAT_WRITE:
04134       res = ast_rtp_instance_set_write_format(p->rtp, *(int *) data);
04135       break;
04136    case AST_OPTION_MAKE_COMPATIBLE:
04137       res = ast_rtp_instance_make_compatible(chan, p->rtp, (struct ast_channel *) data);
04138       break;
04139    case AST_OPTION_DIGIT_DETECT:
04140       if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) ||
04141           (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO)) {
04142          char *cp = (char *) data;
04143 
04144          ast_debug(1, "%sabling digit detection on %s\n", *cp ? "En" : "Dis", chan->name);
04145          if (*cp) {
04146             enable_dsp_detect(p);
04147          } else {
04148             disable_dsp_detect(p);
04149          }
04150          res = 0;
04151       }
04152       break;
04153    case AST_OPTION_SECURE_SIGNALING:
04154       p->req_secure_signaling = *(unsigned int *) data;
04155       res = 0;
04156       break;
04157    case AST_OPTION_SECURE_MEDIA:
04158       ast_set2_flag(&p->flags[1], *(unsigned int *) data, SIP_PAGE2_USE_SRTP);
04159       res = 0;
04160       break;
04161    default:
04162       break;
04163    }
04164 
04165    return res;
04166 }
04167 
04168 /*! \brief Query an option on a SIP dialog */
04169 static int sip_queryoption(struct ast_channel *chan, int option, void *data, int *datalen)
04170 {
04171    int res = -1;
04172    enum ast_t38_state state = T38_STATE_UNAVAILABLE;
04173    struct sip_pvt *p = (struct sip_pvt *) chan->tech_pvt;
04174    char *cp;
04175 
04176    switch (option) {
04177    case AST_OPTION_T38_STATE:
04178       /* Make sure we got an ast_t38_state enum passed in */
04179       if (*datalen != sizeof(enum ast_t38_state)) {
04180          ast_log(LOG_ERROR, "Invalid datalen for AST_OPTION_T38_STATE option. Expected %d, got %d\n", (int)sizeof(enum ast_t38_state), *datalen);
04181          return -1;
04182       }
04183 
04184       sip_pvt_lock(p);
04185 
04186       /* 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 */
04187       if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT)) {
04188          switch (p->t38.state) {
04189          case T38_LOCAL_REINVITE:
04190          case T38_PEER_REINVITE:
04191             state = T38_STATE_NEGOTIATING;
04192             break;
04193          case T38_ENABLED:
04194             state = T38_STATE_NEGOTIATED;
04195             break;
04196          default:
04197             state = T38_STATE_UNKNOWN;
04198          }
04199       }
04200 
04201       sip_pvt_unlock(p);
04202 
04203       *((enum ast_t38_state *) data) = state;
04204       res = 0;
04205 
04206       break;
04207    case AST_OPTION_DIGIT_DETECT:
04208       cp = (char *) data;
04209       *cp = p->dsp ? 1 : 0;
04210       ast_debug(1, "Reporting digit detection %sabled on %s\n", *cp ? "en" : "dis", chan->name);
04211       break;
04212    case AST_OPTION_SECURE_SIGNALING:
04213       *((unsigned int *) data) = p->req_secure_signaling;
04214       res = 0;
04215       break;
04216    case AST_OPTION_SECURE_MEDIA:
04217       *((unsigned int *) data) = ast_test_flag(&p->flags[1], SIP_PAGE2_USE_SRTP) ? 1 : 0;
04218       res = 0;
04219       break;
04220    case AST_OPTION_DEVICE_NAME:
04221       if (p && p->outgoing_call) {
04222          cp = (char *) data;
04223          ast_copy_string(cp, p->dialstring, *datalen);
04224          res = 0;
04225       }
04226       /* We purposely break with a return of -1 in the
04227        * implied else case here
04228        */
04229       break;
04230    default:
04231       break;
04232    }
04233 
04234    return res;
04235 }
04236 
04237 /*! \brief Locate closing quote in a string, skipping escaped quotes.
04238  * optionally with a limit on the search.
04239  * start must be past the first quote.
04240  */
04241 const char *find_closing_quote(const char *start, const char *lim)
04242 {
04243    char last_char = '\0';
04244    const char *s;
04245    for (s = start; *s && s != lim; last_char = *s++) {
04246       if (*s == '"' && last_char != '\\')
04247          break;
04248    }
04249    return s;
04250 }
04251 
04252 /*! \brief Send message with Access-URL header, if this is an HTML URL only! */
04253 static int sip_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen)
04254 {
04255    struct sip_pvt *p = chan->tech_pvt;
04256 
04257    if (subclass != AST_HTML_URL)
04258       return -1;
04259 
04260    ast_string_field_build(p, url, "<%s>;mode=active", data);
04261 
04262    if (sip_debug_test_pvt(p))
04263       ast_debug(1, "Send URL %s, state = %d!\n", data, chan->_state);
04264 
04265    switch (chan->_state) {
04266    case AST_STATE_RING:
04267       transmit_response(p, "100 Trying", &p->initreq);
04268       break;
04269    case AST_STATE_RINGING:
04270       transmit_response(p, "180 Ringing", &p->initreq);
04271       break;
04272    case AST_STATE_UP:
04273       if (!p->pendinginvite) {      /* We are up, and have no outstanding invite */
04274          transmit_reinvite_with_sdp(p, FALSE, FALSE);
04275       } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
04276          ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);   
04277       }  
04278       break;
04279    default:
04280       ast_log(LOG_WARNING, "Don't know how to send URI when state is %d!\n", chan->_state);
04281    }
04282 
04283    return 0;
04284 }
04285 
04286 /*! \brief Deliver SIP call ID for the call */
04287 static const char *sip_get_callid(struct ast_channel *chan)
04288 {
04289    return chan->tech_pvt ? ((struct sip_pvt *) chan->tech_pvt)->callid : "";
04290 }
04291 
04292 /*! \brief Send SIP MESSAGE text within a call
04293    Called from PBX core sendtext() application */
04294 static int sip_sendtext(struct ast_channel *ast, const char *text)
04295 {
04296    struct sip_pvt *dialog = ast->tech_pvt;
04297    int debug = sip_debug_test_pvt(dialog);
04298 
04299    if (!dialog)
04300       return -1;
04301    /* NOT ast_strlen_zero, because a zero-length message is specifically
04302     * allowed by RFC 3428 (See section 10, Examples) */
04303    if (!text)
04304       return 0;
04305    if(!is_method_allowed(&dialog->allowed_methods, SIP_MESSAGE)) {
04306       ast_debug(2, "Trying to send MESSAGE to device that does not support it.\n");
04307       return(0);
04308    }
04309    if (debug)
04310       ast_verbose("Sending text %s on %s\n", text, ast->name);
04311    transmit_message_with_text(dialog, text);
04312    return 0;   
04313 }
04314 
04315 /*! \brief Update peer object in realtime storage
04316    If the Asterisk system name is set in asterisk.conf, we will use
04317    that name and store that in the "regserver" field in the sippeers
04318    table to facilitate multi-server setups.
04319 */
04320 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)
04321 {
04322    char port[10];
04323    char ipaddr[INET6_ADDRSTRLEN];
04324    char regseconds[20];
04325    char *tablename = NULL;
04326    char str_lastms[20];
04327 
04328    const char *sysname = ast_config_AST_SYSTEM_NAME;
04329    char *syslabel = NULL;
04330 
04331    time_t nowtime = time(NULL) + expirey;
04332    const char *fc = fullcontact ? "fullcontact" : NULL;
04333 
04334    int realtimeregs = ast_check_realtime("sipregs");
04335 
04336    tablename = realtimeregs ? "sipregs" : "sippeers";
04337    
04338 
04339    snprintf(str_lastms, sizeof(str_lastms), "%d", lastms);
04340    snprintf(regseconds, sizeof(regseconds), "%d", (int)nowtime);  /* Expiration time */
04341    ast_copy_string(ipaddr, ast_sockaddr_stringify_addr(addr), sizeof(ipaddr));
04342    ast_copy_string(port, ast_sockaddr_stringify_port(addr), sizeof(port));
04343 
04344    if (ast_strlen_zero(sysname)) /* No system name, disable this */
04345       sysname = NULL;
04346    else if (sip_cfg.rtsave_sysname)
04347       syslabel = "regserver";
04348 
04349    /* XXX IMPORTANT: Anytime you add a new parameter to be updated, you
04350          *  must also add it to contrib/scripts/asterisk.ldap-schema,
04351          *  contrib/scripts/asterisk.ldif,
04352          *  and to configs/res_ldap.conf.sample as described in
04353          *  bugs 15156 and 15895 
04354          */
04355    if (fc) {
04356       ast_update_realtime(tablename, "name", peername, "ipaddr", ipaddr,
04357          "port", port, "regseconds", regseconds,
04358          deprecated_username ? "username" : "defaultuser", defaultuser,
04359          "useragent", useragent, "lastms", str_lastms,
04360          fc, fullcontact, syslabel, sysname, SENTINEL); /* note fc and syslabel _can_ be NULL */
04361    } else {
04362       ast_update_realtime(tablename, "name", peername, "ipaddr", ipaddr,
04363          "port", port, "regseconds", regseconds,
04364          "useragent", useragent, "lastms", str_lastms,
04365          deprecated_username ? "username" : "defaultuser", defaultuser,
04366          syslabel, sysname, SENTINEL); /* note syslabel _can_ be NULL */
04367    }
04368 }
04369 
04370 /*! \brief Automatically add peer extension to dial plan */
04371 static void register_peer_exten(struct sip_peer *peer, int onoff)
04372 {
04373    char multi[256];
04374    char *stringp, *ext, *context;
04375    struct pbx_find_info q = { .stacklen = 0 };
04376 
04377    /* XXX note that sip_cfg.regcontext is both a global 'enable' flag and
04378     * the name of the global regexten context, if not specified
04379     * individually.
04380     */
04381    if (ast_strlen_zero(sip_cfg.regcontext))
04382       return;
04383 
04384    ast_copy_string(multi, S_OR(peer->regexten, peer->name), sizeof(multi));
04385    stringp = multi;
04386    while ((ext = strsep(&stringp, "&"))) {
04387       if ((context = strchr(ext, '@'))) {
04388          *context++ = '\0';   /* split ext@context */
04389          if (!ast_context_find(context)) {
04390             ast_log(LOG_WARNING, "Context %s must exist in regcontext= in sip.conf!\n", context);
04391             continue;
04392          }
04393       } else {
04394          context = sip_cfg.regcontext;
04395       }
04396       if (onoff) {
04397          if (!ast_exists_extension(NULL, context, ext, 1, NULL)) {
04398             ast_add_extension(context, 1, ext, 1, NULL, NULL, "Noop",
04399                 ast_strdup(peer->name), ast_free_ptr, "SIP");
04400          }
04401       } else if (pbx_find_extension(NULL, NULL, &q, context, ext, 1, NULL, "", E_MATCH)) {
04402          ast_context_remove_extension(context, ext, 1, NULL);
04403       }
04404    }
04405 }
04406 
04407 /*! Destroy mailbox subscriptions */
04408 static void destroy_mailbox(struct sip_mailbox *mailbox)
04409 {
04410    if (mailbox->event_sub)
04411       ast_event_unsubscribe(mailbox->event_sub);
04412    ast_free(mailbox);
04413 }
04414 
04415 /*! Destroy all peer-related mailbox subscriptions */
04416 static void clear_peer_mailboxes(struct sip_peer *peer)
04417 {
04418    struct sip_mailbox *mailbox;
04419 
04420    while ((mailbox = AST_LIST_REMOVE_HEAD(&peer->mailboxes, entry)))
04421       destroy_mailbox(mailbox);
04422 }
04423 
04424 static void sip_destroy_peer_fn(void *peer)
04425 {
04426    sip_destroy_peer(peer);
04427 }
04428 
04429 /*! \brief Destroy peer object from memory */
04430 static void sip_destroy_peer(struct sip_peer *peer)
04431 {
04432    ast_debug(3, "Destroying SIP peer %s\n", peer->name);
04433    if (peer->outboundproxy)
04434       ao2_ref(peer->outboundproxy, -1);
04435    peer->outboundproxy = NULL;
04436 
04437    /* Delete it, it needs to disappear */
04438    if (peer->call) {
04439       dialog_unlink_all(peer->call, TRUE, TRUE);
04440       peer->call = dialog_unref(peer->call, "peer->call is being unset");
04441    }
04442    
04443 
04444    if (peer->mwipvt) {  /* We have an active subscription, delete it */
04445       dialog_unlink_all(peer->mwipvt, TRUE, TRUE);
04446       peer->mwipvt = dialog_unref(peer->mwipvt, "unreffing peer->mwipvt");
04447    }
04448    
04449    if (peer->chanvars) {
04450       ast_variables_destroy(peer->chanvars);
04451       peer->chanvars = NULL;
04452    }
04453    
04454    register_peer_exten(peer, FALSE);
04455    ast_free_ha(peer->ha);
04456    ast_free_ha(peer->directmediaha);
04457    if (peer->selfdestruct)
04458       ast_atomic_fetchadd_int(&apeerobjs, -1);
04459    else if (peer->is_realtime) {
04460       ast_atomic_fetchadd_int(&rpeerobjs, -1);
04461       ast_debug(3, "-REALTIME- peer Destroyed. Name: %s. Realtime Peer objects: %d\n", peer->name, rpeerobjs);
04462    } else
04463       ast_atomic_fetchadd_int(&speerobjs, -1);
04464    clear_realm_authentication(peer->auth);
04465    peer->auth = NULL;
04466    if (peer->dnsmgr)
04467       ast_dnsmgr_release(peer->dnsmgr);
04468    clear_peer_mailboxes(peer);
04469 
04470    if (peer->socket.tcptls_session) {
04471       ao2_ref(peer->socket.tcptls_session, -1);
04472       peer->socket.tcptls_session = NULL;
04473    }
04474 
04475    ast_cc_config_params_destroy(peer->cc_params);
04476 
04477    ast_string_field_free_memory(peer);
04478 }
04479 
04480 /*! \brief Update peer data in database (if used) */
04481 static void update_peer(struct sip_peer *p, int expire)
04482 {
04483    int rtcachefriends = ast_test_flag(&p->flags[1], SIP_PAGE2_RTCACHEFRIENDS);
04484    if (sip_cfg.peer_rtupdate &&
04485        (p->is_realtime || rtcachefriends)) {
04486       realtime_update_peer(p->name, &p->addr, p->username, rtcachefriends ? p->fullcontact : NULL, p->useragent, expire, p->deprecated_username, p->lastms);
04487    }
04488 }
04489 
04490 static struct ast_variable *get_insecure_variable_from_config(struct ast_config *cfg)
04491 {
04492    struct ast_variable *var = NULL;
04493    struct ast_flags flags = {0};
04494    char *cat = NULL;
04495    const char *insecure;
04496    while ((cat = ast_category_browse(cfg, cat))) {
04497       insecure = ast_variable_retrieve(cfg, cat, "insecure");
04498       set_insecure_flags(&flags, insecure, -1);
04499       if (ast_test_flag(&flags, SIP_INSECURE_PORT)) {
04500          var = ast_category_root(cfg, cat);
04501          break;
04502       }
04503    }
04504    return var;
04505 }
04506 
04507 static const char *get_name_from_variable(struct ast_variable *var, const char *newpeername)
04508 {
04509    struct ast_variable *tmp;
04510    for (tmp = var; tmp; tmp = tmp->next) {
04511       if (!newpeername && !strcasecmp(tmp->name, "name"))
04512          newpeername = tmp->value;
04513    }
04514    return newpeername;
04515 }
04516 
04517 /*! \brief  realtime_peer: Get peer from realtime storage
04518  * Checks the "sippeers" realtime family from extconfig.conf
04519  * Checks the "sipregs" realtime family from extconfig.conf if it's configured.
04520  * This returns a pointer to a peer and because we use build_peer, we can rest
04521  * assured that the refcount is bumped.
04522 */
04523 static struct sip_peer *realtime_peer(const char *newpeername, struct ast_sockaddr *addr, int devstate_only, int which_objects)
04524 {
04525    struct sip_peer *peer;
04526    struct ast_variable *var = NULL;
04527    struct ast_variable *varregs = NULL;
04528    struct ast_variable *tmp;
04529    struct ast_config *peerlist = NULL;
04530    char ipaddr[INET6_ADDRSTRLEN];
04531    char portstring[6]; /*up to 5 digits plus null terminator*/
04532    char *cat = NULL;
04533    int realtimeregs = ast_check_realtime("sipregs");
04534 
04535    /* First check on peer name */
04536    if (newpeername) {
04537       if (realtimeregs)
04538          varregs = ast_load_realtime("sipregs", "name", newpeername, SENTINEL);
04539 
04540       var = ast_load_realtime("sippeers", "name", newpeername, "host", "dynamic", SENTINEL);
04541       if (!var && addr) {
04542          var = ast_load_realtime("sippeers", "name", newpeername, "host", ast_sockaddr_stringify_addr(addr), SENTINEL);
04543       }
04544       if (!var) {
04545          var = ast_load_realtime("sippeers", "name", newpeername, SENTINEL);
04546          /*!\note
04547           * If this one loaded something, then we need to ensure that the host
04548           * field matched.  The only reason why we can't have this as a criteria
04549           * is because we only have the IP address and the host field might be
04550           * set as a name (and the reverse PTR might not match).
04551           */
04552          if (var && addr) {
04553             for (tmp = var; tmp; tmp = tmp->next) {
04554                if (!strcasecmp(tmp->name, "host")) {
04555                   struct ast_sockaddr *addrs = NULL;
04556 
04557                   if (ast_sockaddr_resolve(&addrs,
04558                             tmp->value,
04559                             PARSE_PORT_FORBID,
04560                             get_address_family_filter(&bindaddr)) <= 0 ||
04561                       ast_sockaddr_cmp(&addrs[0], addr)) {
04562                      /* No match */
04563                      ast_variables_destroy(var);
04564                      var = NULL;
04565                   }
04566                   ast_free(addrs);
04567                   break;
04568                }
04569             }
04570          }
04571       }
04572    }
04573 
04574    if (!var && addr) {  /* Then check on IP address for dynamic peers */
04575       ast_copy_string(ipaddr, ast_sockaddr_stringify_addr(addr), sizeof(ipaddr));
04576       ast_copy_string(portstring, ast_sockaddr_stringify_port(addr), sizeof(portstring));
04577       var = ast_load_realtime("sippeers", "host", ipaddr, "port", portstring, SENTINEL);  /* First check for fixed IP hosts */
04578       if (var) {
04579          if (realtimeregs) {
04580             newpeername = get_name_from_variable(var, newpeername);
04581             varregs = ast_load_realtime("sipregs", "name", newpeername, SENTINEL);
04582          }
04583       } else {
04584          if (realtimeregs)
04585             varregs = ast_load_realtime("sipregs", "ipaddr", ipaddr, "port", portstring, SENTINEL); /* Then check for registered hosts */
04586          else
04587             var = ast_load_realtime("sippeers", "ipaddr", ipaddr, "port", portstring, SENTINEL); /* Then check for registered hosts */
04588          if (varregs) {
04589             newpeername = get_name_from_variable(varregs, newpeername);
04590             var = ast_load_realtime("sippeers", "name", newpeername, SENTINEL);
04591          }
04592       }
04593       if (!var) { /*We couldn't match on ipaddress and port, so we need to check if port is insecure*/
04594          peerlist = ast_load_realtime_multientry("sippeers", "host", ipaddr, SENTINEL);
04595          if (peerlist) {
04596             var = get_insecure_variable_from_config(peerlist);
04597             if(var) {
04598                if (realtimeregs) {
04599                   newpeername = get_name_from_variable(var, newpeername);
04600                   varregs = ast_load_realtime("sipregs", "name", newpeername, SENTINEL);
04601                }
04602             } else { /*var wasn't found in the list of "hosts", so try "ipaddr"*/
04603                peerlist = NULL;
04604                cat = NULL;
04605                peerlist = ast_load_realtime_multientry("sippeers", "ipaddr", ipaddr, SENTINEL);
04606                if(peerlist) {
04607                   var = get_insecure_variable_from_config(peerlist);
04608                   if(var) {
04609                      if (realtimeregs) {
04610                         newpeername = get_name_from_variable(var, newpeername);
04611                         varregs = ast_load_realtime("sipregs", "name", newpeername, SENTINEL);
04612                      }
04613                   }
04614                }
04615             }
04616          } else {
04617             if (realtimeregs) {
04618                peerlist = ast_load_realtime_multientry("sipregs", "ipaddr", ipaddr, SENTINEL);
04619                if (peerlist) {
04620                   varregs = get_insecure_variable_from_config(peerlist);
04621                   if (varregs) {
04622                      newpeername = get_name_from_variable(varregs, newpeername);
04623                      var = ast_load_realtime("sippeers", "name", newpeername, SENTINEL);
04624                   }
04625                }
04626             } else {
04627                peerlist = ast_load_realtime_multientry("sippeers", "ipaddr", ipaddr, SENTINEL);
04628                if (peerlist) {
04629                   var = get_insecure_variable_from_config(peerlist);
04630                   if (var) {
04631                      newpeername = get_name_from_variable(var, newpeername);
04632                      varregs = ast_load_realtime("sipregs", "name", newpeername, SENTINEL);
04633                   }
04634                }
04635             }
04636          }
04637       }
04638    }
04639 
04640    if (!var) {
04641       if (peerlist)
04642          ast_config_destroy(peerlist);
04643       return NULL;
04644    }
04645 
04646    for (tmp = var; tmp; tmp = tmp->next) {
04647       if (!strcasecmp(tmp->name, "type") && (!strcasecmp(tmp->value, "peer") && which_objects == FINDUSERS)) {
04648          if (peerlist) {
04649             ast_config_destroy(peerlist);
04650          } else {
04651             ast_variables_destroy(var);
04652             ast_variables_destroy(varregs);
04653          }
04654          return NULL;
04655       } else if (!newpeername && !strcasecmp(tmp->name, "name")) {
04656          newpeername = tmp->value;
04657       }
04658    }
04659 
04660    if (!newpeername) {  /* Did not find peer in realtime */
04661       ast_log(LOG_WARNING, "Cannot Determine peer name ip=%s\n", ipaddr);
04662       if(peerlist)
04663          ast_config_destroy(peerlist);
04664       else
04665          ast_variables_destroy(var);
04666       return NULL;
04667    }
04668 
04669 
04670    /* Peer found in realtime, now build it in memory */
04671    peer = build_peer(newpeername, var, varregs, TRUE, devstate_only);
04672    if (!peer) {
04673       if(peerlist)
04674          ast_config_destroy(peerlist);
04675       else {
04676          ast_variables_destroy(var);
04677          ast_variables_destroy(varregs);
04678       }
04679       return NULL;
04680    }
04681 
04682    ast_debug(3, "-REALTIME- loading peer from database to memory. Name: %s. Peer objects: %d\n", peer->name, rpeerobjs);
04683 
04684    if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) && !devstate_only) {
04685       /* Cache peer */
04686       ast_copy_flags(&peer->flags[1], &global_flags[1], SIP_PAGE2_RTAUTOCLEAR|SIP_PAGE2_RTCACHEFRIENDS);
04687       if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTAUTOCLEAR)) {
04688          AST_SCHED_REPLACE_UNREF(peer->expire, sched, sip_cfg.rtautoclear * 1000, expire_register, peer,
04689                unref_peer(_data, "remove registration ref"),
04690                unref_peer(peer, "remove registration ref"),
04691                ref_peer(peer, "add registration ref"));
04692       }
04693       ao2_t_link(peers, peer, "link peer into peers table");
04694       if (!ast_sockaddr_isnull(&peer->addr)) {
04695          ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
04696       }
04697    }
04698    peer->is_realtime = 1;
04699    if (peerlist)
04700       ast_config_destroy(peerlist);
04701    else {
04702       ast_variables_destroy(var);
04703       ast_variables_destroy(varregs);
04704    }
04705 
04706    return peer;
04707 }
04708 
04709 /* Function to assist finding peers by name only */
04710 static int find_by_name(void *obj, void *arg, void *data, int flags)
04711 {
04712    struct sip_peer *search = obj, *match = arg;
04713    int *which_objects = data;
04714 
04715    /* Usernames in SIP uri's are case sensitive. Domains are not */
04716    if (strcmp(search->name, match->name)) {
04717       return 0;
04718    }
04719 
04720    switch (*which_objects) {
04721    case FINDUSERS:
04722       if (!(search->type & SIP_TYPE_USER)) {
04723          return 0;
04724       }
04725       break;
04726    case FINDPEERS:
04727       if (!(search->type & SIP_TYPE_PEER)) {
04728          return 0;
04729       }
04730       break;
04731    case FINDALLDEVICES:
04732       break;
04733    }
04734 
04735    return CMP_MATCH | CMP_STOP;
04736 }
04737 
04738 /*!
04739  * \brief Locate device by name or ip address
04740  * \param peer, sin, realtime, devstate_only, transport
04741  * \param which_objects Define which objects should be matched when doing a lookup
04742  *        by name.  Valid options are FINDUSERS, FINDPEERS, or FINDALLDEVICES.
04743  *        Note that this option is not used at all when doing a lookup by IP.
04744  *
04745  * This is used on find matching device on name or ip/port.
04746  * If the device was declared as type=peer, we don't match on peer name on incoming INVITEs.
04747  *
04748  * \note Avoid using this function in new functions if there is a way to avoid it,
04749  * since it might cause a database lookup.
04750  */
04751 static struct sip_peer *find_peer(const char *peer, struct ast_sockaddr *addr, int realtime, int which_objects, int devstate_only, int transport)
04752 {
04753    struct sip_peer *p = NULL;
04754    struct sip_peer tmp_peer;
04755 
04756    if (peer) {
04757       ast_copy_string(tmp_peer.name, peer, sizeof(tmp_peer.name));
04758       p = ao2_t_callback_data(peers, OBJ_POINTER, find_by_name, &tmp_peer, &which_objects, "ao2_find in peers table");
04759    } else if (addr) { /* search by addr? */
04760       ast_sockaddr_copy(&tmp_peer.addr, addr);
04761       tmp_peer.flags[0].flags = 0;
04762       tmp_peer.transports = transport;
04763       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); */
04764       if (!p) {
04765          ast_set_flag(&tmp_peer.flags[0], SIP_INSECURE_PORT);
04766          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); */
04767          if (p) {
04768             return p;
04769          }
04770       }
04771    }
04772 
04773    if (!p && (realtime || devstate_only)) {
04774       p = realtime_peer(peer, addr, devstate_only, which_objects);
04775       if (p) {
04776          switch (which_objects) {
04777          case FINDUSERS:
04778             if (!(p->type & SIP_TYPE_USER)) {
04779                unref_peer(p, "Wrong type of realtime SIP endpoint");
04780                return NULL;
04781             }
04782             break;
04783          case FINDPEERS:
04784             if (!(p->type & SIP_TYPE_PEER)) {
04785                unref_peer(p, "Wrong type of realtime SIP endpoint");
04786                return NULL;
04787             }
04788             break;
04789          case FINDALLDEVICES:
04790             break;
04791          }
04792       }
04793    }
04794 
04795    return p;
04796 }
04797 
04798 /*! \brief Set nat mode on the various data sockets */
04799 static void do_setnat(struct sip_pvt *p)
04800 {
04801    const char *mode;
04802    int natflags;
04803 
04804    natflags = ast_test_flag(&p->flags[1], SIP_PAGE2_SYMMETRICRTP);
04805    mode = natflags ? "On" : "Off";
04806 
04807    if (p->rtp) {
04808       ast_debug(1, "Setting NAT on RTP to %s\n", mode);
04809       ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_NAT, natflags);
04810    }
04811    if (p->vrtp) {
04812       ast_debug(1, "Setting NAT on VRTP to %s\n", mode);
04813       ast_rtp_instance_set_prop(p->vrtp, AST_RTP_PROPERTY_NAT, natflags);
04814    }
04815    if (p->udptl) {
04816       ast_debug(1, "Setting NAT on UDPTL to %s\n", mode);
04817       ast_udptl_setnat(p->udptl, natflags);
04818    }
04819    if (p->trtp) {
04820       ast_debug(1, "Setting NAT on TRTP to %s\n", mode);
04821       ast_rtp_instance_set_prop(p->trtp, AST_RTP_PROPERTY_NAT, natflags);
04822    }
04823 }
04824 
04825 /*! \brief Change the T38 state on a SIP dialog */
04826 static void change_t38_state(struct sip_pvt *p, int state)
04827 {
04828    int old = p->t38.state;
04829    struct ast_channel *chan = p->owner;
04830    struct ast_control_t38_parameters parameters = { .request_response = 0 };
04831 
04832    /* Don't bother changing if we are already in the state wanted */
04833    if (old == state)
04834       return;
04835 
04836    p->t38.state = state;
04837    ast_debug(2, "T38 state changed to %d on channel %s\n", p->t38.state, chan ? chan->name : "<none>");
04838 
04839    /* If no channel was provided we can't send off a control frame */
04840    if (!chan)
04841       return;
04842 
04843    /* Given the state requested and old state determine what control frame we want to queue up */
04844    switch (state) {
04845    case T38_PEER_REINVITE:
04846       parameters = p->t38.their_parms;
04847       parameters.max_ifp = ast_udptl_get_far_max_ifp(p->udptl);
04848       parameters.request_response = AST_T38_REQUEST_NEGOTIATE;
04849       ast_udptl_set_tag(p->udptl, "SIP/%s", p->username);
04850       break;
04851    case T38_ENABLED:
04852       parameters = p->t38.their_parms;
04853       parameters.max_ifp = ast_udptl_get_far_max_ifp(p->udptl);
04854       parameters.request_response = AST_T38_NEGOTIATED;
04855       ast_udptl_set_tag(p->udptl, "SIP/%s", p->username);
04856       break;
04857    case T38_DISABLED:
04858       if (old == T38_ENABLED) {
04859          parameters.request_response = AST_T38_TERMINATED;
04860       } else if (old == T38_LOCAL_REINVITE) {
04861          parameters.request_response = AST_T38_REFUSED;
04862       }
04863       break;
04864    case T38_LOCAL_REINVITE:
04865       /* wait until we get a peer response before responding to local reinvite */
04866       break;
04867    }
04868 
04869    /* Woot we got a message, create a control frame and send it on! */
04870    if (parameters.request_response)
04871       ast_queue_control_data(chan, AST_CONTROL_T38_PARAMETERS, &parameters, sizeof(parameters));
04872 }
04873 
04874 /*! \brief Set the global T38 capabilities on a SIP dialog structure */
04875 static void set_t38_capabilities(struct sip_pvt *p)
04876 {
04877    if (p->udptl) {
04878       if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) == SIP_PAGE2_T38SUPPORT_UDPTL_REDUNDANCY) {
04879                         ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_REDUNDANCY);
04880       } else if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) == SIP_PAGE2_T38SUPPORT_UDPTL_FEC) {
04881          ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_FEC);
04882       } else if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) == SIP_PAGE2_T38SUPPORT_UDPTL) {
04883          ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_NONE);
04884       }
04885    }
04886 }
04887 
04888 static void copy_socket_data(struct sip_socket *to_sock, const struct sip_socket *from_sock)
04889 {
04890    if (to_sock->tcptls_session) {
04891       ao2_ref(to_sock->tcptls_session, -1);
04892       to_sock->tcptls_session = NULL;
04893    }
04894 
04895    if (from_sock->tcptls_session) {
04896       ao2_ref(from_sock->tcptls_session, +1);
04897    }
04898 
04899    *to_sock = *from_sock;
04900 }
04901 
04902 /*! \brief Initialize RTP portion of a dialog
04903  * \return -1 on failure, 0 on success
04904  */
04905 static int dialog_initialize_rtp(struct sip_pvt *dialog)
04906 {
04907    struct ast_sockaddr bindaddr_tmp;
04908 
04909    if (!sip_methods[dialog->method].need_rtp) {
04910       return 0;
04911    }
04912 
04913    ast_sockaddr_copy(&bindaddr_tmp, &bindaddr);
04914    if (!(dialog->rtp = ast_rtp_instance_new(dialog->engine, sched, &bindaddr_tmp, NULL))) {
04915       return -1;
04916    }
04917 
04918    if (ast_test_flag(&dialog->flags[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS) ||
04919          (ast_test_flag(&dialog->flags[1], SIP_PAGE2_VIDEOSUPPORT) && (dialog->capability & AST_FORMAT_VIDEO_MASK))) {
04920       if (!(dialog->vrtp = ast_rtp_instance_new(dialog->engine, sched, &bindaddr_tmp, NULL))) {
04921          return -1;
04922       }
04923       ast_rtp_instance_set_timeout(dialog->vrtp, global_rtptimeout);
04924       ast_rtp_instance_set_hold_timeout(dialog->vrtp, global_rtpholdtimeout);
04925 
04926       ast_rtp_instance_set_prop(dialog->vrtp, AST_RTP_PROPERTY_RTCP, 1);
04927    }
04928 
04929    if (ast_test_flag(&dialog->flags[1], SIP_PAGE2_TEXTSUPPORT)) {
04930       if (!(dialog->trtp = ast_rtp_instance_new(dialog->engine, sched, &bindaddr_tmp, NULL))) {
04931          return -1;
04932       }
04933       ast_rtp_instance_set_timeout(dialog->trtp, global_rtptimeout);
04934       ast_rtp_instance_set_hold_timeout(dialog->trtp, global_rtpholdtimeout);
04935 
04936       ast_rtp_instance_set_prop(dialog->trtp, AST_RTP_PROPERTY_RTCP, 1);
04937    }
04938 
04939    ast_rtp_instance_set_timeout(dialog->rtp, global_rtptimeout);
04940    ast_rtp_instance_set_hold_timeout(dialog->rtp, global_rtpholdtimeout);
04941 
04942    ast_rtp_instance_set_prop(dialog->rtp, AST_RTP_PROPERTY_RTCP, 1);
04943    ast_rtp_instance_set_prop(dialog->rtp, AST_RTP_PROPERTY_DTMF, ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
04944    ast_rtp_instance_set_prop(dialog->rtp, AST_RTP_PROPERTY_DTMF_COMPENSATE, ast_test_flag(&dialog->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
04945 
04946    ast_rtp_instance_set_qos(dialog->rtp, global_tos_audio, global_cos_audio, "SIP RTP");
04947 
04948    do_setnat(dialog);
04949 
04950    return 0;
04951 }
04952 
04953 /*! \brief Create address structure from peer reference.
04954  * This function copies data from peer to the dialog, so we don't have to look up the peer
04955  * again from memory or database during the life time of the dialog.
04956  *
04957  * \return -1 on error, 0 on success.
04958  *
04959  */
04960 static int create_addr_from_peer(struct sip_pvt *dialog, struct sip_peer *peer)
04961 {
04962    /* this checks that the dialog is contacting the peer on a valid
04963     * transport type based on the peers transport configuration,
04964     * otherwise, this function bails out */
04965    if (dialog->socket.type && check_request_transport(peer, dialog))
04966       return -1;
04967    copy_socket_data(&dialog->socket, &peer->socket);
04968 
04969    if (!(ast_sockaddr_isnull(&peer->addr) && ast_sockaddr_isnull(&peer->defaddr)) &&
04970        (!peer->maxms || ((peer->lastms >= 0)  && (peer->lastms <= peer->maxms)))) {
04971       dialog->sa = ast_sockaddr_isnull(&peer->addr) ? peer->defaddr : peer->addr;
04972       dialog->recv = dialog->sa;
04973    } else
04974       return -1;
04975 
04976    /* XXX TODO: get flags directly from peer only as they are needed using dialog->relatedpeer */
04977    ast_copy_flags(&dialog->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
04978    ast_copy_flags(&dialog->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
04979    ast_copy_flags(&dialog->flags[2], &peer->flags[2], SIP_PAGE3_FLAGS_TO_COPY);
04980    dialog->capability = peer->capability;
04981    dialog->prefs = peer->prefs;
04982    if (ast_test_flag(&dialog->flags[1], SIP_PAGE2_T38SUPPORT)) {
04983       /* t38pt_udptl was enabled in the peer and not in [general] */
04984       if (dialog->udptl || (!dialog->udptl && (dialog->udptl = ast_udptl_new_with_bindaddr(sched, io, 0, &bindaddr)))) {
04985          dialog->t38_maxdatagram = peer->t38_maxdatagram;
04986          set_t38_capabilities(dialog);
04987       } else {
04988          /* It is impossible to support T38 without udptl */
04989          ast_debug(1, "UDPTL creation failed on dialog.\n");
04990          ast_clear_flag(&dialog->flags[1], SIP_PAGE2_T38SUPPORT);
04991       }
04992    } else if (dialog->udptl) {
04993       ast_udptl_destroy(dialog->udptl);
04994       dialog->udptl = NULL;
04995    }
04996 
04997    ast_string_field_set(dialog, engine, peer->engine);
04998 
04999    if (dialog_initialize_rtp(dialog)) {
05000       return -1;
05001    }
05002 
05003    if (dialog->rtp) { /* Audio */
05004       ast_rtp_instance_set_prop(dialog->rtp, AST_RTP_PROPERTY_DTMF, ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
05005       ast_rtp_instance_set_prop(dialog->rtp, AST_RTP_PROPERTY_DTMF_COMPENSATE, ast_test_flag(&dialog->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
05006       ast_rtp_instance_set_timeout(dialog->rtp, peer->rtptimeout);
05007       ast_rtp_instance_set_hold_timeout(dialog->rtp, peer->rtpholdtimeout);
05008       /* Set Frame packetization */
05009       ast_rtp_codecs_packetization_set(ast_rtp_instance_get_codecs(dialog->rtp), dialog->rtp, &dialog->prefs);
05010       dialog->autoframing = peer->autoframing;
05011    }
05012    if (dialog->vrtp) { /* Video */
05013       ast_rtp_instance_set_timeout(dialog->vrtp, peer->rtptimeout);
05014       ast_rtp_instance_set_hold_timeout(dialog->vrtp, peer->rtpholdtimeout);
05015    }
05016    if (dialog->trtp) { /* Realtime text */
05017       ast_rtp_instance_set_timeout(dialog->trtp, peer->rtptimeout);
05018       ast_rtp_instance_set_hold_timeout(dialog->trtp, peer->rtpholdtimeout);
05019    }
05020 
05021    /* XXX TODO: get fields directly from peer only as they are needed using dialog->relatedpeer */
05022    ast_string_field_set(dialog, peername, peer->name);
05023    ast_string_field_set(dialog, authname, peer->username);
05024    ast_string_field_set(dialog, username, peer->username);
05025    ast_string_field_set(dialog, peersecret, peer->secret);
05026    ast_string_field_set(dialog, peermd5secret, peer->md5secret);
05027    ast_string_field_set(dialog, mohsuggest, peer->mohsuggest);
05028    ast_string_field_set(dialog, mohinterpret, peer->mohinterpret);
05029    ast_string_field_set(dialog, tohost, peer->tohost);
05030    ast_string_field_set(dialog, fullcontact, peer->fullcontact);
05031    ast_string_field_set(dialog, accountcode, peer->accountcode);
05032    ast_string_field_set(dialog, context, peer->context);
05033    ast_string_field_set(dialog, cid_num, peer->cid_num);
05034    ast_string_field_set(dialog, cid_name, peer->cid_name);
05035    ast_string_field_set(dialog, cid_tag, peer->cid_tag);
05036    ast_string_field_set(dialog, mwi_from, peer->mwi_from);
05037    if (!ast_strlen_zero(peer->parkinglot)) {
05038       ast_string_field_set(dialog, parkinglot, peer->parkinglot);
05039    }
05040    ast_string_field_set(dialog, engine, peer->engine);
05041    ref_proxy(dialog, obproxy_get(dialog, peer));
05042    dialog->callgroup = peer->callgroup;
05043    dialog->pickupgroup = peer->pickupgroup;
05044    dialog->allowtransfer = peer->allowtransfer;
05045    dialog->jointnoncodeccapability = dialog->noncodeccapability;
05046    dialog->rtptimeout = peer->rtptimeout;
05047    dialog->peerauth = peer->auth;
05048    dialog->maxcallbitrate = peer->maxcallbitrate;
05049    dialog->disallowed_methods = peer->disallowed_methods;
05050    ast_cc_copy_config_params(dialog->cc_params, peer->cc_params);
05051    if (ast_strlen_zero(dialog->tohost))
05052       ast_string_field_set(dialog, tohost, ast_sockaddr_stringify_host(&dialog->sa));
05053    if (!ast_strlen_zero(peer->fromdomain)) {
05054       ast_string_field_set(dialog, fromdomain, peer->fromdomain);
05055       if (!dialog->initreq.headers) {
05056          char *c;
05057          char *tmpcall = ast_strdupa(dialog->callid);
05058          /* this sure looks to me like we are going to change the callid on this dialog!! */
05059          c = strchr(tmpcall, '@');
05060          if (c) {
05061             *c = '\0';
05062             ao2_t_unlink(dialogs, dialog, "About to change the callid -- remove the old name");
05063             ast_string_field_build(dialog, callid, "%s@%s", tmpcall, peer->fromdomain);
05064             ao2_t_link(dialogs, dialog, "New dialog callid -- inserted back into table");
05065          }
05066       }
05067    }
05068    if (!ast_strlen_zero(peer->fromuser))
05069       ast_string_field_set(dialog, fromuser, peer->fromuser);
05070    if (!ast_strlen_zero(peer->language))
05071       ast_string_field_set(dialog, language, peer->language);
05072    /* Set timer T1 to RTT for this peer (if known by qualify=) */
05073    /* Minimum is settable or default to 100 ms */
05074    /* If there is a maxms and lastms from a qualify use that over a manual T1
05075       value. Otherwise, use the peer's T1 value. */
05076    if (peer->maxms && peer->lastms)
05077       dialog->timer_t1 = peer->lastms < global_t1min ? global_t1min : peer->lastms;
05078    else
05079       dialog->timer_t1 = peer->timer_t1;
05080 
05081    /* Set timer B to control transaction timeouts, the peer setting is the default and overrides
05082       the known timer */
05083    if (peer->timer_b)
05084       dialog->timer_b = peer->timer_b;
05085    else
05086       dialog->timer_b = 64 * dialog->timer_t1;
05087 
05088    if ((ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
05089        (ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
05090       dialog->noncodeccapability |= AST_RTP_DTMF;
05091    else
05092       dialog->noncodeccapability &= ~AST_RTP_DTMF;
05093    dialog->directmediaha = ast_duplicate_ha_list(peer->directmediaha);
05094    if (peer->call_limit)
05095       ast_set_flag(&dialog->flags[0], SIP_CALL_LIMIT);
05096    if (!dialog->portinuri)
05097       dialog->portinuri = peer->portinuri;
05098    dialog->chanvars = copy_vars(peer->chanvars);
05099    if (peer->fromdomainport)
05100       dialog->fromdomainport = peer->fromdomainport;
05101 
05102    return 0;
05103 }
05104 
05105 /*! \brief create address structure from device name
05106  *      Or, if peer not found, find it in the global DNS
05107  *      returns TRUE (-1) on failure, FALSE on success */
05108 static int create_addr(struct sip_pvt *dialog, const char *opeer, struct ast_sockaddr *addr, int newdialog, struct ast_sockaddr *remote_address)
05109 {
05110    struct sip_peer *peer;
05111    char *peername, *peername2, *hostn;
05112    char host[MAXHOSTNAMELEN];
05113    char service[MAXHOSTNAMELEN];
05114    int srv_ret = 0;
05115    int tportno;
05116 
05117    AST_DECLARE_APP_ARGS(hostport,
05118       AST_APP_ARG(host);
05119       AST_APP_ARG(port);
05120    );
05121 
05122    peername = ast_strdupa(opeer);
05123    peername2 = ast_strdupa(opeer);
05124    AST_NONSTANDARD_RAW_ARGS(hostport, peername2, ':');
05125 
05126    if (hostport.port)
05127       dialog->portinuri = 1;
05128 
05129    dialog->timer_t1 = global_t1; /* Default SIP retransmission timer T1 (RFC 3261) */
05130    dialog->timer_b = global_timer_b; /* Default SIP transaction timer B (RFC 3261) */
05131    peer = find_peer(peername, NULL, TRUE, FINDPEERS, FALSE, 0);
05132 
05133    if (peer) {
05134       int res;
05135       if (newdialog) {
05136          set_socket_transport(&dialog->socket, 0);
05137       }
05138       res = create_addr_from_peer(dialog, peer);
05139       if (!ast_sockaddr_isnull(remote_address)) {
05140          ast_sockaddr_copy(&dialog->sa, remote_address);
05141       }
05142       dialog->relatedpeer = ref_peer(peer, "create_addr: setting dialog's relatedpeer pointer");
05143       unref_peer(peer, "create_addr: unref peer from find_peer hashtab lookup");
05144       return res;
05145    }
05146 
05147    if (dialog_initialize_rtp(dialog)) {
05148       return -1;
05149    }
05150 
05151    ast_string_field_set(dialog, tohost, hostport.host);
05152    dialog->allowed_methods &= ~sip_cfg.disallowed_methods;
05153 
05154    /* Get the outbound proxy information */
05155    ref_proxy(dialog, obproxy_get(dialog, NULL));
05156 
05157    if (addr) {
05158       /* This address should be updated using dnsmgr */
05159       ast_sockaddr_copy(&dialog->sa, addr);
05160    } else {
05161 
05162       /* Let's see if we can find the host in DNS. First try DNS SRV records,
05163          then hostname lookup */
05164       /*! \todo Fix this function. When we ask for SRV, we should check all transports
05165            In the future, we should first check NAPTR to find out transport preference
05166        */
05167       hostn = peername;
05168       /* Section 4.2 of RFC 3263 specifies that if a port number is specified, then
05169        * an A record lookup should be used instead of SRV.
05170        */
05171       if (!hostport.port && sip_cfg.srvlookup) {
05172          snprintf(service, sizeof(service), "_%s._%s.%s", 
05173              get_srv_service(dialog->socket.type),
05174              get_srv_protocol(dialog->socket.type), peername);
05175          if ((srv_ret = ast_get_srv(NULL, host, sizeof(host), &tportno,
05176                      service)) > 0) {
05177             hostn = host;
05178          }
05179       }
05180 
05181       if (ast_sockaddr_resolve_first(&dialog->sa, hostn, 0)) {
05182          ast_log(LOG_WARNING, "No such host: %s\n", peername);
05183       }
05184 
05185       if (srv_ret > 0) {
05186          ast_sockaddr_set_port(&dialog->sa, tportno);
05187       }
05188    }
05189 
05190    if (!dialog->socket.type)
05191       set_socket_transport(&dialog->socket, SIP_TRANSPORT_UDP);
05192    if (!dialog->socket.port) {
05193       dialog->socket.port = htons(ast_sockaddr_port(&bindaddr));
05194    }
05195 
05196    if (!ast_sockaddr_port(&dialog->sa)) {
05197       ast_sockaddr_set_port(&dialog->sa,
05198                   (dialog->socket.type == SIP_TRANSPORT_TLS) ?
05199                   STANDARD_TLS_PORT : STANDARD_SIP_PORT);
05200    }
05201    ast_sockaddr_copy(&dialog->recv, &dialog->sa);
05202    return 0;
05203 }
05204 
05205 /*! \brief Scheduled congestion on a call.
05206  * Only called by the scheduler, must return the reference when done.
05207  */
05208 static int auto_congest(const void *arg)
05209 {
05210    struct sip_pvt *p = (struct sip_pvt *)arg;
05211 
05212    sip_pvt_lock(p);
05213    p->initid = -1;   /* event gone, will not be rescheduled */
05214    if (p->owner) {
05215       /* XXX fails on possible deadlock */
05216       if (!ast_channel_trylock(p->owner)) {
05217          append_history(p, "Cong", "Auto-congesting (timer)");
05218          ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
05219          ast_channel_unlock(p->owner);
05220       }
05221 
05222       /* Give the channel a chance to act before we proceed with destruction */
05223       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
05224    }
05225    sip_pvt_unlock(p);
05226    dialog_unref(p, "unreffing arg passed into auto_congest callback (p->initid)");
05227    return 0;
05228 }
05229 
05230 
05231 /*! \brief Initiate SIP call from PBX
05232  *      used from the dial() application      */
05233 static int sip_call(struct ast_channel *ast, char *dest, int timeout)
05234 {
05235    int res;
05236    struct sip_pvt *p = ast->tech_pvt;  /* chan is locked, so the reference cannot go away */
05237    struct varshead *headp;
05238    struct ast_var_t *current;
05239    const char *referer = NULL;   /* SIP referrer */
05240    int cc_core_id;
05241    char uri[SIPBUFSIZE] = "";
05242 
05243    if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
05244       ast_log(LOG_WARNING, "sip_call called on %s, neither down nor reserved\n", ast->name);
05245       return -1;
05246    }
05247 
05248    if (ast_cc_is_recall(ast, &cc_core_id, "SIP")) {
05249       char device_name[AST_CHANNEL_NAME];
05250       struct ast_cc_monitor *recall_monitor;
05251       struct sip_monitor_instance *monitor_instance;
05252       ast_channel_get_device_name(ast, device_name, sizeof(device_name));
05253       if ((recall_monitor = ast_cc_get_monitor_by_recall_core_id(cc_core_id, device_name))) {
05254          monitor_instance = recall_monitor->private_data;
05255          ast_copy_string(uri, monitor_instance->notify_uri, sizeof(uri));
05256          ao2_t_ref(recall_monitor, -1, "Got the URI we need so unreffing monitor");
05257       }
05258    }
05259 
05260    /* Check whether there is vxml_url, distinctive ring variables */
05261    headp=&ast->varshead;
05262    AST_LIST_TRAVERSE(headp, current, entries) {
05263       /* Check whether there is a VXML_URL variable */
05264       if (!p->options->vxml_url && !strcasecmp(ast_var_name(current), "VXML_URL")) {
05265          p->options->vxml_url = ast_var_value(current);
05266       } else if (!p->options->uri_options && !strcasecmp(ast_var_name(current), "SIP_URI_OPTIONS")) {
05267          p->options->uri_options = ast_var_value(current);
05268       } else if (!p->options->addsipheaders && !strncasecmp(ast_var_name(current), "SIPADDHEADER", strlen("SIPADDHEADER"))) {
05269          /* Check whether there is a variable with a name starting with SIPADDHEADER */
05270          p->options->addsipheaders = 1;
05271       } else if (!strcasecmp(ast_var_name(current), "SIPFROMDOMAIN")) {
05272          ast_string_field_set(p, fromdomain, ast_var_value(current));
05273       } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER")) {
05274          /* This is a transfered call */
05275          p->options->transfer = 1;
05276       } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER_REFERER")) {
05277          /* This is the referrer */
05278          referer = ast_var_value(current);
05279       } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER_REPLACES")) {
05280          /* We're replacing a call. */
05281          p->options->replaces = ast_var_value(current);
05282       } else if (!strcasecmp(ast_var_name(current), "SIP_MAX_FORWARDS")) {
05283          if (sscanf(ast_var_value(current), "%d", &(p->maxforwards)) != 1) {
05284             ast_log(LOG_WARNING, "The SIP_MAX_FORWARDS channel variable is not a valid integer.");
05285          }
05286       }
05287    }
05288 
05289    /* Check to see if we should try to force encryption */
05290    if (p->req_secure_signaling && p->socket.type != SIP_TRANSPORT_TLS) {
05291       ast_log(LOG_WARNING, "Encrypted signaling is required\n");
05292       ast->hangupcause = AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
05293       return -1;
05294    }
05295 
05296    if (ast_test_flag(&p->flags[1], SIP_PAGE2_USE_SRTP)) {
05297       if (ast_test_flag(&p->flags[0], SIP_REINVITE)) {
05298          ast_debug(1, "Direct media not possible when using SRTP, ignoring canreinvite setting\n");
05299          ast_clear_flag(&p->flags[0], SIP_REINVITE);
05300       }
05301 
05302       if (p->rtp && !p->srtp && setup_srtp(&p->srtp) < 0) {
05303          ast_log(LOG_WARNING, "SRTP audio setup failed\n");
05304          return -1;
05305       }
05306 
05307       if (p->vrtp && !p->vsrtp && setup_srtp(&p->vsrtp) < 0) {
05308          ast_log(LOG_WARNING, "SRTP video setup failed\n");
05309          return -1;
05310       }
05311 
05312       if (p->trtp && !p->vsrtp && setup_srtp(&p->tsrtp) < 0) {
05313          ast_log(LOG_WARNING, "SRTP text setup failed\n");
05314          return -1;
05315       }
05316    }
05317 
05318    res = 0;
05319    ast_set_flag(&p->flags[0], SIP_OUTGOING);
05320 
05321    /* T.38 re-INVITE FAX detection should never be done for outgoing calls,
05322     * so ensure it is disabled.
05323     */
05324    ast_clear_flag(&p->flags[1], SIP_PAGE2_FAX_DETECT_T38);
05325 
05326    if (p->options->transfer) {
05327       char buf[SIPBUFSIZE/2];
05328 
05329       if (referer) {
05330          if (sipdebug)
05331             ast_debug(3, "Call for %s transfered by %s\n", p->username, referer);
05332          snprintf(buf, sizeof(buf)-1, "-> %s (via %s)", p->cid_name, referer);
05333       } else
05334          snprintf(buf, sizeof(buf)-1, "-> %s", p->cid_name);
05335       ast_string_field_set(p, cid_name, buf);
05336    }
05337    ast_debug(1, "Outgoing Call for %s\n", p->username);
05338 
05339    res = update_call_counter(p, INC_CALL_RINGING);
05340 
05341    if (res == -1) {
05342       ast->hangupcause = AST_CAUSE_USER_BUSY;
05343       return res;
05344    }
05345    p->callingpres = ast_party_id_presentation(&ast->caller.id);
05346    p->jointcapability = ast_rtp_instance_available_formats(p->rtp, p->capability, p->prefcodec);
05347    p->jointnoncodeccapability = p->noncodeccapability;
05348 
05349    /* If there are no audio formats left to offer, punt */
05350    if (!(p->jointcapability & AST_FORMAT_AUDIO_MASK)) {
05351       ast_log(LOG_WARNING, "No audio format found to offer. Cancelling call to %s\n", p->username);
05352       res = -1;
05353    } else {
05354       int xmitres;
05355 
05356       sip_pvt_lock(p);
05357       xmitres = transmit_invite(p, SIP_INVITE, 1, 2, uri);
05358       sip_pvt_unlock(p);
05359       if (xmitres == XMIT_ERROR)
05360          return -1;
05361       p->invitestate = INV_CALLING;
05362 
05363       /* Initialize auto-congest time */
05364       AST_SCHED_REPLACE_UNREF(p->initid, sched, p->timer_b, auto_congest, p,
05365                         dialog_unref(_data, "dialog ptr dec when SCHED_REPLACE del op succeeded"),
05366                         dialog_unref(p, "dialog ptr dec when SCHED_REPLACE add failed"),
05367                         dialog_ref(p, "dialog ptr inc when SCHED_REPLACE add succeeded") );
05368    }
05369    return res;
05370 }
05371 
05372 /*! \brief Destroy registry object
05373    Objects created with the register= statement in static configuration */
05374 static void sip_registry_destroy(struct sip_registry *reg)
05375 {
05376    /* Really delete */
05377    ast_debug(3, "Destroying registry entry for %s@%s\n", reg->username, reg->hostname);
05378 
05379    if (reg->call) {
05380       /* Clear registry before destroying to ensure
05381          we don't get reentered trying to grab the registry lock */
05382       reg->call->registry = registry_unref(reg->call->registry, "destroy reg->call->registry");
05383       ast_debug(3, "Destroying active SIP dialog for registry %s@%s\n", reg->username, reg->hostname);
05384       dialog_unlink_all(reg->call, TRUE, TRUE);
05385       reg->call = dialog_unref(reg->call, "unref reg->call");
05386       /* reg->call = sip_destroy(reg->call); */
05387    }
05388    AST_SCHED_DEL(sched, reg->expire);  
05389    AST_SCHED_DEL(sched, reg->timeout);
05390    
05391    ast_string_field_free_memory(reg);
05392    ast_atomic_fetchadd_int(&regobjs, -1);
05393    ast_dnsmgr_release(reg->dnsmgr);
05394    ast_free(reg);
05395 }
05396 
05397 /*! \brief Destroy MWI subscription object */
05398 static void sip_subscribe_mwi_destroy(struct sip_subscription_mwi *mwi)
05399 {
05400    if (mwi->call) {
05401       mwi->call->mwi = NULL;
05402       sip_destroy(mwi->call);
05403    }
05404    
05405    AST_SCHED_DEL(sched, mwi->resub);
05406    ast_string_field_free_memory(mwi);
05407    ast_dnsmgr_release(mwi->dnsmgr);
05408    ast_free(mwi);
05409 }
05410 
05411 /*! \brief Execute destruction of SIP dialog structure, release memory */
05412 void __sip_destroy(struct sip_pvt *p, int lockowner, int lockdialoglist)
05413 {
05414    struct sip_request *req;
05415 
05416    if (p->stimer) {
05417       ast_free(p->stimer);
05418       p->stimer = NULL;
05419    }
05420 
05421    if (sip_debug_test_pvt(p))
05422       ast_verbose("Really destroying SIP dialog '%s' Method: %s\n", p->callid, sip_methods[p->method].text);
05423 
05424    if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
05425       update_call_counter(p, DEC_CALL_LIMIT);
05426       ast_debug(2, "This call did not properly clean up call limits. Call ID %s\n", p->callid);
05427    }
05428 
05429    /* Unlink us from the owner if we have one */
05430    if (p->owner) {
05431       if (lockowner)
05432          ast_channel_lock(p->owner);
05433       ast_debug(1, "Detaching from %s\n", p->owner->name);
05434       p->owner->tech_pvt = NULL;
05435       /* Make sure that the channel knows its backend is going away */
05436       p->owner->_softhangup |= AST_SOFTHANGUP_DEV;
05437       if (lockowner)
05438          ast_channel_unlock(p->owner);
05439       /* Give the channel a chance to react before deallocation */
05440       usleep(1);
05441    }
05442 
05443    /* Remove link from peer to subscription of MWI */
05444    if (p->relatedpeer && p->relatedpeer->mwipvt)
05445       p->relatedpeer->mwipvt = dialog_unref(p->relatedpeer->mwipvt, "delete ->relatedpeer->mwipvt");
05446    if (p->relatedpeer && p->relatedpeer->call == p)
05447       p->relatedpeer->call = dialog_unref(p->relatedpeer->call, "unset the relatedpeer->call field in tandem with relatedpeer field itself");
05448    
05449    if (p->relatedpeer)
05450       p->relatedpeer = unref_peer(p->relatedpeer,"unsetting a dialog relatedpeer field in sip_destroy");
05451    
05452    if (p->registry) {
05453       if (p->registry->call == p)
05454          p->registry->call = dialog_unref(p->registry->call, "nulling out the registry's call dialog field in unlink_all");
05455       p->registry = registry_unref(p->registry, "delete p->registry");
05456    }
05457    
05458    if (p->mwi) {
05459       p->mwi->call = NULL;
05460    }
05461 
05462    if (dumphistory)
05463       sip_dump_history(p);
05464 
05465    if (p->options)
05466       ast_free(p->options);
05467 
05468    if (p->notify) {
05469       ast_variables_destroy(p->notify->headers);
05470       ast_free(p->notify->content);
05471       ast_free(p->notify);
05472    }
05473    if (p->rtp) {
05474       ast_rtp_instance_destroy(p->rtp);
05475    }
05476    if (p->vrtp) {
05477       ast_rtp_instance_destroy(p->vrtp);
05478    }
05479    if (p->trtp) {
05480       ast_rtp_instance_destroy(p->trtp);
05481    }
05482    if (p->udptl)
05483       ast_udptl_destroy(p->udptl);
05484    if (p->refer)
05485       ast_free(p->refer);
05486    if (p->route) {
05487       free_old_route(p->route);
05488       p->route = NULL;
05489    }
05490    deinit_req(&p->initreq);
05491 
05492    /* Destroy Session-Timers if allocated */
05493    if (p->stimer) {
05494       p->stimer->quit_flag = 1;
05495       if (p->stimer->st_active == TRUE && p->stimer->st_schedid > -1) {
05496          AST_SCHED_DEL_UNREF(sched, p->stimer->st_schedid,
05497                dialog_unref(p, "removing session timer ref"));
05498       }
05499       ast_free(p->stimer);
05500       p->stimer = NULL;
05501    }
05502 
05503    /* Clear history */
05504    if (p->history) {
05505       struct sip_history *hist;
05506       while ( (hist = AST_LIST_REMOVE_HEAD(p->history, list)) ) {
05507          ast_free(hist);
05508          p->history_entries--;
05509       }
05510       ast_free(p->history);
05511       p->history = NULL;
05512    }
05513 
05514    while ((req = AST_LIST_REMOVE_HEAD(&p->request_queue, next))) {
05515       ast_free(req);
05516    }
05517 
05518    if (p->chanvars) {
05519       ast_variables_destroy(p->chanvars);
05520       p->chanvars = NULL;
05521    }
05522 
05523    if (p->srtp) {
05524       sip_srtp_destroy(p->srtp);
05525       p->srtp = NULL;
05526    }
05527 
05528    if (p->vsrtp) {
05529       sip_srtp_destroy(p->vsrtp);
05530       p->vsrtp = NULL;
05531    }
05532 
05533    if (p->tsrtp) {
05534       sip_srtp_destroy(p->tsrtp);
05535       p->tsrtp = NULL;
05536    }
05537 
05538    if (p->directmediaha) {
05539       ast_free_ha(p->directmediaha);
05540       p->directmediaha = NULL;
05541    }
05542 
05543    ast_string_field_free_memory(p);
05544 
05545    ast_cc_config_params_destroy(p->cc_params);
05546 
05547    if (p->epa_entry) {
05548       ao2_ref(p->epa_entry, -1);
05549       p->epa_entry = NULL;
05550    }
05551 
05552    if (p->socket.tcptls_session) {
05553       ao2_ref(p->socket.tcptls_session, -1);
05554       p->socket.tcptls_session = NULL;
05555    }
05556 }
05557 
05558 /*! \brief  update_call_counter: Handle call_limit for SIP devices
05559  * Setting a call-limit will cause calls above the limit not to be accepted.
05560  *
05561  * Remember that for a type=friend, there's one limit for the user and
05562  * another for the peer, not a combined call limit.
05563  * This will cause unexpected behaviour in subscriptions, since a "friend"
05564  * is *two* devices in Asterisk, not one.
05565  *
05566  * Thought: For realtime, we should probably update storage with inuse counter...
05567  *
05568  * \return 0 if call is ok (no call limit, below threshold)
05569  * -1 on rejection of call
05570  *
05571  */
05572 static int update_call_counter(struct sip_pvt *fup, int event)
05573 {
05574    char name[256];
05575    int *inuse = NULL, *call_limit = NULL, *inringing = NULL;
05576    int outgoing = fup->outgoing_call;
05577    struct sip_peer *p = NULL;
05578 
05579    ast_debug(3, "Updating call counter for %s call\n", outgoing ? "outgoing" : "incoming");
05580 
05581 
05582    /* Test if we need to check call limits, in order to avoid
05583       realtime lookups if we do not need it */
05584    if (!ast_test_flag(&fup->flags[0], SIP_CALL_LIMIT) && !ast_test_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD))
05585       return 0;
05586 
05587    ast_copy_string(name, fup->username, sizeof(name));
05588 
05589    /* Check the list of devices */
05590    if (fup->relatedpeer) {
05591       p = ref_peer(fup->relatedpeer, "ref related peer for update_call_counter");
05592       inuse = &p->inUse;
05593       call_limit = &p->call_limit;
05594       inringing = &p->inRinging;
05595       ast_copy_string(name, fup->peername, sizeof(name));
05596    }
05597    if (!p) {
05598       ast_debug(2, "%s is not a local device, no call limit\n", name);
05599       return 0;
05600    }
05601 
05602    switch(event) {
05603    /* incoming and outgoing affects the inUse counter */
05604    case DEC_CALL_LIMIT:
05605       /* Decrement inuse count if applicable */
05606       if (inuse) {
05607          sip_pvt_lock(fup);
05608          ao2_lock(p);
05609          if (*inuse > 0) {
05610             if (ast_test_flag(&fup->flags[0], SIP_INC_COUNT)) {
05611                (*inuse)--;
05612                ast_clear_flag(&fup->flags[0], SIP_INC_COUNT);
05613             }
05614          } else {
05615             *inuse = 0;
05616          }
05617          ao2_unlock(p);
05618          sip_pvt_unlock(fup);
05619       }
05620 
05621       /* Decrement ringing count if applicable */
05622       if (inringing) {
05623          sip_pvt_lock(fup);
05624          ao2_lock(p);
05625          if (*inringing > 0) {
05626             if (ast_test_flag(&fup->flags[0], SIP_INC_RINGING)) {
05627                (*inringing)--;
05628                ast_clear_flag(&fup->flags[0], SIP_INC_RINGING);
05629             }
05630          } else {
05631             *inringing = 0;
05632          }
05633          ao2_unlock(p);
05634          sip_pvt_unlock(fup);
05635       }
05636 
05637       /* Decrement onhold count if applicable */
05638       sip_pvt_lock(fup);
05639       ao2_lock(p);
05640       if (ast_test_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD) && sip_cfg.notifyhold) {
05641          ast_clear_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD);
05642          ao2_unlock(p);
05643          sip_pvt_unlock(fup);
05644          sip_peer_hold(fup, FALSE);
05645       } else {
05646          ao2_unlock(p);
05647          sip_pvt_unlock(fup);
05648       }
05649       if (sipdebug)
05650          ast_debug(2, "Call %s %s '%s' removed from call limit %d\n", outgoing ? "to" : "from", "peer", name, *call_limit);
05651       break;
05652 
05653    case INC_CALL_RINGING:
05654    case INC_CALL_LIMIT:
05655       /* If call limit is active and we have reached the limit, reject the call */
05656       if (*call_limit > 0 ) {
05657          if (*inuse >= *call_limit) {
05658             ast_log(LOG_NOTICE, "Call %s %s '%s' rejected due to usage limit of %d\n", outgoing ? "to" : "from", "peer", name, *call_limit);
05659             unref_peer(p, "update_call_counter: unref peer p, call limit exceeded");
05660             return -1;
05661          }
05662       }
05663       if (inringing && (event == INC_CALL_RINGING)) {
05664          sip_pvt_lock(fup);
05665          ao2_lock(p);
05666          if (!ast_test_flag(&fup->flags[0], SIP_INC_RINGING)) {
05667             (*inringing)++;
05668             ast_set_flag(&fup->flags[0], SIP_INC_RINGING);
05669          }
05670          ao2_unlock(p);
05671          sip_pvt_unlock(fup);
05672       }
05673       if (inuse) {
05674          sip_pvt_lock(fup);
05675          ao2_lock(p);
05676          if (!ast_test_flag(&fup->flags[0], SIP_INC_COUNT)) {
05677             (*inuse)++;
05678             ast_set_flag(&fup->flags[0], SIP_INC_COUNT);
05679          }
05680          ao2_unlock(p);
05681          sip_pvt_unlock(fup);
05682       }
05683       if (sipdebug) {
05684          ast_debug(2, "Call %s %s '%s' is %d out of %d\n", outgoing ? "to" : "from", "peer", name, *inuse, *call_limit);
05685       }
05686       break;
05687 
05688    case DEC_CALL_RINGING:
05689       if (inringing) {
05690          sip_pvt_lock(fup);
05691          ao2_lock(p);
05692          if (ast_test_flag(&fup->flags[0], SIP_INC_RINGING)) {
05693             if (*inringing > 0) {
05694                (*inringing)--;
05695             }
05696             ast_clear_flag(&fup->flags[0], SIP_INC_RINGING);
05697          }
05698          ao2_unlock(p);
05699          sip_pvt_unlock(fup);
05700       }
05701       break;
05702 
05703    default:
05704       ast_log(LOG_ERROR, "update_call_counter(%s, %d) called with no event!\n", name, event);
05705    }
05706 
05707    if (p) {
05708       ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", p->name);
05709       unref_peer(p, "update_call_counter: unref_peer from call counter");
05710    }
05711    return 0;
05712 }
05713 
05714 
05715 static void sip_destroy_fn(void *p)
05716 {
05717    sip_destroy(p);
05718 }
05719 
05720 /*! \brief Destroy SIP call structure.
05721  * Make it return NULL so the caller can do things like
05722  * foo = sip_destroy(foo);
05723  * and reduce the chance of bugs due to dangling pointers.
05724  */
05725 struct sip_pvt *sip_destroy(struct sip_pvt *p)
05726 {
05727    ast_debug(3, "Destroying SIP dialog %s\n", p->callid);
05728    __sip_destroy(p, TRUE, TRUE);
05729    return NULL;
05730 }
05731 
05732 /*! \brief Convert SIP hangup causes to Asterisk hangup causes */
05733 int hangup_sip2cause(int cause)
05734 {
05735    /* Possible values taken from causes.h */
05736 
05737    switch(cause) {
05738       case 401:   /* Unauthorized */
05739          return AST_CAUSE_CALL_REJECTED;
05740       case 403:   /* Not found */
05741          return AST_CAUSE_CALL_REJECTED;
05742       case 404:   /* Not found */
05743          return AST_CAUSE_UNALLOCATED;
05744       case 405:   /* Method not allowed */
05745          return AST_CAUSE_INTERWORKING;
05746       case 407:   /* Proxy authentication required */
05747          return AST_CAUSE_CALL_REJECTED;
05748       case 408:   /* No reaction */
05749          return AST_CAUSE_NO_USER_RESPONSE;
05750       case 409:   /* Conflict */
05751          return AST_CAUSE_NORMAL_TEMPORARY_FAILURE;
05752       case 410:   /* Gone */
05753          return AST_CAUSE_NUMBER_CHANGED;
05754       case 411:   /* Length required */
05755          return AST_CAUSE_INTERWORKING;
05756       case 413:   /* Request entity too large */
05757          return AST_CAUSE_INTERWORKING;
05758       case 414:   /* Request URI too large */
05759          return AST_CAUSE_INTERWORKING;
05760       case 415:   /* Unsupported media type */
05761          return AST_CAUSE_INTERWORKING;
05762       case 420:   /* Bad extension */
05763          return AST_CAUSE_NO_ROUTE_DESTINATION;
05764       case 480:   /* No answer */
05765          return AST_CAUSE_NO_ANSWER;
05766       case 481:   /* No answer */
05767          return AST_CAUSE_INTERWORKING;
05768       case 482:   /* Loop detected */
05769          return AST_CAUSE_INTERWORKING;
05770       case 483:   /* Too many hops */
05771          return AST_CAUSE_NO_ANSWER;
05772       case 484:   /* Address incomplete */
05773          return AST_CAUSE_INVALID_NUMBER_FORMAT;
05774       case 485:   /* Ambiguous */
05775          return AST_CAUSE_UNALLOCATED;
05776       case 486:   /* Busy everywhere */
05777          return AST_CAUSE_BUSY;
05778       case 487:   /* Request terminated */
05779          return AST_CAUSE_INTERWORKING;
05780       case 488:   /* No codecs approved */
05781          return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
05782       case 491:   /* Request pending */
05783          return AST_CAUSE_INTERWORKING;
05784       case 493:   /* Undecipherable */
05785          return AST_CAUSE_INTERWORKING;
05786       case 500:   /* Server internal failure */
05787          return AST_CAUSE_FAILURE;
05788       case 501:   /* Call rejected */
05789          return AST_CAUSE_FACILITY_REJECTED;
05790       case 502:
05791          return AST_CAUSE_DESTINATION_OUT_OF_ORDER;
05792       case 503:   /* Service unavailable */
05793          return AST_CAUSE_CONGESTION;
05794       case 504:   /* Gateway timeout */
05795          return AST_CAUSE_RECOVERY_ON_TIMER_EXPIRE;
05796       case 505:   /* SIP version not supported */
05797          return AST_CAUSE_INTERWORKING;
05798       case 600:   /* Busy everywhere */
05799          return AST_CAUSE_USER_BUSY;
05800       case 603:   /* Decline */
05801          return AST_CAUSE_CALL_REJECTED;
05802       case 604:   /* Does not exist anywhere */
05803          return AST_CAUSE_UNALLOCATED;
05804       case 606:   /* Not acceptable */
05805          return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
05806       default:
05807          if (cause < 500 && cause >= 400) {
05808             /* 4xx class error that is unknown - someting wrong with our request */
05809             return AST_CAUSE_INTERWORKING;
05810          } else if (cause < 600 && cause >= 500) {
05811             /* 5xx class error - problem in the remote end */
05812             return AST_CAUSE_CONGESTION;
05813          } else if (cause < 700 && cause >= 600) {
05814             /* 6xx - global errors in the 4xx class */
05815             return AST_CAUSE_INTERWORKING;
05816          }
05817          return AST_CAUSE_NORMAL;
05818    }
05819    /* Never reached */
05820    return 0;
05821 }
05822 
05823 /*! \brief Convert Asterisk hangup causes to SIP codes
05824 \verbatim
05825  Possible values from causes.h
05826         AST_CAUSE_NOTDEFINED    AST_CAUSE_NORMAL        AST_CAUSE_BUSY
05827         AST_CAUSE_FAILURE       AST_CAUSE_CONGESTION    AST_CAUSE_UNALLOCATED
05828 
05829    In addition to these, a lot of PRI codes is defined in causes.h
05830    ...should we take care of them too ?
05831 
05832    Quote RFC 3398
05833 
05834    ISUP Cause value                        SIP response
05835    ----------------                        ------------
05836    1  unallocated number                   404 Not Found
05837    2  no route to network                  404 Not found
05838    3  no route to destination              404 Not found
05839    16 normal call clearing                 --- (*)
05840    17 user busy                            486 Busy here
05841    18 no user responding                   408 Request Timeout
05842    19 no answer from the user              480 Temporarily unavailable
05843    20 subscriber absent                    480 Temporarily unavailable
05844    21 call rejected                        403 Forbidden (+)
05845    22 number changed (w/o diagnostic)      410 Gone
05846    22 number changed (w/ diagnostic)       301 Moved Permanently
05847    23 redirection to new destination       410 Gone
05848    26 non-selected user clearing           404 Not Found (=)
05849    27 destination out of order             502 Bad Gateway
05850    28 address incomplete                   484 Address incomplete
05851    29 facility rejected                    501 Not implemented
05852    31 normal unspecified                   480 Temporarily unavailable
05853 \endverbatim
05854 */
05855 const char *hangup_cause2sip(int cause)
05856 {
05857    switch (cause) {
05858       case AST_CAUSE_UNALLOCATED:      /* 1 */
05859       case AST_CAUSE_NO_ROUTE_DESTINATION:   /* 3 IAX2: Can't find extension in context */
05860       case AST_CAUSE_NO_ROUTE_TRANSIT_NET:   /* 2 */
05861          return "404 Not Found";
05862       case AST_CAUSE_CONGESTION:    /* 34 */
05863       case AST_CAUSE_SWITCH_CONGESTION:   /* 42 */
05864          return "503 Service Unavailable";
05865       case AST_CAUSE_NO_USER_RESPONSE: /* 18 */
05866          return "408 Request Timeout";
05867       case AST_CAUSE_NO_ANSWER:     /* 19 */
05868       case AST_CAUSE_UNREGISTERED:        /* 20 */
05869          return "480 Temporarily unavailable";
05870       case AST_CAUSE_CALL_REJECTED:    /* 21 */
05871          return "403 Forbidden";
05872       case AST_CAUSE_NUMBER_CHANGED:      /* 22 */
05873          return "410 Gone";
05874       case AST_CAUSE_NORMAL_UNSPECIFIED:  /* 31 */
05875          return "480 Temporarily unavailable";
05876       case AST_CAUSE_INVALID_NUMBER_FORMAT:
05877          return "484 Address incomplete";
05878       case AST_CAUSE_USER_BUSY:
05879          return "486 Busy here";
05880       case AST_CAUSE_FAILURE:
05881          return "500 Server internal failure";
05882       case AST_CAUSE_FACILITY_REJECTED:   /* 29 */
05883          return "501 Not Implemented";
05884       case AST_CAUSE_CHAN_NOT_IMPLEMENTED:
05885          return "503 Service Unavailable";
05886       /* Used in chan_iax2 */
05887       case AST_CAUSE_DESTINATION_OUT_OF_ORDER:
05888          return "502 Bad Gateway";
05889       case AST_CAUSE_BEARERCAPABILITY_NOTAVAIL: /* Can't find codec to connect to host */
05890          return "488 Not Acceptable Here";
05891          
05892       case AST_CAUSE_NOTDEFINED:
05893       default:
05894          ast_debug(1, "AST hangup cause %d (no match found in SIP)\n", cause);
05895          return NULL;
05896    }
05897 
05898    /* Never reached */
05899    return 0;
05900 }
05901 
05902 /*! \brief  sip_hangup: Hangup SIP call
05903  * Part of PBX interface, called from ast_hangup */
05904 static int sip_hangup(struct ast_channel *ast)
05905 {
05906    struct sip_pvt *p = ast->tech_pvt;
05907    int needcancel = FALSE;
05908    int needdestroy = 0;
05909    struct ast_channel *oldowner = ast;
05910 
05911    if (!p) {
05912       ast_debug(1, "Asked to hangup channel that was not connected\n");
05913       return 0;
05914    }
05915    if (ast_test_flag(ast, AST_FLAG_ANSWERED_ELSEWHERE) || ast->hangupcause == AST_CAUSE_ANSWERED_ELSEWHERE) {
05916       ast_debug(1, "This call was answered elsewhere");
05917       if (ast->hangupcause == AST_CAUSE_ANSWERED_ELSEWHERE) {
05918          ast_debug(1, "####### It's the cause code, buddy. The cause code!!!\n");
05919       }
05920       append_history(p, "Cancel", "Call answered elsewhere");
05921       p->answered_elsewhere = TRUE;
05922    }
05923 
05924    /* Store hangupcause locally in PVT so we still have it before disconnect */
05925    if (p->owner)
05926       p->hangupcause = p->owner->hangupcause;
05927 
05928    if (ast_test_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER)) {
05929       if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
05930          if (sipdebug)
05931             ast_debug(1, "update_call_counter(%s) - decrement call limit counter on hangup\n", p->username);
05932          update_call_counter(p, DEC_CALL_LIMIT);
05933       }
05934       ast_debug(4, "SIP Transfer: Not hanging up right now... Rescheduling hangup for %s.\n", p->callid);
05935       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
05936       ast_clear_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER); /* Really hang up next time */
05937       p->needdestroy = 0;
05938       p->owner->tech_pvt = dialog_unref(p->owner->tech_pvt, "unref p->owner->tech_pvt");
05939       sip_pvt_lock(p);
05940       p->owner = NULL;  /* Owner will be gone after we return, so take it away */
05941       sip_pvt_unlock(p);
05942       ast_module_unref(ast_module_info->self);
05943       return 0;
05944    }
05945 
05946    if (ast_test_flag(ast, AST_FLAG_ZOMBIE)) {
05947       if (p->refer)
05948          ast_debug(1, "SIP Transfer: Hanging up Zombie channel %s after transfer ... Call-ID: %s\n", ast->name, p->callid);
05949       else
05950          ast_debug(1, "Hanging up zombie call. Be scared.\n");
05951    } else
05952       ast_debug(1, "Hangup call %s, SIP callid %s\n", ast->name, p->callid);
05953 
05954    sip_pvt_lock(p);
05955    if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
05956       if (sipdebug)
05957          ast_debug(1, "update_call_counter(%s) - decrement call limit counter on hangup\n", p->username);
05958       update_call_counter(p, DEC_CALL_LIMIT);
05959    }
05960 
05961    /* Determine how to disconnect */
05962    if (p->owner != ast) {
05963       ast_log(LOG_WARNING, "Huh?  We aren't the owner? Can't hangup call.\n");
05964       sip_pvt_unlock(p);
05965       return 0;
05966    }
05967    /* If the call is not UP, we need to send CANCEL instead of BYE */
05968    /* In case of re-invites, the call might be UP even though we have an incomplete invite transaction */
05969    if (p->invitestate < INV_COMPLETED && p->owner->_state != AST_STATE_UP) {
05970       needcancel = TRUE;
05971       ast_debug(4, "Hanging up channel in state %s (not UP)\n", ast_state2str(ast->_state));
05972    }
05973 
05974    stop_media_flows(p); /* Immediately stop RTP, VRTP and UDPTL as applicable */
05975 
05976    append_history(p, needcancel ? "Cancel" : "Hangup", "Cause %s", p->owner ? ast_cause2str(p->hangupcause) : "Unknown");
05977 
05978    /* Disconnect */
05979    disable_dsp_detect(p);
05980 
05981    p->owner = NULL;
05982    ast->tech_pvt = dialog_unref(ast->tech_pvt, "unref ast->tech_pvt");
05983 
05984    ast_module_unref(ast_module_info->self);
05985    /* Do not destroy this pvt until we have timeout or
05986       get an answer to the BYE or INVITE/CANCEL
05987       If we get no answer during retransmit period, drop the call anyway.
05988       (Sorry, mother-in-law, you can't deny a hangup by sending
05989       603 declined to BYE...)
05990    */
05991    if (p->alreadygone)
05992       needdestroy = 1;  /* Set destroy flag at end of this function */
05993    else if (p->invitestate != INV_CALLING)
05994       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
05995 
05996    /* Start the process if it's not already started */
05997    if (!p->alreadygone && p->initreq.data && !ast_strlen_zero(p->initreq.data->str)) {
05998       if (needcancel) { /* Outgoing call, not up */
05999          if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06000             /* if we can't send right now, mark it pending */
06001             if (p->invitestate == INV_CALLING) {
06002                /* We can't send anything in CALLING state */
06003                ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
06004                /* 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. */
06005                sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
06006                append_history(p, "DELAY", "Not sending cancel, waiting for timeout");
06007             } else {
06008                struct sip_pkt *cur;
06009 
06010                for (cur = p->packets; cur; cur = cur->next) {
06011                   __sip_semi_ack(p, cur->seqno, cur->is_resp, cur->method ? cur->method : find_sip_method(cur->data->str));
06012                }
06013                p->invitestate = INV_CANCELLED;
06014                /* Send a new request: CANCEL */
06015                transmit_request(p, SIP_CANCEL, p->lastinvite, XMIT_RELIABLE, FALSE);
06016                /* Actually don't destroy us yet, wait for the 487 on our original
06017                   INVITE, but do set an autodestruct just in case we never get it. */
06018                needdestroy = 0;
06019                sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
06020             }
06021          } else { /* Incoming call, not up */
06022             const char *res;
06023             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"));
06024             if (p->hangupcause && (res = hangup_cause2sip(p->hangupcause)))
06025                transmit_response_reliable(p, res, &p->initreq);
06026             else
06027                transmit_response_reliable(p, "603 Declined", &p->initreq);
06028             p->invitestate = INV_TERMINATED;
06029          }
06030       } else { /* Call is in UP state, send BYE */
06031          if (p->stimer->st_active == TRUE) {
06032             stop_session_timer(p);
06033          }
06034 
06035          if (!p->pendinginvite) {
06036             struct ast_channel *bridge = ast_bridged_channel(oldowner);
06037             char quality_buf[AST_MAX_USER_FIELD], *quality;
06038 
06039             /* We need to get the lock on bridge because ast_rtp_instance_set_stats_vars will attempt
06040              * to lock the bridge. This may get hairy...
06041              */
06042             while (bridge && ast_channel_trylock(bridge)) {
06043                sip_pvt_unlock(p);
06044                do {
06045                   CHANNEL_DEADLOCK_AVOIDANCE(oldowner);
06046                } while (sip_pvt_trylock(p));
06047                bridge = ast_bridged_channel(oldowner);
06048             }
06049 
06050             if (p->rtp) {
06051                ast_rtp_instance_set_stats_vars(oldowner, p->rtp);
06052             }
06053 
06054             if (bridge) {
06055                struct sip_pvt *q = bridge->tech_pvt;
06056 
06057                if (IS_SIP_TECH(bridge->tech) && q && q->rtp) {
06058                   ast_rtp_instance_set_stats_vars(bridge, q->rtp);
06059                }
06060                ast_channel_unlock(bridge);
06061             }
06062 
06063             if (p->do_history || oldowner) {
06064                if (p->rtp && (quality = ast_rtp_instance_get_quality(p->rtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY, quality_buf, sizeof(quality_buf)))) {
06065                   if (p->do_history) {
06066                      append_history(p, "RTCPaudio", "Quality:%s", quality);
06067                   }
06068                   if (oldowner) {
06069                      pbx_builtin_setvar_helper(oldowner, "RTPAUDIOQOS", quality);
06070                   }
06071                }
06072                if (p->vrtp && (quality = ast_rtp_instance_get_quality(p->vrtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY, quality_buf, sizeof(quality_buf)))) {
06073                   if (p->do_history) {
06074                      append_history(p, "RTCPvideo", "Quality:%s", quality);
06075                   }
06076                   if (oldowner) {
06077                      pbx_builtin_setvar_helper(oldowner, "RTPVIDEOQOS", quality);
06078                   }
06079                }
06080                if (p->trtp && (quality = ast_rtp_instance_get_quality(p->trtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY, quality_buf, sizeof(quality_buf)))) {
06081                   if (p->do_history) {
06082                      append_history(p, "RTCPtext", "Quality:%s", quality);
06083                   }
06084                   if (oldowner) {
06085                      pbx_builtin_setvar_helper(oldowner, "RTPTEXTQOS", quality);
06086                   }
06087                }
06088             }
06089 
06090             /* Send a hangup */
06091             if (oldowner->_state == AST_STATE_UP) {
06092                transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
06093             }
06094 
06095          } else {
06096             /* Note we will need a BYE when this all settles out
06097                but we can't send one while we have "INVITE" outstanding. */
06098             ast_set_flag(&p->flags[0], SIP_PENDINGBYE);  
06099             ast_clear_flag(&p->flags[0], SIP_NEEDREINVITE); 
06100             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"));
06101             if (sip_cancel_destroy(p))
06102                ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
06103          }
06104       }
06105    }
06106    if (needdestroy) {
06107       pvt_set_needdestroy(p, "hangup");
06108    }
06109    sip_pvt_unlock(p);
06110    return 0;
06111 }
06112 
06113 /*! \brief Try setting codec suggested by the SIP_CODEC channel variable */
06114 static void try_suggested_sip_codec(struct sip_pvt *p)
06115 {
06116    format_t fmt;
06117    const char *codec;
06118 
06119    if (p->outgoing_call) {
06120       codec = pbx_builtin_getvar_helper(p->owner, "SIP_CODEC_OUTBOUND");
06121    } else if (!(codec = pbx_builtin_getvar_helper(p->owner, "SIP_CODEC_INBOUND"))) {
06122       codec = pbx_builtin_getvar_helper(p->owner, "SIP_CODEC");
06123    }
06124 
06125    if (!codec) 
06126       return;
06127 
06128    fmt = ast_getformatbyname(codec);
06129    if (fmt) {
06130       ast_log(LOG_NOTICE, "Changing codec to '%s' for this call because of ${SIP_CODEC} variable\n", codec);
06131       if (p->jointcapability & fmt) {
06132          p->jointcapability &= fmt;
06133          p->capability &= fmt;
06134       } else
06135          ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because it is not shared by both ends.\n");
06136    } else
06137       ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because of unrecognized/not configured codec (check allow/disallow in sip.conf): %s\n", codec);
06138    return;  
06139 }
06140 
06141 /*! \brief  sip_answer: Answer SIP call , send 200 OK on Invite
06142  * Part of PBX interface */
06143 static int sip_answer(struct ast_channel *ast)
06144 {
06145    int res = 0;
06146    struct sip_pvt *p = ast->tech_pvt;
06147 
06148    sip_pvt_lock(p);
06149    if (ast->_state != AST_STATE_UP) {
06150       try_suggested_sip_codec(p);   
06151 
06152       ast_setstate(ast, AST_STATE_UP);
06153       ast_debug(1, "SIP answering channel: %s\n", ast->name);
06154       ast_rtp_instance_update_source(p->rtp);
06155       res = transmit_response_with_sdp(p, "200 OK", &p->initreq, XMIT_CRITICAL, FALSE, TRUE);
06156       ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
06157    }
06158    sip_pvt_unlock(p);
06159    return res;
06160 }
06161 
06162 /*! \brief Send frame to media channel (rtp) */
06163 static int sip_write(struct ast_channel *ast, struct ast_frame *frame)
06164 {
06165    struct sip_pvt *p = ast->tech_pvt;
06166    int res = 0;
06167 
06168    switch (frame->frametype) {
06169    case AST_FRAME_VOICE:
06170       if (!(frame->subclass.codec & ast->nativeformats)) {
06171          char s1[512], s2[512], s3[512];
06172          ast_log(LOG_WARNING, "Asked to transmit frame type %s, while native formats is %s read/write = %s/%s\n",
06173             ast_getformatname(frame->subclass.codec),
06174             ast_getformatname_multiple(s1, sizeof(s1), ast->nativeformats & AST_FORMAT_AUDIO_MASK),
06175             ast_getformatname_multiple(s2, sizeof(s2), ast->readformat),
06176             ast_getformatname_multiple(s3, sizeof(s3), ast->writeformat));
06177          return 0;
06178       }
06179       if (p) {
06180          sip_pvt_lock(p);
06181          if (p->rtp) {
06182             /* If channel is not up, activate early media session */
06183             if ((ast->_state != AST_STATE_UP) &&
06184                 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
06185                 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06186                ast_rtp_instance_update_source(p->rtp);
06187                if (!global_prematuremediafilter) {
06188                   p->invitestate = INV_EARLY_MEDIA;
06189                   transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
06190                   ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
06191                }
06192             } else if (p->t38.state == T38_ENABLED) {
06193                /* drop frame, can't sent VOICE frames while in T.38 mode */
06194             } else {
06195                p->lastrtptx = time(NULL);
06196                res = ast_rtp_instance_write(p->rtp, frame);
06197             }
06198          }
06199          sip_pvt_unlock(p);
06200       }
06201       break;
06202    case AST_FRAME_VIDEO:
06203       if (p) {
06204          sip_pvt_lock(p);
06205          if (p->vrtp) {
06206             /* Activate video early media */
06207             if ((ast->_state != AST_STATE_UP) &&
06208                 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
06209                 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06210                p->invitestate = INV_EARLY_MEDIA;
06211                transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
06212                ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
06213             }
06214             p->lastrtptx = time(NULL);
06215             res = ast_rtp_instance_write(p->vrtp, frame);
06216          }
06217          sip_pvt_unlock(p);
06218       }
06219       break;
06220    case AST_FRAME_TEXT:
06221       if (p) {
06222          sip_pvt_lock(p);
06223          if (p->red) {
06224             ast_rtp_red_buffer(p->trtp, frame);
06225          } else {
06226             if (p->trtp) {
06227                /* Activate text early media */
06228                if ((ast->_state != AST_STATE_UP) &&
06229                    !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
06230                    !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06231                   p->invitestate = INV_EARLY_MEDIA;
06232                   transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
06233                   ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
06234                }
06235                p->lastrtptx = time(NULL);
06236                res = ast_rtp_instance_write(p->trtp, frame);
06237             }
06238          }
06239          sip_pvt_unlock(p);
06240       }
06241       break;
06242    case AST_FRAME_IMAGE:
06243       return 0;
06244       break;
06245    case AST_FRAME_MODEM:
06246       if (p) {
06247          sip_pvt_lock(p);
06248          /* UDPTL requires two-way communication, so early media is not needed here.
06249             we simply forget the frames if we get modem frames before the bridge is up.
06250             Fax will re-transmit.
06251          */
06252          if ((ast->_state == AST_STATE_UP) &&
06253              p->udptl &&
06254              (p->t38.state == T38_ENABLED)) {
06255             res = ast_udptl_write(p->udptl, frame);
06256          }
06257          sip_pvt_unlock(p);
06258       }
06259       break;
06260    default:
06261       ast_log(LOG_WARNING, "Can't send %d type frames with SIP write\n", frame->frametype);
06262       return 0;
06263    }
06264 
06265    return res;
06266 }
06267 
06268 /*! \brief  sip_fixup: Fix up a channel:  If a channel is consumed, this is called.
06269         Basically update any ->owner links */
06270 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
06271 {
06272    int ret = -1;
06273    struct sip_pvt *p;
06274 
06275    if (newchan && ast_test_flag(newchan, AST_FLAG_ZOMBIE))
06276       ast_debug(1, "New channel is zombie\n");
06277    if (oldchan && ast_test_flag(oldchan, AST_FLAG_ZOMBIE))
06278       ast_debug(1, "Old channel is zombie\n");
06279 
06280    if (!newchan || !newchan->tech_pvt) {
06281       if (!newchan)
06282          ast_log(LOG_WARNING, "No new channel! Fixup of %s failed.\n", oldchan->name);
06283       else
06284          ast_log(LOG_WARNING, "No SIP tech_pvt! Fixup of %s failed.\n", oldchan->name);
06285       return -1;
06286    }
06287    p = newchan->tech_pvt;
06288 
06289    sip_pvt_lock(p);
06290    append_history(p, "Masq", "Old channel: %s\n", oldchan->name);
06291    append_history(p, "Masq (cont)", "...new owner: %s\n", newchan->name);
06292    if (p->owner != oldchan)
06293       ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, p->owner);
06294    else {
06295       p->owner = newchan;
06296       /* Re-invite RTP back to Asterisk. Needed if channel is masqueraded out of a native
06297          RTP bridge (i.e., RTP not going through Asterisk): RTP bridge code might not be
06298          able to do this if the masquerade happens before the bridge breaks (e.g., AMI
06299          redirect of both channels). Note that a channel can not be masqueraded *into*
06300          a native bridge. So there is no danger that this breaks a native bridge that
06301          should stay up. */
06302       sip_set_rtp_peer(newchan, NULL, NULL, 0, 0, 0);
06303       ret = 0;
06304    }
06305    ast_debug(3, "SIP Fixup: New owner for dialogue %s: %s (Old parent: %s)\n", p->callid, p->owner->name, oldchan->name);
06306 
06307    sip_pvt_unlock(p);
06308    return ret;
06309 }
06310 
06311 static int sip_senddigit_begin(struct ast_channel *ast, char digit)
06312 {
06313    struct sip_pvt *p = ast->tech_pvt;
06314    int res = 0;
06315 
06316    sip_pvt_lock(p);
06317    switch (ast_test_flag(&p->flags[0], SIP_DTMF)) {
06318    case SIP_DTMF_INBAND:
06319       if (p->rtp && ast_rtp_instance_dtmf_mode_get(p->rtp) == AST_RTP_DTMF_MODE_INBAND) {
06320          ast_rtp_instance_dtmf_begin(p->rtp, digit);
06321       } else {
06322          res = -1; /* Tell Asterisk to generate inband indications */
06323       }
06324       break;
06325    case SIP_DTMF_RFC2833:
06326       if (p->rtp)
06327          ast_rtp_instance_dtmf_begin(p->rtp, digit);
06328       break;
06329    default:
06330       break;
06331    }
06332    sip_pvt_unlock(p);
06333 
06334    return res;
06335 }
06336 
06337 /*! \brief Send DTMF character on SIP channel
06338    within one call, we're able to transmit in many methods simultaneously */
06339 static int sip_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration)
06340 {
06341    struct sip_pvt *p = ast->tech_pvt;
06342    int res = 0;
06343 
06344    sip_pvt_lock(p);
06345    switch (ast_test_flag(&p->flags[0], SIP_DTMF)) {
06346    case SIP_DTMF_INFO:
06347    case SIP_DTMF_SHORTINFO:
06348       transmit_info_with_digit(p, digit, duration);
06349       break;
06350    case SIP_DTMF_RFC2833:
06351       if (p->rtp)
06352          ast_rtp_instance_dtmf_end_with_duration(p->rtp, digit, duration);
06353       break;
06354    case SIP_DTMF_INBAND:
06355       if (p->rtp && ast_rtp_instance_dtmf_mode_get(p->rtp) == AST_RTP_DTMF_MODE_INBAND) {
06356          ast_rtp_instance_dtmf_end(p->rtp, digit);
06357       } else {
06358          res = -1; /* Tell Asterisk to stop inband indications */
06359       }
06360       break;
06361    }
06362    sip_pvt_unlock(p);
06363 
06364    return res;
06365 }
06366 
06367 /*! \brief Transfer SIP call */
06368 static int sip_transfer(struct ast_channel *ast, const char *dest)
06369 {
06370    struct sip_pvt *p = ast->tech_pvt;
06371    int res;
06372 
06373    if (dest == NULL) /* functions below do not take a NULL */
06374       dest = "";
06375    sip_pvt_lock(p);
06376    if (ast->_state == AST_STATE_RING)
06377       res = sip_sipredirect(p, dest);
06378    else
06379       res = transmit_refer(p, dest);
06380    sip_pvt_unlock(p);
06381    return res;
06382 }
06383 
06384 /*! \brief Helper function which updates T.38 capability information and triggers a reinvite */
06385 static int interpret_t38_parameters(struct sip_pvt *p, const struct ast_control_t38_parameters *parameters)
06386 {
06387    int res = 0;
06388 
06389    if (!ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) || !p->udptl) {
06390       return -1;
06391    }
06392    switch (parameters->request_response) {
06393    case AST_T38_NEGOTIATED:
06394    case AST_T38_REQUEST_NEGOTIATE:         /* Request T38 */
06395       /* Negotiation can not take place without a valid max_ifp value. */
06396       if (!parameters->max_ifp) {
06397          change_t38_state(p, T38_DISABLED);
06398          if (p->t38.state == T38_PEER_REINVITE) {
06399             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"));
06400             transmit_response_reliable(p, "488 Not acceptable here", &p->initreq);
06401          }
06402          break;
06403       } else if (p->t38.state == T38_PEER_REINVITE) {
06404          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"));
06405          p->t38.our_parms = *parameters;
06406          /* modify our parameters to conform to the peer's parameters,
06407           * based on the rules in the ITU T.38 recommendation
06408           */
06409          if (!p->t38.their_parms.fill_bit_removal) {
06410             p->t38.our_parms.fill_bit_removal = FALSE;
06411          }
06412          if (!p->t38.their_parms.transcoding_mmr) {
06413             p->t38.our_parms.transcoding_mmr = FALSE;
06414          }
06415          if (!p->t38.their_parms.transcoding_jbig) {
06416             p->t38.our_parms.transcoding_jbig = FALSE;
06417          }
06418          p->t38.our_parms.version = MIN(p->t38.our_parms.version, p->t38.their_parms.version);
06419          p->t38.our_parms.rate_management = p->t38.their_parms.rate_management;
06420          ast_udptl_set_local_max_ifp(p->udptl, p->t38.our_parms.max_ifp);
06421          change_t38_state(p, T38_ENABLED);
06422          transmit_response_with_t38_sdp(p, "200 OK", &p->initreq, XMIT_CRITICAL);
06423       } else if (p->t38.state != T38_ENABLED) {
06424          p->t38.our_parms = *parameters;
06425          ast_udptl_set_local_max_ifp(p->udptl, p->t38.our_parms.max_ifp);
06426          change_t38_state(p, T38_LOCAL_REINVITE);
06427          if (!p->pendinginvite) {
06428             transmit_reinvite_with_sdp(p, TRUE, FALSE);
06429          } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
06430             ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
06431          }
06432       }
06433       break;
06434    case AST_T38_TERMINATED:
06435    case AST_T38_REFUSED:
06436    case AST_T38_REQUEST_TERMINATE:         /* Shutdown T38 */
06437       if (p->t38.state == T38_PEER_REINVITE) {
06438          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"));
06439          change_t38_state(p, T38_DISABLED);
06440          transmit_response_reliable(p, "488 Not acceptable here", &p->initreq);
06441       } else if (p->t38.state == T38_ENABLED)
06442          transmit_reinvite_with_sdp(p, FALSE, FALSE);
06443       break;
06444    case AST_T38_REQUEST_PARMS: {    /* Application wants remote's parameters re-sent */
06445       struct ast_control_t38_parameters parameters = p->t38.their_parms;
06446 
06447       if (p->t38.state == T38_PEER_REINVITE) {
06448          AST_SCHED_DEL(sched, p->t38id);
06449          parameters.max_ifp = ast_udptl_get_far_max_ifp(p->udptl);
06450          parameters.request_response = AST_T38_REQUEST_NEGOTIATE;
06451          ast_queue_control_data(p->owner, AST_CONTROL_T38_PARAMETERS, &parameters, sizeof(parameters));
06452          /* we need to return a positive value here, so that applications that
06453           * send this request can determine conclusively whether it was accepted or not...
06454           * older versions of chan_sip would just silently accept it and return zero.
06455           */
06456          res = AST_T38_REQUEST_PARMS;
06457       }
06458       break;
06459    }
06460    default:
06461       res = -1;
06462       break;
06463    }
06464 
06465    return res;
06466 }
06467 
06468 /*! \brief Play indication to user
06469  * With SIP a lot of indications is sent as messages, letting the device play
06470    the indication - busy signal, congestion etc
06471    \return -1 to force ast_indicate to send indication in audio, 0 if SIP can handle the indication by sending a message
06472 */
06473 static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen)
06474 {
06475    struct sip_pvt *p = ast->tech_pvt;
06476    int res = 0;
06477 
06478    sip_pvt_lock(p);
06479    switch(condition) {
06480    case AST_CONTROL_RINGING:
06481       if (ast->_state == AST_STATE_RING) {
06482          p->invitestate = INV_EARLY_MEDIA;
06483          if (!ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) ||
06484              (ast_test_flag(&p->flags[0], SIP_PROG_INBAND) == SIP_PROG_INBAND_NEVER)) {            
06485             /* Send 180 ringing if out-of-band seems reasonable */
06486             transmit_provisional_response(p, "180 Ringing", &p->initreq, 0);
06487             ast_set_flag(&p->flags[0], SIP_RINGING);
06488             if (ast_test_flag(&p->flags[0], SIP_PROG_INBAND) != SIP_PROG_INBAND_YES)
06489                break;
06490          } else {
06491             /* Well, if it's not reasonable, just send in-band */
06492          }
06493       }
06494       res = -1;
06495       break;
06496    case AST_CONTROL_BUSY:
06497       if (ast->_state != AST_STATE_UP) {
06498          transmit_response_reliable(p, "486 Busy Here", &p->initreq);
06499          p->invitestate = INV_COMPLETED;
06500          sip_alreadygone(p);
06501          ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
06502          break;
06503       }
06504       res = -1;
06505       break;
06506    case AST_CONTROL_CONGESTION:
06507       if (ast->_state != AST_STATE_UP) {
06508          transmit_response_reliable(p, "503 Service Unavailable", &p->initreq);
06509          p->invitestate = INV_COMPLETED;
06510          sip_alreadygone(p);
06511          ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
06512          break;
06513       }
06514       res = -1;
06515       break;
06516    case AST_CONTROL_PROCEEDING:
06517       if ((ast->_state != AST_STATE_UP) &&
06518           !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
06519           !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06520          transmit_response(p, "100 Trying", &p->initreq);
06521          p->invitestate = INV_PROCEEDING;
06522          break;
06523       }
06524       res = -1;
06525       break;
06526    case AST_CONTROL_PROGRESS:
06527       if ((ast->_state != AST_STATE_UP) &&
06528           !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
06529           !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06530          p->invitestate = INV_EARLY_MEDIA;
06531          transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
06532          ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
06533          break;
06534       }
06535       res = -1;
06536       break;
06537    case AST_CONTROL_HOLD:
06538       ast_rtp_instance_update_source(p->rtp);
06539       ast_moh_start(ast, data, p->mohinterpret);
06540       break;
06541    case AST_CONTROL_UNHOLD:
06542       ast_rtp_instance_update_source(p->rtp);
06543       ast_moh_stop(ast);
06544       break;
06545    case AST_CONTROL_VIDUPDATE:   /* Request a video frame update */
06546       if (p->vrtp && !p->novideo) {
06547          transmit_info_with_vidupdate(p);
06548          /* ast_rtcp_send_h261fur(p->vrtp); */
06549       } else
06550          res = -1;
06551       break;
06552    case AST_CONTROL_T38_PARAMETERS:
06553       if (datalen != sizeof(struct ast_control_t38_parameters)) {
06554          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);
06555          res = -1;
06556       } else {
06557          const struct ast_control_t38_parameters *parameters = data;
06558          res = interpret_t38_parameters(p, parameters);
06559       }
06560       break;
06561    case AST_CONTROL_SRCUPDATE:
06562       ast_rtp_instance_update_source(p->rtp);
06563       break;
06564    case AST_CONTROL_SRCCHANGE:
06565       ast_rtp_instance_change_source(p->rtp);
06566       break;
06567    case AST_CONTROL_CONNECTED_LINE:
06568       update_connectedline(p, data, datalen);
06569       break;
06570    case AST_CONTROL_REDIRECTING:
06571       update_redirecting(p, data, datalen);
06572       break;
06573    case AST_CONTROL_AOC:
06574       {
06575          struct ast_aoc_decoded *decoded = ast_aoc_decode((struct ast_aoc_encoded *) data, datalen, ast);
06576          if (!decoded) {
06577             ast_log(LOG_ERROR, "Error decoding indicated AOC data\n");
06578             res = -1;
06579             break;
06580          }
06581          switch (ast_aoc_get_msg_type(decoded)) {
06582          case AST_AOC_REQUEST:
06583             if (ast_aoc_get_termination_request(decoded)) {
06584                /* TODO, once there is a way to get AOC-E on hangup, attempt that here
06585                 * before hanging up the channel.*/
06586 
06587                /* The other side has already initiated the hangup. This frame
06588                 * just says they are waiting to get AOC-E before completely tearing
06589                 * the call down.  Since SIP does not support this at the moment go
06590                 * ahead and terminate the call here to avoid an unnecessary timeout. */
06591                ast_debug(1, "AOC-E termination request received on %s. This is not yet supported on sip. Continue with hangup \n", p->owner->name);
06592                ast_softhangup_nolock(p->owner, AST_SOFTHANGUP_DEV);
06593             }
06594             break;
06595          case AST_AOC_D:
06596          case AST_AOC_E:
06597             if (ast_test_flag(&p->flags[2], SIP_PAGE3_SNOM_AOC)) {
06598                transmit_info_with_aoc(p, decoded);
06599             }
06600             break;
06601          case AST_AOC_S: /* S not supported yet */
06602          default:
06603             break;
06604          }
06605          ast_aoc_destroy_decoded(decoded);
06606       }
06607       break;
06608    case -1:
06609       res = -1;
06610       break;
06611    default:
06612       ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", condition);
06613       res = -1;
06614       break;
06615    }
06616    sip_pvt_unlock(p);
06617    return res;
06618 }
06619 
06620 /*! \brief Initiate a call in the SIP channel
06621    called from sip_request_call (calls from the pbx ) for outbound channels
06622    and from handle_request_invite for inbound channels
06623    
06624 */
06625 static struct ast_channel *sip_new(struct sip_pvt *i, int state, const char *title, const char *linkedid)
06626 {
06627    struct ast_channel *tmp;
06628    struct ast_variable *v = NULL;
06629    format_t fmt;
06630    format_t what;
06631    format_t video;
06632    format_t text;
06633    format_t needvideo = 0;
06634    int needtext = 0;
06635    char buf[SIPBUFSIZE];
06636    char *decoded_exten;
06637 
06638    {
06639       const char *my_name; /* pick a good name */
06640    
06641       if (title) {
06642          my_name = title;
06643       } else {
06644          my_name = ast_strdupa(i->fromdomain);
06645       }
06646 
06647       sip_pvt_unlock(i);
06648       /* Don't hold a sip pvt lock while we allocate a channel */
06649       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));
06650    }
06651    if (!tmp) {
06652       ast_log(LOG_WARNING, "Unable to allocate AST channel structure for SIP channel\n");
06653       sip_pvt_lock(i);
06654       return NULL;
06655    }
06656    ast_channel_lock(tmp);
06657    sip_pvt_lock(i);
06658    ast_channel_cc_params_init(tmp, i->cc_params);
06659    tmp->caller.id.tag = ast_strdup(i->cid_tag);
06660    ast_channel_unlock(tmp);
06661 
06662    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;
06663 
06664    /* Select our native format based on codec preference until we receive
06665       something from another device to the contrary. */
06666    if (i->jointcapability) {  /* The joint capabilities of us and peer */
06667       what = i->jointcapability;
06668       video = i->jointcapability & AST_FORMAT_VIDEO_MASK;
06669       text = i->jointcapability & AST_FORMAT_TEXT_MASK;
06670    } else if (i->capability) {      /* Our configured capability for this peer */
06671       what = i->capability;
06672       video = i->capability & AST_FORMAT_VIDEO_MASK;
06673       text = i->capability & AST_FORMAT_TEXT_MASK;
06674    } else {
06675       what = sip_cfg.capability; /* Global codec support */
06676       video = sip_cfg.capability & AST_FORMAT_VIDEO_MASK;
06677       text = sip_cfg.capability & AST_FORMAT_TEXT_MASK;
06678    }
06679 
06680    /* Set the native formats for audio  and merge in video */
06681    tmp->nativeformats = ast_codec_choose(&i->prefs, what, 1) | video | text;
06682    ast_debug(3, "*** Our native formats are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, tmp->nativeformats));
06683    ast_debug(3, "*** Joint capabilities are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, i->jointcapability));
06684    ast_debug(3, "*** Our capabilities are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, i->capability));
06685    ast_debug(3, "*** AST_CODEC_CHOOSE formats are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, ast_codec_choose(&i->prefs, what, 1)));
06686    if (i->prefcodec)
06687       ast_debug(3, "*** Our preferred formats from the incoming channel are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, i->prefcodec));
06688 
06689    /* XXX Why are we choosing a codec from the native formats?? */
06690    fmt = ast_best_codec(tmp->nativeformats);
06691 
06692    /* If we have a prefcodec setting, we have an inbound channel that set a
06693       preferred format for this call. Otherwise, we check the jointcapability
06694       We also check for vrtp. If it's not there, we are not allowed do any video anyway.
06695     */
06696    if (i->vrtp) {
06697       if (ast_test_flag(&i->flags[1], SIP_PAGE2_VIDEOSUPPORT))
06698          needvideo = AST_FORMAT_VIDEO_MASK;
06699       else if (i->prefcodec)
06700          needvideo = i->prefcodec & AST_FORMAT_VIDEO_MASK;  /* Outbound call */
06701       else
06702          needvideo = i->jointcapability & AST_FORMAT_VIDEO_MASK;  /* Inbound call */
06703    }
06704 
06705    if (i->trtp) {
06706       if (i->prefcodec)
06707          needtext = i->prefcodec & AST_FORMAT_TEXT_MASK; /* Outbound call */
06708       else
06709          needtext = i->jointcapability & AST_FORMAT_TEXT_MASK; /* Inbound call */
06710    }
06711 
06712    if (needvideo)
06713       ast_debug(3, "This channel can handle video! HOLLYWOOD next!\n");
06714    else
06715       ast_debug(3, "This channel will not be able to handle video.\n");
06716 
06717    enable_dsp_detect(i);
06718 
06719    if ((ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) ||
06720        (ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_AUTO)) {
06721       if (!i->rtp || ast_rtp_instance_dtmf_mode_set(i->rtp, AST_RTP_DTMF_MODE_INBAND)) {
06722          enable_dsp_detect(i);
06723       }
06724    } else if (ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) {
06725       if (i->rtp) {
06726          ast_rtp_instance_dtmf_mode_set(i->rtp, AST_RTP_DTMF_MODE_RFC2833);
06727       }
06728    }
06729 
06730    /* Set file descriptors for audio, video, realtime text and UDPTL as needed */
06731    if (i->rtp) {
06732       ast_channel_set_fd(tmp, 0, ast_rtp_instance_fd(i->rtp, 0));
06733       ast_channel_set_fd(tmp, 1, ast_rtp_instance_fd(i->rtp, 1));
06734    }
06735    if (needvideo && i->vrtp) {
06736       ast_channel_set_fd(tmp, 2, ast_rtp_instance_fd(i->vrtp, 0));
06737       ast_channel_set_fd(tmp, 3, ast_rtp_instance_fd(i->vrtp, 1));
06738    }
06739    if (needtext && i->trtp)
06740       ast_channel_set_fd(tmp, 4, ast_rtp_instance_fd(i->trtp, 0));
06741    if (i->udptl)
06742       ast_channel_set_fd(tmp, 5, ast_udptl_fd(i->udptl));
06743 
06744    if (state == AST_STATE_RING)
06745       tmp->rings = 1;
06746    tmp->adsicpe = AST_ADSI_UNAVAILABLE;
06747 
06748    tmp->writeformat = fmt;
06749    tmp->rawwriteformat = fmt;
06750    ast_rtp_instance_set_write_format(i->rtp, fmt);
06751 
06752    tmp->readformat = fmt;
06753    tmp->rawreadformat = fmt;
06754    ast_rtp_instance_set_read_format(i->rtp, fmt);
06755 
06756    tmp->tech_pvt = dialog_ref(i, "sip_new: set chan->tech_pvt to i");
06757 
06758    tmp->callgroup = i->callgroup;
06759    tmp->pickupgroup = i->pickupgroup;
06760    tmp->caller.id.name.presentation = i->callingpres;
06761    tmp->caller.id.number.presentation = i->callingpres;
06762    if (!ast_strlen_zero(i->parkinglot))
06763       ast_string_field_set(tmp, parkinglot, i->parkinglot);
06764    if (!ast_strlen_zero(i->accountcode))
06765       ast_string_field_set(tmp, accountcode, i->accountcode);
06766    if (i->amaflags)
06767       tmp->amaflags = i->amaflags;
06768    if (!ast_strlen_zero(i->language))
06769       ast_string_field_set(tmp, language, i->language);
06770    i->owner = tmp;
06771    ast_module_ref(ast_module_info->self);
06772    ast_copy_string(tmp->context, i->context, sizeof(tmp->context));
06773    /*Since it is valid to have extensions in the dialplan that have unescaped characters in them
06774     * we should decode the uri before storing it in the channel, but leave it encoded in the sip_pvt
06775     * structure so that there aren't issues when forming URI's
06776     */
06777    if (ast_exists_extension(NULL, i->context, i->exten, 1, i->cid_num)) {
06778       /* encoded in dialplan, so keep extension encoded */
06779       ast_copy_string(tmp->exten, i->exten, sizeof(tmp->exten));
06780    } else {
06781       decoded_exten = ast_strdupa(i->exten);
06782       ast_uri_decode(decoded_exten);
06783       ast_copy_string(tmp->exten, decoded_exten, sizeof(tmp->exten));
06784    }
06785 
06786    /* Don't use ast_set_callerid() here because it will
06787     * generate an unnecessary NewCallerID event  */
06788    if (!ast_strlen_zero(i->cid_num)) {
06789       tmp->caller.ani.number.valid = 1;
06790       tmp->caller.ani.number.str = ast_strdup(i->cid_num);
06791    }
06792    if (!ast_strlen_zero(i->rdnis)) {
06793       tmp->redirecting.from.number.valid = 1;
06794       tmp->redirecting.from.number.str = ast_strdup(i->rdnis);
06795    }
06796 
06797    if (!ast_strlen_zero(i->exten) && strcmp(i->exten, "s")) {
06798       tmp->dialed.number.str = ast_strdup(i->exten);
06799    }
06800 
06801    tmp->priority = 1;
06802    if (!ast_strlen_zero(i->uri))
06803       pbx_builtin_setvar_helper(tmp, "SIPURI", i->uri);
06804    if (!ast_strlen_zero(i->domain))
06805       pbx_builtin_setvar_helper(tmp, "SIPDOMAIN", i->domain);
06806    if (!ast_strlen_zero(i->callid))
06807       pbx_builtin_setvar_helper(tmp, "SIPCALLID", i->callid);
06808    if (i->rtp)
06809       ast_jb_configure(tmp, &global_jbconf);
06810 
06811    /* Set channel variables for this call from configuration */
06812    for (v = i->chanvars ; v ; v = v->next) {
06813       char valuebuf[1024];
06814       pbx_builtin_setvar_helper(tmp, v->name, ast_get_encoded_str(v->value, valuebuf, sizeof(valuebuf)));
06815    }
06816 
06817    if (state != AST_STATE_DOWN && ast_pbx_start(tmp)) {
06818       ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
06819       tmp->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
06820       ast_hangup(tmp);
06821       tmp = NULL;
06822    }
06823 
06824    if (i->do_history)
06825       append_history(i, "NewChan", "Channel %s - from %s", tmp->name, i->callid);
06826 
06827    /* Inform manager user about new channel and their SIP call ID */
06828    if (sip_cfg.callevents)
06829       manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
06830          "Channel: %s\r\nUniqueid: %s\r\nChanneltype: %s\r\nSIPcallid: %s\r\nSIPfullcontact: %s\r\n",
06831          tmp->name, tmp->uniqueid, "SIP", i->callid, i->fullcontact);
06832 
06833    return tmp;
06834 }
06835 
06836 /*! \brief Reads one line of SIP message body */
06837 static char *get_body_by_line(const char *line, const char *name, int nameLen, char delimiter)
06838 {
06839    if (!strncasecmp(line, name, nameLen) && line[nameLen] == delimiter)
06840       return ast_skip_blanks(line + nameLen + 1);
06841 
06842    return "";
06843 }
06844 
06845 /*! \brief Lookup 'name' in the SDP starting
06846  * at the 'start' line. Returns the matching line, and 'start'
06847  * is updated with the next line number.
06848  */
06849 static const char *get_sdp_iterate(int *start, struct sip_request *req, const char *name)
06850 {
06851    int len = strlen(name);
06852 
06853    while (*start < (req->sdp_start + req->sdp_count)) {
06854       const char *r = get_body_by_line(REQ_OFFSET_TO_STR(req, line[(*start)++]), name, len, '=');
06855       if (r[0] != '\0')
06856          return r;
06857    }
06858 
06859    /* if the line was not found, ensure that *start points past the SDP */
06860    (*start)++;
06861 
06862    return "";
06863 }
06864 
06865 /*! \brief Fetches the next valid SDP line between the 'start' line
06866  * (inclusive) and the 'stop' line (exclusive). Returns the type
06867  * ('a', 'c', ...) and matching line in reference 'start' is updated
06868  * with the next line number.
06869  */
06870 static char get_sdp_line(int *start, int stop, struct sip_request *req, const char **value)
06871 {
06872    char type = '\0';
06873    const char *line = NULL;
06874 
06875    if (stop > (req->sdp_start + req->sdp_count)) {
06876       stop = req->sdp_start + req->sdp_count;
06877    }
06878 
06879    while (*start < stop) {
06880       line = REQ_OFFSET_TO_STR(req, line[(*start)++]);
06881       if (line[1] == '=') {
06882          type = line[0];
06883          *value = ast_skip_blanks(line + 2);
06884          break;
06885       }
06886    }
06887 
06888    return type;
06889 }
06890 
06891 /*! \brief Get a specific line from the message body */
06892 static char *get_body(struct sip_request *req, char *name, char delimiter)
06893 {
06894    int x;
06895    int len = strlen(name);
06896    char *r;
06897 
06898    for (x = 0; x < req->lines; x++) {
06899       r = get_body_by_line(REQ_OFFSET_TO_STR(req, line[x]), name, len, delimiter);
06900       if (r[0] != '\0')
06901          return r;
06902    }
06903 
06904    return "";
06905 }
06906 
06907 /*! \brief Find compressed SIP alias */
06908 static const char *find_alias(const char *name, const char *_default)
06909 {
06910    /*! \brief Structure for conversion between compressed SIP and "normal" SIP */
06911    static const struct cfalias {
06912       char * const fullname;
06913       char * const shortname;
06914    } aliases[] = {
06915       { "Content-Type",  "c" },
06916       { "Content-Encoding",    "e" },
06917       { "From",       "f" },
06918       { "Call-ID",       "i" },
06919       { "Contact",       "m" },
06920       { "Content-Length",   "l" },
06921       { "Subject",       "s" },
06922       { "To",         "t" },
06923       { "Supported",     "k" },
06924       { "Refer-To",      "r" },
06925       { "Referred-By",   "b" },
06926       { "Allow-Events",  "u" },
06927       { "Event",      "o" },
06928       { "Via",     "v" },
06929       { "Accept-Contact",      "a" },
06930       { "Reject-Contact",      "j" },
06931       { "Request-Disposition", "d" },
06932       { "Session-Expires",     "x" },
06933       { "Identity",            "y" },
06934       { "Identity-Info",       "n" },
06935    };
06936    int x;
06937 
06938    for (x = 0; x < ARRAY_LEN(aliases); x++) {
06939       if (!strcasecmp(aliases[x].fullname, name))
06940          return aliases[x].shortname;
06941    }
06942 
06943    return _default;
06944 }
06945 
06946 static const char *__get_header(const struct sip_request *req, const char *name, int *start)
06947 {
06948    int pass;
06949 
06950    /*
06951     * Technically you can place arbitrary whitespace both before and after the ':' in
06952     * a header, although RFC3261 clearly says you shouldn't before, and place just
06953     * one afterwards.  If you shouldn't do it, what absolute idiot decided it was
06954     * a good idea to say you can do it, and if you can do it, why in the hell would.
06955     * you say you shouldn't.
06956     * Anyways, pedanticsipchecking controls whether we allow spaces before ':',
06957     * and we always allow spaces after that for compatibility.
06958     */
06959    for (pass = 0; name && pass < 2;pass++) {
06960       int x, len = strlen(name);
06961       for (x = *start; x < req->headers; x++) {
06962          const char *header = REQ_OFFSET_TO_STR(req, header[x]);
06963          if (!strncasecmp(header, name, len)) {
06964             const char *r = header + len; /* skip name */
06965             if (sip_cfg.pedanticsipchecking)
06966                r = ast_skip_blanks(r);
06967 
06968             if (*r == ':') {
06969                *start = x+1;
06970                return ast_skip_blanks(r+1);
06971             }
06972          }
06973       }
06974       if (pass == 0) /* Try aliases */
06975          name = find_alias(name, NULL);
06976    }
06977 
06978    /* Don't return NULL, so get_header is always a valid pointer */
06979    return "";
06980 }
06981 
06982 /*! \brief Get header from SIP request
06983    \return Always return something, so don't check for NULL because it won't happen :-)
06984 */
06985 static const char *get_header(const struct sip_request *req, const char *name)
06986 {
06987    int start = 0;
06988    return __get_header(req, name, &start);
06989 }
06990 
06991 /*! \brief Read RTP from network */
06992 static struct ast_frame *sip_rtp_read(struct ast_channel *ast, struct sip_pvt *p, int *faxdetect)
06993 {
06994    /* Retrieve audio/etc from channel.  Assumes p->lock is already held. */
06995    struct ast_frame *f;
06996    
06997    if (!p->rtp) {
06998       /* We have no RTP allocated for this channel */
06999       return &ast_null_frame;
07000    }
07001 
07002    switch(ast->fdno) {
07003    case 0:
07004       f = ast_rtp_instance_read(p->rtp, 0);  /* RTP Audio */
07005       break;
07006    case 1:
07007       f = ast_rtp_instance_read(p->rtp, 1);  /* RTCP Control Channel */
07008       break;
07009    case 2:
07010       f = ast_rtp_instance_read(p->vrtp, 0); /* RTP Video */
07011       break;
07012    case 3:
07013       f = ast_rtp_instance_read(p->vrtp, 1); /* RTCP Control Channel for video */
07014       break;
07015    case 4:
07016       f = ast_rtp_instance_read(p->trtp, 0); /* RTP Text */
07017       if (sipdebug_text) {
07018          int i;
07019          unsigned char* arr = f->data.ptr;
07020          for (i=0; i < f->datalen; i++)
07021             ast_verbose("%c", (arr[i] > ' ' && arr[i] < '}') ? arr[i] : '.');
07022          ast_verbose(" -> ");
07023          for (i=0; i < f->datalen; i++)
07024             ast_verbose("%02X ", arr[i]);
07025          ast_verbose("\n");
07026       }
07027       break;
07028    case 5:
07029       f = ast_udptl_read(p->udptl); /* UDPTL for T.38 */
07030       break;
07031    default:
07032       f = &ast_null_frame;
07033    }
07034    /* Don't forward RFC2833 if we're not supposed to */
07035    if (f && (f->frametype == AST_FRAME_DTMF_BEGIN || f->frametype == AST_FRAME_DTMF_END) &&
07036        (ast_test_flag(&p->flags[0], SIP_DTMF) != SIP_DTMF_RFC2833)) {
07037       ast_debug(1, "Ignoring DTMF (%c) RTP frame because dtmfmode is not RFC2833\n", f->subclass.integer);
07038       return &ast_null_frame;
07039    }
07040 
07041    /* We already hold the channel lock */
07042    if (!p->owner || (f && f->frametype != AST_FRAME_VOICE))
07043       return f;
07044 
07045    if (f && f->subclass.codec != (p->owner->nativeformats & AST_FORMAT_AUDIO_MASK)) {
07046       if (!(f->subclass.codec & p->jointcapability)) {
07047          ast_debug(1, "Bogus frame of format '%s' received from '%s'!\n",
07048             ast_getformatname(f->subclass.codec), p->owner->name);
07049          return &ast_null_frame;
07050       }
07051       ast_debug(1, "Oooh, format changed to %s\n",
07052          ast_getformatname(f->subclass.codec));
07053       p->owner->nativeformats = (p->owner->nativeformats & (AST_FORMAT_VIDEO_MASK | AST_FORMAT_TEXT_MASK)) | f->subclass.codec;
07054       ast_set_read_format(p->owner, p->owner->readformat);
07055       ast_set_write_format(p->owner, p->owner->writeformat);
07056    }
07057 
07058    if (f && p->dsp) {
07059       f = ast_dsp_process(p->owner, p->dsp, f);
07060       if (f && f->frametype == AST_FRAME_DTMF) {
07061          if (f->subclass.integer == 'f') {
07062             ast_debug(1, "Fax CNG detected on %s\n", ast->name);
07063             *faxdetect = 1;
07064             /* If we only needed this DSP for fax detection purposes we can just drop it now */
07065             if (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) {
07066                ast_dsp_set_features(p->dsp, DSP_FEATURE_DIGIT_DETECT);
07067             } else {
07068                ast_dsp_free(p->dsp);
07069                p->dsp = NULL;
07070             }
07071          } else {
07072             ast_debug(1, "* Detected inband DTMF '%c'\n", f->subclass.integer);
07073          }
07074       }
07075    }
07076    
07077    return f;
07078 }
07079 
07080 /*! \brief Read SIP RTP from channel */
07081 static struct ast_frame *sip_read(struct ast_channel *ast)
07082 {
07083    struct ast_frame *fr;
07084    struct sip_pvt *p = ast->tech_pvt;
07085    int faxdetected = FALSE;
07086 
07087    sip_pvt_lock(p);
07088    fr = sip_rtp_read(ast, p, &faxdetected);
07089    p->lastrtprx = time(NULL);
07090 
07091    /* If we detect a CNG tone and fax detection is enabled then send us off to the fax extension */
07092    if (faxdetected && ast_test_flag(&p->flags[1], SIP_PAGE2_FAX_DETECT_CNG)) {
07093       ast_channel_lock(ast);
07094       if (strcmp(ast->exten, "fax")) {
07095          const char *target_context = S_OR(ast->macrocontext, ast->context);
07096          ast_channel_unlock(ast);
07097          if (ast_exists_extension(ast, target_context, "fax", 1,
07098             S_COR(ast->caller.id.number.valid, ast->caller.id.number.str, NULL))) {
07099             ast_verbose(VERBOSE_PREFIX_2 "Redirecting '%s' to fax extension due to CNG detection\n", ast->name);
07100             pbx_builtin_setvar_helper(ast, "FAXEXTEN", ast->exten);
07101             if (ast_async_goto(ast, target_context, "fax", 1)) {
07102                ast_log(LOG_NOTICE, "Failed to async goto '%s' into fax of '%s'\n", ast->name, target_context);
07103             }
07104             fr = &ast_null_frame;
07105          } else {
07106             ast_log(LOG_NOTICE, "FAX CNG detected but no fax extension\n");
07107          }
07108       } else {
07109          ast_channel_unlock(ast);
07110       }
07111    }
07112 
07113    /* Only allow audio through if they sent progress with SDP, or if the channel is actually answered */
07114    if (fr && fr->frametype == AST_FRAME_VOICE && p->invitestate != INV_EARLY_MEDIA && ast->_state != AST_STATE_UP) {
07115       fr = &ast_null_frame;
07116    }
07117 
07118    sip_pvt_unlock(p);
07119 
07120    return fr;
07121 }
07122 
07123 
07124 /*! \brief Generate 32 byte random string for callid's etc */
07125 static char *generate_random_string(char *buf, size_t size)
07126 {
07127    long val[4];
07128    int x;
07129 
07130    for (x=0; x<4; x++)
07131       val[x] = ast_random();
07132    snprintf(buf, size, "%08lx%08lx%08lx%08lx", val[0], val[1], val[2], val[3]);
07133 
07134    return buf;
07135 }
07136 
07137 static char *generate_uri(struct sip_pvt *pvt, char *buf, size_t size)
07138 {
07139    struct ast_str *uri = ast_str_alloca(size);
07140    ast_str_set(&uri, 0, "%s", pvt->socket.type == SIP_TRANSPORT_TLS ? "sips:" : "sip:");
07141    /* Here would be a great place to generate a UUID, but for now we'll
07142     * use the handy random string generation function we already have
07143     */
07144    ast_str_append(&uri, 0, "%s", generate_random_string(buf, size));
07145    ast_str_append(&uri, 0, "@%s", ast_sockaddr_stringify(&pvt->ourip));
07146    ast_copy_string(buf, ast_str_buffer(uri), size);
07147    return buf;
07148 }
07149 
07150 /*! \brief Build SIP Call-ID value for a non-REGISTER transaction */
07151 static void build_callid_pvt(struct sip_pvt *pvt)
07152 {
07153    char buf[33];
07154 
07155    const char *host = S_OR(pvt->fromdomain, ast_sockaddr_stringify(&pvt->ourip));
07156    
07157    ast_string_field_build(pvt, callid, "%s@%s", generate_random_string(buf, sizeof(buf)), host);
07158 
07159 }
07160 
07161 /*! \brief Build SIP Call-ID value for a REGISTER transaction */
07162 static void build_callid_registry(struct sip_registry *reg, const struct ast_sockaddr *ourip, const char *fromdomain)
07163 {
07164    char buf[33];
07165 
07166    const char *host = S_OR(fromdomain, ast_sockaddr_stringify_host(ourip));
07167 
07168    ast_string_field_build(reg, callid, "%s@%s", generate_random_string(buf, sizeof(buf)), host);
07169 }
07170 
07171 /*! \brief Make our SIP dialog tag */
07172 static void make_our_tag(char *tagbuf, size_t len)
07173 {
07174    snprintf(tagbuf, len, "as%08lx", ast_random());
07175 }
07176 
07177 /*! \brief Allocate Session-Timers struct w/in dialog */
07178 static struct sip_st_dlg* sip_st_alloc(struct sip_pvt *const p)
07179 {
07180    struct sip_st_dlg *stp;
07181 
07182    if (p->stimer) {
07183       ast_log(LOG_ERROR, "Session-Timer struct already allocated\n");
07184       return p->stimer;
07185    }
07186 
07187    if (!(stp = ast_calloc(1, sizeof(struct sip_st_dlg))))
07188       return NULL;
07189 
07190    p->stimer = stp;
07191 
07192    stp->st_schedid = -1;           /* Session-Timers ast_sched scheduler id */
07193 
07194    return p->stimer;
07195 }
07196 
07197 /*! \brief Allocate sip_pvt structure, set defaults and link in the container.
07198  * Returns a reference to the object so whoever uses it later must
07199  * remember to release the reference.
07200  */
07201 struct sip_pvt *sip_alloc(ast_string_field callid, struct ast_sockaddr *addr,
07202              int useglobal_nat, const int intended_method, struct sip_request *req)
07203 {
07204    struct sip_pvt *p;
07205 
07206    if (!(p = ao2_t_alloc(sizeof(*p), sip_destroy_fn, "allocate a dialog(pvt) struct")))
07207       return NULL;
07208 
07209    if (ast_string_field_init(p, 512)) {
07210       ao2_t_ref(p, -1, "failed to string_field_init, drop p");
07211       return NULL;
07212    }
07213 
07214    if (!(p->cc_params = ast_cc_config_params_init())) {
07215       ao2_t_ref(p, -1, "Yuck, couldn't allocate cc_params struct. Get rid o' p");
07216       return NULL;
07217    }
07218 
07219    /* If this dialog is created as the result of an incoming Request. Lets store
07220     * some information about that request */
07221    if (req) {
07222       char *sent_by, *branch;
07223       const char *cseq = get_header(req, "Cseq");
07224       unsigned int seqno;
07225 
07226       /* get branch parameter from initial Request that started this dialog */
07227       get_viabranch(ast_strdupa(get_header(req, "Via")), &sent_by, &branch);
07228       /* only store the branch if it begins with the magic prefix "z9hG4bK", otherwise
07229        * it is not useful to us to have it */
07230       if (!ast_strlen_zero(branch) && !strncasecmp(branch, "z9hG4bK", 7)) {
07231          ast_string_field_set(p, initviabranch, branch);
07232          ast_string_field_set(p, initviasentby, sent_by);
07233       }
07234 
07235       /* Store initial incoming cseq. An error in sscanf here is ignored.  There is no approperiate
07236        * except not storing the number.  CSeq validation must take place before dialog creation in find_call */
07237       if (!ast_strlen_zero(cseq) && (sscanf(cseq, "%30u", &seqno) == 1)) {
07238          p->init_icseq = seqno;
07239       }
07240       /* Later in ast_sip_ouraddrfor we need this to choose the right ip and port for the specific transport */
07241       set_socket_transport(&p->socket, req->socket.type);
07242    } else {
07243       set_socket_transport(&p->socket, SIP_TRANSPORT_UDP);
07244    }
07245 
07246    p->socket.fd = -1;
07247    p->method = intended_method;
07248    p->initid = -1;
07249    p->waitid = -1;
07250    p->autokillid = -1;
07251    p->request_queue_sched_id = -1;
07252    p->provisional_keepalive_sched_id = -1;
07253    p->t38id = -1;
07254    p->subscribed = NONE;
07255    p->stateid = -1;
07256    p->sessionversion_remote = -1;
07257    p->session_modify = TRUE;
07258    p->stimer = NULL;
07259    p->prefs = default_prefs;     /* Set default codecs for this call */
07260    p->maxforwards = sip_cfg.default_max_forwards;
07261 
07262    if (intended_method != SIP_OPTIONS) {  /* Peerpoke has it's own system */
07263       p->timer_t1 = global_t1;   /* Default SIP retransmission timer T1 (RFC 3261) */
07264       p->timer_b = global_timer_b;  /* Default SIP transaction timer B (RFC 3261) */
07265    }
07266 
07267    if (!addr) {
07268       p->ourip = internip;
07269    } else {
07270       ast_sockaddr_copy(&p->sa, addr);
07271       ast_sip_ouraddrfor(&p->sa, &p->ourip, p);
07272    }
07273 
07274    /* Copy global flags to this PVT at setup. */
07275    ast_copy_flags(&p->flags[0], &global_flags[0], SIP_FLAGS_TO_COPY);
07276    ast_copy_flags(&p->flags[1], &global_flags[1], SIP_PAGE2_FLAGS_TO_COPY);
07277    ast_copy_flags(&p->flags[2], &global_flags[2], SIP_PAGE3_FLAGS_TO_COPY);
07278 
07279    p->do_history = recordhistory;
07280 
07281    p->branch = ast_random();  
07282    make_our_tag(p->tag, sizeof(p->tag));
07283    p->ocseq = INITIAL_CSEQ;
07284    p->allowed_methods = UINT_MAX;
07285 
07286    if (sip_methods[intended_method].need_rtp) {
07287       if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT)) {
07288          if ((p->udptl = ast_udptl_new_with_bindaddr(sched, io, 0, &bindaddr))) {
07289             ast_udptl_setqos(p->udptl, global_tos_audio, global_cos_audio);
07290             p->t38_maxdatagram = global_t38_maxdatagram;
07291          } else {
07292             /* udptl creation failed, T38 can not be supported on this dialog */
07293             ast_log(LOG_ERROR, "UDPTL creation failed\n");
07294             ast_clear_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT);
07295          }
07296       }
07297       p->maxcallbitrate = default_maxcallbitrate;
07298       p->autoframing = global_autoframing;
07299    }
07300 
07301    if (useglobal_nat && addr) {
07302       /* Setup NAT structure according to global settings if we have an address */
07303       ast_copy_flags(&p->flags[0], &global_flags[0], SIP_NAT_FORCE_RPORT);
07304       ast_sockaddr_copy(&p->recv, addr);
07305 
07306       do_setnat(p);
07307    }
07308 
07309    if (p->method != SIP_REGISTER) {
07310       ast_string_field_set(p, fromdomain, default_fromdomain);
07311       p->fromdomainport = default_fromdomainport;
07312    }
07313    build_via(p);
07314    if (!callid)
07315       build_callid_pvt(p);
07316    else
07317       ast_string_field_set(p, callid, callid);
07318    /* Assign default music on hold class */
07319    ast_string_field_set(p, mohinterpret, default_mohinterpret);
07320    ast_string_field_set(p, mohsuggest, default_mohsuggest);
07321    p->capability = sip_cfg.capability;
07322    p->allowtransfer = sip_cfg.allowtransfer;
07323    if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
07324        (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
07325       p->noncodeccapability |= AST_RTP_DTMF;
07326    if (p->udptl) {
07327       p->t38_maxdatagram = global_t38_maxdatagram;
07328       set_t38_capabilities(p);
07329    }
07330    ast_string_field_set(p, context, sip_cfg.default_context);
07331    ast_string_field_set(p, parkinglot, default_parkinglot);
07332    ast_string_field_set(p, engine, default_engine);
07333 
07334    AST_LIST_HEAD_INIT_NOLOCK(&p->request_queue);
07335 
07336    /* Add to active dialog list */
07337 
07338    ao2_t_link(dialogs, p, "link pvt into dialogs table");
07339    
07340    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");
07341    return p;
07342 }
07343 
07344 /* \brief arguments used for Request/Response to matching */
07345 struct match_req_args {
07346    int method;
07347    const char *callid;
07348    const char *totag;
07349    const char *fromtag;
07350    unsigned int seqno;
07351 
07352    /* Set if the method is a Request */
07353    const char *ruri;
07354    const char *viabranch;
07355    const char *viasentby;
07356 
07357    /* Set this if the Authentication header is present in the Request. */
07358    int authentication_present;
07359 };
07360 
07361 enum match_req_res {
07362    SIP_REQ_MATCH,
07363    SIP_REQ_NOT_MATCH,
07364    SIP_REQ_LOOP_DETECTED,
07365 };
07366 
07367 /*
07368  * \brief Match a incoming Request/Response to a dialog
07369  *
07370  * \retval enum match_req_res indicating if the dialog matches the arg
07371  */
07372 static enum match_req_res match_req_to_dialog(struct sip_pvt *sip_pvt_ptr, struct match_req_args *arg)
07373 {
07374    const char *init_ruri = NULL;
07375    if (sip_pvt_ptr->initreq.headers) {
07376       init_ruri = REQ_OFFSET_TO_STR(&sip_pvt_ptr->initreq, rlPart2);
07377    }
07378 
07379    /*
07380     * Match Tags and call-id to Dialog
07381     */
07382    if (!ast_strlen_zero(arg->callid) && strcmp(sip_pvt_ptr->callid, arg->callid)) {
07383       /* call-id does not match. */
07384       return SIP_REQ_NOT_MATCH;
07385    }
07386    if (arg->method == SIP_RESPONSE) {
07387       /* Verify totag if we have one stored for this dialog, but never be strict about this for
07388        * a response until the dialog is established */
07389       if (!ast_strlen_zero(sip_pvt_ptr->theirtag) && ast_test_flag(&sip_pvt_ptr->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED)) {
07390          if (ast_strlen_zero(arg->totag)) {
07391             /* missing totag when they already gave us one earlier */
07392             return SIP_REQ_NOT_MATCH;
07393          }
07394          if (strcmp(arg->totag, sip_pvt_ptr->theirtag)) {
07395             /* The totag of the response does not match the one we have stored */
07396             return SIP_REQ_NOT_MATCH;
07397          }
07398       }
07399       /* Verify fromtag of response matches the tag we gave them. */
07400       if (strcmp(arg->fromtag, sip_pvt_ptr->tag)) {
07401          /* fromtag from response does not match our tag */
07402          return SIP_REQ_NOT_MATCH;
07403       }
07404    } else {
07405       /* Verify the fromtag of Request matches the tag they provided earlier.
07406        * If this is a Request with authentication credentials, forget their old
07407        * tag as it is not valid after the 401 or 407 response. */
07408       if (!arg->authentication_present && strcmp(arg->fromtag, sip_pvt_ptr->theirtag)) {
07409          /* their tag does not match the one was have stored for them */
07410          return SIP_REQ_NOT_MATCH;
07411       }
07412       /* Verify if totag is present in Request, that it matches what we gave them as our tag earlier */
07413       if (!ast_strlen_zero(arg->totag) && (strcmp(arg->totag, sip_pvt_ptr->tag))) {
07414          /* totag from Request does not match our tag */
07415          return SIP_REQ_NOT_MATCH;
07416       }
07417    }
07418 
07419    /*
07420     * Compare incoming request against initial transaction.
07421     * 
07422     * This is a best effort attempt at distinguishing forked requests from
07423     * our initial transaction.  If all the elements are NOT in place to evaluate
07424     * this, this block is ignored and the dialog match is made regardless.
07425     * Once the totag is established after the dialog is confirmed, this is not necessary.
07426     *
07427     * CRITERIA required for initial transaction matching.
07428     * 
07429     * 1. Is a Request
07430     * 2. Callid and theirtag match (this is done in the dialog matching block)
07431     * 3. totag is NOT present
07432     * 4. CSeq matchs our initial transaction's cseq number
07433     * 5. pvt has init via branch parameter stored
07434     */
07435    if ((arg->method != SIP_RESPONSE) &&                 /* must be a Request */
07436       ast_strlen_zero(arg->totag) &&                   /* must not have a totag */
07437       (sip_pvt_ptr->init_icseq == arg->seqno) &&       /* the cseq must be the same as this dialogs initial cseq */
07438       !ast_strlen_zero(sip_pvt_ptr->initviabranch) &&  /* The dialog must have started with a RFC3261 compliant branch tag */
07439       init_ruri) {                                     /* the dialog must have an initial request uri associated with it */
07440       /* This Request matches all the criteria required for Loop/Merge detection.
07441        * Now we must go down the path of comparing VIA's and RURIs. */
07442       if (ast_strlen_zero(arg->viabranch) ||
07443          strcmp(arg->viabranch, sip_pvt_ptr->initviabranch) ||
07444          ast_strlen_zero(arg->viasentby) ||
07445          strcmp(arg->viasentby, sip_pvt_ptr->initviasentby)) {
07446          /* At this point, this request does not match this Dialog.*/
07447 
07448          /* if methods are different this is just a mismatch */
07449          if ((sip_pvt_ptr->method != arg->method)) {
07450             return SIP_REQ_NOT_MATCH;
07451          }
07452 
07453          /* If RUIs are different, this is a forked request to a separate URI.
07454           * Returning a mismatch allows this Request to be processed separately. */
07455          if (sip_uri_cmp(init_ruri, arg->ruri)) {
07456             /* not a match, request uris are different */
07457             return SIP_REQ_NOT_MATCH;
07458          }
07459 
07460          /* Loop/Merge Detected
07461           *
07462           * ---Current Matches to Initial Request---
07463           * request uri
07464           * Call-id
07465           * their-tag
07466           * no totag present
07467           * method
07468           * cseq
07469           *
07470           * --- Does not Match Initial Request ---
07471           * Top Via
07472           *
07473           * Without the same Via, this can not match our initial transaction for this dialog,
07474           * but given that this Request matches everything else associated with that initial
07475           * Request this is most certainly a Forked request in which we have already received
07476           * part of the fork.
07477           */
07478          return SIP_REQ_LOOP_DETECTED;
07479       }
07480    } /* end of Request Via check */
07481 
07482    /* Match Authentication Request.
07483     *
07484     * A Request with an Authentication header must come back with the
07485     * same Request URI.  Otherwise it is not a match.
07486     */
07487    if ((arg->method != SIP_RESPONSE) &&      /* Must be a Request type to even begin checking this */
07488       ast_strlen_zero(arg->totag) &&        /* no totag is present to match */
07489       arg->authentication_present &&        /* Authentication header is present in Request */
07490       sip_uri_cmp(init_ruri, arg->ruri)) {  /* Compare the Request URI of both the last Request and this new one */
07491 
07492       /* Authentication was provided, but the Request URI did not match the last one on this dialog. */
07493       return SIP_REQ_NOT_MATCH;
07494    }
07495 
07496    return SIP_REQ_MATCH;
07497 }
07498 
07499 /*! \brief find or create a dialog structure for an incoming SIP message.
07500  * Connect incoming SIP message to current dialog or create new dialog structure
07501  * Returns a reference to the sip_pvt object, remember to give it back once done.
07502  *     Called by handle_incoming(), sipsock_read
07503  */
07504 static struct sip_pvt *find_call(struct sip_request *req, struct ast_sockaddr *addr, const int intended_method)
07505 {
07506    char totag[128];
07507    char fromtag[128];
07508    const char *callid = get_header(req, "Call-ID");
07509    const char *from = get_header(req, "From");
07510    const char *to = get_header(req, "To");
07511    const char *cseq = get_header(req, "Cseq");
07512    struct sip_pvt *sip_pvt_ptr;
07513    unsigned int seqno;
07514    /* Call-ID, to, from and Cseq are required by RFC 3261. (Max-forwards and via too - ignored now) */
07515    /* get_header always returns non-NULL so we must use ast_strlen_zero() */
07516    if (ast_strlen_zero(callid) || ast_strlen_zero(to) ||
07517          ast_strlen_zero(from) || ast_strlen_zero(cseq) ||
07518          (sscanf(cseq, "%30u", &seqno) != 1)) {
07519 
07520       /* RFC 3261 section 24.4.1.   Send a 400 Bad Request if the request is malformed. */
07521       if (intended_method != SIP_RESPONSE && intended_method != SIP_ACK) {
07522          transmit_response_using_temp(callid, addr, 1, intended_method,
07523                        req, "400 Bad Request");
07524       }
07525       return NULL;   /* Invalid packet */
07526    }
07527 
07528    if (sip_cfg.pedanticsipchecking) {
07529       /* In principle Call-ID's uniquely identify a call, but with a forking SIP proxy
07530          we need more to identify a branch - so we have to check branch, from
07531          and to tags to identify a call leg.
07532          For Asterisk to behave correctly, you need to turn on pedanticsipchecking
07533          in sip.conf
07534          */
07535       if (gettag(req, "To", totag, sizeof(totag)))
07536          req->has_to_tag = 1; /* Used in handle_request/response */
07537       gettag(req, "From", fromtag, sizeof(fromtag));
07538 
07539       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);
07540 
07541       /* All messages must always have From: tag */
07542       if (ast_strlen_zero(fromtag)) {
07543          ast_debug(5, "%s request has no from tag, dropping callid: %s from: %s\n", sip_methods[req->method].text , callid, from );
07544          return NULL;
07545       }
07546       /* reject requests that must always have a To: tag */
07547       if (ast_strlen_zero(totag) && (req->method == SIP_ACK || req->method == SIP_BYE || req->method == SIP_INFO )) {
07548          ast_debug(5, "%s must have a to tag. dropping callid: %s from: %s\n", sip_methods[req->method].text , callid, from );
07549          return NULL;
07550       }
07551    }
07552 
07553    if (!sip_cfg.pedanticsipchecking) {
07554       struct sip_pvt tmp_dialog = {
07555          .callid = callid,
07556       };
07557       sip_pvt_ptr = ao2_t_find(dialogs, &tmp_dialog, OBJ_POINTER, "ao2_find in dialogs");
07558       if (sip_pvt_ptr) {  /* well, if we don't find it-- what IS in there? */
07559          /* Found the call */
07560          sip_pvt_lock(sip_pvt_ptr);
07561          return sip_pvt_ptr;
07562       }
07563    } else { /* in pedantic mode! -- do the fancy search */
07564       struct sip_pvt tmp_dialog = {
07565          .callid = callid,
07566       };
07567       struct match_req_args args = { 0, };
07568       int found;
07569       struct ao2_iterator *iterator = ao2_t_callback(dialogs,
07570          OBJ_POINTER | OBJ_MULTIPLE,
07571          dialog_find_multiple,
07572          &tmp_dialog,
07573          "pedantic ao2_find in dialogs");
07574 
07575       args.method = req->method;
07576       args.callid = NULL; /* we already matched this. */
07577       args.totag = totag;
07578       args.fromtag = fromtag;
07579       args.seqno = seqno;
07580 
07581       /* If this is a Request, set the Via and Authorization header arguments */
07582       if (req->method != SIP_RESPONSE) {
07583          args.ruri = REQ_OFFSET_TO_STR(req, rlPart2);
07584          get_viabranch(ast_strdupa(get_header(req, "Via")), (char **) &args.viasentby, (char **) &args.viabranch);
07585          if (!ast_strlen_zero(get_header(req, "Authorization")) ||
07586             !ast_strlen_zero(get_header(req, "Proxy-Authorization"))) {
07587             args.authentication_present = 1;
07588          }
07589       }
07590 
07591       /* Iterate a list of dialogs already matched by Call-id */
07592       while (iterator && (sip_pvt_ptr = ao2_iterator_next(iterator))) {
07593          found = match_req_to_dialog(sip_pvt_ptr, &args);
07594 
07595          switch (found) {
07596          case SIP_REQ_MATCH:
07597             sip_pvt_lock(sip_pvt_ptr);
07598             ao2_iterator_destroy(iterator);
07599             return sip_pvt_ptr; /* return pvt with ref */
07600          case SIP_REQ_LOOP_DETECTED:
07601             /* This is likely a forked Request that somehow resulted in us receiving multiple parts of the fork.
07602             * RFC 3261 section 8.2.2.2, Indicate that we want to merge requests by sending a 482 response. */
07603             transmit_response_using_temp(callid, addr, 1, intended_method, req, "482 (Loop Detected)");
07604             dialog_unref(sip_pvt_ptr, "pvt did not match incoming SIP msg, unref from search.");
07605             ao2_iterator_destroy(iterator);
07606             return NULL;
07607          case SIP_REQ_NOT_MATCH:
07608          default:
07609             dialog_unref(sip_pvt_ptr, "pvt did not match incoming SIP msg, unref from search");
07610          }
07611       }
07612       if (iterator) {
07613          ao2_iterator_destroy(iterator);
07614       }
07615    } /* end of pedantic mode Request/Reponse to Dialog matching */
07616 
07617    /* See if the method is capable of creating a dialog */
07618    if (sip_methods[intended_method].can_create == CAN_CREATE_DIALOG) {
07619       struct sip_pvt *p = NULL;
07620 
07621       if (intended_method == SIP_REFER) {
07622          /* We do support REFER, but not outside of a dialog yet */
07623          transmit_response_using_temp(callid, addr, 1, intended_method, req, "603 Declined (no dialog)");
07624       } else {
07625          /* Ok, time to create a new SIP dialog object, a pvt */
07626          if ((p = sip_alloc(callid, addr, 1, intended_method, req)))  {
07627             /* Ok, we've created a dialog, let's go and process it */
07628             sip_pvt_lock(p);
07629          } else {
07630             /* We have a memory or file/socket error (can't allocate RTP sockets or something) so we're not
07631                getting a dialog from sip_alloc.
07632    
07633                Without a dialog we can't retransmit and handle ACKs and all that, but at least
07634                send an error message.
07635    
07636                Sorry, we apologize for the inconvienience
07637             */
07638             transmit_response_using_temp(callid, addr, 1, intended_method, req, "500 Server internal error");
07639             ast_debug(4, "Failed allocating SIP dialog, sending 500 Server internal error and giving up\n");
07640          }
07641       }
07642       return p; /* can be NULL */
07643    } else if( sip_methods[intended_method].can_create == CAN_CREATE_DIALOG_UNSUPPORTED_METHOD) {
07644       /* A method we do not support, let's take it on the volley */
07645       transmit_response_using_temp(callid, addr, 1, intended_method, req, "501 Method Not Implemented");
07646       ast_debug(2, "Got a request with unsupported SIP method.\n");
07647    } else if (intended_method != SIP_RESPONSE && intended_method != SIP_ACK) {
07648       /* This is a request outside of a dialog that we don't know about */
07649       transmit_response_using_temp(callid, addr, 1, intended_method, req, "481 Call leg/transaction does not exist");
07650       ast_debug(2, "That's odd...  Got a request in unknown dialog. Callid %s\n", callid ? callid : "<unknown>");
07651    }
07652    /* We do not respond to responses for dialogs that we don't know about, we just drop
07653       the session quickly */
07654    if (intended_method == SIP_RESPONSE)
07655       ast_debug(2, "That's odd...  Got a response on a call we don't know about. Callid %s\n", callid ? callid : "<unknown>");
07656 
07657    return NULL;
07658 }
07659 
07660 /*! \brief create sip_registry object from register=> line in sip.conf and link into reg container */
07661 static int sip_register(const char *value, int lineno)
07662 {
07663    struct sip_registry *reg;
07664 
07665    if (!(reg = ast_calloc_with_stringfields(1, struct sip_registry, 256))) {
07666       ast_log(LOG_ERROR, "Out of memory. Can't allocate SIP registry entry\n");
07667       return -1;
07668    }
07669 
07670    ast_atomic_fetchadd_int(&regobjs, 1);
07671    ASTOBJ_INIT(reg);
07672 
07673    if (sip_parse_register_line(reg, default_expiry, value, lineno)) {
07674       registry_unref(reg, "failure to parse, unref the reg pointer");
07675       return -1;
07676    }
07677 
07678    /* set default expiry if necessary */
07679    if (reg->refresh && !reg->expiry && !reg->configured_expiry) {
07680       reg->refresh = reg->expiry = reg->configured_expiry = default_expiry;
07681    }
07682 
07683    /* Add the new registry entry to the list */
07684    ASTOBJ_CONTAINER_LINK(&regl, reg);
07685 
07686    /* release the reference given by ASTOBJ_INIT. The container has another reference */
07687    registry_unref(reg, "unref the reg pointer");
07688 
07689    return 0;
07690 }
07691 
07692 /*! \brief Parse mwi=> line in sip.conf and add to list */
07693 static int sip_subscribe_mwi(const char *value, int lineno)
07694 {
07695    struct sip_subscription_mwi *mwi;
07696    int portnum = 0;
07697    enum sip_transport transport = SIP_TRANSPORT_UDP;
07698    char buf[256] = "";
07699    char *username = NULL, *hostname = NULL, *secret = NULL, *authuser = NULL, *porta = NULL, *mailbox = NULL, *at = NULL;
07700 
07701    if (!value) {
07702       return -1;
07703    }
07704 
07705    ast_copy_string(buf, value, sizeof(buf));
07706 
07707    if (!(at = strstr(buf, "@"))) {
07708       return -1;
07709    }
07710 
07711    if ((hostname = strrchr(buf, '@'))) {
07712       *hostname++ = '\0';
07713       username = buf;
07714    }
07715 
07716    if ((secret = strchr(username, ':'))) {
07717       *secret++ = '\0';
07718       if ((authuser = strchr(secret, ':'))) {
07719          *authuser++ = '\0';
07720       }
07721    }
07722 
07723    if ((mailbox = strchr(hostname, '/'))) {
07724       *mailbox++ = '\0';
07725    }
07726 
07727    if (ast_strlen_zero(username) || ast_strlen_zero(hostname) || ast_strlen_zero(mailbox)) {
07728       ast_log(LOG_WARNING, "Format for MWI subscription is user[:secret[:authuser]]@host[:port]/mailbox at line %d\n", lineno);
07729       return -1;
07730    }
07731 
07732    if ((porta = strchr(hostname, ':'))) {
07733       *porta++ = '\0';
07734       if (!(portnum = atoi(porta))) {
07735          ast_log(LOG_WARNING, "%s is not a valid port number at line %d\n", porta, lineno);
07736          return -1;
07737       }
07738    }
07739 
07740    if (!(mwi = ast_calloc_with_stringfields(1, struct sip_subscription_mwi, 256))) {
07741       return -1;
07742    }
07743 
07744    ASTOBJ_INIT(mwi);
07745    ast_string_field_set(mwi, username, username);
07746    if (secret) {
07747       ast_string_field_set(mwi, secret, secret);
07748    }
07749    if (authuser) {
07750       ast_string_field_set(mwi, authuser, authuser);
07751    }
07752    ast_string_field_set(mwi, hostname, hostname);
07753    ast_string_field_set(mwi, mailbox, mailbox);
07754    mwi->resub = -1;
07755    mwi->portno = portnum;
07756    mwi->transport = transport;
07757 
07758    ASTOBJ_CONTAINER_LINK(&submwil, mwi);
07759    ASTOBJ_UNREF(mwi, sip_subscribe_mwi_destroy);
07760 
07761    return 0;
07762 }
07763 
07764 static void mark_method_allowed(unsigned int *allowed_methods, enum sipmethod method)
07765 {
07766    (*allowed_methods) |= (1 << method);
07767 }
07768 
07769 static void mark_method_unallowed(unsigned int *allowed_methods, enum sipmethod method)
07770 {
07771    (*allowed_methods) &= ~(1 << method);
07772 }
07773 
07774 /*! \brief Check if method is allowed for a device or a dialog */
07775 static int is_method_allowed(unsigned int *allowed_methods, enum sipmethod method)
07776 {
07777    return ((*allowed_methods) >> method) & 1;
07778 }
07779 
07780 static void mark_parsed_methods(unsigned int *methods, char *methods_str)
07781 {
07782    char *method;
07783    for (method = strsep(&methods_str, ","); !ast_strlen_zero(method); method = strsep(&methods_str, ",")) {
07784       int id = find_sip_method(ast_skip_blanks(method));
07785       if (id == SIP_UNKNOWN) {
07786          continue;
07787       }
07788       mark_method_allowed(methods, id);
07789    }
07790 }
07791 /*!
07792  * \brief parse the Allow header to see what methods the endpoint we
07793  * are communicating with allows.
07794  *
07795  * We parse the allow header on incoming Registrations and save the
07796  * result to the SIP peer that is registering. When the registration
07797  * expires, we clear what we know about the peer's allowed methods.
07798  * When the peer re-registers, we once again parse to see if the
07799  * list of allowed methods has changed.
07800  *
07801  * For peers that do not register, we parse the first message we receive
07802  * during a call to see what is allowed, and save the information
07803  * for the duration of the call.
07804  * \param req The SIP request we are parsing
07805  * \retval The methods allowed
07806  */
07807 static unsigned int parse_allowed_methods(struct sip_request *req)
07808 {
07809    char *allow = ast_strdupa(get_header(req, "Allow"));
07810    unsigned int allowed_methods = SIP_UNKNOWN;
07811 
07812    if (ast_strlen_zero(allow)) {
07813       /* I have witnessed that REGISTER requests from Polycom phones do not
07814        * place the phone's allowed methods in an Allow header. Instead, they place the
07815        * allowed methods in a methods= parameter in the Contact header.
07816        */
07817       char *contact = ast_strdupa(get_header(req, "Contact"));
07818       char *methods = strstr(contact, ";methods=");
07819 
07820       if (ast_strlen_zero(methods)) {
07821          /* RFC 3261 states:
07822           *
07823           * "The absence of an Allow header field MUST NOT be
07824           * interpreted to mean that the UA sending the message supports no
07825           * methods.   Rather, it implies that the UA is not providing any
07826           * information on what methods it supports."
07827           *
07828           * For simplicity, we'll assume that the peer allows all known
07829           * SIP methods if they have no Allow header. We can then clear out the necessary
07830           * bits if the peer lets us know that we have sent an unsupported method.
07831           */
07832          return UINT_MAX;
07833       }
07834       allow = ast_strip_quoted(methods + 9, "\"", "\"");
07835    }
07836    mark_parsed_methods(&allowed_methods, allow);
07837    return allowed_methods;
07838 }
07839 
07840 /*! A wrapper for parse_allowed_methods geared toward sip_pvts
07841  *
07842  * This function, in addition to setting the allowed methods for a sip_pvt
07843  * also will take into account the setting of the SIP_PAGE2_RPID_UPDATE flag.
07844  *
07845  * \param pvt The sip_pvt we are setting the allowed_methods for
07846  * \param req The request which we are parsing
07847  * \retval The methods alloweded by the sip_pvt
07848  */
07849 static unsigned int set_pvt_allowed_methods(struct sip_pvt *pvt, struct sip_request *req)
07850 {
07851    pvt->allowed_methods = parse_allowed_methods(req);
07852    
07853    if (ast_test_flag(&pvt->flags[1], SIP_PAGE2_RPID_UPDATE)) {
07854       mark_method_allowed(&pvt->allowed_methods, SIP_UPDATE);
07855    }
07856    pvt->allowed_methods &= ~(pvt->disallowed_methods);
07857 
07858    return pvt->allowed_methods;
07859 }
07860 
07861 /*! \brief  Parse multiline SIP headers into one header
07862    This is enabled if pedanticsipchecking is enabled */
07863 static int lws2sws(char *msgbuf, int len)
07864 {
07865    int h = 0, t = 0;
07866    int lws = 0;
07867 
07868    for (; h < len;) {
07869       /* Eliminate all CRs */
07870       if (msgbuf[h] == '\r') {
07871          h++;
07872          continue;
07873       }
07874       /* Check for end-of-line */
07875       if (msgbuf[h] == '\n') {
07876          /* Check for end-of-message */
07877          if (h + 1 == len)
07878             break;
07879          /* Check for a continuation line */
07880          if (msgbuf[h + 1] == ' ' || msgbuf[h + 1] == '\t') {
07881             /* Merge continuation line */
07882             h++;
07883             continue;
07884          }
07885          /* Propagate LF and start new line */
07886          msgbuf[t++] = msgbuf[h++];
07887          lws = 0;
07888          continue;
07889       }
07890       if (msgbuf[h] == ' ' || msgbuf[h] == '\t') {
07891          if (lws) {
07892             h++;
07893             continue;
07894          }
07895          msgbuf[t++] = msgbuf[h++];
07896          lws = 1;
07897          continue;
07898       }
07899       msgbuf[t++] = msgbuf[h++];
07900       if (lws)
07901          lws = 0;
07902    }
07903    msgbuf[t] = '\0';
07904    return t;
07905 }
07906 
07907 /*! \brief Parse a SIP message
07908    \note this function is used both on incoming and outgoing packets
07909 */
07910 static int parse_request(struct sip_request *req)
07911 {
07912    char *c = req->data->str;
07913    ptrdiff_t *dst = req->header;
07914    int i = 0, lim = SIP_MAX_HEADERS - 1;
07915    unsigned int skipping_headers = 0;
07916    ptrdiff_t current_header_offset = 0;
07917    char *previous_header = "";
07918 
07919    req->header[0] = 0;
07920    req->headers = -1;   /* mark that we are working on the header */
07921    for (; *c; c++) {
07922       if (*c == '\r') {    /* remove \r */
07923          *c = '\0';
07924       } else if (*c == '\n') {   /* end of this line */
07925          *c = '\0';
07926          current_header_offset = (c + 1) - req->data->str;
07927          previous_header = req->data->str + dst[i];
07928          if (skipping_headers) {
07929             /* check to see if this line is blank; if so, turn off
07930                the skipping flag, so the next line will be processed
07931                as a body line */
07932             if (ast_strlen_zero(previous_header)) {
07933                skipping_headers = 0;
07934             }
07935             dst[i] = current_header_offset; /* record start of next line */
07936             continue;
07937          }
07938          if (sipdebug) {
07939             ast_debug(4, "%7s %2d [%3d]: %s\n",
07940                  req->headers < 0 ? "Header" : "Body",
07941                  i, (int) strlen(previous_header), previous_header);
07942          }
07943          if (ast_strlen_zero(previous_header) && req->headers < 0) {
07944             req->headers = i; /* record number of header lines */
07945             dst = req->line;  /* start working on the body */
07946             i = 0;
07947             lim = SIP_MAX_LINES - 1;
07948          } else { /* move to next line, check for overflows */
07949             if (i++ == lim) {
07950                /* if we're processing headers, then skip any remaining
07951                   headers and move on to processing the body, otherwise
07952                   we're done */
07953                if (req->headers != -1) {
07954                   break;
07955                } else {
07956                   req->headers = i;
07957                   dst = req->line;
07958                   i = 0;
07959                   lim = SIP_MAX_LINES - 1;
07960                   skipping_headers = 1;
07961                }
07962             }
07963          }
07964          dst[i] = current_header_offset; /* record start of next line */
07965       }
07966    }
07967 
07968    /* Check for last header or body line without CRLF. The RFC for SDP requires CRLF,
07969       but since some devices send without, we'll be generous in what we accept. However,
07970       if we've already reached the maximum number of lines for portion of the message
07971       we were parsing, we can't accept any more, so just ignore it.
07972    */
07973    previous_header = req->data->str + dst[i];
07974    if ((i < lim) && !ast_strlen_zero(previous_header)) {
07975       if (sipdebug) {
07976          ast_debug(4, "%7s %2d [%3d]: %s\n",
07977               req->headers < 0 ? "Header" : "Body",
07978               i, (int) strlen(previous_header), previous_header );
07979       }
07980       i++;
07981    }
07982 
07983    /* update count of header or body lines */
07984    if (req->headers >= 0) {   /* we are in the body */
07985       req->lines = i;
07986    } else {       /* no body */
07987       req->headers = i;
07988       req->lines = 0;
07989       /* req->data->used will be a NULL byte */
07990       req->line[0] = ast_str_strlen(req->data);
07991    }
07992 
07993    if (*c) {
07994       ast_log(LOG_WARNING, "Too many lines, skipping <%s>\n", c);
07995    }
07996 
07997    /* Split up the first line parts */
07998    return determine_firstline_parts(req);
07999 }
08000 
08001 /*!
08002   \brief Determine whether a SIP message contains an SDP in its body
08003   \param req the SIP request to process
08004   \return 1 if SDP found, 0 if not found
08005 
08006   Also updates req->sdp_start and req->sdp_count to indicate where the SDP
08007   lives in the message body.
08008 */
08009 static int find_sdp(struct sip_request *req)
08010 {
08011    const char *content_type;
08012    const char *content_length;
08013    const char *search;
08014    char *boundary;
08015    unsigned int x;
08016    int boundaryisquoted = FALSE;
08017    int found_application_sdp = FALSE;
08018    int found_end_of_headers = FALSE;
08019 
08020    content_length = get_header(req, "Content-Length");
08021 
08022    if (!ast_strlen_zero(content_length)) {
08023       if (sscanf(content_length, "%30u", &x) != 1) {
08024          ast_log(LOG_WARNING, "Invalid Content-Length: %s\n", content_length);
08025          return 0;
08026       }
08027 
08028       /* Content-Length of zero means there can't possibly be an
08029          SDP here, even if the Content-Type says there is */
08030       if (x == 0)
08031          return 0;
08032    }
08033 
08034    content_type = get_header(req, "Content-Type");
08035 
08036    /* if the body contains only SDP, this is easy */
08037    if (!strncasecmp(content_type, "application/sdp", 15)) {
08038       req->sdp_start = 0;
08039       req->sdp_count = req->lines;
08040       return req->lines ? 1 : 0;
08041    }
08042 
08043    /* if it's not multipart/mixed, there cannot be an SDP */
08044    if (strncasecmp(content_type, "multipart/mixed", 15))
08045       return 0;
08046 
08047    /* if there is no boundary marker, it's invalid */
08048    if ((search = strcasestr(content_type, ";boundary=")))
08049       search += 10;
08050    else if ((search = strcasestr(content_type, "; boundary=")))
08051       search += 11;
08052    else
08053       return 0;
08054 
08055    if (ast_strlen_zero(search))
08056       return 0;
08057 
08058    /* If the boundary is quoted with ", remove quote */
08059    if (*search == '\"')  {
08060       search++;
08061       boundaryisquoted = TRUE;
08062    }
08063 
08064    /* make a duplicate of the string, with two extra characters
08065       at the beginning */
08066    boundary = ast_strdupa(search - 2);
08067    boundary[0] = boundary[1] = '-';
08068    /* Remove final quote */
08069    if (boundaryisquoted)
08070       boundary[strlen(boundary) - 1] = '\0';
08071 
08072    /* search for the boundary marker, the empty line delimiting headers from
08073       sdp part and the end boundry if it exists */
08074 
08075    for (x = 0; x < (req->lines); x++) {
08076       const char *line = REQ_OFFSET_TO_STR(req, line[x]);
08077       if (!strncasecmp(line, boundary, strlen(boundary))){
08078          if (found_application_sdp && found_end_of_headers) {
08079             req->sdp_count = (x - 1) - req->sdp_start;
08080             return 1;
08081          }
08082          found_application_sdp = FALSE;
08083       }
08084       if (!strcasecmp(line, "Content-Type: application/sdp"))
08085          found_application_sdp = TRUE;
08086       
08087       if (ast_strlen_zero(line)) {
08088          if (found_application_sdp && !found_end_of_headers){
08089             req->sdp_start = x;
08090             found_end_of_headers = TRUE;
08091          }
08092       }
08093    }
08094    if (found_application_sdp && found_end_of_headers) {
08095       req->sdp_count = x - req->sdp_start;
08096       return TRUE;
08097    }
08098    return FALSE;
08099 }
08100 
08101 /*! \brief Change hold state for a call */
08102 static void change_hold_state(struct sip_pvt *dialog, struct sip_request *req, int holdstate, int sendonly)
08103 {
08104    if (sip_cfg.notifyhold && (!holdstate || !ast_test_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD)))
08105       sip_peer_hold(dialog, holdstate);
08106    if (sip_cfg.callevents)
08107       manager_event(EVENT_FLAG_CALL, "Hold",
08108                "Status: %s\r\n"
08109                "Channel: %s\r\n"
08110                "Uniqueid: %s\r\n",
08111                holdstate ? "On" : "Off",
08112                dialog->owner->name,
08113                dialog->owner->uniqueid);
08114    append_history(dialog, holdstate ? "Hold" : "Unhold", "%s", req->data->str);
08115    if (!holdstate) { /* Put off remote hold */
08116       ast_clear_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD);   /* Clear both flags */
08117       return;
08118    }
08119    /* No address for RTP, we're on hold */
08120 
08121    if (sendonly == 1)   /* One directional hold (sendonly/recvonly) */
08122       ast_set_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD_ONEDIR);
08123    else if (sendonly == 2) /* Inactive stream */
08124       ast_set_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD_INACTIVE);
08125    else
08126       ast_set_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD_ACTIVE);
08127    return;
08128 }
08129 
08130 
08131 static int get_ip_and_port_from_sdp(struct sip_request *req, const enum media_type media, struct ast_sockaddr *addr)
08132 {
08133    const char *m;
08134    const char *c;
08135    int miterator = req->sdp_start;
08136    int citerator = req->sdp_start;
08137    int x = 0;
08138    int numberofports;
08139    int len;
08140    int af;
08141    char proto[4], host[258] = ""; /*Initialize to empty so we will know if we have any input */
08142 
08143    c = get_sdp_iterate(&citerator, req, "c");
08144    if (sscanf(c, "IN %3s %256s", proto, host) != 2) {
08145          ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
08146          /* Continue since there may be a valid host in a c= line specific to the audio stream */
08147    }
08148    /* We only want the m and c lines for audio */
08149    for (m = get_sdp_iterate(&miterator, req, "m"); !ast_strlen_zero(m); m = get_sdp_iterate(&miterator, req, "m")) {
08150       if ((media == SDP_AUDIO && ((sscanf(m, "audio %30u/%30u RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
08151           (sscanf(m, "audio %30u RTP/AVP %n", &x, &len) == 1 && len > 0))) ||
08152          (media == SDP_VIDEO && ((sscanf(m, "video %30u/%30u RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
08153           (sscanf(m, "video %30u RTP/AVP %n", &x, &len) == 1 && len > 0)))) {
08154          /* See if there's a c= line for this media stream.
08155           * XXX There is no guarantee that we'll be grabbing the c= line for this
08156           * particular media stream here. However, this is the same logic used in process_sdp.
08157           */
08158          c = get_sdp_iterate(&citerator, req, "c");
08159          if (!ast_strlen_zero(c)) {
08160             sscanf(c, "IN %3s %256s", proto, host);
08161          }
08162          break;
08163       }
08164    }
08165 
08166    if (!strcmp("IP4", proto)) {
08167       af = AF_INET;
08168    } else if (!strcmp("IP6", proto)) {
08169       af = AF_INET6;
08170    } else {
08171       ast_log(LOG_WARNING, "Unknown protocol '%s'.\n", proto);
08172       return -1;
08173    }
08174 
08175    if (ast_strlen_zero(host) || x == 0) {
08176       ast_log(LOG_WARNING, "Failed to read an alternate host or port in SDP. Expect %s problems\n", media == SDP_AUDIO ? "audio" : "video");
08177       return -1;
08178    }
08179 
08180    if (ast_sockaddr_resolve_first_af(addr, host, 0, af)) {
08181       ast_log(LOG_WARNING, "Could not look up IP address of alternate hostname. Expect %s problems\n", media == SDP_AUDIO? "audio" : "video");
08182       return -1;
08183    }
08184 
08185    return 0;
08186 }
08187 
08188 /*! \brief Process SIP SDP offer, select formats and activate RTP channels
08189    If offer is rejected, we will not change any properties of the call
08190    Return 0 on success, a negative value on errors.
08191    Must be called after find_sdp().
08192 */
08193 static int process_sdp(struct sip_pvt *p, struct sip_request *req, int t38action)
08194 {
08195    /* Iterators for SDP parsing */
08196    int start = req->sdp_start;
08197    int next = start;
08198    int iterator = start;
08199 
08200    /* Temporary vars for SDP parsing */
08201    char type = '\0';
08202    const char *value = NULL;
08203    const char *m = NULL;           /* SDP media offer */
08204    const char *nextm = NULL;
08205    int len = -1;
08206 
08207    /* Host information */
08208    struct ast_sockaddr sessionsa;
08209    struct ast_sockaddr audiosa;
08210    struct ast_sockaddr videosa;
08211    struct ast_sockaddr textsa;
08212    struct ast_sockaddr imagesa;
08213    struct ast_sockaddr *sa = NULL;  /*!< RTP Audio host IP */
08214    struct ast_sockaddr *vsa = NULL; /*!< RTP video host IP */
08215    struct ast_sockaddr *tsa = NULL; /*!< RTP text host IP */
08216    struct ast_sockaddr *isa = NULL;     /*!< UDPTL host ip */
08217    int portno = -1;     /*!< RTP Audio port number */
08218    int vportno = -1;    /*!< RTP Video port number */
08219    int tportno = -1;    /*!< RTP Text port number */
08220    int udptlportno = -1;      /*!< UDPTL Image port number */
08221 
08222    /* Peer capability is the capability in the SDP, non codec is RFC2833 DTMF (101) */ 
08223    format_t peercapability = 0, vpeercapability = 0, tpeercapability = 0;
08224    int peernoncodeccapability = 0, vpeernoncodeccapability = 0, tpeernoncodeccapability = 0;
08225 
08226    struct ast_rtp_codecs newaudiortp, newvideortp, newtextrtp;
08227    format_t newjointcapability;           /* Negotiated capability */
08228    format_t newpeercapability;
08229    int newnoncodeccapability;
08230 
08231    const char *codecs;
08232    int codec;
08233 
08234    /* SRTP */
08235    int secure_audio = FALSE;
08236    int secure_video = FALSE;
08237 
08238    /* Others */
08239    int sendonly = -1;
08240    int vsendonly = -1;
08241    int numberofports;
08242    int numberofmediastreams = 0;
08243    int last_rtpmap_codec = 0;
08244    int red_data_pt[10];    /* For T.140 red */
08245    int red_num_gen = 0;    /* For T.140 red */
08246    char red_fmtp[100] = "empty"; /* For T.140 red */
08247    int debug = sip_debug_test_pvt(p);
08248 
08249    /* START UNKNOWN */
08250    char buf[SIPBUFSIZE];
08251    /* END UNKNOWN */
08252 
08253    /* Initial check */
08254    if (!p->rtp) {
08255       ast_log(LOG_ERROR, "Got SDP but have no RTP session allocated.\n");
08256       return -1;
08257    }
08258 
08259    /* Make sure that the codec structures are all cleared out */
08260    ast_rtp_codecs_payloads_clear(&newaudiortp, NULL);
08261    ast_rtp_codecs_payloads_clear(&newvideortp, NULL);
08262    ast_rtp_codecs_payloads_clear(&newtextrtp, NULL);
08263 
08264    /* Update our last rtprx when we receive an SDP, too */
08265    p->lastrtprx = p->lastrtptx = time(NULL); /* XXX why both ? */
08266 
08267    memset(p->offered_media, 0, sizeof(p->offered_media));
08268 
08269 
08270    /* default: novideo and notext set */
08271    p->novideo = TRUE;
08272    p->notext = TRUE;
08273 
08274    if (p->vrtp) {
08275       ast_rtp_codecs_payloads_clear(&newvideortp, NULL);
08276    }
08277 
08278    if (p->trtp) {
08279       ast_rtp_codecs_payloads_clear(&newtextrtp, NULL);
08280    }
08281 
08282    /* Scan for the first media stream (m=) line to limit scanning of globals */
08283    nextm = get_sdp_iterate(&next, req, "m");
08284    if (ast_strlen_zero(nextm)) {
08285       ast_log(LOG_WARNING, "Insufficient information for SDP (m= not found)\n");
08286       return -1;
08287    }
08288 
08289    /* Scan session level SDP parameters (lines before first media stream) */
08290    while ((type = get_sdp_line(&iterator, next - 1, req, &value)) != '\0') {
08291       int processed = FALSE;
08292       switch (type) {
08293       case 'o':
08294          /* If we end up receiving SDP that doesn't actually modify the session we don't want to treat this as a fatal
08295           * error. We just want to ignore the SDP and let the rest of the packet be handled as normal.
08296           */
08297          if (!process_sdp_o(value, p))
08298             return (p->session_modify == FALSE) ? 0 : -1;
08299          break;
08300       case 'c':
08301          if (process_sdp_c(value, &sessionsa)) {
08302             processed = TRUE;
08303             sa = &sessionsa;
08304             vsa = sa;
08305             tsa = sa;
08306             isa = sa;
08307          }
08308          break;
08309       case 'a':
08310          if (process_sdp_a_sendonly(value, &sendonly)) {
08311             processed = TRUE;
08312             vsendonly = sendonly;
08313          }
08314          else if (process_sdp_a_audio(value, p, &newaudiortp, &last_rtpmap_codec))
08315             processed = TRUE;
08316          else if (process_sdp_a_video(value, p, &newvideortp, &last_rtpmap_codec))
08317             processed = TRUE;
08318          else if (process_sdp_a_text(value, p, &newtextrtp, red_fmtp, &red_num_gen, red_data_pt, &last_rtpmap_codec))
08319             processed = TRUE;
08320          else if (process_sdp_a_image(value, p))
08321             processed = TRUE;
08322          break;
08323       }
08324 
08325       ast_debug(3, "Processing session-level SDP %c=%s... %s\n", type, value, (processed == TRUE)? "OK." : "UNSUPPORTED.");
08326    }
08327 
08328 
08329 
08330    /* Scan media stream (m=) specific parameters loop */
08331    while (!ast_strlen_zero(nextm)) {
08332       int audio = FALSE;
08333       int video = FALSE;
08334       int image = FALSE;
08335       int text = FALSE;
08336       char protocol[5] = {0,};
08337       int x;
08338 
08339       numberofports = 1;
08340       len = -1;
08341       start = next;
08342       m = nextm;
08343       iterator = next;
08344       nextm = get_sdp_iterate(&next, req, "m");
08345 
08346       /* Search for audio media definition */
08347       if ((sscanf(m, "audio %30u/%30u RTP/%4s %n", &x, &numberofports, protocol, &len) == 3 && len > 0) ||
08348           (sscanf(m, "audio %30u RTP/%4s %n", &x, protocol, &len) == 2 && len > 0)) {
08349          if (!strcmp(protocol, "SAVP")) {
08350             secure_audio = 1;
08351          } else if (strcmp(protocol, "AVP")) {
08352             ast_log(LOG_WARNING, "unknown SDP media protocol in offer: %s\n", protocol);
08353             continue;
08354          }
08355          audio = TRUE;
08356          p->offered_media[SDP_AUDIO].offered = TRUE;
08357          numberofmediastreams++;
08358          portno = x;
08359 
08360          /* Scan through the RTP payload types specified in a "m=" line: */
08361          codecs = m + len;
08362          ast_copy_string(p->offered_media[SDP_AUDIO].codecs, codecs, sizeof(p->offered_media[SDP_AUDIO].codecs));
08363          for (; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
08364             if (sscanf(codecs, "%30u%n", &codec, &len) != 1) {
08365                ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
08366                return -1;
08367             }
08368             if (debug)
08369                ast_verbose("Found RTP audio format %d\n", codec);
08370             
08371             ast_rtp_codecs_payloads_set_m_type(&newaudiortp, NULL, codec);
08372          }
08373       /* Search for video media definition */
08374       } else if ((sscanf(m, "video %30u/%30u RTP/%4s %n", &x, &numberofports, protocol, &len) == 3 && len > 0) ||
08375             (sscanf(m, "video %30u RTP/%4s %n", &x, protocol, &len) == 2 && len >= 0)) {
08376          if (!strcmp(protocol, "SAVP")) {
08377             secure_video = 1;
08378          } else if (strcmp(protocol, "AVP")) {
08379             ast_log(LOG_WARNING, "unknown SDP media protocol in offer: %s\n", protocol);
08380             continue;
08381          }
08382          video = TRUE;
08383          p->novideo = FALSE;
08384          p->offered_media[SDP_VIDEO].offered = TRUE;
08385          numberofmediastreams++;
08386          vportno = x;
08387 
08388          /* Scan through the RTP payload types specified in a "m=" line: */
08389          codecs = m + len;
08390          ast_copy_string(p->offered_media[SDP_VIDEO].codecs, codecs, sizeof(p->offered_media[SDP_VIDEO].codecs));
08391          for (; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
08392             if (sscanf(codecs, "%30u%n", &codec, &len) != 1) {
08393                ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
08394                return -1;
08395             }
08396             if (debug)
08397                ast_verbose("Found RTP video format %d\n", codec);
08398             ast_rtp_codecs_payloads_set_m_type(&newvideortp, NULL, codec);
08399          }
08400       /* Search for text media definition */
08401       } else if ((sscanf(m, "text %30u/%30u RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
08402             (sscanf(m, "text %30u RTP/AVP %n", &x, &len) == 1 && len > 0)) {
08403          text = TRUE;
08404          p->notext = FALSE;
08405          p->offered_media[SDP_TEXT].offered = TRUE;
08406          numberofmediastreams++;
08407          tportno = x;
08408 
08409          /* Scan through the RTP payload types specified in a "m=" line: */
08410          codecs = m + len;
08411          ast_copy_string(p->offered_media[SDP_TEXT].codecs, codecs, sizeof(p->offered_media[SDP_TEXT].codecs));
08412          for (; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
08413             if (sscanf(codecs, "%30u%n", &codec, &len) != 1) {
08414                ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
08415                return -1;
08416             }
08417             if (debug)
08418                ast_verbose("Found RTP text format %d\n", codec);
08419             ast_rtp_codecs_payloads_set_m_type(&newtextrtp, NULL, codec);
08420          }
08421       /* Search for image media definition */
08422       } else if (p->udptl && ((sscanf(m, "image %30u udptl t38%n", &x, &len) == 1 && len > 0) ||
08423                (sscanf(m, "image %30u UDPTL t38%n", &x, &len) == 1 && len > 0) )) {
08424          image = TRUE;
08425          if (debug)
08426             ast_verbose("Got T.38 offer in SDP in dialog %s\n", p->callid);
08427          p->offered_media[SDP_IMAGE].offered = TRUE;
08428          udptlportno = x;
08429          numberofmediastreams++;
08430 
08431          if (p->t38.state != T38_ENABLED) {
08432             memset(&p->t38.their_parms, 0, sizeof(p->t38.their_parms));
08433 
08434             /* default EC to none, the remote end should
08435              * respond with the EC they want to use */
08436             ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_NONE);
08437          }
08438       } else {
08439          ast_log(LOG_WARNING, "Unsupported SDP media type in offer: %s\n", m);
08440          continue;
08441       }
08442 
08443       /* Check for number of ports */
08444       if (numberofports > 1)
08445          ast_log(LOG_WARNING, "SDP offered %d ports for media, not supported by Asterisk. Will try anyway...\n", numberofports);
08446       
08447       /* Media stream specific parameters */
08448       while ((type = get_sdp_line(&iterator, next - 1, req, &value)) != '\0') {
08449          int processed = FALSE;
08450 
08451          switch (type) {
08452          case 'c':
08453             if (audio) {
08454                if (process_sdp_c(value, &audiosa)) {
08455                   processed = TRUE;
08456                   sa = &audiosa;
08457                }
08458             } else if (video) {
08459                if (process_sdp_c(value, &videosa)) {
08460                   processed = TRUE;
08461                   vsa = &videosa;
08462                }
08463             } else if (text) {
08464                if (process_sdp_c(value, &textsa)) {
08465                   processed = TRUE;
08466                   tsa = &textsa;
08467                }
08468             } else if (image) {
08469                if (process_sdp_c(value, &imagesa)) {
08470                   processed = TRUE;
08471                   isa = &imagesa;
08472                }
08473             }
08474             break;
08475          case 'a':
08476             /* Audio specific scanning */
08477             if (audio) {
08478                if (process_sdp_a_sendonly(value, &sendonly))
08479                   processed = TRUE;
08480                else if (process_crypto(p, p->rtp, &p->srtp, value))
08481                   processed = TRUE;
08482                else if (process_sdp_a_audio(value, p, &newaudiortp, &last_rtpmap_codec))
08483                   processed = TRUE;
08484             }
08485             /* Video specific scanning */
08486             else if (video) {
08487                if (process_sdp_a_sendonly(value, &vsendonly))
08488                   processed = TRUE;
08489                else if (process_crypto(p, p->vrtp, &p->vsrtp, value))
08490                   processed = TRUE;
08491                else if (process_sdp_a_video(value, p, &newvideortp, &last_rtpmap_codec))
08492                   processed = TRUE;
08493             }
08494             /* Text (T.140) specific scanning */
08495             else if (text) {
08496                if (process_sdp_a_text(value, p, &newtextrtp, red_fmtp, &red_num_gen, red_data_pt, &last_rtpmap_codec))
08497                   processed = TRUE;
08498                else if (process_crypto(p, p->trtp, &p->tsrtp, value))
08499                   processed = TRUE;
08500             }
08501             /* Image (T.38 FAX) specific scanning */
08502             else if (image) {
08503                if (process_sdp_a_image(value, p))
08504                   processed = TRUE;
08505             }
08506             break;
08507          }
08508 
08509          ast_debug(3, "Processing media-level (%s) SDP %c=%s... %s\n",
08510                (audio == TRUE)? "audio" : (video == TRUE)? "video" : "image",
08511                type, value,
08512                (processed == TRUE)? "OK." : "UNSUPPORTED.");
08513       }
08514    }
08515 
08516 
08517    /* Sanity checks */
08518    if (!sa && !vsa && !tsa && !isa) {
08519       ast_log(LOG_WARNING, "Insufficient information in SDP (c=)...\n");
08520       return -1;
08521    }
08522 
08523    if (portno == -1 && vportno == -1 && udptlportno == -1  && tportno == -1) {
08524       /* No acceptable offer found in SDP  - we have no ports */
08525       /* Do not change RTP or VRTP if this is a re-invite */
08526       ast_log(LOG_WARNING, "Failing due to no acceptable offer found\n");
08527       return -2;
08528    }
08529 
08530    if (numberofmediastreams > 3) {
08531       /* We have too many fax, audio and/or video and/or text media streams, fail this offer */
08532       ast_log(LOG_WARNING, "Faling due to too many media streams\n");
08533       return -3;
08534    }
08535 
08536    if (secure_audio && !(p->srtp && (ast_test_flag(p->srtp, SRTP_CRYPTO_OFFER_OK)))) {
08537       ast_log(LOG_WARNING, "Can't provide secure audio requested in SDP offer\n");
08538       return -4;
08539    }
08540 
08541    if (!secure_audio && p->srtp) {
08542       ast_log(LOG_WARNING, "We are requesting SRTP, but they responded without it!\n");
08543       return -4;
08544    }
08545 
08546    if (secure_video && !(p->vsrtp && (ast_test_flag(p->vsrtp, SRTP_CRYPTO_OFFER_OK)))) {
08547       ast_log(LOG_WARNING, "Can't provide secure video requested in SDP offer\n");
08548       return -4;
08549    }
08550 
08551    if (!p->novideo && !secure_video && p->vsrtp) {
08552       ast_log(LOG_WARNING, "We are requesting SRTP, but they responded without it!\n");
08553       return -4;
08554    }
08555 
08556    if (!(secure_audio || secure_video) && ast_test_flag(&p->flags[1], SIP_PAGE2_USE_SRTP)) {
08557       ast_log(LOG_WARNING, "Matched device setup to use SRTP, but request was not!\n");
08558       return -4;
08559    }
08560 
08561    if (udptlportno == -1) {
08562       change_t38_state(p, T38_DISABLED);
08563    }
08564 
08565    /* Now gather all of the codecs that we are asked for: */
08566    ast_rtp_codecs_payload_formats(&newaudiortp, &peercapability, &peernoncodeccapability);
08567    ast_rtp_codecs_payload_formats(&newvideortp, &vpeercapability, &vpeernoncodeccapability);
08568    ast_rtp_codecs_payload_formats(&newtextrtp, &tpeercapability, &tpeernoncodeccapability);
08569 
08570    newjointcapability = p->capability & (peercapability | vpeercapability | tpeercapability);
08571    newpeercapability = (peercapability | vpeercapability | tpeercapability);
08572    newnoncodeccapability = p->noncodeccapability & peernoncodeccapability;
08573 
08574    if (debug) {
08575       /* shame on whoever coded this.... */
08576       char s1[SIPBUFSIZE], s2[SIPBUFSIZE], s3[SIPBUFSIZE], s4[SIPBUFSIZE], s5[SIPBUFSIZE];
08577 
08578       ast_verbose("Capabilities: us - %s, peer - audio=%s/video=%s/text=%s, combined - %s\n",
08579              ast_getformatname_multiple(s1, SIPBUFSIZE, p->capability),
08580              ast_getformatname_multiple(s2, SIPBUFSIZE, peercapability),
08581              ast_getformatname_multiple(s3, SIPBUFSIZE, vpeercapability),
08582              ast_getformatname_multiple(s4, SIPBUFSIZE, tpeercapability),
08583              ast_getformatname_multiple(s5, SIPBUFSIZE, newjointcapability));
08584    }
08585    if (debug) {
08586       struct ast_str *s1 = ast_str_alloca(SIPBUFSIZE);
08587       struct ast_str *s2 = ast_str_alloca(SIPBUFSIZE);
08588       struct ast_str *s3 = ast_str_alloca(SIPBUFSIZE);
08589 
08590       ast_verbose("Non-codec capabilities (dtmf): us - %s, peer - %s, combined - %s\n",
08591              ast_rtp_lookup_mime_multiple2(s1, p->noncodeccapability, 0, 0),
08592              ast_rtp_lookup_mime_multiple2(s2, peernoncodeccapability, 0, 0),
08593              ast_rtp_lookup_mime_multiple2(s3, newnoncodeccapability, 0, 0));
08594    }
08595    if (!newjointcapability && (portno != -1)) {
08596       ast_log(LOG_NOTICE, "No compatible codecs, not accepting this offer!\n");
08597       /* Do NOT Change current setting */
08598       return -1;
08599    }
08600 
08601    /* Setup audio address and port */
08602    if (p->rtp) {
08603       if (portno > 0) {
08604          ast_sockaddr_set_port(sa, portno);
08605          ast_rtp_instance_set_remote_address(p->rtp, sa);
08606          if (debug) {
08607             ast_verbose("Peer audio RTP is at port %s\n",
08608                    ast_sockaddr_stringify(sa));
08609          }
08610          /* We are now ready to change the sip session and p->rtp and p->vrtp with the offered codecs, since
08611             they are acceptable */
08612          p->jointcapability = newjointcapability;                /* Our joint codec profile for this call */
08613          p->peercapability = newpeercapability;                  /* The other sides capability in latest offer */
08614          p->jointnoncodeccapability = newnoncodeccapability;     /* DTMF capabilities */
08615 
08616          if (ast_test_flag(&p->flags[1], SIP_PAGE2_PREFERRED_CODEC)) { /* respond with single most preferred joint codec, limiting the other side's choice */
08617             p->jointcapability = ast_codec_choose(&p->prefs, p->jointcapability, 1);
08618          }
08619 
08620          ast_rtp_codecs_payloads_copy(&newaudiortp, ast_rtp_instance_get_codecs(p->rtp), p->rtp);
08621 
08622          if (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO) {
08623             ast_clear_flag(&p->flags[0], SIP_DTMF);
08624             if (newnoncodeccapability & AST_RTP_DTMF) {
08625                /* XXX Would it be reasonable to drop the DSP at this point? XXX */
08626                ast_set_flag(&p->flags[0], SIP_DTMF_RFC2833);
08627                /* Since RFC2833 is now negotiated we need to change some properties of the RTP stream */
08628                ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_DTMF, 1);
08629                ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_DTMF_COMPENSATE, ast_test_flag(&p->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
08630             } else {
08631                ast_set_flag(&p->flags[0], SIP_DTMF_INBAND);
08632             }
08633          }
08634       } else if (udptlportno > 0) {
08635          if (debug)
08636             ast_verbose("Got T.38 Re-invite without audio. Keeping RTP active during T.38 session.\n");
08637       } else {
08638          ast_rtp_instance_stop(p->rtp);
08639          if (debug)
08640             ast_verbose("Peer doesn't provide audio\n");
08641       }
08642    }
08643 
08644    /* Setup video address and port */
08645    if (p->vrtp) {
08646       if (vportno > 0) {
08647          ast_sockaddr_set_port(vsa, vportno);
08648          ast_rtp_instance_set_remote_address(p->vrtp, vsa);
08649          if (debug) {
08650             ast_verbose("Peer video RTP is at port %s\n",
08651                    ast_sockaddr_stringify(vsa));
08652          }
08653          ast_rtp_codecs_payloads_copy(&newvideortp, ast_rtp_instance_get_codecs(p->vrtp), p->vrtp);
08654       } else {
08655          ast_rtp_instance_stop(p->vrtp);
08656          if (debug)
08657             ast_verbose("Peer doesn't provide video\n");
08658       }
08659    }
08660 
08661    /* Setup text address and port */
08662    if (p->trtp) {
08663       if (tportno > 0) {
08664          ast_sockaddr_set_port(tsa, tportno);
08665          ast_rtp_instance_set_remote_address(p->trtp, tsa);
08666          if (debug) {
08667             ast_verbose("Peer T.140 RTP is at port %s\n",
08668                    ast_sockaddr_stringify(tsa));
08669          }
08670          if ((p->jointcapability & AST_FORMAT_T140RED)) {
08671             p->red = 1;
08672             ast_rtp_red_init(p->trtp, 300, red_data_pt, 2);
08673          } else {
08674             p->red = 0;
08675          }
08676          ast_rtp_codecs_payloads_copy(&newtextrtp, ast_rtp_instance_get_codecs(p->trtp), p->trtp);
08677       } else {
08678          ast_rtp_instance_stop(p->trtp);
08679          if (debug)
08680             ast_verbose("Peer doesn't provide T.140\n");
08681       }
08682    }
08683    /* Setup image address and port */
08684    if (p->udptl) {
08685       if (udptlportno > 0) {
08686          if (ast_test_flag(&p->flags[1], SIP_PAGE2_SYMMETRICRTP) && ast_test_flag(&p->flags[1], SIP_PAGE2_UDPTL_DESTINATION)) {
08687             ast_rtp_instance_get_remote_address(p->rtp, isa);
08688             if (!ast_sockaddr_isnull(isa) && debug) {
08689                ast_debug(1, "Peer T.38 UDPTL is set behind NAT and with destination, destination address now %s\n", ast_sockaddr_stringify(isa));
08690             }
08691          }
08692          ast_sockaddr_set_port(isa, udptlportno);
08693          ast_udptl_set_peer(p->udptl, isa);
08694          if (debug)
08695             ast_debug(1,"Peer T.38 UDPTL is at port %s\n", ast_sockaddr_stringify(isa));
08696 
08697          /* verify the far max ifp can be calculated. this requires far max datagram to be set. */
08698          if (!ast_udptl_get_far_max_datagram(p->udptl)) {
08699             /* setting to zero will force a default if none was provided by the SDP */
08700             ast_udptl_set_far_max_datagram(p->udptl, 0);
08701          }
08702 
08703          /* Remote party offers T38, we need to update state */
08704          if ((t38action == SDP_T38_ACCEPT) &&
08705              (p->t38.state == T38_LOCAL_REINVITE)) {
08706             change_t38_state(p, T38_ENABLED);
08707          } else if ((t38action == SDP_T38_INITIATE) &&
08708                p->owner && p->lastinvite) {
08709             change_t38_state(p, T38_PEER_REINVITE); /* T38 Offered in re-invite from remote party */
08710             /* If fax detection is enabled then send us off to the fax extension */
08711             if (ast_test_flag(&p->flags[1], SIP_PAGE2_FAX_DETECT_T38)) {
08712                ast_channel_lock(p->owner);
08713                if (strcmp(p->owner->exten, "fax")) {
08714                   const char *target_context = S_OR(p->owner->macrocontext, p->owner->context);
08715                   ast_channel_unlock(p->owner);
08716                   if (ast_exists_extension(p->owner, target_context, "fax", 1,
08717                      S_COR(p->owner->caller.id.number.valid, p->owner->caller.id.number.str, NULL))) {
08718                      ast_verbose(VERBOSE_PREFIX_2 "Redirecting '%s' to fax extension due to peer T.38 re-INVITE\n", p->owner->name);
08719                      pbx_builtin_setvar_helper(p->owner, "FAXEXTEN", p->owner->exten);
08720                      if (ast_async_goto(p->owner, target_context, "fax", 1)) {
08721                         ast_log(LOG_NOTICE, "Failed to async goto '%s' into fax of '%s'\n", p->owner->name, target_context);
08722                      }
08723                   } else {
08724                      ast_log(LOG_NOTICE, "T.38 re-INVITE detected but no fax extension\n");
08725                   }
08726                } else {
08727                   ast_channel_unlock(p->owner);
08728                }
08729             }
08730          }
08731       } else {
08732          ast_udptl_stop(p->udptl);
08733          if (debug)
08734             ast_debug(1, "Peer doesn't provide T.38 UDPTL\n");
08735       }
08736    }
08737 
08738    if ((portno == -1) && (p->t38.state != T38_DISABLED)) {
08739       ast_debug(3, "Have T.38 but no audio, accepting offer anyway\n");
08740       return 0;
08741         }
08742 
08743    /* Ok, we're going with this offer */
08744    ast_debug(2, "We're settling with these formats: %s\n", ast_getformatname_multiple(buf, SIPBUFSIZE, p->jointcapability));
08745 
08746    if (!p->owner)    /* There's no open channel owning us so we can return here. For a re-invite or so, we proceed */
08747       return 0;
08748 
08749    ast_debug(4, "We have an owner, now see if we need to change this call\n");
08750 
08751    if (!(p->owner->nativeformats & p->jointcapability) && (p->jointcapability & AST_FORMAT_AUDIO_MASK)) {
08752       if (debug) {
08753          char s1[SIPBUFSIZE], s2[SIPBUFSIZE];
08754          ast_debug(1, "Oooh, we need to change our audio formats since our peer supports only %s and not %s\n",
08755             ast_getformatname_multiple(s1, SIPBUFSIZE, p->jointcapability),
08756             ast_getformatname_multiple(s2, SIPBUFSIZE, p->owner->nativeformats));
08757       }
08758       p->owner->nativeformats = ast_codec_choose(&p->prefs, p->jointcapability, 1) | (p->capability & vpeercapability) | (p->capability & tpeercapability);
08759       ast_set_read_format(p->owner, p->owner->readformat);
08760       ast_set_write_format(p->owner, p->owner->writeformat);
08761    }
08762    
08763    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)) {
08764       ast_queue_control(p->owner, AST_CONTROL_UNHOLD);
08765       /* Activate a re-invite */
08766       ast_queue_frame(p->owner, &ast_null_frame);
08767       change_hold_state(p, req, FALSE, sendonly);
08768    } else if ((ast_sockaddr_isnull(sa) && ast_sockaddr_isnull(vsa) && ast_sockaddr_isnull(tsa) && ast_sockaddr_isnull(isa)) || (sendonly && sendonly != -1)) {
08769       ast_queue_control_data(p->owner, AST_CONTROL_HOLD,
08770                    S_OR(p->mohsuggest, NULL),
08771                    !ast_strlen_zero(p->mohsuggest) ? strlen(p->mohsuggest) + 1 : 0);
08772       if (sendonly)
08773          ast_rtp_instance_stop(p->rtp);
08774       /* RTCP needs to go ahead, even if we're on hold!!! */
08775       /* Activate a re-invite */
08776       ast_queue_frame(p->owner, &ast_null_frame);
08777       change_hold_state(p, req, TRUE, sendonly);
08778    }
08779    
08780    return 0;
08781 }
08782 
08783 static int process_sdp_o(const char *o, struct sip_pvt *p)
08784 {
08785    char *o_copy;
08786    char *token;
08787    int64_t rua_version;
08788 
08789    /* Store the SDP version number of remote UA. This will allow us to
08790    distinguish between session modifications and session refreshes. If
08791    the remote UA does not send an incremented SDP version number in a
08792    subsequent RE-INVITE then that means its not changing media session.
08793    The RE-INVITE may have been sent to update connected party, remote
08794    target or to refresh the session (Session-Timers).  Asterisk must not
08795    change media session and increment its own version number in answer
08796    SDP in this case. */
08797 
08798    p->session_modify = TRUE;
08799 
08800    if (ast_strlen_zero(o)) {
08801       ast_log(LOG_WARNING, "SDP syntax error. SDP without an o= line\n");
08802       return FALSE;
08803    }
08804 
08805    o_copy = ast_strdupa(o);
08806    token = strsep(&o_copy, " ");  /* Skip username   */
08807    if (!o_copy) {
08808       ast_log(LOG_WARNING, "SDP syntax error in o= line username\n");
08809       return FALSE;
08810    }
08811    token = strsep(&o_copy, " ");  /* Skip session-id */
08812    if (!o_copy) {
08813       ast_log(LOG_WARNING, "SDP syntax error in o= line session-id\n");
08814       return FALSE;
08815    }
08816    token = strsep(&o_copy, " ");  /* Version         */
08817    if (!o_copy) {
08818       ast_log(LOG_WARNING, "SDP syntax error in o= line\n");
08819       return FALSE;
08820    }
08821    if (!sscanf(token, "%30" SCNd64, &rua_version)) {
08822       ast_log(LOG_WARNING, "SDP syntax error in o= line version\n");
08823       return FALSE;
08824    }
08825 
08826    /* we need to check the SDP version number the other end sent us;
08827     * our rules for deciding what to accept are a bit complex.
08828     *
08829     * 1) if 'ignoresdpversion' has been set for this dialog, then
08830     *    we will just accept whatever they sent and assume it is
08831     *    a modification of the session, even if it is not
08832     * 2) otherwise, if this is the first SDP we've seen from them
08833     *    we accept it
08834     * 3) otherwise, if the new SDP version number is higher than the
08835     *    old one, we accept it
08836     * 4) otherwise, if this SDP is in response to us requesting a switch
08837     *    to T.38, we accept the SDP, but also generate a warning message
08838     *    that this peer should have the 'ignoresdpversion' option set,
08839     *    because it is not following the SDP offer/answer RFC; if we did
08840     *    not request a switch to T.38, then we stop parsing the SDP, as it
08841     *    has not changed from the previous version
08842     */
08843 
08844    if (ast_test_flag(&p->flags[1], SIP_PAGE2_IGNORESDPVERSION) ||
08845        (p->sessionversion_remote < 0) ||
08846        (p->sessionversion_remote < rua_version)) {
08847       p->sessionversion_remote = rua_version;
08848    } else {
08849       if (p->t38.state == T38_LOCAL_REINVITE) {
08850          p->sessionversion_remote = rua_version;
08851          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);
08852       } else {
08853          p->session_modify = FALSE;
08854          ast_debug(2, "Call %s responded to our reinvite without changing SDP version; ignoring SDP.\n", p->callid);
08855          return FALSE;
08856       }
08857    }
08858 
08859    return TRUE;
08860 }
08861 
08862 static int process_sdp_c(const char *c, struct ast_sockaddr *addr)
08863 {
08864    char proto[4], host[258];
08865    int af;
08866 
08867    /* Check for Media-description-level-address */
08868    if (sscanf(c, "IN %3s %255s", proto, host) == 2) {
08869       if (!strcmp("IP4", proto)) {
08870          af = AF_INET;
08871       } else if (!strcmp("IP6", proto)) {
08872          af = AF_INET6;
08873       } else {
08874          ast_log(LOG_WARNING, "Unknown protocol '%s'.\n", proto);
08875          return FALSE;
08876       }
08877       if (ast_sockaddr_resolve_first_af(addr, host, 0, af)) {
08878          ast_log(LOG_WARNING, "Unable to lookup RTP Audio host in c= line, '%s'\n", c);
08879          return FALSE;
08880       }
08881       return TRUE;
08882    } else {
08883       ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
08884       return FALSE;
08885    }
08886    return FALSE;
08887 }
08888 
08889 static int process_sdp_a_sendonly(const char *a, int *sendonly)
08890 {
08891    int found = FALSE;
08892 
08893    if (!strcasecmp(a, "sendonly")) {
08894       if (*sendonly == -1)
08895          *sendonly = 1;
08896       found = TRUE;
08897    } else if (!strcasecmp(a, "inactive")) {
08898       if (*sendonly == -1)
08899          *sendonly = 2;
08900       found = TRUE;
08901    }  else if (!strcasecmp(a, "sendrecv")) {
08902       if (*sendonly == -1)
08903          *sendonly = 0;
08904       found = TRUE;
08905    }
08906    return found;
08907 }
08908 
08909 static int process_sdp_a_audio(const char *a, struct sip_pvt *p, struct ast_rtp_codecs *newaudiortp, int *last_rtpmap_codec)
08910 {
08911    int found = FALSE;
08912    int codec;
08913    char mimeSubtype[128];
08914    char fmtp_string[64];
08915    unsigned int sample_rate;
08916    int debug = sip_debug_test_pvt(p);
08917 
08918    if (!strncasecmp(a, "ptime", 5)) {
08919       char *tmp = strrchr(a, ':');
08920       long int framing = 0;
08921       if (tmp) {
08922          tmp++;
08923          framing = strtol(tmp, NULL, 10);
08924          if (framing == LONG_MIN || framing == LONG_MAX) {
08925             framing = 0;
08926             ast_debug(1, "Can't read framing from SDP: %s\n", a);
08927          }
08928       }
08929       if (framing && p->autoframing) {
08930          struct ast_codec_pref *pref = &ast_rtp_instance_get_codecs(p->rtp)->pref;
08931          int codec_n;
08932          for (codec_n = 0; codec_n < AST_RTP_MAX_PT; codec_n++) {
08933             struct ast_rtp_payload_type format = ast_rtp_codecs_payload_lookup(ast_rtp_instance_get_codecs(p->rtp), codec_n);
08934             if (!format.asterisk_format || !format.code) /* non-codec or not found */
08935                continue;
08936             ast_debug(1, "Setting framing for %s to %ld\n", ast_getformatname(format.code), framing);
08937             ast_codec_pref_setsize(pref, format.code, framing);
08938          }
08939          ast_rtp_codecs_packetization_set(ast_rtp_instance_get_codecs(p->rtp), p->rtp, pref);
08940       }
08941       found = TRUE;
08942    } else if (sscanf(a, "rtpmap: %30u %127[^/]/%30u", &codec, mimeSubtype, &sample_rate) == 3) {
08943       /* We have a rtpmap to handle */
08944       if (*last_rtpmap_codec < SDP_MAX_RTPMAP_CODECS) {
08945          if (ast_rtp_codecs_payloads_set_rtpmap_type_rate(newaudiortp, NULL, codec, "audio", mimeSubtype,
08946              ast_test_flag(&p->flags[0], SIP_G726_NONSTANDARD) ? AST_RTP_OPT_G726_NONSTANDARD : 0, sample_rate) != -1) {
08947             if (debug)
08948                ast_verbose("Found audio description format %s for ID %d\n", mimeSubtype, codec);
08949             //found_rtpmap_codecs[last_rtpmap_codec] = codec;
08950             (*last_rtpmap_codec)++;
08951             found = TRUE;
08952          } else {
08953             ast_rtp_codecs_payloads_unset(newaudiortp, NULL, codec);
08954             if (debug)
08955                ast_verbose("Found unknown media description format %s for ID %d\n", mimeSubtype, codec);
08956          }
08957       } else {
08958          if (debug)
08959             ast_verbose("Discarded description format %s for ID %d\n", mimeSubtype, codec);
08960       }
08961    } else if (sscanf(a, "fmtp: %30u %63s", &codec, fmtp_string) == 2) {
08962       struct ast_rtp_payload_type payload;
08963 
08964       payload = ast_rtp_codecs_payload_lookup(newaudiortp, codec);
08965       if (payload.code && payload.asterisk_format) {
08966          unsigned int bit_rate;
08967 
08968          switch (payload.code) {
08969          case AST_FORMAT_SIREN7:
08970             if (sscanf(fmtp_string, "bitrate=%30u", &bit_rate) == 1) {
08971                if (bit_rate != 32000) {
08972                   ast_log(LOG_WARNING, "Got Siren7 offer at %d bps, but only 32000 bps supported; ignoring.\n", bit_rate);
08973                   ast_rtp_codecs_payloads_unset(newaudiortp, NULL, codec);
08974                } else {
08975                   found = TRUE;
08976                }
08977             }
08978             break;
08979          case AST_FORMAT_SIREN14:
08980             if (sscanf(fmtp_string, "bitrate=%30u", &bit_rate) == 1) {
08981                if (bit_rate != 48000) {
08982                   ast_log(LOG_WARNING, "Got Siren14 offer at %d bps, but only 48000 bps supported; ignoring.\n", bit_rate);
08983                   ast_rtp_codecs_payloads_unset(newaudiortp, NULL, codec);
08984                } else {
08985                   found = TRUE;
08986                }
08987             }
08988             break;
08989          case AST_FORMAT_G719:
08990             if (sscanf(fmtp_string, "bitrate=%30u", &bit_rate) == 1) {
08991                if (bit_rate != 64000) {
08992                   ast_log(LOG_WARNING, "Got G.719 offer at %d bps, but only 64000 bps supported; ignoring.\n", bit_rate);
08993                   ast_rtp_codecs_payloads_unset(newaudiortp, NULL, codec);
08994                } else {
08995                   found = TRUE;
08996                }
08997             }
08998          }
08999       }
09000    }
09001 
09002    return found;
09003 }
09004 
09005 static int process_sdp_a_video(const char *a, struct sip_pvt *p, struct ast_rtp_codecs *newvideortp, int *last_rtpmap_codec)
09006 {
09007    int found = FALSE;
09008    int codec;
09009    char mimeSubtype[128];
09010    unsigned int sample_rate;
09011    int debug = sip_debug_test_pvt(p);
09012 
09013    if (sscanf(a, "rtpmap: %30u %127[^/]/%30u", &codec, mimeSubtype, &sample_rate) == 3) {
09014       /* We have a rtpmap to handle */
09015       if (*last_rtpmap_codec < SDP_MAX_RTPMAP_CODECS) {
09016          /* Note: should really look at the '#chans' params too */
09017          if (!strncasecmp(mimeSubtype, "H26", 3) || !strncasecmp(mimeSubtype, "MP4", 3)) {
09018             if (ast_rtp_codecs_payloads_set_rtpmap_type_rate(newvideortp, NULL, codec, "video", mimeSubtype, 0, sample_rate) != -1) {
09019                if (debug)
09020                   ast_verbose("Found video description format %s for ID %d\n", mimeSubtype, codec);
09021                //found_rtpmap_codecs[last_rtpmap_codec] = codec;
09022                (*last_rtpmap_codec)++;
09023                found = TRUE;
09024             } else {
09025                ast_rtp_codecs_payloads_unset(newvideortp, NULL, codec);
09026                if (debug)
09027                   ast_verbose("Found unknown media description format %s for ID %d\n", mimeSubtype, codec);
09028             }
09029          }
09030       } else {
09031          if (debug)
09032             ast_verbose("Discarded description format %s for ID %d\n", mimeSubtype, codec);
09033       }
09034    }
09035 
09036    return found;
09037 }
09038 
09039 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)
09040 {
09041    int found = FALSE;
09042    int codec;
09043    char mimeSubtype[128];
09044    unsigned int sample_rate;
09045    char *red_cp;
09046    int debug = sip_debug_test_pvt(p);
09047 
09048    if (sscanf(a, "rtpmap: %30u %127[^/]/%30u", &codec, mimeSubtype, &sample_rate) == 3) {
09049       /* We have a rtpmap to handle */
09050       if (*last_rtpmap_codec < SDP_MAX_RTPMAP_CODECS) {
09051          if (!strncasecmp(mimeSubtype, "T140", 4)) { /* Text */
09052             if (p->trtp) {
09053                /* ast_verbose("Adding t140 mimeSubtype to textrtp struct\n"); */
09054                ast_rtp_codecs_payloads_set_rtpmap_type_rate(newtextrtp, NULL, codec, "text", mimeSubtype, 0, sample_rate);
09055                found = TRUE;
09056             }
09057          } else if (!strncasecmp(mimeSubtype, "RED", 3)) { /* Text with Redudancy */
09058             if (p->trtp) {
09059                ast_rtp_codecs_payloads_set_rtpmap_type_rate(newtextrtp, NULL, codec, "text", mimeSubtype, 0, sample_rate);
09060                sprintf(red_fmtp, "fmtp:%d ", codec);
09061                if (debug)
09062                   ast_verbose("RED submimetype has payload type: %d\n", codec);
09063                found = TRUE;
09064             }
09065          }
09066       } else {
09067          if (debug)
09068             ast_verbose("Discarded description format %s for ID %d\n", mimeSubtype, codec);
09069       }
09070    } else if (!strncmp(a, red_fmtp, strlen(red_fmtp))) {
09071       /* count numbers of generations in fmtp */
09072       red_cp = &red_fmtp[strlen(red_fmtp)];
09073       strncpy(red_fmtp, a, 100);
09074 
09075       sscanf(red_cp, "%30u", &red_data_pt[*red_num_gen]);
09076       red_cp = strtok(red_cp, "/");
09077       while (red_cp && (*red_num_gen)++ < AST_RED_MAX_GENERATION) {
09078          sscanf(red_cp, "%30u", &red_data_pt[*red_num_gen]);
09079          red_cp = strtok(NULL, "/");
09080       }
09081       red_cp = red_fmtp;
09082       found = TRUE;
09083    }
09084 
09085    return found;
09086 }
09087 
09088 static int process_sdp_a_image(const char *a, struct sip_pvt *p)
09089 {
09090    int found = FALSE;
09091    char s[256];
09092    unsigned int x;
09093 
09094    if ((sscanf(a, "T38FaxMaxBuffer:%30u", &x) == 1)) {
09095       ast_debug(3, "MaxBufferSize:%d\n", x);
09096       found = TRUE;
09097    } else if ((sscanf(a, "T38MaxBitRate:%30u", &x) == 1) || (sscanf(a, "T38FaxMaxRate:%30u", &x) == 1)) {
09098       ast_debug(3, "T38MaxBitRate: %d\n", x);
09099       switch (x) {
09100       case 14400:
09101          p->t38.their_parms.rate = AST_T38_RATE_14400;
09102          break;
09103       case 12000:
09104          p->t38.their_parms.rate = AST_T38_RATE_12000;
09105          break;
09106       case 9600:
09107          p->t38.their_parms.rate = AST_T38_RATE_9600;
09108          break;
09109       case 7200:
09110          p->t38.their_parms.rate = AST_T38_RATE_7200;
09111          break;
09112       case 4800:
09113          p->t38.their_parms.rate = AST_T38_RATE_4800;
09114          break;
09115       case 2400:
09116          p->t38.their_parms.rate = AST_T38_RATE_2400;
09117          break;
09118       }
09119       found = TRUE;
09120    } else if ((sscanf(a, "T38FaxVersion:%30u", &x) == 1)) {
09121       ast_debug(3, "FaxVersion: %u\n", x);
09122       p->t38.their_parms.version = x;
09123       found = TRUE;
09124    } else if ((sscanf(a, "T38FaxMaxDatagram:%30u", &x) == 1) || (sscanf(a, "T38MaxDatagram:%30u", &x) == 1)) {
09125       /* override the supplied value if the configuration requests it */
09126       if (((signed int) p->t38_maxdatagram >= 0) && ((unsigned int) p->t38_maxdatagram > x)) {
09127          ast_debug(1, "Overriding T38FaxMaxDatagram '%d' with '%d'\n", x, p->t38_maxdatagram);
09128          x = p->t38_maxdatagram;
09129       }
09130       ast_debug(3, "FaxMaxDatagram: %u\n", x);
09131       ast_udptl_set_far_max_datagram(p->udptl, x);
09132       found = TRUE;
09133    } else if ((strncmp(a, "T38FaxFillBitRemoval", 20) == 0)) {
09134       if (sscanf(a, "T38FaxFillBitRemoval:%30u", &x) == 1) {
09135          ast_debug(3, "FillBitRemoval: %d\n", x);
09136          if (x == 1) {
09137             p->t38.their_parms.fill_bit_removal = TRUE;
09138          }
09139       } else {
09140          ast_debug(3, "FillBitRemoval\n");
09141          p->t38.their_parms.fill_bit_removal = TRUE;
09142       }
09143       found = TRUE;
09144    } else if ((strncmp(a, "T38FaxTranscodingMMR", 20) == 0)) {
09145       if (sscanf(a, "T38FaxTranscodingMMR:%30u", &x) == 1) {
09146          ast_debug(3, "Transcoding MMR: %d\n", x);
09147          if (x == 1) {
09148             p->t38.their_parms.transcoding_mmr = TRUE;
09149          }
09150       } else {
09151          ast_debug(3, "Transcoding MMR\n");
09152          p->t38.their_parms.transcoding_mmr = TRUE;
09153       }
09154       found = TRUE;
09155    } else if ((strncmp(a, "T38FaxTranscodingJBIG", 21) == 0)) {
09156       if (sscanf(a, "T38FaxTranscodingJBIG:%30u", &x) == 1) {
09157          ast_debug(3, "Transcoding JBIG: %d\n", x);
09158          if (x == 1) {
09159             p->t38.their_parms.transcoding_jbig = TRUE;
09160          }
09161       } else {
09162          ast_debug(3, "Transcoding JBIG\n");
09163          p->t38.their_parms.transcoding_jbig = TRUE;
09164       }
09165       found = TRUE;
09166    } else if ((sscanf(a, "T38FaxRateManagement:%255s", s) == 1)) {
09167       ast_debug(3, "RateManagement: %s\n", s);
09168       if (!strcasecmp(s, "localTCF"))
09169          p->t38.their_parms.rate_management = AST_T38_RATE_MANAGEMENT_LOCAL_TCF;
09170       else if (!strcasecmp(s, "transferredTCF"))
09171          p->t38.their_parms.rate_management = AST_T38_RATE_MANAGEMENT_TRANSFERRED_TCF;
09172       found = TRUE;
09173    } else if ((sscanf(a, "T38FaxUdpEC:%255s", s) == 1)) {
09174       ast_debug(3, "UDP EC: %s\n", s);
09175       if (!strcasecmp(s, "t38UDPRedundancy")) {
09176          ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_REDUNDANCY);
09177       } else if (!strcasecmp(s, "t38UDPFEC")) {
09178          ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_FEC);
09179       } else {
09180          ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_NONE);
09181       }
09182       found = TRUE;
09183    }
09184 
09185    return found;
09186 }
09187 
09188 /*! \brief Add "Supported" header to sip message.  Since some options may
09189  *  be disabled in the config, the sip_pvt must be inspected to determine what
09190  *  is supported for this dialog. */
09191 static int add_supported_header(struct sip_pvt *pvt, struct sip_request *req)
09192 {
09193    int res;
09194    if (st_get_mode(pvt) != SESSION_TIMER_MODE_REFUSE) {
09195       res = add_header(req, "Supported", "replaces, timer");
09196    } else {
09197       res = add_header(req, "Supported", "replaces");
09198    }
09199    return res;
09200 }
09201 
09202 /*! \brief Add header to SIP message */
09203 static int add_header(struct sip_request *req, const char *var, const char *value)
09204 {
09205    if (req->headers == SIP_MAX_HEADERS) {
09206       ast_log(LOG_WARNING, "Out of SIP header space\n");
09207       return -1;
09208    }
09209 
09210    if (req->lines) {
09211       ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
09212       return -1;
09213    }
09214 
09215    if (sip_cfg.compactheaders) {
09216       var = find_alias(var, var);
09217    }
09218 
09219    ast_str_append(&req->data, 0, "%s: %s\r\n", var, value);
09220    req->header[req->headers] = req->len;
09221 
09222    req->len = ast_str_strlen(req->data);
09223    req->headers++;
09224 
09225    return 0;   
09226 }
09227 
09228 /*! 
09229  * \pre dialog is assumed to be locked while calling this function
09230  * \brief Add 'Max-Forwards' header to SIP message 
09231  */
09232 static int add_header_max_forwards(struct sip_pvt *dialog, struct sip_request *req)
09233 {
09234    char clen[10];
09235 
09236    snprintf(clen, sizeof(clen), "%d", dialog->maxforwards);
09237 
09238    return add_header(req, "Max-Forwards", clen);
09239 }
09240 
09241 /*! \brief Add 'Content-Length' header and content to SIP message */
09242 static int finalize_content(struct sip_request *req)
09243 {
09244    char clen[10];
09245 
09246    if (req->lines) {
09247       ast_log(LOG_WARNING, "finalize_content() called on a message that has already been finalized\n");
09248       return -1;
09249    }
09250 
09251    snprintf(clen, sizeof(clen), "%zd", ast_str_strlen(req->content));
09252    add_header(req, "Content-Length", clen);
09253 
09254    if (ast_str_strlen(req->content)) {
09255       ast_str_append(&req->data, 0, "\r\n%s", ast_str_buffer(req->content));
09256       req->len = ast_str_strlen(req->data);
09257    }
09258    req->lines = ast_str_strlen(req->content) ? 1 : 0;
09259    return 0;
09260 }
09261 
09262 /*! \brief Add content (not header) to SIP message */
09263 static int add_content(struct sip_request *req, const char *line)
09264 {
09265    if (req->lines) {
09266       ast_log(LOG_WARNING, "Can't add more content when the content has been finalized\n");
09267       return -1;
09268    }
09269 
09270    ast_str_append(&req->content, 0, "%s", line);
09271    return 0;
09272 }
09273 
09274 /*! \brief Copy one header field from one request to another */
09275 static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field)
09276 {
09277    const char *tmp = get_header(orig, field);
09278 
09279    if (!ast_strlen_zero(tmp)) /* Add what we're responding to */
09280       return add_header(req, field, tmp);
09281    ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
09282    return -1;
09283 }
09284 
09285 /*! \brief Copy all headers from one request to another */
09286 static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field)
09287 {
09288    int start = 0;
09289    int copied = 0;
09290    for (;;) {
09291       const char *tmp = __get_header(orig, field, &start);
09292 
09293       if (ast_strlen_zero(tmp))
09294          break;
09295       /* Add what we're responding to */
09296       add_header(req, field, tmp);
09297       copied++;
09298    }
09299    return copied ? 0 : -1;
09300 }
09301 
09302 /*! \brief Copy SIP VIA Headers from the request to the response
09303 \note If the client indicates that it wishes to know the port we received from,
09304    it adds ;rport without an argument to the topmost via header. We need to
09305    add the port number (from our point of view) to that parameter.
09306 \verbatim
09307    We always add ;received=<ip address> to the topmost via header.
09308 \endverbatim
09309    Received: RFC 3261, rport RFC 3581 */
09310 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field)
09311 {
09312    int copied = 0;
09313    int start = 0;
09314 
09315    for (;;) {
09316       char new[512];
09317       const char *oh = __get_header(orig, field, &start);
09318 
09319       if (ast_strlen_zero(oh))
09320          break;
09321 
09322       if (!copied) { /* Only check for empty rport in topmost via header */
09323          char leftmost[512], *others, *rport;
09324 
09325          /* Only work on leftmost value */
09326          ast_copy_string(leftmost, oh, sizeof(leftmost));
09327          others = strchr(leftmost, ',');
09328          if (others)
09329              *others++ = '\0';
09330 
09331          /* Find ;rport;  (empty request) */
09332          rport = strstr(leftmost, ";rport");
09333          if (rport && *(rport+6) == '=')
09334             rport = NULL;     /* We already have a parameter to rport */
09335 
09336          if (((ast_test_flag(&p->flags[0], SIP_NAT_FORCE_RPORT)) || (rport && ast_test_flag(&p->flags[0], SIP_NAT_RPORT_PRESENT)))) {
09337             /* We need to add received port - rport */
09338             char *end;
09339 
09340             rport = strstr(leftmost, ";rport");
09341 
09342             if (rport) {
09343                end = strchr(rport + 1, ';');
09344                if (end)
09345                   memmove(rport, end, strlen(end) + 1);
09346                else
09347                   *rport = '\0';
09348             }
09349 
09350             /* Add rport to first VIA header if requested */
09351             snprintf(new, sizeof(new), "%s;received=%s;rport=%d%s%s",
09352                leftmost, ast_sockaddr_stringify_addr(&p->recv),
09353                ast_sockaddr_port(&p->recv),
09354                others ? "," : "", others ? others : "");
09355          } else {
09356             /* We should *always* add a received to the topmost via */
09357             snprintf(new, sizeof(new), "%s;received=%s%s%s",
09358                leftmost, ast_sockaddr_stringify_addr(&p->recv),
09359                others ? "," : "", others ? others : "");
09360          }
09361          oh = new;   /* the header to copy */
09362       }  /* else add the following via headers untouched */
09363       add_header(req, field, oh);
09364       copied++;
09365    }
09366    if (!copied) {
09367       ast_log(LOG_NOTICE, "No header field '%s' present to copy\n", field);
09368       return -1;
09369    }
09370    return 0;
09371 }
09372 
09373 /*! \brief Add route header into request per learned route */
09374 static void add_route(struct sip_request *req, struct sip_route *route)
09375 {
09376    char r[SIPBUFSIZE*2], *p;
09377    int n, rem = sizeof(r);
09378 
09379    if (!route)
09380       return;
09381 
09382    p = r;
09383    for (;route ; route = route->next) {
09384       n = strlen(route->hop);
09385       if (rem < n+3) /* we need room for ",<route>" */
09386          break;
09387       if (p != r) {  /* add a separator after fist route */
09388          *p++ = ',';
09389          --rem;
09390       }
09391       *p++ = '<';
09392       ast_copy_string(p, route->hop, rem); /* cannot fail */
09393       p += n;
09394       *p++ = '>';
09395       rem -= (n+2);
09396    }
09397    *p = '\0';
09398    add_header(req, "Route", r);
09399 }
09400 
09401 /*! \brief Set destination from SIP URI
09402  *
09403  * Parse uri to h (host) and port - uri is already just the part inside the <>
09404  * general form we are expecting is sip[s]:username[:password][;parameter]@host[:port][;...]
09405  * If there's a port given, turn NAPTR/SRV off. NAPTR might indicate SIPS preference even
09406  * for SIP: uri's
09407  *
09408  * If there's a sips: uri scheme, TLS will be required.
09409  */
09410 static void set_destination(struct sip_pvt *p, char *uri)
09411 {
09412    char *h, *maddr, hostname[256];
09413    int hn;
09414    int debug=sip_debug_test_pvt(p);
09415    int tls_on = FALSE;
09416 
09417    if (debug)
09418       ast_verbose("set_destination: Parsing <%s> for address/port to send to\n", uri);
09419 
09420    /* Find and parse hostname */
09421    h = strchr(uri, '@');
09422    if (h)
09423       ++h;
09424    else {
09425       h = uri;
09426       if (!strncasecmp(h, "sip:", 4)) {
09427          h += 4;
09428       } else if (!strncasecmp(h, "sips:", 5)) {
09429          h += 5;
09430          tls_on = TRUE;
09431       }
09432    }
09433    hn = strcspn(h, ";>") + 1;
09434    if (hn > sizeof(hostname))
09435       hn = sizeof(hostname);
09436    ast_copy_string(hostname, h, hn);
09437    /* XXX bug here if string has been trimmed to sizeof(hostname) */
09438    h += hn - 1;
09439 
09440    /*! \todo XXX If we have sip_cfg.srvlookup on, then look for NAPTR/SRV,
09441     * otherwise, just look for A records */
09442    if (ast_sockaddr_resolve_first(&p->sa, hostname, 0)) {
09443       ast_log(LOG_WARNING, "Can't find address for host '%s'\n", hostname);
09444       return;
09445    }
09446 
09447    /* Got the hostname - but maybe there's a "maddr=" to override address? */
09448    maddr = strstr(h, "maddr=");
09449    if (maddr) {
09450       int port;
09451 
09452       maddr += 6;
09453       hn = strspn(maddr, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
09454                     "0123456789-.:[]") + 1;
09455       if (hn > sizeof(hostname))
09456          hn = sizeof(hostname);
09457       ast_copy_string(hostname, maddr, hn);
09458 
09459       port = ast_sockaddr_port(&p->sa);
09460 
09461       /*! \todo XXX If we have sip_cfg.srvlookup on, then look for
09462        * NAPTR/SRV, otherwise, just look for A records */
09463       if (ast_sockaddr_resolve_first(&p->sa, hostname, PARSE_PORT_FORBID)) {
09464          ast_log(LOG_WARNING, "Can't find address for host '%s'\n", hostname);
09465          return;
09466       }
09467 
09468       ast_sockaddr_set_port(&p->sa, port);
09469    }
09470 
09471    if (!ast_sockaddr_port(&p->sa)) {
09472       ast_sockaddr_set_port(&p->sa, tls_on ?
09473                   STANDARD_TLS_PORT : STANDARD_SIP_PORT);
09474    }
09475 
09476    if (debug) {
09477       ast_verbose("set_destination: set destination to %s\n",
09478              ast_sockaddr_stringify(&p->sa));
09479    }
09480 }
09481 
09482 /*! \brief Initialize SIP response, based on SIP request */
09483 static int init_resp(struct sip_request *resp, const char *msg)
09484 {
09485    /* Initialize a response */
09486    memset(resp, 0, sizeof(*resp));
09487    resp->method = SIP_RESPONSE;
09488    if (!(resp->data = ast_str_create(SIP_MIN_PACKET)))
09489       goto e_return;
09490    if (!(resp->content = ast_str_create(SIP_MIN_PACKET)))
09491       goto e_free_data;
09492    resp->header[0] = 0;
09493    ast_str_set(&resp->data, 0, "SIP/2.0 %s\r\n", msg);
09494    resp->len = resp->data->used;
09495    resp->headers++;
09496    return 0;
09497 
09498 e_free_data:
09499    ast_free(resp->data);
09500    resp->data = NULL;
09501 e_return:
09502    return -1;
09503 }
09504 
09505 /*! \brief Initialize SIP request */
09506 static int init_req(struct sip_request *req, int sipmethod, const char *recip)
09507 {
09508    /* Initialize a request */
09509    memset(req, 0, sizeof(*req));
09510    if (!(req->data = ast_str_create(SIP_MIN_PACKET)))
09511       goto e_return;
09512    if (!(req->content = ast_str_create(SIP_MIN_PACKET)))
09513       goto e_free_data;
09514    req->method = sipmethod;
09515    req->header[0] = 0;
09516    ast_str_set(&req->data, 0, "%s %s SIP/2.0\r\n", sip_methods[sipmethod].text, recip);
09517    req->len = ast_str_strlen(req->data);
09518    req->headers++;
09519    return 0;
09520 
09521 e_free_data:
09522    ast_free(req->data);
09523    req->data = NULL;
09524 e_return:
09525    return -1;
09526 }
09527 
09528 /*! \brief Deinitialize SIP response/request */
09529 static void deinit_req(struct sip_request *req)
09530 {
09531    if (req->data) {
09532       ast_free(req->data);
09533       req->data = NULL;
09534    }
09535    if (req->content) {
09536       ast_free(req->content);
09537       req->content = NULL;
09538    }
09539 }
09540 
09541 
09542 /*! \brief Test if this response needs a contact header */
09543 static inline int resp_needs_contact(const char *msg, enum sipmethod method) {
09544    /* Requirements for Contact header inclusion in responses generated
09545     * from the header tables found in the following RFCs.  Where the
09546     * Contact header was marked mandatory (m) or optional (o) this
09547     * function returns 1.
09548     *
09549     * - RFC 3261 (ACK, BYE, CANCEL, INVITE, OPTIONS, REGISTER)
09550     * - RFC 2976 (INFO)
09551     * - RFC 3262 (PRACK)
09552     * - RFC 3265 (SUBSCRIBE, NOTIFY)
09553     * - RFC 3311 (UPDATE)
09554     * - RFC 3428 (MESSAGE)
09555     * - RFC 3515 (REFER)
09556     * - RFC 3903 (PUBLISH)
09557     */
09558 
09559    switch (method) {
09560       /* 1xx, 2xx, 3xx, 485 */
09561       case SIP_INVITE:
09562       case SIP_UPDATE:
09563       case SIP_SUBSCRIBE:
09564       case SIP_NOTIFY:
09565          if ((msg[0] >= '1' && msg[0] <= '3') || !strncmp(msg, "485", 3))
09566             return 1;
09567          break;
09568 
09569       /* 2xx, 3xx, 485 */
09570       case SIP_REGISTER:
09571       case SIP_OPTIONS:
09572          if (msg[0] == '2' || msg[0] == '3' || !strncmp(msg, "485", 3))
09573             return 1;
09574          break;
09575 
09576       /* 3xx, 485 */
09577       case SIP_BYE:
09578       case SIP_PRACK:
09579       case SIP_MESSAGE:
09580       case SIP_PUBLISH:
09581          if (msg[0] == '3' || !strncmp(msg, "485", 3))
09582             return 1;
09583          break;
09584 
09585       /* 2xx, 3xx, 4xx, 5xx, 6xx */
09586       case SIP_REFER:
09587          if (msg[0] >= '2' && msg[0] <= '6')
09588             return 1;
09589          break;
09590 
09591       /* contact will not be included for everything else */
09592       case SIP_ACK:
09593       case SIP_CANCEL:
09594       case SIP_INFO:
09595       case SIP_PING:
09596       default:
09597          return 0;
09598    }
09599    return 0;
09600 }
09601 
09602 /*! \brief Prepare SIP response packet */
09603 static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req)
09604 {
09605    char newto[256];
09606    const char *ot;
09607 
09608    init_resp(resp, msg);
09609    copy_via_headers(p, resp, req, "Via");
09610    if (msg[0] == '1' || msg[0] == '2')
09611       copy_all_header(resp, req, "Record-Route");
09612    copy_header(resp, req, "From");
09613    ot = get_header(req, "To");
09614    if (!strcasestr(ot, "tag=") && strncmp(msg, "100", 3)) {
09615       /* Add the proper tag if we don't have it already.  If they have specified
09616          their tag, use it.  Otherwise, use our own tag */
09617       if (!ast_strlen_zero(p->theirtag) && ast_test_flag(&p->flags[0], SIP_OUTGOING))
09618          snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
09619       else if (p->tag && !ast_test_flag(&p->flags[0], SIP_OUTGOING))
09620          snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->tag);
09621       else
09622          ast_copy_string(newto, ot, sizeof(newto));
09623       ot = newto;
09624    }
09625    add_header(resp, "To", ot);
09626    copy_header(resp, req, "Call-ID");
09627    copy_header(resp, req, "CSeq");
09628    if (!ast_strlen_zero(global_useragent))
09629       add_header(resp, "Server", global_useragent);
09630    add_header(resp, "Allow", ALLOWED_METHODS);
09631    add_supported_header(p, resp);
09632 
09633    /* If this is an invite, add Session-Timers related headers if the feature is active for this session */
09634    if (p->method == SIP_INVITE && p->stimer && p->stimer->st_active == TRUE && p->stimer->st_active_peer_ua == TRUE) {
09635       char se_hdr[256];
09636       snprintf(se_hdr, sizeof(se_hdr), "%d;refresher=%s", p->stimer->st_interval,
09637          strefresher2str(p->stimer->st_ref));
09638       add_header(resp, "Session-Expires", se_hdr);
09639    }
09640 
09641    if (msg[0] == '2' && (p->method == SIP_SUBSCRIBE || p->method == SIP_REGISTER)) {
09642       /* For registration responses, we also need expiry and
09643          contact info */
09644       char tmp[256];
09645 
09646       snprintf(tmp, sizeof(tmp), "%d", p->expiry);
09647       add_header(resp, "Expires", tmp);
09648       if (p->expiry) {  /* Only add contact if we have an expiry time */
09649          char contact[SIPBUFSIZE];
09650          const char *contact_uri = p->method == SIP_SUBSCRIBE ? p->our_contact : p->fullcontact;
09651          char *brackets = strchr(contact_uri, '<');
09652          snprintf(contact, sizeof(contact), "%s%s%s;expires=%d", brackets ? "" : "<", contact_uri, brackets ? "" : ">", p->expiry);
09653          add_header(resp, "Contact", contact);  /* Not when we unregister */
09654       }
09655    } else if (!ast_strlen_zero(p->our_contact) && resp_needs_contact(msg, p->method)) {
09656       add_header(resp, "Contact", p->our_contact);
09657    }
09658 
09659    if (!ast_strlen_zero(p->url)) {
09660       add_header(resp, "Access-URL", p->url);
09661       ast_string_field_set(p, url, NULL);
09662    }
09663 
09664    return 0;
09665 }
09666 
09667 /*! \brief Initialize a SIP request message (not the initial one in a dialog) */
09668 static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, int seqno, int newbranch)
09669 {
09670    struct sip_request *orig = &p->initreq;
09671    char stripped[80];
09672    char tmp[80];
09673    char newto[256];
09674    const char *c;
09675    const char *ot, *of;
09676    int is_strict = FALSE;     /*!< Strict routing flag */
09677    int is_outbound = ast_test_flag(&p->flags[0], SIP_OUTGOING);   /* Session direction */
09678 
09679    memset(req, 0, sizeof(struct sip_request));
09680    
09681    snprintf(p->lastmsg, sizeof(p->lastmsg), "Tx: %s", sip_methods[sipmethod].text);
09682    
09683    if (!seqno) {
09684       p->ocseq++;
09685       seqno = p->ocseq;
09686    }
09687    
09688    /* A CANCEL must have the same branch as the INVITE that it is canceling. */
09689    if (sipmethod == SIP_CANCEL) {
09690       p->branch = p->invite_branch;
09691       build_via(p);
09692    } else if (newbranch && (sipmethod == SIP_INVITE)) {
09693       p->branch ^= ast_random();
09694       p->invite_branch = p->branch;
09695       build_via(p);
09696    } else if (newbranch) {
09697       p->branch ^= ast_random();
09698       build_via(p);
09699    }
09700 
09701    /* Check for strict or loose router */
09702    if (p->route && !ast_strlen_zero(p->route->hop) && strstr(p->route->hop, ";lr") == NULL) {
09703       is_strict = TRUE;
09704       if (sipdebug)
09705          ast_debug(1, "Strict routing enforced for session %s\n", p->callid);
09706    }
09707    
09708    if (sipmethod == SIP_CANCEL)
09709       c = REQ_OFFSET_TO_STR(&p->initreq, rlPart2); /* Use original URI */
09710    else if (sipmethod == SIP_ACK) {
09711       /* Use URI from Contact: in 200 OK (if INVITE)
09712       (we only have the contacturi on INVITEs) */
09713       if (!ast_strlen_zero(p->okcontacturi))
09714          c = is_strict ? p->route->hop : p->okcontacturi;
09715       else
09716          c = REQ_OFFSET_TO_STR(&p->initreq, rlPart2);
09717    } else if (!ast_strlen_zero(p->okcontacturi))
09718       c = is_strict ? p->route->hop : p->okcontacturi; /* Use for BYE or REINVITE */
09719    else if (!ast_strlen_zero(p->uri))
09720       c = p->uri;
09721    else {
09722       char *n;
09723       /* We have no URI, use To: or From:  header as URI (depending on direction) */
09724       ast_copy_string(stripped, get_header(orig, is_outbound ? "To" : "From"),
09725             sizeof(stripped));
09726       n = get_in_brackets(stripped);
09727       c = remove_uri_parameters(n);
09728    }  
09729    init_req(req, sipmethod, c);
09730 
09731    snprintf(tmp, sizeof(tmp), "%d %s", seqno, sip_methods[sipmethod].text);
09732 
09733    add_header(req, "Via", p->via);
09734    if (p->route) {
09735       set_destination(p, p->route->hop);
09736       add_route(req, is_strict ? p->route->next : p->route);
09737    }
09738    add_header_max_forwards(p, req);
09739 
09740    ot = get_header(orig, "To");
09741    of = get_header(orig, "From");
09742 
09743    /* Add tag *unless* this is a CANCEL, in which case we need to send it exactly
09744       as our original request, including tag (or presumably lack thereof) */
09745    if (!strcasestr(ot, "tag=") && sipmethod != SIP_CANCEL) {
09746       /* Add the proper tag if we don't have it already.  If they have specified
09747          their tag, use it.  Otherwise, use our own tag */
09748       if (is_outbound && !ast_strlen_zero(p->theirtag))
09749          snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
09750       else if (!is_outbound)
09751          snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->tag);
09752       else
09753          snprintf(newto, sizeof(newto), "%s", ot);
09754       ot = newto;
09755    }
09756 
09757    if (is_outbound) {
09758       add_header(req, "From", of);
09759       add_header(req, "To", ot);
09760    } else {
09761       add_header(req, "From", ot);
09762       add_header(req, "To", of);
09763    }
09764    /* Do not add Contact for MESSAGE, BYE and Cancel requests */
09765    if (sipmethod != SIP_BYE && sipmethod != SIP_CANCEL && sipmethod != SIP_MESSAGE)
09766       add_header(req, "Contact", p->our_contact);
09767 
09768    copy_header(req, orig, "Call-ID");
09769    add_header(req, "CSeq", tmp);
09770 
09771    if (!ast_strlen_zero(global_useragent))
09772       add_header(req, "User-Agent", global_useragent);
09773 
09774    if (!ast_strlen_zero(p->url)) {
09775       add_header(req, "Access-URL", p->url);
09776       ast_string_field_set(p, url, NULL);
09777    }
09778 
09779    /* Add Session-Timers related headers if the feature is active for this session.
09780       An exception to this behavior is the ACK request. Since Asterisk never requires
09781       session-timers support from a remote end-point (UAS) in an INVITE, it must
09782       not send 'Require: timer' header in the ACK request.
09783       This should only be added in the INVITE transactions, not MESSAGE or REFER or other
09784       in-dialog messages.
09785    */
09786    if (p->stimer && p->stimer->st_active == TRUE && p->stimer->st_active_peer_ua == TRUE
09787        && sipmethod == SIP_INVITE) {
09788       char se_hdr[256];
09789       snprintf(se_hdr, sizeof(se_hdr), "%d;refresher=%s", p->stimer->st_interval,
09790          strefresher2str(p->stimer->st_ref));
09791       add_header(req, "Require", "timer");
09792       add_header(req, "Session-Expires", se_hdr);
09793       snprintf(se_hdr, sizeof(se_hdr), "%d", st_get_se(p, FALSE));
09794       add_header(req, "Min-SE", se_hdr);
09795    }
09796 
09797    return 0;
09798 }
09799 
09800 /*! \brief Base transmit response function */
09801 static int __transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable)
09802 {
09803    struct sip_request resp;
09804    int seqno = 0;
09805 
09806    if (reliable && (sscanf(get_header(req, "CSeq"), "%30d ", &seqno) != 1)) {
09807       ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
09808       return -1;
09809    }
09810    respprep(&resp, p, msg, req);
09811 
09812    if (ast_test_flag(&p->flags[0], SIP_SENDRPID)
09813          && ast_test_flag(&p->flags[1], SIP_PAGE2_CONNECTLINEUPDATE_PEND)
09814          && (!strncmp(msg, "180", 3) || !strncmp(msg, "183", 3))) {
09815       ast_clear_flag(&p->flags[1], SIP_PAGE2_CONNECTLINEUPDATE_PEND);
09816       add_rpid(&resp, p);
09817    }
09818    if (ast_test_flag(&p->flags[0], SIP_OFFER_CC)) {
09819       add_cc_call_info_to_response(p, &resp);
09820    }
09821 
09822    /* If we are cancelling an incoming invite for some reason, add information
09823       about the reason why we are doing this in clear text */
09824    if (p->method == SIP_INVITE && msg[0] != '1') {
09825       char buf[20];
09826 
09827       if (ast_test_flag(&p->flags[1], SIP_PAGE2_Q850_REASON)) {
09828          int hangupcause = 0;
09829 
09830          if (p->owner && p->owner->hangupcause) {
09831             hangupcause = p->owner->hangupcause;
09832          } else if (p->hangupcause) {
09833             hangupcause = p->hangupcause;
09834          } else {
09835             int respcode;
09836             if (sscanf(msg, "%30d ", &respcode))
09837                hangupcause = hangup_sip2cause(respcode);
09838          }
09839 
09840          if (hangupcause) {
09841             sprintf(buf, "Q.850;cause=%i", hangupcause & 0x7f);
09842             add_header(&resp, "Reason", buf);
09843          }
09844       }
09845 
09846       if (p->owner && p->owner->hangupcause) {
09847          add_header(&resp, "X-Asterisk-HangupCause", ast_cause2str(p->owner->hangupcause));
09848          snprintf(buf, sizeof(buf), "%d", p->owner->hangupcause);
09849          add_header(&resp, "X-Asterisk-HangupCauseCode", buf);
09850       }
09851    }
09852    return send_response(p, &resp, reliable, seqno);
09853 }
09854 
09855 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)
09856 {
09857    struct sip_request resp;
09858 
09859    if (need_new_etag) {
09860       create_new_sip_etag(esc_entry, 1);
09861    }
09862    respprep(&resp, p, msg, req);
09863    add_header(&resp, "SIP-ETag", esc_entry->entity_tag);
09864 
09865    return send_response(p, &resp, 0, 0);
09866 }
09867 
09868 static int temp_pvt_init(void *data)
09869 {
09870    struct sip_pvt *p = data;
09871 
09872    p->do_history = 0;   /* XXX do we need it ? isn't already all 0 ? */
09873    return ast_string_field_init(p, 512);
09874 }
09875 
09876 static void temp_pvt_cleanup(void *data)
09877 {
09878    struct sip_pvt *p = data;
09879 
09880    ast_string_field_free_memory(p);
09881 
09882    ast_free(data);
09883 }
09884 
09885 /*! \brief Transmit response, no retransmits, using a temporary pvt structure */
09886 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)
09887 {
09888    struct sip_pvt *p = NULL;
09889 
09890    if (!(p = ast_threadstorage_get(&ts_temp_pvt, sizeof(*p)))) {
09891       ast_log(LOG_ERROR, "Failed to get temporary pvt\n");
09892       return -1;
09893    }
09894 
09895    /* XXX the structure may be dirty from previous usage.
09896     * Here we should state clearly how we should reinitialize it
09897     * before using it.
09898     * E.g. certainly the threadstorage should be left alone,
09899     * but other thihngs such as flags etc. maybe need cleanup ?
09900     */
09901 
09902    /* Initialize the bare minimum */
09903    p->method = intended_method;
09904 
09905    if (!addr) {
09906       ast_sockaddr_copy(&p->ourip, &internip);
09907    } else {
09908       ast_sockaddr_copy(&p->sa, addr);
09909       ast_sip_ouraddrfor(&p->sa, &p->ourip, p);
09910    }
09911 
09912    p->branch = ast_random();
09913    make_our_tag(p->tag, sizeof(p->tag));
09914    p->ocseq = INITIAL_CSEQ;
09915 
09916    if (useglobal_nat && addr) {
09917       ast_copy_flags(&p->flags[0], &global_flags[0], SIP_NAT_FORCE_RPORT);
09918       ast_sockaddr_copy(&p->recv, addr);
09919       do_setnat(p);
09920    }
09921 
09922    ast_string_field_set(p, fromdomain, default_fromdomain);
09923    p->fromdomainport = default_fromdomainport;
09924    build_via(p);
09925    ast_string_field_set(p, callid, callid);
09926 
09927    copy_socket_data(&p->socket, &req->socket);
09928 
09929    /* Use this temporary pvt structure to send the message */
09930    __transmit_response(p, msg, req, XMIT_UNRELIABLE);
09931 
09932    /* Free the string fields, but not the pool space */
09933    ast_string_field_init(p, 0);
09934 
09935    return 0;
09936 }
09937 
09938 /*! \brief Transmit response, no retransmits */
09939 static int transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req)
09940 {
09941    return __transmit_response(p, msg, req, XMIT_UNRELIABLE);
09942 }
09943 
09944 /*! \brief Transmit response, no retransmits */
09945 static int transmit_response_with_unsupported(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *unsupported)
09946 {
09947    struct sip_request resp;
09948    respprep(&resp, p, msg, req);
09949    append_date(&resp);
09950    add_header(&resp, "Unsupported", unsupported);
09951    return send_response(p, &resp, XMIT_UNRELIABLE, 0);
09952 }
09953 
09954 /*! \brief Transmit 422 response with Min-SE header (Session-Timers)  */
09955 static int transmit_response_with_minse(struct sip_pvt *p, const char *msg, const struct sip_request *req, int minse_int)
09956 {
09957    struct sip_request resp;
09958    char minse_str[20];
09959 
09960    respprep(&resp, p, msg, req);
09961    append_date(&resp);
09962 
09963    snprintf(minse_str, sizeof(minse_str), "%d", minse_int);
09964    add_header(&resp, "Min-SE", minse_str);
09965    return send_response(p, &resp, XMIT_UNRELIABLE, 0);
09966 }
09967 
09968 
09969 /*! \brief Transmit response, Make sure you get an ACK
09970    This is only used for responses to INVITEs, where we need to make sure we get an ACK
09971 */
09972 static int transmit_response_reliable(struct sip_pvt *p, const char *msg, const struct sip_request *req)
09973 {
09974    return __transmit_response(p, msg, req, req->ignore ? XMIT_UNRELIABLE : XMIT_CRITICAL);
09975 }
09976 
09977 /*! \brief Append date to SIP message */
09978 static void append_date(struct sip_request *req)
09979 {
09980    char tmpdat[256];
09981    struct tm tm;
09982    time_t t = time(NULL);
09983 
09984    gmtime_r(&t, &tm);
09985    strftime(tmpdat, sizeof(tmpdat), "%a, %d %b %Y %T GMT", &tm);
09986    add_header(req, "Date", tmpdat);
09987 }
09988 
09989 /*! \brief Append Retry-After header field when transmitting response */
09990 static int transmit_response_with_retry_after(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *seconds)
09991 {
09992    struct sip_request resp;
09993    respprep(&resp, p, msg, req);
09994    add_header(&resp, "Retry-After", seconds);
09995    return send_response(p, &resp, XMIT_UNRELIABLE, 0);
09996 }
09997 
09998 /*! \brief Append date and content length before transmitting response */
09999 static int transmit_response_with_date(struct sip_pvt *p, const char *msg, const struct sip_request *req)
10000 {
10001    struct sip_request resp;
10002    respprep(&resp, p, msg, req);
10003    append_date(&resp);
10004    return send_response(p, &resp, XMIT_UNRELIABLE, 0);
10005 }
10006 
10007 /*! \brief Append Accept header, content length before transmitting response */
10008 static int transmit_response_with_allow(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable)
10009 {
10010    struct sip_request resp;
10011    respprep(&resp, p, msg, req);
10012    add_header(&resp, "Accept", "application/sdp");
10013    return send_response(p, &resp, reliable, 0);
10014 }
10015 
10016 /*! \brief Append Min-Expires header, content length before transmitting response */
10017 static int transmit_response_with_minexpires(struct sip_pvt *p, const char *msg, const struct sip_request *req)
10018 {
10019    struct sip_request resp;
10020    char tmp[32];
10021 
10022    snprintf(tmp, sizeof(tmp), "%d", min_expiry);
10023    respprep(&resp, p, msg, req);
10024    add_header(&resp, "Min-Expires", tmp);
10025    return send_response(p, &resp, XMIT_UNRELIABLE, 0);
10026 }
10027 
10028 /*! \brief Respond with authorization request */
10029 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)
10030 {
10031    struct sip_request resp;
10032    char tmp[512];
10033    int seqno = 0;
10034 
10035    if (reliable && (sscanf(get_header(req, "CSeq"), "%30d ", &seqno) != 1)) {
10036       ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
10037       return -1;
10038    }
10039    /* Choose Realm */
10040    get_realm(p, req);
10041 
10042    /* Stale means that they sent us correct authentication, but
10043       based it on an old challenge (nonce) */
10044    snprintf(tmp, sizeof(tmp), "Digest algorithm=MD5, realm=\"%s\", nonce=\"%s\"%s", p->realm, randdata, stale ? ", stale=true" : "");
10045    respprep(&resp, p, msg, req);
10046    add_header(&resp, header, tmp);
10047    append_history(p, "AuthChal", "Auth challenge sent for %s - nc %d", p->username, p->noncecount);
10048    return send_response(p, &resp, reliable, seqno);
10049 }
10050 
10051 /*!
10052  \brief Extract domain from SIP To/From header
10053  \return -1 on error, 1 if domain string is empty, 0 if domain was properly extracted
10054  \note TODO: Such code is all over SIP channel, there is a sense to organize
10055       this patern in one function
10056 */
10057 static int get_domain(const char *str, char *domain, int len)
10058 {
10059    char tmpf[256];
10060    char *a, *from;
10061 
10062    *domain = '\0';
10063    ast_copy_string(tmpf, str, sizeof(tmpf));
10064    from = get_in_brackets(tmpf);
10065    if (!ast_strlen_zero(from)) {
10066       if (strncasecmp(from, "sip:", 4)) {
10067          ast_log(LOG_WARNING, "Huh?  Not a SIP header (%s)?\n", from);
10068          return -1;
10069       }
10070       from += 4;
10071    } else
10072       from = NULL;
10073 
10074    if (from) {
10075       int bracket = 0;
10076 
10077       /* Strip any params or options from user */
10078       if ((a = strchr(from, ';')))
10079          *a = '\0';
10080       /* Strip port from domain if present */
10081       for (a = from; *a != '\0'; ++a) {
10082          if (*a == ':' && bracket == 0) {
10083             *a = '\0';
10084             break;
10085          } else if (*a == '[') {
10086             ++bracket;
10087          } else if (*a == ']') {
10088             --bracket;
10089          }
10090       }
10091       if ((a = strchr(from, '@'))) {
10092          *a = '\0';
10093          ast_copy_string(domain, a + 1, len);
10094       } else
10095          ast_copy_string(domain, from, len);
10096    }
10097 
10098    return ast_strlen_zero(domain);
10099 }
10100 
10101 /*!
10102   \brief Choose realm based on From header and then To header or use globaly configured realm.
10103   Realm from From/To header should be listed among served domains in config file: domain=...
10104 */
10105 static void get_realm(struct sip_pvt *p, const struct sip_request *req)
10106 {
10107    char domain[MAXHOSTNAMELEN];
10108 
10109    if (!ast_strlen_zero(p->realm))
10110       return;
10111 
10112    if (sip_cfg.domainsasrealm &&
10113        !AST_LIST_EMPTY(&domain_list))
10114    {
10115       /* Check From header first */
10116       if (!get_domain(get_header(req, "From"), domain, sizeof(domain))) {
10117          if (check_sip_domain(domain, NULL, 0)) {
10118             ast_string_field_set(p, realm, domain);
10119             return;
10120          }
10121       }
10122       /* Check To header */
10123       if (!get_domain(get_header(req, "To"), domain, sizeof(domain))) {
10124          if (check_sip_domain(domain, NULL, 0)) {
10125             ast_string_field_set(p, realm, domain);
10126             return;
10127          }
10128       }
10129    }
10130    
10131    /* Use default realm from config file */
10132    ast_string_field_set(p, realm, sip_cfg.realm);
10133 }
10134 
10135 /* Only use a static string for the msg, here! */
10136 static int transmit_provisional_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, int with_sdp)
10137 {
10138    int res;
10139 
10140    if (!(res = with_sdp ? transmit_response_with_sdp(p, msg, req, XMIT_UNRELIABLE, FALSE, FALSE) : transmit_response(p, msg, req))) {
10141       p->last_provisional = msg;
10142       update_provisional_keepalive(p, with_sdp);
10143    }
10144 
10145    return res;
10146 }
10147 
10148 /*! \brief Add text body to SIP message */
10149 static int add_text(struct sip_request *req, const char *text)
10150 {
10151    /* XXX Convert \n's to \r\n's XXX */
10152    add_header(req, "Content-Type", "text/plain;charset=UTF-8");
10153    add_content(req, text);
10154    return 0;
10155 }
10156 
10157 /*! \brief Add DTMF INFO tone to sip message
10158    Mode =   0 for application/dtmf-relay (Cisco)
10159       1 for application/dtmf
10160 */
10161 static int add_digit(struct sip_request *req, char digit, unsigned int duration, int mode)
10162 {
10163    char tmp[256];
10164    int event;
10165    if (mode) {
10166       /* Application/dtmf short version used by some implementations */
10167       if (digit == '*')
10168          event = 10;
10169       else if (digit == '#')
10170          event = 11;
10171       else if ((digit >= 'A') && (digit <= 'D'))
10172          event = 12 + digit - 'A';
10173       else
10174          event = atoi(&digit);
10175       snprintf(tmp, sizeof(tmp), "%d\r\n", event);
10176       add_header(req, "Content-Type", "application/dtmf");
10177       add_content(req, tmp);
10178    } else {
10179       /* Application/dtmf-relay as documented by Cisco */
10180       snprintf(tmp, sizeof(tmp), "Signal=%c\r\nDuration=%u\r\n", digit, duration);
10181       add_header(req, "Content-Type", "application/dtmf-relay");
10182       add_content(req, tmp);
10183    }
10184    return 0;
10185 }
10186 
10187 /*!
10188  * \pre if p->owner exists, it must be locked
10189  * \brief Add Remote-Party-ID header to SIP message
10190  */
10191 static int add_rpid(struct sip_request *req, struct sip_pvt *p)
10192 {
10193    struct ast_str *tmp = ast_str_alloca(256);
10194    char tmp2[256];
10195    char *lid_num = NULL;
10196    char *lid_name = NULL;
10197    int lid_pres;
10198    const char *fromdomain;
10199    const char *privacy = NULL;
10200    const char *screen = NULL;
10201    const char *anonymous_string = "\"Anonymous\" <sip:anonymous@anonymous.invalid>";
10202 
10203    if (!ast_test_flag(&p->flags[0], SIP_SENDRPID)) {
10204       return 0;
10205    }
10206 
10207    if (p->owner && p->owner->connected.id.number.valid
10208       && p->owner->connected.id.number.str) {
10209       lid_num = p->owner->connected.id.number.str;
10210    }
10211    if (p->owner && p->owner->connected.id.name.valid
10212       && p->owner->connected.id.name.str) {
10213       lid_name = p->owner->connected.id.name.str;
10214    }
10215    lid_pres = (p->owner) ? ast_party_id_presentation(&p->owner->connected.id) : AST_PRES_NUMBER_NOT_AVAILABLE;
10216 
10217    if (ast_strlen_zero(lid_num))
10218       return 0;
10219    if (ast_strlen_zero(lid_name))
10220       lid_name = lid_num;
10221    fromdomain = S_OR(p->fromdomain, ast_sockaddr_stringify_host(&p->ourip));
10222 
10223    lid_num = ast_uri_encode(lid_num, tmp2, sizeof(tmp2), 1);
10224 
10225    if (ast_test_flag(&p->flags[0], SIP_SENDRPID_PAI)) {
10226       if ((lid_pres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED) {
10227          ast_str_set(&tmp, -1, "%s", anonymous_string);
10228       } else {
10229          ast_str_set(&tmp, -1, "\"%s\" <sip:%s@%s>", lid_name, lid_num, fromdomain);
10230       }
10231       add_header(req, "P-Asserted-Identity", ast_str_buffer(tmp));
10232    } else {
10233       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");
10234 
10235       switch (lid_pres) {
10236       case AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED:
10237       case AST_PRES_ALLOWED_USER_NUMBER_FAILED_SCREEN:
10238          privacy = "off";
10239          screen = "no";
10240          break;
10241       case AST_PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN:
10242       case AST_PRES_ALLOWED_NETWORK_NUMBER:
10243          privacy = "off";
10244          screen = "yes";
10245          break;
10246       case AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED:
10247       case AST_PRES_PROHIB_USER_NUMBER_FAILED_SCREEN:
10248          privacy = "full";
10249          screen = "no";
10250          break;
10251       case AST_PRES_PROHIB_USER_NUMBER_PASSED_SCREEN:
10252       case AST_PRES_PROHIB_NETWORK_NUMBER:
10253          privacy = "full";
10254          screen = "yes";
10255          break;
10256       case AST_PRES_NUMBER_NOT_AVAILABLE:
10257          break;
10258       default:
10259          if ((lid_pres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED) {
10260             privacy = "full";
10261          }
10262          else
10263             privacy = "off";
10264          screen = "no";
10265          break;
10266       }
10267 
10268       if (!ast_strlen_zero(privacy) && !ast_strlen_zero(screen)) {
10269          ast_str_append(&tmp, -1, ";privacy=%s;screen=%s", privacy, screen);
10270       }
10271 
10272       add_header(req, "Remote-Party-ID", ast_str_buffer(tmp));
10273    }
10274    return 0;
10275 }
10276 
10277 /*! \brief add XML encoded media control with update
10278    \note XML: The only way to turn 0 bits of information into a few hundred. (markster) */
10279 static int add_vidupdate(struct sip_request *req)
10280 {
10281    const char *xml_is_a_huge_waste_of_space =
10282       "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\r\n"
10283       " <media_control>\r\n"
10284       "  <vc_primitive>\r\n"
10285       "   <to_encoder>\r\n"
10286       "    <picture_fast_update>\r\n"
10287       "    </picture_fast_update>\r\n"
10288       "   </to_encoder>\r\n"
10289       "  </vc_primitive>\r\n"
10290       " </media_control>\r\n";
10291    add_header(req, "Content-Type", "application/media_control+xml");
10292    add_content(req, xml_is_a_huge_waste_of_space);
10293    return 0;
10294 }
10295 
10296 /*! \brief Add codec offer to SDP offer/answer body in INVITE or 200 OK */
10297 static void add_codec_to_sdp(const struct sip_pvt *p, format_t codec,
10298               struct ast_str **m_buf, struct ast_str **a_buf,
10299               int debug, int *min_packet_size)
10300 {
10301    int rtp_code;
10302    struct ast_format_list fmt;
10303 
10304 
10305    if (debug)
10306       ast_verbose("Adding codec 0x%" PRIx64 " (%s) to SDP\n", codec, ast_getformatname(codec));
10307    if ((rtp_code = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(p->rtp), 1, codec)) == -1)
10308       return;
10309 
10310    if (p->rtp) {
10311       struct ast_codec_pref *pref = &ast_rtp_instance_get_codecs(p->rtp)->pref;
10312       fmt = ast_codec_pref_getsize(pref, codec);
10313    } 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 */
10314       return;
10315    ast_str_append(m_buf, 0, " %d", rtp_code);
10316    ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%d\r\n", rtp_code,
10317              ast_rtp_lookup_mime_subtype2(1, codec,
10318                      ast_test_flag(&p->flags[0], SIP_G726_NONSTANDARD) ? AST_RTP_OPT_G726_NONSTANDARD : 0),
10319              ast_rtp_lookup_sample_rate2(1, codec));
10320 
10321    switch (codec) {
10322    case AST_FORMAT_G729A:
10323       /* Indicate that we don't support VAD (G.729 annex B) */
10324       ast_str_append(a_buf, 0, "a=fmtp:%d annexb=no\r\n", rtp_code);
10325       break;
10326    case AST_FORMAT_G723_1:
10327       /* Indicate that we don't support VAD (G.723.1 annex A) */
10328       ast_str_append(a_buf, 0, "a=fmtp:%d annexa=no\r\n", rtp_code);
10329       break;
10330    case AST_FORMAT_ILBC:
10331       /* Add information about us using only 20/30 ms packetization */
10332       ast_str_append(a_buf, 0, "a=fmtp:%d mode=%d\r\n", rtp_code, fmt.cur_ms);
10333       break;
10334    case AST_FORMAT_SIREN7:
10335       /* Indicate that we only expect 32Kbps */
10336       ast_str_append(a_buf, 0, "a=fmtp:%d bitrate=32000\r\n", rtp_code);
10337       break;
10338    case AST_FORMAT_SIREN14:
10339       /* Indicate that we only expect 48Kbps */
10340       ast_str_append(a_buf, 0, "a=fmtp:%d bitrate=48000\r\n", rtp_code);
10341       break;
10342    case AST_FORMAT_G719:
10343       /* Indicate that we only expect 64Kbps */
10344       ast_str_append(a_buf, 0, "a=fmtp:%d bitrate=64000\r\n", rtp_code);
10345       break;
10346    }
10347 
10348    if (fmt.cur_ms && (fmt.cur_ms < *min_packet_size))
10349       *min_packet_size = fmt.cur_ms;
10350 
10351    /* Our first codec packetization processed cannot be zero */
10352    if ((*min_packet_size)==0 && fmt.cur_ms)
10353       *min_packet_size = fmt.cur_ms;
10354 }
10355 
10356 /*! \brief Add video codec offer to SDP offer/answer body in INVITE or 200 OK */
10357 /* This is different to the audio one now so we can add more caps later */
10358 static void add_vcodec_to_sdp(const struct sip_pvt *p, format_t codec,
10359               struct ast_str **m_buf, struct ast_str **a_buf,
10360               int debug, int *min_packet_size)
10361 {
10362    int rtp_code;
10363 
10364    if (!p->vrtp)
10365       return;
10366 
10367    if (debug)
10368       ast_verbose("Adding video codec 0x%" PRIx64 " (%s) to SDP\n", codec, ast_getformatname(codec));
10369 
10370    if ((rtp_code = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(p->vrtp), 1, codec)) == -1)
10371       return;
10372 
10373    ast_str_append(m_buf, 0, " %d", rtp_code);
10374    ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%d\r\n", rtp_code,
10375              ast_rtp_lookup_mime_subtype2(1, codec, 0),
10376              ast_rtp_lookup_sample_rate2(1, codec));
10377    /* Add fmtp code here */
10378 }
10379 
10380 /*! \brief Add text codec offer to SDP offer/answer body in INVITE or 200 OK */
10381 static void add_tcodec_to_sdp(const struct sip_pvt *p, int codec,
10382               struct ast_str **m_buf, struct ast_str **a_buf,
10383               int debug, int *min_packet_size)
10384 {
10385    int rtp_code;
10386 
10387    if (!p->trtp)
10388       return;
10389 
10390    if (debug)
10391       ast_verbose("Adding text codec 0x%x (%s) to SDP\n", codec, ast_getformatname(codec));
10392 
10393    if ((rtp_code = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(p->trtp), 1, codec)) == -1)
10394       return;
10395 
10396    ast_str_append(m_buf, 0, " %d", rtp_code);
10397    ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%d\r\n", rtp_code,
10398              ast_rtp_lookup_mime_subtype2(1, codec, 0),
10399              ast_rtp_lookup_sample_rate2(1, codec));
10400    /* Add fmtp code here */
10401 
10402    if (codec == AST_FORMAT_T140RED) {
10403       int t140code = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(p->trtp), 1, AST_FORMAT_T140);
10404       ast_str_append(a_buf, 0, "a=fmtp:%d %d/%d/%d\r\n", rtp_code,
10405           t140code,
10406           t140code,
10407           t140code);
10408 
10409    }
10410 }
10411 
10412 
10413 /*! \brief Get Max T.38 Transmission rate from T38 capabilities */
10414 static unsigned int t38_get_rate(enum ast_control_t38_rate rate)
10415 {
10416    switch (rate) {
10417    case AST_T38_RATE_2400:
10418       return 2400;
10419    case AST_T38_RATE_4800:
10420       return 4800;
10421    case AST_T38_RATE_7200:
10422       return 7200;
10423    case AST_T38_RATE_9600:
10424       return 9600;
10425    case AST_T38_RATE_12000:
10426       return 12000;
10427    case AST_T38_RATE_14400:
10428       return 14400;
10429    default:
10430       return 0;
10431    }
10432 }
10433 
10434 /*! \brief Add RFC 2833 DTMF offer to SDP */
10435 static void add_noncodec_to_sdp(const struct sip_pvt *p, int format,
10436             struct ast_str **m_buf, struct ast_str **a_buf,
10437             int debug)
10438 {
10439    int rtp_code;
10440 
10441    if (debug)
10442       ast_verbose("Adding non-codec 0x%x (%s) to SDP\n", format, ast_rtp_lookup_mime_subtype2(0, format, 0));
10443    if ((rtp_code = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(p->rtp), 0, format)) == -1)
10444       return;
10445 
10446    ast_str_append(m_buf, 0, " %d", rtp_code);
10447    ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%d\r\n", rtp_code,
10448              ast_rtp_lookup_mime_subtype2(0, format, 0),
10449              ast_rtp_lookup_sample_rate2(0, format));
10450    if (format == AST_RTP_DTMF)   /* Indicate we support DTMF and FLASH... */
10451       ast_str_append(a_buf, 0, "a=fmtp:%d 0-16\r\n", rtp_code);
10452 }
10453 
10454 /*! \brief Set all IP media addresses for this call
10455    \note called from add_sdp()
10456 */
10457 static void get_our_media_address(struct sip_pvt *p, int needvideo, int needtext,
10458               struct ast_sockaddr *addr, struct ast_sockaddr *vaddr,
10459               struct ast_sockaddr *taddr, struct ast_sockaddr *dest,
10460               struct ast_sockaddr *vdest, struct ast_sockaddr *tdest)
10461 {
10462    int use_externip = 0;
10463 
10464    /* First, get our address */
10465    ast_rtp_instance_get_local_address(p->rtp, addr);
10466    if (p->vrtp) {
10467       ast_rtp_instance_get_local_address(p->vrtp, vaddr);
10468    }
10469    if (p->trtp) {
10470       ast_rtp_instance_get_local_address(p->trtp, taddr);
10471    }
10472 
10473    /* If our real IP differs from the local address returned by the RTP engine, use it. */
10474    /* The premise is that if we are already using that IP to communicate with the client, */
10475    /* we should be using it for RTP too. */
10476         use_externip = ast_sockaddr_cmp_addr(&p->ourip, addr);
10477 
10478    /* Now, try to figure out where we want them to send data */
10479    /* Is this a re-invite to move the media out, then use the original offer from caller  */
10480    if (!ast_sockaddr_isnull(&p->redirip)) {  /* If we have a redirection IP, use it */
10481       ast_sockaddr_copy(dest, &p->redirip);
10482    } else {
10483       /*
10484        * Audio Destination IP:
10485        *
10486        * 1. Specifically configured media address.
10487        * 2. Local address as specified by the RTP engine.
10488        * 3. The local IP as defined by chan_sip.
10489        *
10490        * Audio Destination Port:
10491        *
10492        * 1. Provided by the RTP engine.
10493        */
10494       ast_sockaddr_copy(dest,
10495               !ast_sockaddr_isnull(&media_address) ? &media_address :
10496               !ast_sockaddr_is_any(addr) && !use_externip ? addr    :
10497               &p->ourip);
10498       ast_sockaddr_set_port(dest, ast_sockaddr_port(addr));
10499    }
10500 
10501    if (needvideo) {
10502       /* Determine video destination */
10503       if (!ast_sockaddr_isnull(&p->vredirip)) {
10504          ast_sockaddr_copy(vdest, &p->vredirip);
10505       } else {
10506          /*
10507           * Video Destination IP:
10508           *
10509           * 1. Specifically configured media address.
10510           * 2. Local address as specified by the RTP engine.
10511           * 3. The local IP as defined by chan_sip.
10512           *
10513           * Video Destination Port:
10514           *
10515           * 1. Provided by the RTP engine.
10516           */
10517          ast_sockaddr_copy(vdest,
10518                  !ast_sockaddr_isnull(&media_address) ? &media_address :
10519                  !ast_sockaddr_is_any(vaddr) && !use_externip ? vaddr  :
10520                  &p->ourip);
10521          ast_sockaddr_set_port(vdest, ast_sockaddr_port(vaddr));
10522       }
10523    }
10524 
10525    if (needtext) {
10526       /* Determine text destination */
10527       if (!ast_sockaddr_isnull(&p->tredirip)) {
10528          ast_sockaddr_copy(tdest, &p->tredirip);
10529       } else {
10530          /*
10531           * Text Destination IP:
10532           *
10533           * 1. Specifically configured media address.
10534           * 2. Local address as specified by the RTP engine.
10535           * 3. The local IP as defined by chan_sip.
10536           *
10537           * Text Destination Port:
10538           *
10539           * 1. Provided by the RTP engine.
10540           */
10541          ast_sockaddr_copy(tdest,
10542                  !ast_sockaddr_isnull(&media_address) ? &media_address  :
10543                  !ast_sockaddr_is_any(taddr) && !use_externip ? taddr   :
10544                  &p->ourip);
10545          ast_sockaddr_set_port(tdest, ast_sockaddr_port(taddr));
10546       }
10547    }
10548 }
10549 
10550 static void get_crypto_attrib(struct sip_srtp *srtp, const char **a_crypto)
10551 {
10552    /* Set encryption properties */
10553    if (srtp) {
10554       if (!srtp->crypto) {
10555          srtp->crypto = sdp_crypto_setup();
10556       }
10557       if (srtp->crypto && (sdp_crypto_offer(srtp->crypto) >= 0)) {
10558          *a_crypto = sdp_crypto_attrib(srtp->crypto);
10559       }
10560 
10561       if (!*a_crypto) {
10562          ast_log(LOG_WARNING, "No SRTP key management enabled\n");
10563       }
10564    }
10565 }
10566 
10567 /*! \brief Add Session Description Protocol message
10568 
10569     If oldsdp is TRUE, then the SDP version number is not incremented. This mechanism
10570     is used in Session-Timers where RE-INVITEs are used for refreshing SIP sessions
10571     without modifying the media session in any way.
10572 */
10573 static enum sip_result add_sdp(struct sip_request *resp, struct sip_pvt *p, int oldsdp, int add_audio, int add_t38)
10574 {
10575    format_t alreadysent = 0;
10576    int doing_directmedia = FALSE;
10577 
10578    struct ast_sockaddr addr = { {0,} };
10579    struct ast_sockaddr vaddr = { {0,} };
10580    struct ast_sockaddr taddr = { {0,} };
10581    struct ast_sockaddr udptladdr = { {0,} };
10582    struct ast_sockaddr dest = { {0,} };
10583    struct ast_sockaddr vdest = { {0,} };
10584    struct ast_sockaddr tdest = { {0,} };
10585    struct ast_sockaddr udptldest = { {0,} };
10586 
10587    /* SDP fields */
10588    char *version =   "v=0\r\n";     /* Protocol version */
10589    char subject[256];            /* Subject of the session */
10590    char owner[256];           /* Session owner/creator */
10591    char connection[256];            /* Connection data */
10592    char *session_time = "t=0 0\r\n";         /* Time the session is active */
10593    char bandwidth[256] = "";        /* Max bitrate */
10594    char *hold = "";
10595    struct ast_str *m_audio = ast_str_alloca(256);  /* Media declaration line for audio */
10596    struct ast_str *m_video = ast_str_alloca(256);  /* Media declaration line for video */
10597    struct ast_str *m_text = ast_str_alloca(256);   /* Media declaration line for text */
10598    struct ast_str *m_modem = ast_str_alloca(256);  /* Media declaration line for modem */
10599    struct ast_str *a_audio = ast_str_alloca(1024); /* Attributes for audio */
10600    struct ast_str *a_video = ast_str_alloca(1024); /* Attributes for video */
10601    struct ast_str *a_text = ast_str_alloca(1024);  /* Attributes for text */
10602    struct ast_str *a_modem = ast_str_alloca(1024); /* Attributes for modem */
10603    const char *a_crypto = NULL;
10604    const char *v_a_crypto = NULL;
10605    const char *t_a_crypto = NULL;
10606 
10607    format_t x;
10608    format_t capability = 0;
10609    int needaudio = FALSE;
10610    int needvideo = FALSE;
10611    int needtext = FALSE;
10612    int debug = sip_debug_test_pvt(p);
10613    int min_audio_packet_size = 0;
10614    int min_video_packet_size = 0;
10615    int min_text_packet_size = 0;
10616 
10617    char codecbuf[SIPBUFSIZE];
10618    char buf[SIPBUFSIZE];
10619    char dummy_answer[256];
10620 
10621    /* Set the SDP session name */
10622    snprintf(subject, sizeof(subject), "s=%s\r\n", ast_strlen_zero(global_sdpsession) ? "-" : global_sdpsession);
10623 
10624    if (!p->rtp) {
10625       ast_log(LOG_WARNING, "No way to add SDP without an RTP structure\n");
10626       return AST_FAILURE;
10627    }
10628    /* XXX We should not change properties in the SIP dialog until
10629       we have acceptance of the offer if this is a re-invite */
10630 
10631    /* Set RTP Session ID and version */
10632    if (!p->sessionid) {
10633       p->sessionid = (int)ast_random();
10634       p->sessionversion = p->sessionid;
10635    } else {
10636       if (oldsdp == FALSE)
10637          p->sessionversion++;
10638    }
10639 
10640    if (add_audio) {
10641       doing_directmedia = (!ast_sockaddr_isnull(&p->redirip) && p->redircodecs) ? TRUE : FALSE;
10642       /* Check if we need video in this call */
10643       if ((p->jointcapability & AST_FORMAT_VIDEO_MASK) && !p->novideo) {
10644          if (p->vrtp) {
10645             needvideo = TRUE;
10646             ast_debug(2, "This call needs video offers!\n");
10647          } else
10648             ast_debug(2, "This call needs video offers, but there's no video support enabled!\n");
10649       }
10650       /* Check if we need text in this call */
10651       if ((p->jointcapability & AST_FORMAT_TEXT_MASK) && !p->notext) {
10652          if (sipdebug_text)
10653             ast_verbose("We think we can do text\n");
10654          if (p->trtp) {
10655             if (sipdebug_text) {
10656                ast_verbose("And we have a text rtp object\n");
10657             }
10658             needtext = TRUE;
10659             ast_debug(2, "This call needs text offers! \n");
10660          } else {
10661             ast_debug(2, "This call needs text offers, but there's no text support enabled ! \n");
10662          }
10663       }
10664    }
10665 
10666    get_our_media_address(p, needvideo, needtext, &addr, &vaddr, &taddr, &dest, &vdest, &tdest);
10667 
10668    snprintf(owner, sizeof(owner), "o=%s %d %d IN %s %s\r\n",
10669        ast_strlen_zero(global_sdpowner) ? "-" : global_sdpowner,
10670        p->sessionid, p->sessionversion,
10671        (ast_sockaddr_is_ipv6(&dest) && !ast_sockaddr_is_ipv4_mapped(&dest)) ?
10672          "IP6" : "IP4",
10673        ast_sockaddr_stringify_addr(&dest));
10674 
10675    snprintf(connection, sizeof(connection), "c=IN %s %s\r\n",
10676        (ast_sockaddr_is_ipv6(&dest) && !ast_sockaddr_is_ipv4_mapped(&dest)) ?
10677          "IP6" : "IP4",
10678        ast_sockaddr_stringify_addr(&dest));
10679 
10680    if (add_audio) {
10681       if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD) == SIP_PAGE2_CALL_ONHOLD_ONEDIR) {
10682          hold = "a=recvonly\r\n";
10683          doing_directmedia = FALSE;
10684       } else if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD) == SIP_PAGE2_CALL_ONHOLD_INACTIVE) {
10685          hold = "a=inactive\r\n";
10686          doing_directmedia = FALSE;
10687       } else {
10688          hold = "a=sendrecv\r\n";
10689       }
10690 
10691       capability = p->jointcapability;
10692 
10693       /* XXX note, Video and Text are negated - 'true' means 'no' */
10694       ast_debug(1, "** Our capability: %s Video flag: %s Text flag: %s\n", ast_getformatname_multiple(codecbuf, sizeof(codecbuf), capability),
10695            p->novideo ? "True" : "False", p->notext ? "True" : "False");
10696       ast_debug(1, "** Our prefcodec: %s \n", ast_getformatname_multiple(codecbuf, sizeof(codecbuf), p->prefcodec));
10697 
10698       if (doing_directmedia) {
10699          capability &= p->redircodecs;
10700          ast_debug(1, "** Our native-bridge filtered capablity: %s\n", ast_getformatname_multiple(codecbuf, sizeof(codecbuf), capability));
10701       }
10702 
10703       /* Check if we need audio */
10704       if (capability & AST_FORMAT_AUDIO_MASK)
10705          needaudio = TRUE;
10706 
10707       if (debug) {
10708          ast_verbose("Audio is at %s\n", ast_sockaddr_stringify_port(&p->ourip));
10709       }
10710 
10711       /* Ok, we need video. Let's add what we need for video and set codecs.
10712          Video is handled differently than audio since we can not transcode. */
10713       if (needvideo) {
10714          get_crypto_attrib(p->vsrtp, &v_a_crypto);
10715          ast_str_append(&m_video, 0, "m=video %d RTP/%s", ast_sockaddr_port(&vdest),
10716             v_a_crypto ? "SAVP" : "AVP");
10717 
10718          /* Build max bitrate string */
10719          if (p->maxcallbitrate)
10720             snprintf(bandwidth, sizeof(bandwidth), "b=CT:%d\r\n", p->maxcallbitrate);
10721          if (debug) {
10722             ast_verbose("Video is at %s\n", ast_sockaddr_stringify(&p->ourip));
10723          }
10724       }
10725 
10726       /* Ok, we need text. Let's add what we need for text and set codecs.
10727          Text is handled differently than audio since we can not transcode. */
10728       if (needtext) {
10729          if (sipdebug_text)
10730             ast_verbose("Lets set up the text sdp\n");
10731          get_crypto_attrib(p->tsrtp, &t_a_crypto);
10732          ast_str_append(&m_text, 0, "m=text %d RTP/%s", ast_sockaddr_port(&tdest),
10733             t_a_crypto ? "SAVP" : "AVP");
10734          if (debug) {  /* XXX should I use tdest below ? */
10735             ast_verbose("Text is at %s\n", ast_sockaddr_stringify(&p->ourip));
10736          }
10737       }
10738 
10739       /* Start building generic SDP headers */
10740 
10741       /* We break with the "recommendation" and send our IP, in order that our
10742          peer doesn't have to ast_gethostbyname() us */
10743 
10744       get_crypto_attrib(p->srtp, &a_crypto);
10745       ast_str_append(&m_audio, 0, "m=audio %d RTP/%s", ast_sockaddr_port(&dest),
10746          a_crypto ? "SAVP" : "AVP");
10747 
10748       /* Now, start adding audio codecs. These are added in this order:
10749          - First what was requested by the calling channel
10750          - Then preferences in order from sip.conf device config for this peer/user
10751          - Then other codecs in capabilities, including video
10752       */
10753 
10754       /* Prefer the audio codec we were requested to use, first, no matter what
10755          Note that p->prefcodec can include video codecs, so mask them out
10756       */
10757       if (capability & p->prefcodec) {
10758          format_t codec = p->prefcodec & AST_FORMAT_AUDIO_MASK;
10759 
10760          add_codec_to_sdp(p, codec, &m_audio, &a_audio, debug, &min_audio_packet_size);
10761          alreadysent |= codec;
10762       }
10763 
10764       /* Start by sending our preferred audio/video codecs */
10765       for (x = 0; x < 64; x++) {
10766          format_t codec;
10767 
10768          if (!(codec = ast_codec_pref_index(&p->prefs, x)))
10769             break;
10770 
10771          if (!(capability & codec))
10772             continue;
10773 
10774          if (alreadysent & codec)
10775             continue;
10776 
10777          add_codec_to_sdp(p, codec, &m_audio, &a_audio, debug, &min_audio_packet_size);
10778          alreadysent |= codec;
10779       }
10780 
10781       /* Now send any other common audio and video codecs, and non-codec formats: */
10782       for (x = 1ULL; x <= (needtext ? AST_FORMAT_TEXT_MASK : (needvideo ? AST_FORMAT_VIDEO_MASK : AST_FORMAT_AUDIO_MASK)); x <<= 1) {
10783          if (!(capability & x))  /* Codec not requested */
10784             continue;
10785 
10786          if (alreadysent & x) /* Already added to SDP */
10787             continue;
10788 
10789          if (x & AST_FORMAT_AUDIO_MASK)
10790             add_codec_to_sdp(p, x, &m_audio, &a_audio, debug, &min_audio_packet_size);
10791          else if (x & AST_FORMAT_VIDEO_MASK)
10792             add_vcodec_to_sdp(p, x, &m_video, &a_video, debug, &min_video_packet_size);
10793          else if (x & AST_FORMAT_TEXT_MASK)
10794             add_tcodec_to_sdp(p, x, &m_text, &a_text, debug, &min_text_packet_size);
10795       }
10796 
10797       /* Now add DTMF RFC2833 telephony-event as a codec */
10798       for (x = 1LL; x <= AST_RTP_MAX; x <<= 1) {
10799          if (!(p->jointnoncodeccapability & x))
10800             continue;
10801 
10802          add_noncodec_to_sdp(p, x, &m_audio, &a_audio, debug);
10803       }
10804 
10805       ast_debug(3, "-- Done with adding codecs to SDP\n");
10806 
10807       if (!p->owner || !ast_internal_timing_enabled(p->owner))
10808          ast_str_append(&a_audio, 0, "a=silenceSupp:off - - - -\r\n");
10809 
10810       if (min_audio_packet_size)
10811          ast_str_append(&a_audio, 0, "a=ptime:%d\r\n", min_audio_packet_size);
10812 
10813       /* XXX don't think you can have ptime for video */
10814       if (min_video_packet_size)
10815          ast_str_append(&a_video, 0, "a=ptime:%d\r\n", min_video_packet_size);
10816 
10817       /* XXX don't think you can have ptime for text */
10818       if (min_text_packet_size)
10819          ast_str_append(&a_text, 0, "a=ptime:%d\r\n", min_text_packet_size);
10820 
10821       if (m_audio->len - m_audio->used < 2 || m_video->len - m_video->used < 2 ||
10822           m_text->len - m_text->used < 2 || a_text->len - a_text->used < 2 ||
10823           a_audio->len - a_audio->used < 2 || a_video->len - a_video->used < 2)
10824          ast_log(LOG_WARNING, "SIP SDP may be truncated due to undersized buffer!!\n");
10825    }
10826 
10827    if (add_t38) {
10828       /* Our T.38 end is */
10829       ast_udptl_get_us(p->udptl, &udptladdr);
10830 
10831       /* Determine T.38 UDPTL destination */
10832       if (!ast_sockaddr_isnull(&p->udptlredirip)) {
10833          ast_sockaddr_copy(&udptldest, &p->udptlredirip);
10834       } else {
10835          ast_sockaddr_copy(&udptldest, &p->ourip);
10836          ast_sockaddr_set_port(&udptldest, ast_sockaddr_port(&udptladdr));
10837       }
10838 
10839       if (debug) {
10840          ast_debug(1, "T.38 UDPTL is at %s port %d\n", ast_sockaddr_stringify_addr(&p->ourip), ast_sockaddr_port(&udptladdr));
10841       }
10842 
10843       /* We break with the "recommendation" and send our IP, in order that our
10844          peer doesn't have to ast_gethostbyname() us */
10845 
10846       ast_str_append(&m_modem, 0, "m=image %d udptl t38\r\n", ast_sockaddr_port(&udptldest));
10847 
10848       if (!ast_sockaddr_cmp(&udptldest, &dest)) {
10849          ast_str_append(&m_modem, 0, "c=IN %s %s\r\n",
10850                (ast_sockaddr_is_ipv6(&dest) && !ast_sockaddr_is_ipv4_mapped(&dest)) ?
10851                "IP6" : "IP4", ast_sockaddr_stringify_addr(&udptldest));
10852       }
10853 
10854       ast_str_append(&a_modem, 0, "a=T38FaxVersion:%d\r\n", p->t38.our_parms.version);
10855       ast_str_append(&a_modem, 0, "a=T38MaxBitRate:%d\r\n", t38_get_rate(p->t38.our_parms.rate));
10856       if (p->t38.our_parms.fill_bit_removal) {
10857          ast_str_append(&a_modem, 0, "a=T38FaxFillBitRemoval\r\n");
10858       }
10859       if (p->t38.our_parms.transcoding_mmr) {
10860          ast_str_append(&a_modem, 0, "a=T38FaxTranscodingMMR\r\n");
10861       }
10862       if (p->t38.our_parms.transcoding_jbig) {
10863          ast_str_append(&a_modem, 0, "a=T38FaxTranscodingJBIG\r\n");
10864       }
10865       switch (p->t38.our_parms.rate_management) {
10866       case AST_T38_RATE_MANAGEMENT_TRANSFERRED_TCF:
10867          ast_str_append(&a_modem, 0, "a=T38FaxRateManagement:transferredTCF\r\n");
10868          break;
10869       case AST_T38_RATE_MANAGEMENT_LOCAL_TCF:
10870          ast_str_append(&a_modem, 0, "a=T38FaxRateManagement:localTCF\r\n");
10871          break;
10872       }
10873       ast_str_append(&a_modem, 0, "a=T38FaxMaxDatagram:%u\r\n", ast_udptl_get_local_max_datagram(p->udptl));
10874       switch (ast_udptl_get_error_correction_scheme(p->udptl)) {
10875       case UDPTL_ERROR_CORRECTION_NONE:
10876          break;
10877       case UDPTL_ERROR_CORRECTION_FEC:
10878          ast_str_append(&a_modem, 0, "a=T38FaxUdpEC:t38UDPFEC\r\n");
10879          break;
10880       case UDPTL_ERROR_CORRECTION_REDUNDANCY:
10881          ast_str_append(&a_modem, 0, "a=T38FaxUdpEC:t38UDPRedundancy\r\n");
10882          break;
10883       }
10884    }
10885 
10886    if (needaudio)
10887       ast_str_append(&m_audio, 0, "\r\n");
10888    if (needvideo)
10889       ast_str_append(&m_video, 0, "\r\n");
10890    if (needtext)
10891       ast_str_append(&m_text, 0, "\r\n");
10892 
10893    add_header(resp, "Content-Type", "application/sdp");
10894    add_content(resp, version);
10895    add_content(resp, owner);
10896    add_content(resp, subject);
10897    add_content(resp, connection);
10898    if (needvideo)    /* only if video response is appropriate */
10899       add_content(resp, bandwidth);
10900    add_content(resp, session_time);
10901    if (needaudio) {
10902       add_content(resp, m_audio->str);
10903       add_content(resp, a_audio->str);
10904       add_content(resp, hold);
10905       if (a_crypto) {
10906          add_content(resp, a_crypto);
10907       }
10908    } else if (p->offered_media[SDP_AUDIO].offered) {
10909       snprintf(dummy_answer, sizeof(dummy_answer), "m=audio 0 RTP/AVP %s\r\n", p->offered_media[SDP_AUDIO].codecs);
10910       add_content(resp, dummy_answer);
10911    }
10912    if (needvideo) { /* only if video response is appropriate */
10913       add_content(resp, m_video->str);
10914       add_content(resp, a_video->str);
10915       add_content(resp, hold);   /* Repeat hold for the video stream */
10916       if (v_a_crypto) {
10917          add_content(resp, v_a_crypto);
10918       }
10919    } else if (p->offered_media[SDP_VIDEO].offered) {
10920       snprintf(dummy_answer, sizeof(dummy_answer), "m=video 0 RTP/AVP %s\r\n", p->offered_media[SDP_VIDEO].codecs);
10921       add_content(resp, dummy_answer);
10922    }
10923    if (needtext) { /* only if text response is appropriate */
10924       add_content(resp, m_text->str);
10925       add_content(resp, a_text->str);
10926       add_content(resp, hold);   /* Repeat hold for the text stream */
10927       if (t_a_crypto) {
10928          add_content(resp, t_a_crypto);
10929       }
10930    } else if (p->offered_media[SDP_TEXT].offered) {
10931       snprintf(dummy_answer, sizeof(dummy_answer), "m=text 0 RTP/AVP %s\r\n", p->offered_media[SDP_TEXT].codecs);
10932       add_content(resp, dummy_answer);
10933    }
10934    if (add_t38) {
10935       add_content(resp, m_modem->str);
10936       add_content(resp, a_modem->str);
10937    } else if (p->offered_media[SDP_IMAGE].offered) {
10938       add_content(resp, "m=image 0 udptl t38\r\n");
10939    }
10940 
10941    /* Update lastrtprx when we send our SDP */
10942    p->lastrtprx = p->lastrtptx = time(NULL); /* XXX why both ? */
10943 
10944    ast_debug(3, "Done building SDP. Settling with this capability: %s\n", ast_getformatname_multiple(buf, SIPBUFSIZE, capability));
10945 
10946    return AST_SUCCESS;
10947 }
10948 
10949 /*! \brief Used for 200 OK and 183 early media */
10950 static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans)
10951 {
10952    struct sip_request resp;
10953    int seqno;
10954    
10955    if (sscanf(get_header(req, "CSeq"), "%30d ", &seqno) != 1) {
10956       ast_log(LOG_WARNING, "Unable to get seqno from '%s'\n", get_header(req, "CSeq"));
10957       return -1;
10958    }
10959    respprep(&resp, p, msg, req);
10960    if (p->udptl) {
10961       add_sdp(&resp, p, 0, 0, 1);
10962    } else
10963       ast_log(LOG_ERROR, "Can't add SDP to response, since we have no UDPTL session allocated. Call-ID %s\n", p->callid);
10964    if (retrans && !p->pendinginvite)
10965       p->pendinginvite = seqno;     /* Buggy clients sends ACK on RINGING too */
10966    return send_response(p, &resp, retrans, seqno);
10967 }
10968 
10969 /*! \brief copy SIP request (mostly used to save request for responses) */
10970 static void copy_request(struct sip_request *dst, const struct sip_request *src)
10971 {
10972    /* XXX this function can encounter memory allocation errors, perhaps it
10973     * should return a value */
10974 
10975    struct ast_str *duplicate = dst->data;
10976    struct ast_str *duplicate_content = dst->content;
10977 
10978    /* copy the entire request then restore the original data and content
10979     * members from the dst request */
10980    memcpy(dst, src, sizeof(*dst));
10981    dst->data = duplicate;
10982    dst->content = duplicate_content;
10983 
10984    /* copy the data into the dst request */
10985    if (!dst->data && !(dst->data = ast_str_create(ast_str_strlen(src->data) + 1)))
10986       return;
10987    ast_str_copy_string(&dst->data, src->data);
10988 
10989    /* copy the content into the dst request (if it exists) */
10990    if (src->content) {
10991       if (!dst->content && !(dst->content = ast_str_create(ast_str_strlen(src->content) + 1)))
10992          return;
10993       ast_str_copy_string(&dst->content, src->content);
10994    }
10995 }
10996 
10997 static void add_cc_call_info_to_response(struct sip_pvt *p, struct sip_request *resp)
10998 {
10999    char uri[SIPBUFSIZE];
11000    struct ast_str *header = ast_str_alloca(SIPBUFSIZE);
11001    struct ast_cc_agent *agent = find_sip_cc_agent_by_original_callid(p);
11002    struct sip_cc_agent_pvt *agent_pvt;
11003 
11004    if (!agent) {
11005       /* Um, what? How could the SIP_OFFER_CC flag be set but there not be an
11006        * agent? Oh well, we'll just warn and return without adding the header.
11007        */
11008       ast_log(LOG_WARNING, "Can't find SIP CC agent for call '%s' even though OFFER_CC flag was set?\n", p->callid);
11009       return;
11010    }
11011 
11012    agent_pvt = agent->private_data;
11013 
11014    if (!ast_strlen_zero(agent_pvt->subscribe_uri)) {
11015       ast_copy_string(uri, agent_pvt->subscribe_uri, sizeof(uri));
11016    } else {
11017       generate_uri(p, uri, sizeof(uri));
11018       ast_copy_string(agent_pvt->subscribe_uri, uri, sizeof(agent_pvt->subscribe_uri));
11019    }
11020    /* XXX Hardcode "NR" as the m reason for now. This should perhaps be changed
11021     * to be more accurate. This parameter has no bearing on the actual operation
11022     * of the feature; it's just there for informational purposes.
11023     */
11024    ast_str_set(&header, 0, "<%s>;purpose=call-completion;m=%s", uri, "NR");
11025    add_header(resp, "Call-Info", ast_str_buffer(header));
11026    ao2_ref(agent, -1);
11027 }
11028 
11029 /*! \brief Used for 200 OK and 183 early media
11030    \return Will return XMIT_ERROR for network errors.
11031 */
11032 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)
11033 {
11034    struct sip_request resp;
11035    int seqno;
11036    if (sscanf(get_header(req, "CSeq"), "%30d ", &seqno) != 1) {
11037       ast_log(LOG_WARNING, "Unable to get seqno from '%s'\n", get_header(req, "CSeq"));
11038       return -1;
11039    }
11040    respprep(&resp, p, msg, req);
11041    if (rpid == TRUE) {
11042       add_rpid(&resp, p);
11043    }
11044    if (ast_test_flag(&p->flags[0], SIP_OFFER_CC)) {
11045       add_cc_call_info_to_response(p, &resp);
11046    }
11047    if (p->rtp) {
11048       if (!p->autoframing && !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
11049          ast_debug(1, "Setting framing from config on incoming call\n");
11050          ast_rtp_codecs_packetization_set(ast_rtp_instance_get_codecs(p->rtp), p->rtp, &p->prefs);
11051       }
11052       ast_rtp_instance_activate(p->rtp);
11053       try_suggested_sip_codec(p);
11054       if (p->t38.state == T38_ENABLED) {
11055          add_sdp(&resp, p, oldsdp, TRUE, TRUE);
11056       } else {
11057          add_sdp(&resp, p, oldsdp, TRUE, FALSE);
11058       }
11059    } else
11060       ast_log(LOG_ERROR, "Can't add SDP to response, since we have no RTP session allocated. Call-ID %s\n", p->callid);
11061    if (reliable && !p->pendinginvite)
11062       p->pendinginvite = seqno;     /* Buggy clients sends ACK on RINGING too */
11063    return send_response(p, &resp, reliable, seqno);
11064 }
11065 
11066 /*! \brief Parse first line of incoming SIP request */
11067 static int determine_firstline_parts(struct sip_request *req)
11068 {
11069    char *e = ast_skip_blanks(req->data->str);   /* there shouldn't be any */
11070    char *local_rlPart1;
11071 
11072    if (!*e)
11073       return -1;
11074    req->rlPart1 = e - req->data->str;  /* method or protocol */
11075    local_rlPart1 = e;
11076    e = ast_skip_nonblanks(e);
11077    if (*e)
11078       *e++ = '\0';
11079    /* Get URI or status code */
11080    e = ast_skip_blanks(e);
11081    if ( !*e )
11082       return -1;
11083    ast_trim_blanks(e);
11084 
11085    if (!strcasecmp(local_rlPart1, "SIP/2.0") ) { /* We have a response */
11086       if (strlen(e) < 3)   /* status code is 3 digits */
11087          return -1;
11088       req->rlPart2 = e - req->data->str;
11089    } else { /* We have a request */
11090       if ( *e == '<' ) { /* XXX the spec says it must not be in <> ! */
11091          ast_debug(3, "Oops. Bogus uri in <> %s\n", e);
11092          e++;
11093          if (!*e)
11094             return -1;
11095       }
11096       req->rlPart2 = e - req->data->str;  /* URI */
11097       e = ast_skip_nonblanks(e);
11098       if (*e)
11099          *e++ = '\0';
11100       e = ast_skip_blanks(e);
11101       if (strcasecmp(e, "SIP/2.0") ) {
11102          ast_debug(3, "Skipping packet - Bad request protocol %s\n", e);
11103          return -1;
11104       }
11105    }
11106    return 1;
11107 }
11108 
11109 /*! \brief Transmit reinvite with SDP
11110 \note    A re-invite is basically a new INVITE with the same CALL-ID and TAG as the
11111    INVITE that opened the SIP dialogue
11112    We reinvite so that the audio stream (RTP) go directly between
11113    the SIP UAs. SIP Signalling stays with * in the path.
11114    
11115    If t38version is TRUE, we send T38 SDP for re-invite from audio/video to
11116    T38 UDPTL transmission on the channel
11117 
11118     If oldsdp is TRUE then the SDP version number is not incremented. This
11119     is needed for Session-Timers so we can send a re-invite to refresh the
11120     SIP session without modifying the media session.
11121 */
11122 static int transmit_reinvite_with_sdp(struct sip_pvt *p, int t38version, int oldsdp)
11123 {
11124    struct sip_request req;
11125    
11126    reqprep(&req, p, ast_test_flag(&p->flags[0], SIP_REINVITE_UPDATE) ?  SIP_UPDATE : SIP_INVITE, 0, 1);
11127 
11128    add_header(&req, "Allow", ALLOWED_METHODS);
11129    add_supported_header(p, &req);
11130    if (sipdebug) {
11131       if (oldsdp == TRUE)
11132          add_header(&req, "X-asterisk-Info", "SIP re-invite (Session-Timers)");
11133       else
11134          add_header(&req, "X-asterisk-Info", "SIP re-invite (External RTP bridge)");
11135    }
11136 
11137    if (ast_test_flag(&p->flags[0], SIP_SENDRPID))
11138       add_rpid(&req, p);
11139 
11140    if (p->do_history) {
11141       append_history(p, "ReInv", "Re-invite sent");
11142    }
11143    memset(p->offered_media, 0, sizeof(p->offered_media));
11144 
11145    try_suggested_sip_codec(p);
11146    if (t38version) {
11147       add_sdp(&req, p, oldsdp, FALSE, TRUE);
11148    } else {
11149       add_sdp(&req, p, oldsdp, TRUE, FALSE);
11150    }
11151 
11152    /* Use this as the basis */
11153    initialize_initreq(p, &req);
11154    p->lastinvite = p->ocseq;
11155    ast_set_flag(&p->flags[0], SIP_OUTGOING);       /* Change direction of this dialog */
11156 
11157    return send_request(p, &req, XMIT_CRITICAL, p->ocseq);
11158 }
11159 
11160 /* \brief Remove URI parameters at end of URI, not in username part though */
11161 static char *remove_uri_parameters(char *uri)
11162 {
11163    char *atsign;
11164    atsign = strchr(uri, '@'); /* First, locate the at sign */
11165    if (!atsign) {
11166       atsign = uri;  /* Ok hostname only, let's stick with the rest */
11167    }
11168    atsign = strchr(atsign, ';'); /* Locate semi colon */
11169    if (atsign)
11170       *atsign = '\0';   /* Kill at the semi colon */
11171    return uri;
11172 }
11173 
11174 /*! \brief Check Contact: URI of SIP message */
11175 static void extract_uri(struct sip_pvt *p, struct sip_request *req)
11176 {
11177    char stripped[SIPBUFSIZE];
11178    char *c;
11179 
11180    ast_copy_string(stripped, get_header(req, "Contact"), sizeof(stripped));
11181    c = get_in_brackets(stripped);
11182    /* Cut the URI at the at sign after the @, not in the username part */
11183    c = remove_uri_parameters(c);
11184    if (!ast_strlen_zero(c)) {
11185       ast_string_field_set(p, uri, c);
11186    }
11187 
11188 }
11189 
11190 /*! \brief Build contact header - the contact header we send out */
11191 static void build_contact(struct sip_pvt *p)
11192 {
11193    if (p->socket.type == SIP_TRANSPORT_UDP) {
11194       ast_string_field_build(p, our_contact, "<sip:%s%s%s>", p->exten,
11195          ast_strlen_zero(p->exten) ? "" : "@", ast_sockaddr_stringify(&p->ourip));
11196    } else {
11197       ast_string_field_build(p, our_contact, "<sip:%s%s%s;transport=%s>", p->exten,
11198          ast_strlen_zero(p->exten) ? "" : "@", ast_sockaddr_stringify(&p->ourip),
11199          get_transport(p->socket.type));
11200    }
11201 }
11202 
11203 /*! \brief Initiate new SIP request to peer/user */
11204 static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, const char * const explicit_uri)
11205 {
11206    struct ast_str *invite = ast_str_alloca(256);
11207    char from[256];
11208    char to[256];
11209    char tmp_n[SIPBUFSIZE/2];  /* build a local copy of 'n' if needed */
11210    char tmp_l[SIPBUFSIZE/2];  /* build a local copy of 'l' if needed */
11211    const char *l = NULL;   /* XXX what is this, exactly ? */
11212    const char *n = NULL;   /* XXX what is this, exactly ? */
11213    const char *d = NULL;   /* domain in from header */
11214    const char *urioptions = "";
11215    int ourport;
11216 
11217    if (ast_test_flag(&p->flags[0], SIP_USEREQPHONE)) {
11218       const char *s = p->username;  /* being a string field, cannot be NULL */
11219 
11220       /* Test p->username against allowed characters in AST_DIGIT_ANY
11221          If it matches the allowed characters list, then sipuser = ";user=phone"
11222          If not, then sipuser = ""
11223       */
11224       /* + is allowed in first position in a tel: uri */
11225       if (*s == '+')
11226          s++;
11227       for (; *s; s++) {
11228          if (!strchr(AST_DIGIT_ANYNUM, *s) )
11229             break;
11230       }
11231       /* If we have only digits, add ;user=phone to the uri */
11232       if (!*s)
11233          urioptions = ";user=phone";
11234    }
11235 
11236 
11237    snprintf(p->lastmsg, sizeof(p->lastmsg), "Init: %s", sip_methods[sipmethod].text);
11238 
11239    d = S_OR(p->fromdomain, ast_sockaddr_stringify_host(&p->ourip));
11240    if (p->owner) {
11241       if ((ast_party_id_presentation(&p->owner->connected.id) & AST_PRES_RESTRICTION) == AST_PRES_ALLOWED) {
11242          l = p->owner->connected.id.number.valid ? p->owner->connected.id.number.str : NULL;
11243          n = p->owner->connected.id.name.valid ? p->owner->connected.id.name.str : NULL;
11244       } else if (!ast_test_flag(&p->flags[0], SIP_SENDRPID)) {
11245          /* if we are not sending RPID and user wants his callerid restricted */    
11246          l = CALLERID_UNKNOWN;
11247          n = l;
11248          d = FROMDOMAIN_INVALID;
11249       }
11250    }
11251 
11252    /* Hey, it's a NOTIFY! See if they've configured a mwi_from.
11253     * XXX Right now, this logic works because the only place that mwi_from
11254     * is set on the sip_pvt is in sip_send_mwi_to_peer. If things changed, then
11255     * we might end up putting the mwi_from setting into other types of NOTIFY
11256     * messages as well.
11257     */
11258    if (sipmethod == SIP_NOTIFY && !ast_strlen_zero(p->mwi_from)) {
11259       l = p->mwi_from;
11260    }
11261 
11262    if (ast_strlen_zero(l))
11263       l = default_callerid;
11264    if (ast_strlen_zero(n))
11265       n = l;
11266    /* Allow user to be overridden */
11267    if (!ast_strlen_zero(p->fromuser))
11268       l = p->fromuser;
11269    else /* Save for any further attempts */
11270       ast_string_field_set(p, fromuser, l);
11271 
11272    /* Allow user to be overridden */
11273    if (!ast_strlen_zero(p->fromname))
11274       n = p->fromname;
11275    else /* Save for any further attempts */
11276       ast_string_field_set(p, fromname, n);
11277 
11278    if (sip_cfg.pedanticsipchecking) {
11279       ast_uri_encode(n, tmp_n, sizeof(tmp_n), 0);
11280       n = tmp_n;
11281       ast_uri_encode(l, tmp_l, sizeof(tmp_l), 0);
11282       l = tmp_l;
11283    }
11284 
11285    ourport = (p->fromdomainport) ? p->fromdomainport : ast_sockaddr_port(&p->ourip);
11286    if (!sip_standard_port(p->socket.type, ourport)) {
11287       snprintf(from, sizeof(from), "\"%s\" <sip:%s@%s:%d>;tag=%s", n, l, d, ourport, p->tag);
11288    } else {
11289       snprintf(from, sizeof(from), "\"%s\" <sip:%s@%s>;tag=%s", n, l, d, p->tag);
11290    }
11291 
11292    if (!ast_strlen_zero(explicit_uri)) {
11293       ast_str_set(&invite, 0, "%s", explicit_uri);
11294    } else {
11295       /* If we're calling a registered SIP peer, use the fullcontact to dial to the peer */
11296       if (!ast_strlen_zero(p->fullcontact)) {
11297          /* If we have full contact, trust it */
11298          ast_str_append(&invite, 0, "%s", p->fullcontact);
11299       } else {
11300          /* Otherwise, use the username while waiting for registration */
11301          ast_str_append(&invite, 0, "sip:");
11302          if (!ast_strlen_zero(p->username)) {
11303             n = p->username;
11304             if (sip_cfg.pedanticsipchecking) {
11305                ast_uri_encode(n, tmp_n, sizeof(tmp_n), 0);
11306                n = tmp_n;
11307             }
11308             ast_str_append(&invite, 0, "%s@", n);
11309          }
11310          ast_str_append(&invite, 0, "%s", p->tohost);
11311          if (p->portinuri) {
11312             ast_str_append(&invite, 0, ":%d", ast_sockaddr_port(&p->sa));
11313          }
11314          ast_str_append(&invite, 0, "%s", urioptions);
11315       }
11316    }
11317 
11318    /* If custom URI options have been provided, append them */
11319    if (p->options && !ast_strlen_zero(p->options->uri_options))
11320       ast_str_append(&invite, 0, ";%s", p->options->uri_options);
11321    
11322    /* This is the request URI, which is the next hop of the call
11323       which may or may not be the destination of the call
11324    */
11325    ast_string_field_set(p, uri, invite->str);
11326 
11327    if (!ast_strlen_zero(p->todnid)) {
11328       /*! \todo Need to add back the VXML URL here at some point, possibly use build_string for all this junk */
11329       if (!strchr(p->todnid, '@')) {
11330          /* We have no domain in the dnid */
11331          snprintf(to, sizeof(to), "<sip:%s@%s>%s%s", p->todnid, p->tohost, ast_strlen_zero(p->theirtag) ? "" : ";tag=", p->theirtag);
11332       } else {
11333          snprintf(to, sizeof(to), "<sip:%s>%s%s", p->todnid, ast_strlen_zero(p->theirtag) ? "" : ";tag=", p->theirtag);
11334       }
11335    } else {
11336       if (sipmethod == SIP_NOTIFY && !ast_strlen_zero(p->theirtag)) {
11337          /* If this is a NOTIFY, use the From: tag in the subscribe (RFC 3265) */
11338          snprintf(to, sizeof(to), "<%s%s>;tag=%s", (strncasecmp(p->uri, "sip:", 4) ? "sip:" : ""), p->uri, p->theirtag);
11339       } else if (p->options && p->options->vxml_url) {
11340          /* If there is a VXML URL append it to the SIP URL */
11341          snprintf(to, sizeof(to), "<%s>;%s", p->uri, p->options->vxml_url);
11342       } else {
11343          snprintf(to, sizeof(to), "<%s>", p->uri);
11344       }
11345    }
11346 
11347    init_req(req, sipmethod, p->uri);
11348    /* now tmp_n is available so reuse it to build the CSeq */
11349    snprintf(tmp_n, sizeof(tmp_n), "%d %s", ++p->ocseq, sip_methods[sipmethod].text);
11350 
11351    add_header(req, "Via", p->via);
11352    add_header_max_forwards(p, req);
11353    /* This will be a no-op most of the time. However, under certain circumstances,
11354     * NOTIFY messages will use this function for preparing the request and should
11355     * have Route headers present.
11356     */
11357    add_route(req, p->route);
11358 
11359    add_header(req, "From", from);
11360    add_header(req, "To", to);
11361    ast_string_field_set(p, exten, l);
11362    build_contact(p);
11363    add_header(req, "Contact", p->our_contact);
11364    add_header(req, "Call-ID", p->callid);
11365    add_header(req, "CSeq", tmp_n);
11366    if (!ast_strlen_zero(global_useragent)) {
11367       add_header(req, "User-Agent", global_useragent);
11368    }
11369 }
11370 
11371 /*! \brief Add "Diversion" header to outgoing message
11372  *
11373  * We need to add a Diversion header if the owner channel of
11374  * this dialog has redirecting information associated with it.
11375  *
11376  * \param req The request/response to which we will add the header
11377  * \param pvt The sip_pvt which represents the call-leg
11378  */
11379 static void add_diversion_header(struct sip_request *req, struct sip_pvt *pvt)
11380 {
11381    const char *diverting_number;
11382    const char *diverting_name;
11383    const char *reason;
11384    char header_text[256];
11385 
11386    if (!pvt->owner) {
11387       return;
11388    }
11389 
11390    diverting_number = pvt->owner->redirecting.from.number.str;
11391    if (!pvt->owner->redirecting.from.number.valid
11392       || ast_strlen_zero(diverting_number)) {
11393       return;
11394    }
11395 
11396    reason = sip_reason_code_to_str(pvt->owner->redirecting.reason);
11397 
11398    /* We at least have a number to place in the Diversion header, which is enough */
11399    diverting_name = pvt->owner->redirecting.from.name.str;
11400    if (!pvt->owner->redirecting.from.name.valid
11401       || ast_strlen_zero(diverting_name)) {
11402       snprintf(header_text, sizeof(header_text), "<sip:%s@%s>;reason=%s", diverting_number,
11403             ast_sockaddr_stringify_host(&pvt->ourip), reason);
11404    } else {
11405       snprintf(header_text, sizeof(header_text), "\"%s\" <sip:%s@%s>;reason=%s",
11406             diverting_name, diverting_number,
11407             ast_sockaddr_stringify_host(&pvt->ourip), reason);
11408    }
11409 
11410    add_header(req, "Diversion", header_text);
11411 }
11412 
11413 static int transmit_publish(struct sip_epa_entry *epa_entry, enum sip_publish_type publish_type, const char * const explicit_uri)
11414 {
11415    struct sip_pvt *pvt;
11416    int expires;
11417 
11418    epa_entry->publish_type = publish_type;
11419 
11420    if (!(pvt = sip_alloc(NULL, NULL, 0, SIP_PUBLISH, NULL))) {
11421       return -1;
11422    }
11423 
11424    sip_pvt_lock(pvt);
11425 
11426    if (create_addr(pvt, epa_entry->destination, NULL, TRUE, NULL)) {
11427       sip_pvt_unlock(pvt);
11428       dialog_unlink_all(pvt, TRUE, TRUE);
11429       dialog_unref(pvt, "create_addr failed in transmit_publish. Unref dialog");
11430       return -1;
11431    }
11432    ast_sip_ouraddrfor(&pvt->sa, &pvt->ourip, pvt);
11433    ast_set_flag(&pvt->flags[0], SIP_OUTGOING);
11434    expires = (publish_type == SIP_PUBLISH_REMOVE) ? 0 : DEFAULT_PUBLISH_EXPIRES;
11435    pvt->expiry = expires;
11436 
11437    /* Bump refcount for sip_pvt's reference */
11438    ao2_ref(epa_entry, +1);
11439    pvt->epa_entry = epa_entry;
11440 
11441    transmit_invite(pvt, SIP_PUBLISH, FALSE, 2, explicit_uri);
11442    sip_pvt_unlock(pvt);
11443    sip_scheddestroy(pvt, DEFAULT_TRANS_TIMEOUT);
11444    dialog_unref(pvt, "Done with the sip_pvt allocated for transmitting PUBLISH");
11445    return 0;
11446 }
11447 
11448 /*! 
11449  * \brief Build REFER/INVITE/OPTIONS/SUBSCRIBE message and transmit it
11450  * \param p sip_pvt structure
11451  * \param sipmethod
11452  * \param sdp unknown
11453  * \param init 0 = Prepare request within dialog, 1= prepare request, new branch,
11454  *  2= prepare new request and new dialog. do_proxy_auth calls this with init!=2
11455  * \param explicit_uri
11456 */
11457 static int transmit_invite(struct sip_pvt *p, int sipmethod, int sdp, int init, const char * const explicit_uri)
11458 {
11459    struct sip_request req;
11460    struct ast_variable *var;
11461    
11462    req.method = sipmethod;
11463    if (init) {/* Bump branch even on initial requests */
11464       p->branch ^= ast_random();
11465       p->invite_branch = p->branch;
11466       build_via(p);
11467    }
11468    if (init > 1) {
11469       initreqprep(&req, p, sipmethod, explicit_uri);
11470    } else {
11471       /* If init=1, we should not generate a new branch. If it's 0, we need a new branch. */
11472       reqprep(&req, p, sipmethod, 0, init ? 0 : 1);
11473    }
11474       
11475    if (p->options && p->options->auth) {
11476       add_header(&req, p->options->authheader, p->options->auth);
11477    }
11478    append_date(&req);
11479    if (sipmethod == SIP_REFER) { /* Call transfer */
11480       if (p->refer) {
11481          char buf[SIPBUFSIZE];
11482          if (!ast_strlen_zero(p->refer->refer_to)) {
11483             add_header(&req, "Refer-To", p->refer->refer_to);
11484          }
11485          if (!ast_strlen_zero(p->refer->referred_by)) {
11486             snprintf(buf, sizeof(buf), "%s <%s>", p->refer->referred_by_name, p->refer->referred_by);
11487             add_header(&req, "Referred-By", buf);
11488          }
11489       }
11490    } else if (sipmethod == SIP_SUBSCRIBE) {
11491       char buf[SIPBUFSIZE];
11492       if (p->subscribed == MWI_NOTIFICATION) {
11493          add_header(&req, "Event", "message-summary");
11494          add_header(&req, "Accept", "application/simple-message-summary");
11495       } else if (p->subscribed == CALL_COMPLETION) {
11496          add_header(&req, "Event", "call-completion");
11497          add_header(&req, "Accept", "application/call-completion");
11498       }
11499       snprintf(buf, sizeof(buf), "%d", p->expiry);
11500       add_header(&req, "Expires", buf);
11501    }
11502 
11503    /* This new INVITE is part of an attended transfer. Make sure that the
11504    other end knows and replace the current call with this new call */
11505    if (p->options && !ast_strlen_zero(p->options->replaces)) {
11506       add_header(&req, "Replaces", p->options->replaces);
11507       add_header(&req, "Require", "replaces");
11508    }
11509 
11510    /* Add Session-Timers related headers */
11511    if (st_get_mode(p) == SESSION_TIMER_MODE_ORIGINATE) {
11512       char i2astr[10];
11513 
11514       if (!p->stimer->st_interval) {
11515          p->stimer->st_interval = st_get_se(p, TRUE);
11516       }
11517 
11518       p->stimer->st_active = TRUE;
11519       
11520       snprintf(i2astr, sizeof(i2astr), "%d", p->stimer->st_interval);
11521       add_header(&req, "Session-Expires", i2astr);
11522       snprintf(i2astr, sizeof(i2astr), "%d", st_get_se(p, FALSE));
11523       add_header(&req, "Min-SE", i2astr);
11524    }
11525 
11526    add_header(&req, "Allow", ALLOWED_METHODS);
11527    add_supported_header(p, &req);
11528 
11529    if (p->options && p->options->addsipheaders && p->owner) {
11530       struct ast_channel *chan = p->owner; /* The owner channel */
11531       struct varshead *headp;
11532    
11533       ast_channel_lock(chan);
11534 
11535       headp = &chan->varshead;
11536 
11537       if (!headp) {
11538          ast_log(LOG_WARNING, "No Headp for the channel...ooops!\n");
11539       } else {
11540          const struct ast_var_t *current;
11541          AST_LIST_TRAVERSE(headp, current, entries) {
11542             /* SIPADDHEADER: Add SIP header to outgoing call */
11543             if (!strncasecmp(ast_var_name(current), "SIPADDHEADER", strlen("SIPADDHEADER"))) {
11544                char *content, *end;
11545                const char *header = ast_var_value(current);
11546                char *headdup = ast_strdupa(header);
11547 
11548                /* Strip of the starting " (if it's there) */
11549                if (*headdup == '"') {
11550                   headdup++;
11551                }
11552                if ((content = strchr(headdup, ':'))) {
11553                   *content++ = '\0';
11554                   content = ast_skip_blanks(content); /* Skip white space */
11555                   /* Strip the ending " (if it's there) */
11556                   end = content + strlen(content) -1; 
11557                   if (*end == '"') {
11558                      *end = '\0';
11559                   }
11560                
11561                   add_header(&req, headdup, content);
11562                   if (sipdebug) {
11563                      ast_debug(1, "Adding SIP Header \"%s\" with content :%s: \n", headdup, content);
11564                   }
11565                }
11566             }
11567          }
11568       }
11569 
11570       ast_channel_unlock(chan);
11571    }
11572    if ((sipmethod == SIP_INVITE || sipmethod == SIP_UPDATE) && ast_test_flag(&p->flags[0], SIP_SENDRPID))
11573       add_rpid(&req, p);
11574    if (sipmethod == SIP_INVITE) {
11575       add_diversion_header(&req, p);
11576    }
11577    if (sdp) {
11578       memset(p->offered_media, 0, sizeof(p->offered_media));
11579       if (p->udptl && p->t38.state == T38_LOCAL_REINVITE) {
11580          ast_debug(1, "T38 is in state %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
11581          add_sdp(&req, p, FALSE, FALSE, TRUE);
11582       } else if (p->rtp) {
11583          try_suggested_sip_codec(p);
11584          add_sdp(&req, p, FALSE, TRUE, FALSE);
11585       }
11586    } else if (p->notify) {
11587       for (var = p->notify->headers; var; var = var->next) {
11588          add_header(&req, var->name, var->value);
11589       }
11590       if (ast_str_strlen(p->notify->content)) {
11591          add_content(&req, ast_str_buffer(p->notify->content));
11592       }
11593    } else if (sipmethod == SIP_PUBLISH) {
11594       char expires[SIPBUFSIZE];
11595 
11596       switch (p->epa_entry->static_data->event) {
11597       case CALL_COMPLETION:
11598          snprintf(expires, sizeof(expires), "%d", p->expiry);
11599          add_header(&req, "Event", "call-completion");
11600          add_header(&req, "Expires", expires);
11601          if (p->epa_entry->publish_type != SIP_PUBLISH_INITIAL) {
11602             add_header(&req, "SIP-If-Match", p->epa_entry->entity_tag);
11603          }
11604 
11605          if (!ast_strlen_zero(p->epa_entry->body)) {
11606             add_header(&req, "Content-Type", "application/pidf+xml");
11607             add_content(&req, p->epa_entry->body);
11608          }
11609       default:
11610          break;
11611       }
11612    }
11613 
11614    if (!p->initreq.headers || init > 2) {
11615       initialize_initreq(p, &req);
11616    }
11617    if (sipmethod == SIP_INVITE || sipmethod == SIP_SUBSCRIBE) {
11618       p->lastinvite = p->ocseq;
11619    }
11620    return send_request(p, &req, init ? XMIT_CRITICAL : XMIT_RELIABLE, p->ocseq);
11621 }
11622 
11623 /*! \brief Send a subscription or resubscription for MWI */
11624 static int sip_subscribe_mwi_do(const void *data)
11625 {
11626    struct sip_subscription_mwi *mwi = (struct sip_subscription_mwi*)data;
11627    
11628    if (!mwi) {
11629       return -1;
11630    }
11631    
11632    mwi->resub = -1;
11633    __sip_subscribe_mwi_do(mwi);
11634    ASTOBJ_UNREF(mwi, sip_subscribe_mwi_destroy);
11635    
11636    return 0;
11637 }
11638 
11639 /*! \brief Actually setup an MWI subscription or resubscribe */
11640 static int __sip_subscribe_mwi_do(struct sip_subscription_mwi *mwi)
11641 {
11642    /* If we have no DNS manager let's do a lookup */
11643    if (!mwi->dnsmgr) {
11644       char transport[MAXHOSTNAMELEN];
11645       snprintf(transport, sizeof(transport), "_%s._%s", get_srv_service(mwi->transport), get_srv_protocol(mwi->transport));
11646 
11647       mwi->us.ss.ss_family = get_address_family_filter(&bindaddr); /* Filter address family */
11648       ast_dnsmgr_lookup(mwi->hostname, &mwi->us, &mwi->dnsmgr, sip_cfg.srvlookup ? transport : NULL);
11649    }
11650 
11651    /* If we already have a subscription up simply send a resubscription */
11652    if (mwi->call) {
11653       transmit_invite(mwi->call, SIP_SUBSCRIBE, 0, 0, NULL);
11654       return 0;
11655    }
11656    
11657    /* Create a dialog that we will use for the subscription */
11658    if (!(mwi->call = sip_alloc(NULL, NULL, 0, SIP_SUBSCRIBE, NULL))) {
11659       return -1;
11660    }
11661 
11662    ref_proxy(mwi->call, obproxy_get(mwi->call, NULL));
11663 
11664    if (!ast_sockaddr_port(&mwi->us) && mwi->portno) {
11665       ast_sockaddr_set_port(&mwi->us, mwi->portno);
11666    }
11667    
11668    /* Setup the destination of our subscription */
11669    if (create_addr(mwi->call, mwi->hostname, &mwi->us, 0, NULL)) {
11670       dialog_unlink_all(mwi->call, TRUE, TRUE);
11671       mwi->call = dialog_unref(mwi->call, "unref dialog after unlink_all");
11672       return 0;
11673    }
11674 
11675    mwi->call->expiry = mwi_expiry;
11676    
11677    if (!mwi->dnsmgr && mwi->portno) {
11678       ast_sockaddr_set_port(&mwi->call->sa, mwi->portno);
11679       ast_sockaddr_set_port(&mwi->call->recv, mwi->portno);
11680    } else {
11681       mwi->portno = ast_sockaddr_port(&mwi->call->sa);
11682    }
11683    
11684    /* Set various other information */
11685    if (!ast_strlen_zero(mwi->authuser)) {
11686       ast_string_field_set(mwi->call, peername, mwi->authuser);
11687       ast_string_field_set(mwi->call, authname, mwi->authuser);
11688       ast_string_field_set(mwi->call, fromuser, mwi->authuser);
11689    } else {
11690       ast_string_field_set(mwi->call, peername, mwi->username);
11691       ast_string_field_set(mwi->call, authname, mwi->username);
11692       ast_string_field_set(mwi->call, fromuser, mwi->username);
11693    }
11694    ast_string_field_set(mwi->call, username, mwi->username);
11695    if (!ast_strlen_zero(mwi->secret)) {
11696       ast_string_field_set(mwi->call, peersecret, mwi->secret);
11697    }
11698    set_socket_transport(&mwi->call->socket, mwi->transport);
11699    mwi->call->socket.port = htons(mwi->portno);
11700    ast_sip_ouraddrfor(&mwi->call->sa, &mwi->call->ourip, mwi->call);
11701    build_contact(mwi->call);
11702    build_via(mwi->call);
11703    build_callid_pvt(mwi->call);
11704    ast_set_flag(&mwi->call->flags[0], SIP_OUTGOING);
11705    
11706    /* Associate the call with us */
11707    mwi->call->mwi = ASTOBJ_REF(mwi);
11708 
11709    mwi->call->subscribed = MWI_NOTIFICATION;
11710 
11711    /* Actually send the packet */
11712    transmit_invite(mwi->call, SIP_SUBSCRIBE, 0, 2, NULL);
11713 
11714    return 0;
11715 }
11716 
11717 /*! \brief Find the channel that is causing the RINGING update */
11718 static int find_calling_channel(void *obj, void *arg, void *data, int flags)
11719 {
11720    struct ast_channel *c = obj;
11721    struct sip_pvt *p = data;
11722    int res;
11723 
11724    ast_channel_lock(c);
11725 
11726    res = (c->pbx &&
11727          (!strcasecmp(c->macroexten, p->exten) || !strcasecmp(c->exten, p->exten)) &&
11728          (sip_cfg.notifycid == IGNORE_CONTEXT || !strcasecmp(c->context, p->context)));
11729 
11730    ast_channel_unlock(c);
11731 
11732    return res ? CMP_MATCH | CMP_STOP : 0;
11733 }
11734 
11735 /*! \brief Builds XML portion of NOTIFY messages for presence or dialog updates */
11736 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)
11737 {
11738    enum state { NOTIFY_OPEN, NOTIFY_INUSE, NOTIFY_CLOSED } local_state = NOTIFY_OPEN;
11739    const char *statestring = "terminated";
11740    const char *pidfstate = "--";
11741    const char *pidfnote= "Ready";
11742    char hint[AST_MAX_EXTENSION];
11743 
11744    switch (state) {
11745    case (AST_EXTENSION_RINGING | AST_EXTENSION_INUSE):
11746       statestring = (sip_cfg.notifyringing) ? "early" : "confirmed";
11747       local_state = NOTIFY_INUSE;
11748       pidfstate = "busy";
11749       pidfnote = "Ringing";
11750       break;
11751    case AST_EXTENSION_RINGING:
11752       statestring = "early";
11753       local_state = NOTIFY_INUSE;
11754       pidfstate = "busy";
11755       pidfnote = "Ringing";
11756       break;
11757    case AST_EXTENSION_INUSE:
11758       statestring = "confirmed";
11759       local_state = NOTIFY_INUSE;
11760       pidfstate = "busy";
11761       pidfnote = "On the phone";
11762       break;
11763    case AST_EXTENSION_BUSY:
11764       statestring = "confirmed";
11765       local_state = NOTIFY_CLOSED;
11766       pidfstate = "busy";
11767       pidfnote = "On the phone";
11768       break;
11769    case AST_EXTENSION_UNAVAILABLE:
11770       statestring = "terminated";
11771       local_state = NOTIFY_CLOSED;
11772       pidfstate = "away";
11773       pidfnote = "Unavailable";
11774       break;
11775    case AST_EXTENSION_ONHOLD:
11776       statestring = "confirmed";
11777       local_state = NOTIFY_CLOSED;
11778       pidfstate = "busy";
11779       pidfnote = "On hold";
11780       break;
11781    case AST_EXTENSION_NOT_INUSE:
11782    default:
11783       /* Default setting */
11784       break;
11785    }
11786 
11787    /* Check which device/devices we are watching  and if they are registered */
11788    if (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, context, exten)) {
11789       char *hint2 = hint, *individual_hint = NULL;
11790       int hint_count = 0, unavailable_count = 0;
11791 
11792       while ((individual_hint = strsep(&hint2, "&"))) {
11793          hint_count++;
11794 
11795          if (ast_device_state(individual_hint) == AST_DEVICE_UNAVAILABLE)
11796             unavailable_count++;
11797       }
11798 
11799       /* If none of the hinted devices are registered, we will
11800        * override notification and show no availability.
11801        */
11802       if (hint_count > 0 && hint_count == unavailable_count) {
11803          local_state = NOTIFY_CLOSED;
11804          pidfstate = "away";
11805          pidfnote = "Not online";
11806       }
11807    }
11808 
11809    switch (subscribed) {
11810    case XPIDF_XML:
11811    case CPIM_PIDF_XML:
11812       ast_str_append(tmp, 0,
11813          "<?xml version=\"1.0\"?>\n"
11814          "<!DOCTYPE presence PUBLIC \"-//IETF//DTD RFCxxxx XPIDF 1.0//EN\" \"xpidf.dtd\">\n"
11815          "<presence>\n");
11816       ast_str_append(tmp, 0, "<presentity uri=\"%s;method=SUBSCRIBE\" />\n", mfrom);
11817       ast_str_append(tmp, 0, "<atom id=\"%s\">\n", exten);
11818       ast_str_append(tmp, 0, "<address uri=\"%s;user=ip\" priority=\"0.800000\">\n", mto);
11819       ast_str_append(tmp, 0, "<status status=\"%s\" />\n", (local_state ==  NOTIFY_OPEN) ? "open" : (local_state == NOTIFY_INUSE) ? "inuse" : "closed");
11820       ast_str_append(tmp, 0, "<msnsubstatus substatus=\"%s\" />\n", (local_state == NOTIFY_OPEN) ? "online" : (local_state == NOTIFY_INUSE) ? "onthephone" : "offline");
11821       ast_str_append(tmp, 0, "</address>\n</atom>\n</presence>\n");
11822       break;
11823    case PIDF_XML: /* Eyebeam supports this format */
11824       ast_str_append(tmp, 0,
11825          "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n"
11826          "<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);
11827       ast_str_append(tmp, 0, "<pp:person><status>\n");
11828       if (pidfstate[0] != '-') {
11829          ast_str_append(tmp, 0, "<ep:activities><ep:%s/></ep:activities>\n", pidfstate);
11830       }
11831       ast_str_append(tmp, 0, "</status></pp:person>\n");
11832       ast_str_append(tmp, 0, "<note>%s</note>\n", pidfnote); /* Note */
11833       ast_str_append(tmp, 0, "<tuple id=\"%s\">\n", exten); /* Tuple start */
11834       ast_str_append(tmp, 0, "<contact priority=\"1\">%s</contact>\n", mto);
11835       if (pidfstate[0] == 'b') /* Busy? Still open ... */
11836          ast_str_append(tmp, 0, "<status><basic>open</basic></status>\n");
11837       else
11838          ast_str_append(tmp, 0, "<status><basic>%s</basic></status>\n", (local_state != NOTIFY_CLOSED) ? "open" : "closed");
11839       ast_str_append(tmp, 0, "</tuple>\n</presence>\n");
11840       break;
11841    case DIALOG_INFO_XML: /* SNOM subscribes in this format */
11842       ast_str_append(tmp, 0, "<?xml version=\"1.0\"?>");
11843       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);
11844       if ((state & AST_EXTENSION_RINGING) && sip_cfg.notifyringing) {
11845          const char *local_display = exten;
11846          char *local_target = ast_strdupa(mto);
11847 
11848          /* There are some limitations to how this works.  The primary one is that the
11849             callee must be dialing the same extension that is being monitored.  Simply dialing
11850             the hint'd device is not sufficient. */
11851          if (sip_cfg.notifycid) {
11852             struct ast_channel *caller;
11853 
11854             if ((caller = ast_channel_callback(find_calling_channel, NULL, p, 0))) {
11855                char *cid_num;
11856                int need;
11857 
11858                ast_channel_lock(caller);
11859                cid_num = S_COR(caller->caller.id.number.valid,
11860                   caller->caller.id.number.str, "");
11861                need = strlen(cid_num) + strlen(p->fromdomain) + sizeof("sip:@");
11862                local_target = alloca(need);
11863                snprintf(local_target, need, "sip:%s@%s", cid_num, p->fromdomain);
11864                local_display = ast_strdupa(S_COR(caller->caller.id.name.valid,
11865                   caller->caller.id.name.str, ""));
11866                ast_channel_unlock(caller);
11867                caller = ast_channel_unref(caller);
11868             }
11869 
11870             /* We create a fake call-id which the phone will send back in an INVITE
11871                Replaces header which we can grab and do some magic with. */
11872             if (sip_cfg.pedanticsipchecking) {
11873                ast_str_append(tmp, 0, "<dialog id=\"%s\" call-id=\"pickup-%s\" local-tag=\"%s\" remote-tag=\"%s\" direction=\"recipient\">\n",
11874                   exten, p->callid, p->theirtag, p->tag);
11875             } else {
11876                ast_str_append(tmp, 0, "<dialog id=\"%s\" call-id=\"pickup-%s\" direction=\"recipient\">\n",
11877                   exten, p->callid);
11878             }
11879             ast_str_append(tmp, 0,
11880                   "<remote>\n"
11881                   /* See the limitations of this above.  Luckily the phone seems to still be
11882                      happy when these values are not correct. */
11883                   "<identity display=\"%s\">%s</identity>\n"
11884                   "<target uri=\"%s\"/>\n"
11885                   "</remote>\n"
11886                   "<local>\n"
11887                   "<identity>%s</identity>\n"
11888                   "<target uri=\"%s\"/>\n"
11889                   "</local>\n",
11890                   local_display, local_target, local_target, mto, mto);
11891          } else {
11892             ast_str_append(tmp, 0, "<dialog id=\"%s\" direction=\"recipient\">\n", exten);
11893          }
11894 
11895       } else {
11896          ast_str_append(tmp, 0, "<dialog id=\"%s\">", exten);
11897       }
11898       ast_str_append(tmp, 0, "<state>%s</state>\n", statestring);
11899       if (state == AST_EXTENSION_ONHOLD) {
11900             ast_str_append(tmp, 0, "<local>\n<target uri=\"%s\">\n"
11901                                              "<param pname=\"+sip.rendering\" pvalue=\"no\"/>\n"
11902                                              "</target>\n</local>\n", mto);
11903       }
11904       ast_str_append(tmp, 0, "</dialog>\n</dialog-info>\n");
11905       break;
11906    case NONE:
11907    default:
11908       break;
11909    }
11910 }
11911 
11912 static int transmit_cc_notify(struct ast_cc_agent *agent, struct sip_pvt *subscription, enum sip_cc_notify_state state)
11913 {
11914    struct sip_request req;
11915    struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
11916    char uri[SIPBUFSIZE];
11917    char state_str[64];
11918 
11919    if (state < CC_QUEUED || state > CC_READY) {
11920       ast_log(LOG_WARNING, "Invalid state provided for transmit_cc_notify (%d)\n", state);
11921       return -1;
11922    }
11923 
11924    reqprep(&req, subscription, SIP_NOTIFY, 0, TRUE);
11925    snprintf(state_str, sizeof(state_str), "%s\r\n", sip_cc_notify_state_map[state].state_string);
11926    add_header(&req, "Event", "call-completion");
11927    add_header(&req, "Content-Type", "application/call-completion");
11928    if (state == CC_READY) {
11929       generate_uri(subscription, agent_pvt->notify_uri, sizeof(agent_pvt->notify_uri));
11930       snprintf(uri, sizeof(uri) - 1, "cc-URI: %s\r\n", agent_pvt->notify_uri);
11931    }
11932    add_content(&req, state_str);
11933    if (state == CC_READY) {
11934       add_content(&req, uri);
11935    }
11936    return send_request(subscription, &req, XMIT_RELIABLE, subscription->ocseq);
11937 }
11938 
11939 /*! \brief Used in the SUBSCRIBE notification subsystem (RFC3265) */
11940 static int transmit_state_notify(struct sip_pvt *p, int state, int full, int timeout)
11941 {
11942    struct ast_str *tmp = ast_str_alloca(4000);
11943    char from[256], to[256];
11944    char *c, *mfrom, *mto;
11945    struct sip_request req;
11946    const struct cfsubscription_types *subscriptiontype;
11947 
11948    memset(from, 0, sizeof(from));
11949    memset(to, 0, sizeof(to));
11950 
11951    subscriptiontype = find_subscription_type(p->subscribed);
11952 
11953    ast_copy_string(from, get_header(&p->initreq, "From"), sizeof(from));
11954    c = get_in_brackets(from);
11955    if (strncasecmp(c, "sip:", 4) && strncasecmp(c, "sips:", 5)) {
11956       ast_log(LOG_WARNING, "Huh?  Not a SIP header (%s)?\n", c);
11957       return -1;
11958    }
11959 
11960    mfrom = remove_uri_parameters(c);
11961 
11962    ast_copy_string(to, get_header(&p->initreq, "To"), sizeof(to));
11963    c = get_in_brackets(to);
11964    if (strncasecmp(c, "sip:", 4) && strncasecmp(c, "sips:", 5)) {
11965       ast_log(LOG_WARNING, "Huh?  Not a SIP header (%s)?\n", c);
11966       return -1;
11967    }
11968    mto = remove_uri_parameters(c);
11969 
11970    reqprep(&req, p, SIP_NOTIFY, 0, 1);
11971 
11972    switch(state) {
11973    case AST_EXTENSION_DEACTIVATED:
11974       if (timeout)
11975          add_header(&req, "Subscription-State", "terminated;reason=timeout");
11976       else {
11977          add_header(&req, "Subscription-State", "terminated;reason=probation");
11978          add_header(&req, "Retry-After", "60");
11979       }
11980       break;
11981    case AST_EXTENSION_REMOVED:
11982       add_header(&req, "Subscription-State", "terminated;reason=noresource");
11983       break;
11984    default:
11985       if (p->expiry)
11986          add_header(&req, "Subscription-State", "active");
11987       else  /* Expired */
11988          add_header(&req, "Subscription-State", "terminated;reason=timeout");
11989    }
11990 
11991    switch (p->subscribed) {
11992    case XPIDF_XML:
11993    case CPIM_PIDF_XML:
11994       add_header(&req, "Event", subscriptiontype->event);
11995       state_notify_build_xml(state, full, p->exten, p->context, &tmp, p, p->subscribed, mfrom, mto);
11996       add_header(&req, "Content-Type", subscriptiontype->mediatype);
11997       p->dialogver++;
11998       break;
11999    case PIDF_XML: /* Eyebeam supports this format */
12000       add_header(&req, "Event", subscriptiontype->event);
12001       state_notify_build_xml(state, full, p->exten, p->context, &tmp, p, p->subscribed, mfrom, mto);
12002       add_header(&req, "Content-Type", subscriptiontype->mediatype);
12003       p->dialogver++;
12004       break;
12005    case DIALOG_INFO_XML: /* SNOM subscribes in this format */
12006       add_header(&req, "Event", subscriptiontype->event);
12007       state_notify_build_xml(state, full, p->exten, p->context, &tmp, p, p->subscribed, mfrom, mto);
12008       add_header(&req, "Content-Type", subscriptiontype->mediatype);
12009       p->dialogver++;
12010       break;
12011    case NONE:
12012    default:
12013       break;
12014    }
12015 
12016    add_content(&req, tmp->str);
12017 
12018    p->pendinginvite = p->ocseq;  /* Remember that we have a pending NOTIFY in order not to confuse the NOTIFY subsystem */
12019 
12020    return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
12021 }
12022 
12023 /*! \brief Notify user of messages waiting in voicemail (RFC3842)
12024 \note - Notification only works for registered peers with mailbox= definitions
12025    in sip.conf
12026    - We use the SIP Event package message-summary
12027     MIME type defaults to  "application/simple-message-summary";
12028  */
12029 static int transmit_notify_with_mwi(struct sip_pvt *p, int newmsgs, int oldmsgs, const char *vmexten)
12030 {
12031    struct sip_request req;
12032    struct ast_str *out = ast_str_alloca(500);
12033    int ourport = (p->fromdomainport) ? p->fromdomainport : ast_sockaddr_port(&p->ourip);
12034    const char *domain = S_OR(p->fromdomain, ast_sockaddr_stringify_host(&p->ourip));
12035    const char *exten = S_OR(vmexten, default_vmexten);
12036 
12037    initreqprep(&req, p, SIP_NOTIFY, NULL);
12038    add_header(&req, "Event", "message-summary");
12039    add_header(&req, "Content-Type", default_notifymime);
12040    ast_str_append(&out, 0, "Messages-Waiting: %s\r\n", newmsgs ? "yes" : "no");
12041 
12042 
12043    if (!sip_standard_port(p->socket.type, ourport)) {
12044       if (p->socket.type == SIP_TRANSPORT_UDP) {
12045          ast_str_append(&out, 0, "Message-Account: sip:%s@%s:%d\r\n", exten, domain, ourport);
12046       } else {
12047          ast_str_append(&out, 0, "Message-Account: sip:%s@%s:%d;transport=%s\r\n", exten, domain, ourport, get_transport(p->socket.type));
12048       }
12049    } else {
12050       if (p->socket.type == SIP_TRANSPORT_UDP) {
12051          ast_str_append(&out, 0, "Message-Account: sip:%s@%s\r\n", exten, domain);
12052       } else {
12053          ast_str_append(&out, 0, "Message-Account: sip:%s@%s;transport=%s\r\n", exten, domain, get_transport(p->socket.type));
12054       }
12055    }
12056    /* Cisco has a bug in the SIP stack where it can't accept the
12057       (0/0) notification. This can temporarily be disabled in
12058       sip.conf with the "buggymwi" option */
12059    ast_str_append(&out, 0, "Voice-Message: %d/%d%s\r\n",
12060       newmsgs, oldmsgs, (ast_test_flag(&p->flags[1], SIP_PAGE2_BUGGY_MWI) ? "" : " (0/0)"));
12061 
12062    if (p->subscribed) {
12063       if (p->expiry) {
12064          add_header(&req, "Subscription-State", "active");
12065       } else { /* Expired */
12066          add_header(&req, "Subscription-State", "terminated;reason=timeout");
12067       }
12068    }
12069 
12070    add_content(&req, out->str);
12071 
12072    if (!p->initreq.headers) {
12073       initialize_initreq(p, &req);
12074    }
12075    return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
12076 }
12077 
12078 /*! \brief Notify a transferring party of the status of transfer (RFC3515) */
12079 static int transmit_notify_with_sipfrag(struct sip_pvt *p, int cseq, char *message, int terminate)
12080 {
12081    struct sip_request req;
12082    char tmp[SIPBUFSIZE/2];
12083    
12084    reqprep(&req, p, SIP_NOTIFY, 0, 1);
12085    snprintf(tmp, sizeof(tmp), "refer;id=%d", cseq);
12086    add_header(&req, "Event", tmp);
12087    add_header(&req, "Subscription-state", terminate ? "terminated;reason=noresource" : "active");
12088    add_header(&req, "Content-Type", "message/sipfrag;version=2.0");
12089    add_header(&req, "Allow", ALLOWED_METHODS);
12090    add_supported_header(p, &req);
12091 
12092    snprintf(tmp, sizeof(tmp), "SIP/2.0 %s\r\n", message);
12093    add_content(&req, tmp);
12094 
12095    if (!p->initreq.headers) {
12096       initialize_initreq(p, &req);
12097    }
12098 
12099    return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
12100 }
12101 
12102 static int manager_sipnotify(struct mansession *s, const struct message *m)
12103 {
12104    const char *channame = astman_get_header(m, "Channel");
12105    struct ast_variable *vars = astman_get_variables(m);
12106    struct sip_pvt *p;
12107    struct ast_variable *header, *var;
12108 
12109    if (ast_strlen_zero(channame)) {
12110       astman_send_error(s, m, "SIPNotify requires a channel name");
12111       return 0;
12112    }
12113 
12114    if (!strncasecmp(channame, "sip/", 4)) {
12115       channame += 4;
12116    }
12117 
12118    if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY, NULL))) {
12119       astman_send_error(s, m, "Unable to build sip pvt data for notify (memory/socket error)");
12120       return 0;
12121    }
12122 
12123    if (create_addr(p, channame, NULL, 0, NULL)) {
12124       /* Maybe they're not registered, etc. */
12125       dialog_unlink_all(p, TRUE, TRUE);
12126       dialog_unref(p, "unref dialog inside for loop" );
12127       /* sip_destroy(p); */
12128       astman_send_error(s, m, "Could not create address");
12129       return 0;
12130    }
12131 
12132    /* Notify is outgoing call */
12133    ast_set_flag(&p->flags[0], SIP_OUTGOING);
12134    sip_notify_allocate(p);
12135 
12136    p->notify->headers = header = ast_variable_new("Subscription-State", "terminated", "");
12137 
12138    for (var = vars; var; var = var->next) {
12139       if (!strcasecmp(var->name, "Content")) {
12140          if (ast_str_strlen(p->notify->content))
12141             ast_str_append(&p->notify->content, 0, "\r\n");
12142          ast_str_append(&p->notify->content, 0, "%s", var->value);
12143       } else if (!strcasecmp(var->name, "Content-Length")) {
12144          ast_log(LOG_WARNING, "it is not necessary to specify Content-Length, ignoring");
12145       } else {
12146          header->next = ast_variable_new(var->name, var->value, "");
12147          header = header->next;
12148       }
12149    }
12150 
12151    dialog_ref(p, "bump the count of p, which transmit_sip_request will decrement.");
12152    sip_scheddestroy(p, SIP_TRANS_TIMEOUT);
12153    transmit_invite(p, SIP_NOTIFY, 0, 2, NULL);
12154 
12155    astman_send_ack(s, m, "Notify Sent");
12156    ast_variables_destroy(vars);
12157    return 0;
12158 }
12159 
12160 /*! \brief Send a provisional response indicating that a call was redirected
12161  */
12162 static void update_redirecting(struct sip_pvt *p, const void *data, size_t datalen)
12163 {
12164    struct sip_request resp;
12165 
12166    if (p->owner->_state == AST_STATE_UP || ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
12167       return;
12168    }
12169 
12170    respprep(&resp, p, "181 Call is being forwarded", &p->initreq);
12171    add_diversion_header(&resp, p);
12172    send_response(p, &resp, XMIT_UNRELIABLE, 0);
12173 }
12174 
12175 /*! \brief Notify peer that the connected line has changed */
12176 static void update_connectedline(struct sip_pvt *p, const void *data, size_t datalen)
12177 {
12178 
12179    if (!ast_test_flag(&p->flags[0], SIP_SENDRPID)) {
12180       return;
12181    }
12182    if (!p->owner->connected.id.number.valid
12183       || ast_strlen_zero(p->owner->connected.id.number.str)) {
12184       return;
12185    }
12186 
12187    append_history(p, "ConnectedLine", "%s party is now %s <%s>",
12188       ast_test_flag(&p->flags[0], SIP_OUTGOING) ? "Calling" : "Called",
12189       S_COR(p->owner->connected.id.name.valid, p->owner->connected.id.name.str, ""),
12190       S_COR(p->owner->connected.id.number.valid, p->owner->connected.id.number.str, ""));
12191 
12192    if (p->owner->_state == AST_STATE_UP || ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
12193       struct sip_request req;
12194 
12195       if (p->invitestate == INV_CONFIRMED || p->invitestate == INV_TERMINATED) {
12196          reqprep(&req, p, ast_test_flag(&p->flags[0], SIP_REINVITE_UPDATE) ? SIP_UPDATE : SIP_INVITE, 0, 1);
12197 
12198          add_header(&req, "Allow", ALLOWED_METHODS);
12199          add_supported_header(p, &req);
12200          add_rpid(&req, p);
12201          add_sdp(&req, p, FALSE, TRUE, FALSE);
12202 
12203          initialize_initreq(p, &req);
12204          p->lastinvite = p->ocseq;
12205          ast_set_flag(&p->flags[0], SIP_OUTGOING);
12206          p->invitestate = INV_CALLING;
12207          send_request(p, &req, XMIT_CRITICAL, p->ocseq);
12208       } else if (is_method_allowed(&p->allowed_methods, SIP_UPDATE)) {
12209          reqprep(&req, p, SIP_UPDATE, 0, 1);
12210          add_rpid(&req, p);
12211          add_header(&req, "X-Asterisk-rpid-update", "Yes");
12212          send_request(p, &req, XMIT_CRITICAL, p->ocseq);
12213       } else {
12214          /* We cannot send the update yet, so we have to wait until we can */
12215          ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
12216       }
12217    } else {
12218       if (ast_test_flag(&p->flags[1], SIP_PAGE2_RPID_IMMEDIATE)) {
12219          struct sip_request resp;
12220 
12221          if ((p->owner->_state == AST_STATE_RING) && !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT)) {
12222             respprep(&resp, p, "180 Ringing", &p->initreq);
12223             add_rpid(&resp, p);
12224             send_response(p, &resp, XMIT_UNRELIABLE, 0);
12225             ast_set_flag(&p->flags[0], SIP_RINGING);
12226          } else if (p->owner->_state == AST_STATE_RINGING) {
12227             respprep(&resp, p, "183 Session Progress", &p->initreq);
12228             add_rpid(&resp, p);
12229             send_response(p, &resp, XMIT_UNRELIABLE, 0);
12230             ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
12231          } else {
12232             ast_debug(1, "Unable able to send update to '%s' in state '%s'\n", p->owner->name, ast_state2str(p->owner->_state));
12233          }
12234       } else {
12235          ast_set_flag(&p->flags[1], SIP_PAGE2_CONNECTLINEUPDATE_PEND);
12236       }
12237    }
12238 }
12239 
12240 static const struct _map_x_s regstatestrings[] = {
12241    { REG_STATE_FAILED,     "Failed" },
12242    { REG_STATE_UNREGISTERED, "Unregistered"},
12243    { REG_STATE_REGSENT, "Request Sent"},
12244    { REG_STATE_AUTHSENT, "Auth. Sent"},
12245    { REG_STATE_REGISTERED, "Registered"},
12246    { REG_STATE_REJECTED, "Rejected"},
12247    { REG_STATE_TIMEOUT, "Timeout"},
12248    { REG_STATE_NOAUTH, "No Authentication"},
12249    { -1, NULL } /* terminator */
12250 };
12251 
12252 /*! \brief Convert registration state status to string */
12253 static const char *regstate2str(enum sipregistrystate regstate)
12254 {
12255    return map_x_s(regstatestrings, regstate, "Unknown");
12256 }
12257 
12258 /*! \brief Update registration with SIP Proxy.
12259  * Called from the scheduler when the previous registration expires,
12260  * so we don't have to cancel the pending event.
12261  * We assume the reference so the sip_registry is valid, since it
12262  * is stored in the scheduled event anyways.
12263  */
12264 static int sip_reregister(const void *data)
12265 {
12266    /* if we are here, we know that we need to reregister. */
12267    struct sip_registry *r = (struct sip_registry *) data;
12268 
12269    /* if we couldn't get a reference to the registry object, punt */
12270    if (!r) {
12271       return 0;
12272    }
12273 
12274    if (r->call && r->call->do_history) {
12275       append_history(r->call, "RegistryRenew", "Account: %s@%s", r->username, r->hostname);
12276    }
12277    /* Since registry's are only added/removed by the the monitor thread, this
12278       may be overkill to reference/dereference at all here */
12279    if (sipdebug) {
12280       ast_log(LOG_NOTICE, "   -- Re-registration for  %s@%s\n", r->username, r->hostname);
12281    }
12282 
12283    r->expire = -1;
12284    r->expiry = r->configured_expiry;
12285    __sip_do_register(r);
12286    registry_unref(r, "unref the re-register scheduled event");
12287    return 0;
12288 }
12289 
12290 /*! \brief Register with SIP proxy 
12291    \return see \ref __sip_xmit 
12292 */
12293 static int __sip_do_register(struct sip_registry *r)
12294 {
12295    int res;
12296 
12297    res = transmit_register(r, SIP_REGISTER, NULL, NULL);
12298    return res;
12299 }
12300 
12301 /*! \brief Registration timeout, register again
12302  * Registered as a timeout handler during transmit_register(),
12303  * to retransmit the packet if a reply does not come back.
12304  * This is called by the scheduler so the event is not pending anymore when
12305  * we are called.
12306  */
12307 static int sip_reg_timeout(const void *data)
12308 {
12309 
12310    /* if we are here, our registration timed out, so we'll just do it over */
12311    struct sip_registry *r = (struct sip_registry *)data; /* the ref count should have been bumped when the sched item was added */
12312    struct sip_pvt *p;
12313    int res;
12314 
12315    /* if we couldn't get a reference to the registry object, punt */
12316    if (!r) {
12317       return 0;
12318    }
12319 
12320    if (r->dnsmgr) {
12321       /* If the registration has timed out, maybe the IP changed.  Force a refresh. */
12322       ast_dnsmgr_refresh(r->dnsmgr);
12323    }
12324 
12325    /* If the initial tranmission failed, we may not have an existing dialog,
12326     * so it is possible that r->call == NULL.
12327     * Otherwise destroy it, as we have a timeout so we don't want it.
12328     */
12329    if (r->call) {
12330       /* Unlink us, destroy old call.  Locking is not relevant here because all this happens
12331          in the single SIP manager thread. */
12332       p = r->call;
12333       sip_pvt_lock(p);
12334       pvt_set_needdestroy(p, "registration timeout");
12335       /* Pretend to ACK anything just in case */
12336       __sip_pretend_ack(p);
12337       sip_pvt_unlock(p);
12338 
12339       /* decouple the two objects */
12340       /* p->registry == r, so r has 2 refs, and the unref won't take the object away */
12341       if (p->registry) {
12342          p->registry = registry_unref(p->registry, "p->registry unreffed");
12343       }
12344       r->call = dialog_unref(r->call, "unrefing r->call");
12345    }
12346    /* If we have a limit, stop registration and give up */
12347    r->timeout = -1;
12348    if (global_regattempts_max && r->regattempts >= global_regattempts_max) {
12349       /* Ok, enough is enough. Don't try any more */
12350       /* We could add an external notification here...
12351          steal it from app_voicemail :-) */
12352       ast_log(LOG_NOTICE, "   -- Last Registration Attempt #%d failed, Giving up forever trying to register '%s@%s'\n", r->regattempts, r->username, r->hostname);
12353       r->regstate = REG_STATE_FAILED;
12354    } else {
12355       r->regstate = REG_STATE_UNREGISTERED;
12356       res = transmit_register(r, SIP_REGISTER, NULL, NULL);
12357       ast_log(LOG_NOTICE, "   -- Registration for '%s@%s' timed out, trying again (Attempt #%d)\n", r->username, r->hostname, r->regattempts);
12358    }
12359    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));
12360    registry_unref(r, "unreffing registry_unref r");
12361    return 0;
12362 }
12363 
12364 /*! \brief Transmit register to SIP proxy or UA
12365  * auth = NULL on the initial registration (from sip_reregister())
12366  */
12367 static int transmit_register(struct sip_registry *r, int sipmethod, const char *auth, const char *authheader)
12368 {
12369    struct sip_request req;
12370    char from[256];
12371    char to[256];
12372    char tmp[80];
12373    char addr[80];
12374    struct sip_pvt *p;
12375    struct sip_peer *peer = NULL;
12376    int res;
12377    int portno = 0;
12378 
12379    /* exit if we are already in process with this registrar ?*/
12380    if (r == NULL || ((auth == NULL) && (r->regstate == REG_STATE_REGSENT || r->regstate == REG_STATE_AUTHSENT))) {
12381       if (r) {
12382          ast_log(LOG_NOTICE, "Strange, trying to register %s@%s when registration already pending\n", r->username, r->hostname);
12383       }
12384       return 0;
12385    }
12386 
12387    if (r->dnsmgr == NULL) {
12388       char transport[MAXHOSTNAMELEN];
12389       peer = find_peer(r->hostname, NULL, TRUE, FINDPEERS, FALSE, 0);
12390       snprintf(transport, sizeof(transport), "_%s._%s",get_srv_service(r->transport), get_srv_protocol(r->transport)); /* have to use static get_transport function */
12391       r->us.ss.ss_family = get_address_family_filter(&bindaddr); /* Filter address family */
12392       ast_dnsmgr_lookup(peer ? peer->tohost : r->hostname, &r->us, &r->dnsmgr, sip_cfg.srvlookup ? transport : NULL);
12393       if (peer) {
12394          peer = unref_peer(peer, "removing peer ref for dnsmgr_lookup");
12395       }
12396    }
12397 
12398    if (r->call) { /* We have a registration */
12399       if (!auth) {
12400          ast_log(LOG_WARNING, "Already have a REGISTER going on to %s@%s?? \n", r->username, r->hostname);
12401          return 0;
12402       } else {
12403          p = dialog_ref(r->call, "getting a copy of the r->call dialog in transmit_register");
12404          make_our_tag(p->tag, sizeof(p->tag));  /* create a new local tag for every register attempt */
12405          ast_string_field_set(p, theirtag, NULL);  /* forget their old tag, so we don't match tags when getting response */
12406       }
12407    } else {
12408       /* Build callid for registration if we haven't registered before */
12409       if (!r->callid_valid) {
12410          build_callid_registry(r, &internip, default_fromdomain);
12411          r->callid_valid = TRUE;
12412       }
12413       /* Allocate SIP dialog for registration */
12414       if (!(p = sip_alloc( r->callid, NULL, 0, SIP_REGISTER, NULL))) {
12415          ast_log(LOG_WARNING, "Unable to allocate registration transaction (memory or socket error)\n");
12416          return 0;
12417       }
12418       
12419       if (p->do_history) {
12420          append_history(p, "RegistryInit", "Account: %s@%s", r->username, r->hostname);
12421       }
12422 
12423       /* Use port number specified if no SRV record was found */
12424       if (!ast_sockaddr_port(&r->us) && r->portno) {
12425          ast_sockaddr_set_port(&r->us, r->portno);
12426       }
12427 
12428       /* Find address to hostname */
12429       if (create_addr(p, S_OR(r->peername, r->hostname), &r->us, 0, NULL)) {
12430          /* we have what we hope is a temporary network error,
12431           * probably DNS.  We need to reschedule a registration try */
12432          dialog_unlink_all(p, TRUE, TRUE);
12433          p = dialog_unref(p, "unref dialog after unlink_all");
12434          if (r->timeout > -1) {
12435             AST_SCHED_REPLACE_UNREF(r->timeout, sched, global_reg_timeout * 1000, sip_reg_timeout, r,
12436                               registry_unref(_data, "del for REPLACE of registry ptr"),
12437                               registry_unref(r, "object ptr dec when SCHED_REPLACE add failed"),
12438                               registry_addref(r,"add for REPLACE registry ptr"));
12439             ast_log(LOG_WARNING, "Still have a registration timeout for %s@%s (create_addr() error), %d\n", r->username, r->hostname, r->timeout);
12440          } else {
12441             r->timeout = ast_sched_add(sched, global_reg_timeout * 1000, sip_reg_timeout, registry_addref(r, "add for REPLACE registry ptr"));
12442             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);
12443          }
12444          r->regattempts++;
12445          return 0;
12446       }
12447 
12448       /* Copy back Call-ID in case create_addr changed it */
12449       ast_string_field_set(r, callid, p->callid);
12450 
12451       if (!r->dnsmgr && r->portno) {
12452          ast_sockaddr_set_port(&p->sa, r->portno);
12453          ast_sockaddr_set_port(&p->recv, r->portno);
12454       }
12455       if (!ast_strlen_zero(p->fromdomain)) {
12456          portno = (p->fromdomainport) ? p->fromdomainport : STANDARD_SIP_PORT;
12457       } else if (!ast_strlen_zero(r->regdomain)) {
12458          portno = (r->regdomainport) ? r->regdomainport : STANDARD_SIP_PORT;
12459       } else {
12460          portno = ast_sockaddr_port(&p->sa);
12461       }
12462 
12463       ast_set_flag(&p->flags[0], SIP_OUTGOING); /* Registration is outgoing call */
12464       r->call = dialog_ref(p, "copying dialog into registry r->call");     /* Save pointer to SIP dialog */
12465       p->registry = registry_addref(r, "transmit_register: addref to p->registry in transmit_register"); /* Add pointer to registry in packet */
12466       if (!ast_strlen_zero(r->secret)) {  /* Secret (password) */
12467          ast_string_field_set(p, peersecret, r->secret);
12468       }
12469       if (!ast_strlen_zero(r->md5secret))
12470          ast_string_field_set(p, peermd5secret, r->md5secret);
12471       /* User name in this realm
12472       - if authuser is set, use that, otherwise use username */
12473       if (!ast_strlen_zero(r->authuser)) {
12474          ast_string_field_set(p, peername, r->authuser);
12475          ast_string_field_set(p, authname, r->authuser);
12476       } else if (!ast_strlen_zero(r->username)) {
12477          ast_string_field_set(p, peername, r->username);
12478          ast_string_field_set(p, authname, r->username);
12479          ast_string_field_set(p, fromuser, r->username);
12480       }
12481       if (!ast_strlen_zero(r->username)) {
12482          ast_string_field_set(p, username, r->username);
12483       }
12484       /* Save extension in packet */
12485       if (!ast_strlen_zero(r->callback)) {
12486          ast_string_field_set(p, exten, r->callback);
12487       }
12488 
12489       /* Set transport and port so the correct contact is built */
12490       set_socket_transport(&p->socket, r->transport);
12491       if (r->transport == SIP_TRANSPORT_TLS || r->transport == SIP_TRANSPORT_TCP) {
12492          p->socket.port =
12493              htons(ast_sockaddr_port(&sip_tcp_desc.local_address));
12494       }
12495 
12496       /*
12497         check which address we should use in our contact header
12498         based on whether the remote host is on the external or
12499         internal network so we can register through nat
12500        */
12501       ast_sip_ouraddrfor(&p->sa, &p->ourip, p);
12502       build_contact(p);
12503    }
12504 
12505    /* set up a timeout */
12506    if (auth == NULL)  {
12507       if (r->timeout > -1) {
12508          ast_log(LOG_WARNING, "Still have a registration timeout, #%d - deleting it\n", r->timeout);
12509       }
12510       AST_SCHED_REPLACE_UNREF(r->timeout, sched, global_reg_timeout * 1000, sip_reg_timeout, r,
12511                         registry_unref(_data,"reg ptr unrefed from del in SCHED_REPLACE"),
12512                         registry_unref(r,"reg ptr unrefed from add failure in SCHED_REPLACE"),
12513                         registry_addref(r,"reg ptr reffed from add in SCHED_REPLACE"));
12514       ast_debug(1, "Scheduled a registration timeout for %s id  #%d \n", r->hostname, r->timeout);
12515    }
12516 
12517    snprintf(from, sizeof(from), "<sip:%s@%s>;tag=%s", r->username, S_OR(r->regdomain,p->tohost), p->tag);
12518    if (!ast_strlen_zero(p->theirtag)) {
12519       snprintf(to, sizeof(to), "<sip:%s@%s>;tag=%s", r->username, S_OR(r->regdomain,p->tohost), p->theirtag);
12520    } else {
12521       snprintf(to, sizeof(to), "<sip:%s@%s>", r->username, S_OR(r->regdomain,p->tohost));
12522    }
12523 
12524    /* Fromdomain is what we are registering to, regardless of actual
12525       host name from SRV */
12526    if (portno && portno != STANDARD_SIP_PORT) {
12527       snprintf(addr, sizeof(addr), "sip:%s:%d", S_OR(p->fromdomain,S_OR(r->regdomain,r->hostname)), portno);
12528    } else {
12529       snprintf(addr, sizeof(addr), "sip:%s", S_OR(p->fromdomain,S_OR(r->regdomain,r->hostname)));
12530    }
12531 
12532    ast_string_field_set(p, uri, addr);
12533 
12534    p->branch ^= ast_random();
12535 
12536    init_req(&req, sipmethod, addr);
12537 
12538    /* Add to CSEQ */
12539    snprintf(tmp, sizeof(tmp), "%u %s", ++r->ocseq, sip_methods[sipmethod].text);
12540    p->ocseq = r->ocseq;
12541 
12542    build_via(p);
12543    add_header(&req, "Via", p->via);
12544    add_header_max_forwards(p, &req);
12545    add_header(&req, "From", from);
12546    add_header(&req, "To", to);
12547    add_header(&req, "Call-ID", p->callid);
12548    add_header(&req, "CSeq", tmp);
12549    if (!ast_strlen_zero(global_useragent))
12550       add_header(&req, "User-Agent", global_useragent);
12551 
12552    if (auth) {    /* Add auth header */
12553       add_header(&req, authheader, auth);
12554    } else if (!ast_strlen_zero(r->nonce)) {
12555       char digest[1024];
12556 
12557       /* We have auth data to reuse, build a digest header.
12558        * Note, this is not always useful because some parties do not
12559        * like nonces to be reused (for good reasons!) so they will
12560        * challenge us anyways.
12561        */
12562       if (sipdebug) {
12563          ast_debug(1, "   >>> Re-using Auth data for %s@%s\n", r->username, r->hostname);
12564       }
12565       ast_string_field_set(p, realm, r->realm);
12566       ast_string_field_set(p, nonce, r->nonce);
12567       ast_string_field_set(p, domain, r->authdomain);
12568       ast_string_field_set(p, opaque, r->opaque);
12569       ast_string_field_set(p, qop, r->qop);
12570       p->noncecount = ++r->noncecount;
12571 
12572       memset(digest, 0, sizeof(digest));
12573       if(!build_reply_digest(p, sipmethod, digest, sizeof(digest))) {
12574          add_header(&req, "Authorization", digest);
12575       } else {
12576          ast_log(LOG_NOTICE, "No authorization available for authentication of registration to %s@%s\n", r->username, r->hostname);
12577       }
12578    }
12579 
12580    snprintf(tmp, sizeof(tmp), "%d", r->expiry);
12581    add_header(&req, "Expires", tmp);
12582    add_header(&req, "Contact", p->our_contact);
12583 
12584    initialize_initreq(p, &req);
12585    if (sip_debug_test_pvt(p)) {
12586       ast_verbose("REGISTER %d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
12587    }
12588    r->regstate = auth ? REG_STATE_AUTHSENT : REG_STATE_REGSENT;
12589    r->regattempts++; /* Another attempt */
12590    ast_debug(4, "REGISTER attempt %d to %s@%s\n", r->regattempts, r->username, r->hostname);
12591    res = send_request(p, &req, XMIT_CRITICAL, p->ocseq);
12592    dialog_unref(p, "p is finished here at the end of transmit_register");
12593    return res;
12594 }
12595 
12596 /*! \brief Transmit text with SIP MESSAGE method */
12597 static int transmit_message_with_text(struct sip_pvt *p, const char *text)
12598 {
12599    struct sip_request req;
12600    
12601    reqprep(&req, p, SIP_MESSAGE, 0, 1);
12602    add_text(&req, text);
12603    return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
12604 }
12605 
12606 /*! \brief Allocate SIP refer structure */
12607 static int sip_refer_allocate(struct sip_pvt *p)
12608 {
12609    p->refer = ast_calloc(1, sizeof(struct sip_refer));
12610    return p->refer ? 1 : 0;
12611 }
12612 
12613 /*! \brief Allocate SIP refer structure */
12614 static int sip_notify_allocate(struct sip_pvt *p)
12615 {
12616    p->notify = ast_calloc(1, sizeof(struct sip_notify));
12617    if (p->notify) {
12618       p->notify->content = ast_str_create(128);
12619    }
12620    return p->notify ? 1 : 0;
12621 }
12622 
12623 /*! \brief Transmit SIP REFER message (initiated by the transfer() dialplan application
12624    \note this is currently broken as we have no way of telling the dialplan
12625    engine whether a transfer succeeds or fails.
12626    \todo Fix the transfer() dialplan function so that a transfer may fail
12627 */
12628 static int transmit_refer(struct sip_pvt *p, const char *dest)
12629 {
12630    struct sip_request req = {
12631       .headers = 0,  
12632    };
12633    char from[256];
12634    const char *of;
12635    char *c;
12636    char referto[256];
12637    char *ttag, *ftag;
12638    char *theirtag = ast_strdupa(p->theirtag);
12639    int   use_tls=FALSE;
12640 
12641    if (sipdebug) {
12642       ast_debug(1, "SIP transfer of %s to %s\n", p->callid, dest);
12643    }
12644 
12645    /* Are we transfering an inbound or outbound call ? */
12646    if (ast_test_flag(&p->flags[0], SIP_OUTGOING))  {
12647       of = get_header(&p->initreq, "To");
12648       ttag = theirtag;
12649       ftag = p->tag;
12650    } else {
12651       of = get_header(&p->initreq, "From");
12652       ftag = theirtag;
12653       ttag = p->tag;
12654    }
12655 
12656    ast_copy_string(from, of, sizeof(from));
12657    of = get_in_brackets(from);
12658    ast_string_field_set(p, from, of);
12659    if (!strncasecmp(of, "sip:", 4)) {
12660       of += 4;
12661    } else if (!strncasecmp(of, "sips:", 5)) {
12662       of += 5;
12663       use_tls = TRUE;
12664    } else {
12665       ast_log(LOG_NOTICE, "From address missing 'sip(s):', assuming sip:\n");
12666    }
12667    /* Get just the username part */
12668    if ((c = strchr(dest, '@'))) {
12669       c = NULL;
12670    } else if ((c = strchr(of, '@'))) {
12671       *c++ = '\0';
12672    }
12673    if (c) {
12674       snprintf(referto, sizeof(referto), "<sip%s:%s@%s>", use_tls ? "s" : "", dest, c);
12675    } else {
12676       snprintf(referto, sizeof(referto), "<sip%s:%s>", use_tls ? "s" : "", dest);
12677    }
12678 
12679    /* save in case we get 407 challenge */
12680    sip_refer_allocate(p);
12681    ast_copy_string(p->refer->refer_to, referto, sizeof(p->refer->refer_to));
12682    ast_copy_string(p->refer->referred_by, p->our_contact, sizeof(p->refer->referred_by));
12683    p->refer->status = REFER_SENT;   /* Set refer status */
12684 
12685    reqprep(&req, p, SIP_REFER, 0, 1);
12686 
12687    add_header(&req, "Refer-To", referto);
12688    add_header(&req, "Allow", ALLOWED_METHODS);
12689    add_supported_header(p, &req);
12690    if (!ast_strlen_zero(p->our_contact)) {
12691       add_header(&req, "Referred-By", p->our_contact);
12692    }
12693 
12694    return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
12695 
12696    /* We should propably wait for a NOTIFY here until we ack the transfer */
12697    /* Maybe fork a new thread and wait for a STATUS of REFER_200OK on the refer status before returning to app_transfer */
12698 
12699    /*! \todo In theory, we should hang around and wait for a reply, before
12700    returning to the dial plan here. Don't know really how that would
12701    affect the transfer() app or the pbx, but, well, to make this
12702    useful we should have a STATUS code on transfer().
12703    */
12704 }
12705 
12706 /*! \brief Send SIP INFO advice of charge message */
12707 static int transmit_info_with_aoc(struct sip_pvt *p, struct ast_aoc_decoded *decoded)
12708 {
12709    struct sip_request req;
12710    struct ast_str *str = ast_str_alloca(512);
12711    const struct ast_aoc_unit_entry *unit_entry = ast_aoc_get_unit_info(decoded, 0);
12712    enum ast_aoc_charge_type charging = ast_aoc_get_charge_type(decoded);
12713 
12714    reqprep(&req, p, SIP_INFO, 0, 1);
12715 
12716    if (ast_aoc_get_msg_type(decoded) == AST_AOC_D) {
12717       ast_str_append(&str, 0, "type=active;");
12718    } else if (ast_aoc_get_msg_type(decoded) == AST_AOC_E) {
12719       ast_str_append(&str, 0, "type=terminated;");
12720    } else {
12721       /* unsupported message type */
12722       return -1;
12723    }
12724 
12725    switch (charging) {
12726    case AST_AOC_CHARGE_FREE:
12727       ast_str_append(&str, 0, "free-of-charge;");
12728       break;
12729    case AST_AOC_CHARGE_CURRENCY:
12730       ast_str_append(&str, 0, "charging;");
12731       ast_str_append(&str, 0, "charging-info=currency;");
12732       ast_str_append(&str, 0, "amount=%u;", ast_aoc_get_currency_amount(decoded));
12733       ast_str_append(&str, 0, "multiplier=%s;", ast_aoc_get_currency_multiplier_decimal(decoded));
12734       if (!ast_strlen_zero(ast_aoc_get_currency_name(decoded))) {
12735          ast_str_append(&str, 0, "currency=%s;", ast_aoc_get_currency_name(decoded));
12736       }
12737       break;
12738    case AST_AOC_CHARGE_UNIT:
12739       ast_str_append(&str, 0, "charging;");
12740       ast_str_append(&str, 0, "charging-info=pulse;");
12741       if (unit_entry) {
12742          ast_str_append(&str, 0, "recorded-units=%u;", unit_entry->amount);
12743       }
12744       break;
12745    default:
12746       ast_str_append(&str, 0, "not-available;");
12747    };
12748 
12749    add_header(&req, "AOC", ast_str_buffer(str));
12750 
12751    return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
12752 }
12753 
12754 /*! \brief Send SIP INFO dtmf message, see Cisco documentation on cisco.com */
12755 static int transmit_info_with_digit(struct sip_pvt *p, const char digit, unsigned int duration)
12756 {
12757    struct sip_request req;
12758    
12759    reqprep(&req, p, SIP_INFO, 0, 1);
12760    add_digit(&req, digit, duration, (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_SHORTINFO));
12761    return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
12762 }
12763 
12764 /*! \brief Send SIP INFO with video update request */
12765 static int transmit_info_with_vidupdate(struct sip_pvt *p)
12766 {
12767    struct sip_request req;
12768    
12769    reqprep(&req, p, SIP_INFO, 0, 1);
12770    add_vidupdate(&req);
12771    return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
12772 }
12773 
12774 /*! \brief Transmit generic SIP request
12775    returns XMIT_ERROR if transmit failed with a critical error (don't retry)
12776 */
12777 static int transmit_request(struct sip_pvt *p, int sipmethod, int seqno, enum xmittype reliable, int newbranch)
12778 {
12779    struct sip_request resp;
12780    
12781    if (sipmethod == SIP_ACK) {
12782       p->invitestate = INV_CONFIRMED;
12783    }
12784 
12785    reqprep(&resp, p, sipmethod, seqno, newbranch);
12786    if (sipmethod == SIP_CANCEL && p->answered_elsewhere) {
12787       add_header(&resp, "Reason", "SIP;cause=200;text=\"Call completed elsewhere\"");
12788    }
12789 
12790    return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);
12791 }
12792 
12793 /*! \brief return the request and response heade for a 401 or 407 code */
12794 static void auth_headers(enum sip_auth_type code, char **header, char **respheader)
12795 {
12796    if (code == WWW_AUTH) {       /* 401 */
12797       *header = "WWW-Authenticate";
12798       *respheader = "Authorization";
12799    } else if (code == PROXY_AUTH) { /* 407 */
12800       *header = "Proxy-Authenticate";
12801       *respheader = "Proxy-Authorization";
12802    } else {
12803       ast_verbose("-- wrong response code %d\n", code);
12804       *header = *respheader = "Invalid";
12805    }
12806 }
12807 
12808 /*! \brief Transmit SIP request, auth added */
12809 static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, int seqno, enum xmittype reliable, int newbranch)
12810 {
12811    struct sip_request resp;
12812    
12813    reqprep(&resp, p, sipmethod, seqno, newbranch);
12814    if (!ast_strlen_zero(p->realm)) {
12815       char digest[1024];
12816 
12817       memset(digest, 0, sizeof(digest));
12818       if(!build_reply_digest(p, sipmethod, digest, sizeof(digest))) {
12819          char *dummy, *response;
12820          enum sip_auth_type code = p->options ? p->options->auth_type : PROXY_AUTH; /* XXX force 407 if unknown */
12821          auth_headers(code, &dummy, &response);
12822          add_header(&resp, response, digest);
12823       } else {
12824          ast_log(LOG_WARNING, "No authentication available for call %s\n", p->callid);
12825       }
12826    }
12827    /* If we are hanging up and know a cause for that, send it in clear text to make
12828       debugging easier. */
12829    if (sipmethod == SIP_BYE)  {
12830       char buf[20];
12831 
12832       if (ast_test_flag(&p->flags[1], SIP_PAGE2_Q850_REASON) && p->hangupcause) {
12833          sprintf(buf, "Q.850;cause=%i", p->hangupcause & 0x7f);
12834          add_header(&resp, "Reason", buf);
12835       }
12836 
12837       add_header(&resp, "X-Asterisk-HangupCause", ast_cause2str(p->hangupcause));
12838       snprintf(buf, sizeof(buf), "%d", p->hangupcause);
12839       add_header(&resp, "X-Asterisk-HangupCauseCode", buf);
12840    }
12841 
12842    return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);   
12843 }
12844 
12845 /*! \brief Remove registration data from realtime database or AST/DB when registration expires */
12846 static void destroy_association(struct sip_peer *peer)
12847 {
12848    int realtimeregs = ast_check_realtime("sipregs");
12849    char *tablename = (realtimeregs) ? "sipregs" : "sippeers";
12850 
12851    if (!sip_cfg.ignore_regexpire) {
12852       if (peer->rt_fromcontact && sip_cfg.peer_rtupdate) {
12853          ast_update_realtime(tablename, "name", peer->name, "fullcontact", "", "ipaddr", "", "port", "", "regseconds", "0", "regserver", "", "useragent", "", "lastms", "", SENTINEL);
12854       } else {
12855          ast_db_del("SIP/Registry", peer->name);
12856          ast_db_del("SIP/PeerMethods", peer->name);
12857       }
12858    }
12859 }
12860 
12861 static void set_socket_transport(struct sip_socket *socket, int transport)
12862 {
12863    /* if the transport type changes, clear all socket data */
12864    if (socket->type != transport) {
12865       socket->fd = -1;
12866       socket->type = transport;
12867       if (socket->tcptls_session) {
12868          ao2_ref(socket->tcptls_session, -1);
12869          socket->tcptls_session = NULL;
12870       }
12871    }
12872 }
12873 
12874 /*! \brief Expire registration of SIP peer */
12875 static int expire_register(const void *data)
12876 {
12877    struct sip_peer *peer = (struct sip_peer *)data;
12878 
12879    if (!peer) {      /* Hmmm. We have no peer. Weird. */
12880       return 0;
12881    }
12882 
12883    peer->expire = -1;
12884    peer->portinuri = 0;
12885 
12886    destroy_association(peer); /* remove registration data from storage */
12887    set_socket_transport(&peer->socket, peer->default_outbound_transport);
12888 
12889    if (peer->socket.tcptls_session) {
12890       ao2_ref(peer->socket.tcptls_session, -1);
12891       peer->socket.tcptls_session = NULL;
12892    }
12893 
12894    manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: Unregistered\r\nCause: Expired\r\n", peer->name);
12895    register_peer_exten(peer, FALSE);   /* Remove regexten */
12896    ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", peer->name);
12897 
12898    /* Do we need to release this peer from memory?
12899       Only for realtime peers and autocreated peers
12900    */
12901    if (peer->is_realtime) {
12902       ast_debug(3, "-REALTIME- peer expired registration. Name: %s. Realtime peer objects now %d\n", peer->name, rpeerobjs);
12903    }
12904 
12905    if (peer->selfdestruct ||
12906        ast_test_flag(&peer->flags[1], SIP_PAGE2_RTAUTOCLEAR)) {
12907       unlink_peer_from_tables(peer);
12908    }
12909 
12910    /* Only clear the addr after we check for destruction.  The addr must remain
12911     * in order to unlink from the peers_by_ip container correctly */
12912    memset(&peer->addr, 0, sizeof(peer->addr));
12913 
12914    unref_peer(peer, "removing peer ref for expire_register");
12915 
12916    return 0;
12917 }
12918 
12919 /*! \brief Poke peer (send qualify to check if peer is alive and well) */
12920 static int sip_poke_peer_s(const void *data)
12921 {
12922    struct sip_peer *peer = (struct sip_peer *)data;
12923    struct sip_peer *foundpeer;
12924 
12925    peer->pokeexpire = -1;
12926 
12927    foundpeer = ao2_find(peers, peer, OBJ_POINTER);
12928    if (!foundpeer) {
12929       unref_peer(peer, "removing poke peer ref");
12930       return 0;
12931    } else if (foundpeer->name != peer->name) {
12932       unref_peer(foundpeer, "removing above peer ref");
12933       unref_peer(peer, "removing poke peer ref");
12934       return 0;
12935    }
12936 
12937    unref_peer(foundpeer, "removing above peer ref");
12938    sip_poke_peer(peer, 0);
12939    unref_peer(peer, "removing poke peer ref");
12940 
12941    return 0;
12942 }
12943 
12944 /*! \brief Get registration details from Asterisk DB */
12945 static void reg_source_db(struct sip_peer *peer)
12946 {
12947    char data[256];
12948    struct ast_sockaddr sa;
12949    int expire;
12950    char full_addr[128];
12951    AST_DECLARE_APP_ARGS(args,
12952       AST_APP_ARG(addr);
12953       AST_APP_ARG(port);
12954       AST_APP_ARG(expiry_str);
12955       AST_APP_ARG(username);
12956       AST_APP_ARG(contact);
12957    );
12958 
12959    if (peer->rt_fromcontact) {
12960       return;
12961    }
12962    if (ast_db_get("SIP/Registry", peer->name, data, sizeof(data))) {
12963       return;
12964    }
12965 
12966    AST_NONSTANDARD_RAW_ARGS(args, data, ':');
12967 
12968    snprintf(full_addr, sizeof(full_addr), "%s:%s", args.addr, args.port);
12969 
12970    if (!ast_sockaddr_parse(&sa, full_addr, 0)) {
12971       return;
12972    }
12973 
12974    if (args.expiry_str) {
12975       expire = atoi(args.expiry_str);
12976    } else {
12977       return;
12978    }
12979 
12980    if (args.username) {
12981       ast_string_field_set(peer, username, args.username);
12982    }
12983    if (args.contact) {
12984       ast_string_field_set(peer, fullcontact, args.contact);
12985    }
12986 
12987    ast_debug(2, "SIP Seeding peer from astdb: '%s' at %s@%s for %d\n",
12988        peer->name, peer->username, ast_sockaddr_stringify_host(&sa), expire);
12989 
12990    ast_sockaddr_copy(&peer->addr, &sa);
12991    if (sipsock < 0) {
12992       /* SIP isn't up yet, so schedule a poke only, pretty soon */
12993       AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched, ast_random() % 5000 + 1, sip_poke_peer_s, peer,
12994             unref_peer(_data, "removing poke peer ref"),
12995             unref_peer(peer, "removing poke peer ref"),
12996             ref_peer(peer, "adding poke peer ref"));
12997    } else {
12998       sip_poke_peer(peer, 0);
12999    }
13000    AST_SCHED_REPLACE_UNREF(peer->expire, sched, (expire + 10) * 1000, expire_register, peer,
13001          unref_peer(_data, "remove registration ref"),
13002          unref_peer(peer, "remove registration ref"),
13003          ref_peer(peer, "add registration ref"));
13004    register_peer_exten(peer, TRUE);
13005 }
13006 
13007 /*! \brief Save contact header for 200 OK on INVITE */
13008 static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req)
13009 {
13010    char contact[SIPBUFSIZE];
13011    char *c;
13012 
13013    /* Look for brackets */
13014    ast_copy_string(contact, get_header(req, "Contact"), sizeof(contact));
13015    c = get_in_brackets(contact);
13016 
13017    /* Save full contact to call pvt for later bye or re-invite */
13018    ast_string_field_set(pvt, fullcontact, c);
13019 
13020    /* Save URI for later ACKs, BYE or RE-invites */
13021    ast_string_field_set(pvt, okcontacturi, c);
13022 
13023    /* We should return false for URI:s we can't handle,
13024       like tel:, mailto:,ldap: etc */
13025    return TRUE;      
13026 }
13027 
13028 static int __set_address_from_contact(const char *fullcontact, struct ast_sockaddr *addr, int tcp)
13029 {
13030    char *domain, *transport;
13031    char contact_buf[256];
13032    char *contact;
13033 
13034    /* Work on a copy */
13035    ast_copy_string(contact_buf, fullcontact, sizeof(contact_buf));
13036    contact = contact_buf;
13037 
13038    /* 
13039     * We have only the part in <brackets> here so we just need to parse a SIP URI.
13040     *
13041     * Note: The outbound proxy could be using UDP between the proxy and Asterisk.
13042     * We still need to be able to send to the remote agent through the proxy.
13043     */
13044 
13045    if (parse_uri(contact, "sip:,sips:", &contact, NULL, &domain,
13046             &transport)) {
13047       ast_log(LOG_WARNING, "Invalid contact uri %s (missing sip: or sips:), attempting to use anyway\n", fullcontact);
13048    }
13049 
13050    /* XXX This could block for a long time XXX */
13051    /* We should only do this if it's a name, not an IP */
13052    /* \todo - if there's no PORT number in contact - we are required to check NAPTR/SRV records
13053       to find transport, port address and hostname. If there's a port number, we have to
13054       assume that the domain part is a host name and only look for an A/AAAA record in DNS.
13055    */
13056 
13057    if (ast_sockaddr_resolve_first(addr, domain, 0)) {
13058       ast_log(LOG_WARNING, "Invalid host name in Contact: (can't "
13059          "resolve in DNS) : '%s'\n", domain);
13060       return -1;
13061    }
13062 
13063    /* set port */
13064    if (!ast_sockaddr_port(addr)) {
13065       ast_sockaddr_set_port(addr,
13066                   (get_transport_str2enum(transport) ==
13067                    SIP_TRANSPORT_TLS ||
13068                    !strncasecmp(fullcontact, "sips", 4)) ?
13069                   STANDARD_TLS_PORT : STANDARD_SIP_PORT);
13070    }
13071 
13072    return 0;
13073 }
13074 
13075 /*! \brief Change the other partys IP address based on given contact */
13076 static int set_address_from_contact(struct sip_pvt *pvt)
13077 {
13078    if (ast_test_flag(&pvt->flags[0], SIP_NAT_FORCE_RPORT)) {
13079       /* NAT: Don't trust the contact field.  Just use what they came to us
13080          with. */
13081       /*! \todo We need to save the TRANSPORT here too */
13082       pvt->sa = pvt->recv;
13083       return 0;
13084    }
13085 
13086    return __set_address_from_contact(pvt->fullcontact, &pvt->sa, pvt->socket.type == SIP_TRANSPORT_TLS ? 1 : 0);
13087 }
13088 
13089 /*! \brief Parse contact header and save registration (peer registration) */
13090 static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *peer, struct sip_request *req)
13091 {
13092    char contact[SIPBUFSIZE];
13093    char data[SIPBUFSIZE];
13094    const char *expires = get_header(req, "Expires");
13095    int expire = atoi(expires);
13096    char *curi, *domain, *transport;
13097    int transport_type;
13098    const char *useragent;
13099    struct ast_sockaddr oldsin, testsa;
13100    char *firstcuri = NULL;
13101    int start = 0;
13102    int wildcard_found = 0;
13103    int single_binding_found;
13104 
13105    ast_copy_string(contact, __get_header(req, "Contact", &start), sizeof(contact));
13106 
13107    if (ast_strlen_zero(expires)) {  /* No expires header, try look in Contact: */
13108       char *s = strcasestr(contact, ";expires=");
13109       if (s) {
13110          expires = strsep(&s, ";"); /* trim ; and beyond */
13111          if (sscanf(expires + 9, "%30d", &expire) != 1) {
13112             expire = default_expiry;
13113          }
13114       } else {
13115          /* Nothing has been specified */
13116          expire = default_expiry;
13117       }
13118    }
13119 
13120    copy_socket_data(&pvt->socket, &req->socket);
13121 
13122    do {
13123       /* Look for brackets */
13124       curi = contact;
13125       if (strchr(contact, '<') == NULL)   /* No <, check for ; and strip it */
13126          strsep(&curi, ";");  /* This is Header options, not URI options */
13127       curi = get_in_brackets(contact);
13128       if (!firstcuri) {
13129          firstcuri = ast_strdupa(curi);
13130       }
13131 
13132       if (!strcasecmp(curi, "*")) {
13133          wildcard_found = 1;
13134       } else {
13135          single_binding_found = 1;
13136       }
13137 
13138       if (wildcard_found && (ast_strlen_zero(expires) || expire != 0 || single_binding_found)) {
13139          /* Contact header parameter "*" detected, so punt if: Expires header is missing,
13140           * Expires value is not zero, or another Contact header is present. */
13141          return PARSE_REGISTER_FAILED;
13142       }
13143 
13144       ast_copy_string(contact, __get_header(req, "Contact", &start), sizeof(contact));
13145    } while (!ast_strlen_zero(contact));
13146    curi = firstcuri;
13147 
13148    /* if they did not specify Contact: or Expires:, they are querying
13149       what we currently have stored as their contact address, so return
13150       it
13151    */
13152    if (ast_strlen_zero(curi) && ast_strlen_zero(expires)) {
13153       /* If we have an active registration, tell them when the registration is going to expire */
13154       if (peer->expire > -1 && !ast_strlen_zero(peer->fullcontact)) {
13155          pvt->expiry = ast_sched_when(sched, peer->expire);
13156       }
13157       return PARSE_REGISTER_QUERY;
13158    } else if (!strcasecmp(curi, "*") || !expire) { /* Unregister this peer */
13159       /* This means remove all registrations and return OK */
13160       memset(&peer->addr, 0, sizeof(peer->addr));
13161       set_socket_transport(&peer->socket, peer->default_outbound_transport);
13162 
13163       AST_SCHED_DEL_UNREF(sched, peer->expire,
13164             unref_peer(peer, "remove register expire ref"));
13165 
13166       destroy_association(peer);
13167 
13168       register_peer_exten(peer, FALSE);   /* Remove extension from regexten= setting in sip.conf */
13169       ast_string_field_set(peer, fullcontact, "");
13170       ast_string_field_set(peer, useragent, "");
13171       peer->sipoptions = 0;
13172       peer->lastms = 0;
13173       peer->portinuri = 0;
13174       pvt->expiry = 0;
13175 
13176       ast_verb(3, "Unregistered SIP '%s'\n", peer->name);
13177 
13178       manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: Unregistered\r\n", peer->name);
13179       return PARSE_REGISTER_UPDATE;
13180    }
13181 
13182    /* Store whatever we got as a contact from the client */
13183    ast_string_field_set(peer, fullcontact, curi);
13184 
13185    /* For the 200 OK, we should use the received contact */
13186    ast_string_field_build(pvt, our_contact, "<%s>", curi);
13187 
13188    /* Make sure it's a SIP URL */
13189    if (parse_uri(curi, "sip:,sips:", &curi, NULL, &domain, &transport)) {
13190       ast_log(LOG_NOTICE, "Not a valid SIP contact (missing sip:/sips:) trying to use anyway\n");
13191    }
13192 
13193    /* handle the transport type specified in Contact header. */
13194    if (!(transport_type = get_transport_str2enum(transport))) {
13195       transport_type = pvt->socket.type;
13196    }
13197 
13198    /* if the peer's socket type is different than the Registration
13199     * transport type, change it.  If it got this far, it is a
13200     * supported type, but check just in case */
13201    if ((peer->socket.type != transport_type) && (peer->transports & transport_type)) {
13202       set_socket_transport(&peer->socket, transport_type);
13203    }
13204 
13205    oldsin = peer->addr;
13206 
13207    /* If we were already linked into the peers_by_ip container unlink ourselves so nobody can find us */
13208    if (!ast_sockaddr_isnull(&peer->addr)) {
13209       ao2_t_unlink(peers_by_ip, peer, "ao2_unlink of peer from peers_by_ip table");
13210    }
13211 
13212    if (!ast_test_flag(&peer->flags[0], SIP_NAT_FORCE_RPORT) && !ast_test_flag(&peer->flags[0], SIP_NAT_RPORT_PRESENT)) {
13213        /* use the data provided in the Contact header for call routing */
13214       ast_debug(1, "Store REGISTER's Contact header for call routing.\n");
13215       /* XXX This could block for a long time XXX */
13216       /*! \todo Check NAPTR/SRV if we have not got a port in the URI */
13217       if (ast_sockaddr_resolve_first(&testsa, domain, 0)) {
13218          ast_log(LOG_WARNING, "Invalid domain '%s'\n", domain);
13219          ast_string_field_set(peer, fullcontact, "");
13220          ast_string_field_set(pvt, our_contact, "");
13221          return PARSE_REGISTER_FAILED;
13222       }
13223 
13224       /* If we have a port number in the given URI, make sure we do remember to not check for NAPTR/SRV records.
13225          The domain part is actually a host. */
13226       peer->portinuri = ast_sockaddr_port(&testsa) ? TRUE : FALSE;
13227 
13228       if (!ast_sockaddr_port(&testsa)) {
13229          ast_sockaddr_set_port(&testsa,
13230                     transport_type == SIP_TRANSPORT_TLS ?
13231                     STANDARD_TLS_PORT : STANDARD_SIP_PORT);
13232       }
13233 
13234       ast_sockaddr_copy(&peer->addr, &testsa);
13235    } else {
13236       /* Don't trust the contact field.  Just use what they came to us
13237          with */
13238       ast_debug(1, "Store REGISTER's src-IP:port for call routing.\n");
13239       peer->addr = pvt->recv;
13240    }
13241 
13242    /* Check that they're allowed to register at this IP */
13243    if (ast_apply_ha(sip_cfg.contact_ha, &peer->addr) != AST_SENSE_ALLOW ||
13244          ast_apply_ha(peer->contactha, &peer->addr) != AST_SENSE_ALLOW) {
13245       ast_log(LOG_WARNING, "Domain '%s' disallowed by contact ACL (violating IP %s)\n", domain,
13246          ast_sockaddr_stringify_addr(&testsa));
13247       ast_string_field_set(peer, fullcontact, "");
13248       ast_string_field_set(pvt, our_contact, "");
13249       return PARSE_REGISTER_DENIED;
13250    }
13251 
13252    /* if the Contact header information copied into peer->addr matches the
13253     * received address, and the transport types are the same, then copy socket
13254     * data into the peer struct */
13255    if ((peer->socket.type == pvt->socket.type) &&
13256       !ast_sockaddr_cmp(&peer->addr, &pvt->recv)) {
13257       copy_socket_data(&peer->socket, &pvt->socket);
13258    }
13259 
13260    /* Now that our address has been updated put ourselves back into the container for lookups */
13261    ao2_t_link(peers_by_ip, peer, "ao2_link into peers_by_ip table");
13262 
13263    /* Save SIP options profile */
13264    peer->sipoptions = pvt->sipoptions;
13265 
13266    if (!ast_strlen_zero(curi) && ast_strlen_zero(peer->username)) {
13267       ast_string_field_set(peer, username, curi);
13268    }
13269 
13270    AST_SCHED_DEL_UNREF(sched, peer->expire,
13271          unref_peer(peer, "remove register expire ref"));
13272 
13273    if (expire > max_expiry) {
13274       expire = max_expiry;
13275    }
13276    if (expire < min_expiry) {
13277       expire = min_expiry;
13278    }
13279    if (peer->is_realtime && !ast_test_flag(&peer->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
13280       peer->expire = -1;
13281    } else {
13282       peer->expire = ast_sched_add(sched, (expire + 10) * 1000, expire_register,
13283             ref_peer(peer, "add registration ref"));
13284       if (peer->expire == -1) {
13285          unref_peer(peer, "remote registration ref");
13286       }
13287    }
13288    pvt->expiry = expire;
13289    snprintf(data, sizeof(data), "%s:%d:%s:%s", ast_sockaddr_stringify(&peer->addr),
13290        expire, peer->username, peer->fullcontact);
13291    /* Saving TCP connections is useless, we won't be able to reconnect
13292       XXX WHY???? XXX
13293       \todo Fix this immediately.
13294    */
13295    if (!peer->rt_fromcontact && (peer->socket.type & SIP_TRANSPORT_UDP))
13296       ast_db_put("SIP/Registry", peer->name, data);
13297    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));
13298 
13299    /* Is this a new IP address for us? */
13300    if (VERBOSITY_ATLEAST(2) && ast_sockaddr_cmp(&peer->addr, &oldsin)) {
13301       ast_verbose(VERBOSE_PREFIX_3 "Registered SIP '%s' at %s\n", peer->name,
13302             ast_sockaddr_stringify(&peer->addr));
13303    }
13304    sip_poke_peer(peer, 0);
13305    register_peer_exten(peer, 1);
13306    
13307    /* Save User agent */
13308    useragent = get_header(req, "User-Agent");
13309    if (strcasecmp(useragent, peer->useragent)) {
13310       ast_string_field_set(peer, useragent, useragent);
13311       ast_verb(4, "Saved useragent \"%s\" for peer %s\n", peer->useragent, peer->name);
13312    }
13313    return PARSE_REGISTER_UPDATE;
13314 }
13315 
13316 /*! \brief Remove route from route list */
13317 static void free_old_route(struct sip_route *route)
13318 {
13319    struct sip_route *next;
13320 
13321    while (route) {
13322       next = route->next;
13323       ast_free(route);
13324       route = next;
13325    }
13326 }
13327 
13328 /*! \brief List all routes - mostly for debugging */
13329 static void list_route(struct sip_route *route)
13330 {
13331    if (!route) {
13332       ast_verbose("list_route: no route\n");
13333    } else {
13334       for (;route; route = route->next)
13335          ast_verbose("list_route: hop: <%s>\n", route->hop);
13336    }
13337 }
13338 
13339 /*! \brief Build route list from Record-Route header */
13340 static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards)
13341 {
13342    struct sip_route *thishop, *head, *tail;
13343    int start = 0;
13344    int len;
13345    const char *rr, *contact, *c;
13346 
13347    /* Once a persistent route is set, don't fool with it */
13348    if (p->route && p->route_persistent) {
13349       ast_debug(1, "build_route: Retaining previous route: <%s>\n", p->route->hop);
13350       return;
13351    }
13352 
13353    if (p->route) {
13354       free_old_route(p->route);
13355       p->route = NULL;
13356    }
13357 
13358    /* We only want to create the route set the first time this is called */
13359    p->route_persistent = 1;
13360    
13361    /* Build a tailq, then assign it to p->route when done.
13362     * If backwards, we add entries from the head so they end up
13363     * in reverse order. However, we do need to maintain a correct
13364     * tail pointer because the contact is always at the end.
13365     */
13366    head = NULL;
13367    tail = head;
13368    /* 1st we pass through all the hops in any Record-Route headers */
13369    for (;;) {
13370       /* Each Record-Route header */
13371       rr = __get_header(req, "Record-Route", &start);
13372       if (*rr == '\0') {
13373          break;
13374       }
13375       for (; (rr = strchr(rr, '<')) ; rr += len) { /* Each route entry */
13376          ++rr;
13377          len = strcspn(rr, ">") + 1;
13378          /* Make a struct route */
13379          if ((thishop = ast_malloc(sizeof(*thishop) + len))) {
13380             /* ast_calloc is not needed because all fields are initialized in this block */
13381             ast_copy_string(thishop->hop, rr, len);
13382             ast_debug(2, "build_route: Record-Route hop: <%s>\n", thishop->hop);
13383             /* Link in */
13384             if (backwards) {
13385                /* Link in at head so they end up in reverse order */
13386                thishop->next = head;
13387                head = thishop;
13388                /* If this was the first then it'll be the tail */
13389                if (!tail) {
13390                   tail = thishop;
13391                }
13392             } else {
13393                thishop->next = NULL;
13394                /* Link in at the end */
13395                if (tail) {
13396                   tail->next = thishop;
13397                } else {
13398                   head = thishop;
13399                }
13400                tail = thishop;
13401             }
13402          }
13403       }
13404    }
13405 
13406    /* Only append the contact if we are dealing with a strict router */
13407    if (!head || (!ast_strlen_zero(head->hop) && strstr(head->hop, ";lr") == NULL) ) {
13408       /* 2nd append the Contact: if there is one */
13409       /* Can be multiple Contact headers, comma separated values - we just take the first */
13410       contact = get_header(req, "Contact");
13411       if (!ast_strlen_zero(contact)) {
13412          ast_debug(2, "build_route: Contact hop: %s\n", contact);
13413          /* Look for <: delimited address */
13414          c = strchr(contact, '<');
13415          if (c) {
13416             /* Take to > */
13417             ++c;
13418             len = strcspn(c, ">") + 1;
13419          } else {
13420             /* No <> - just take the lot */
13421             c = contact;
13422             len = strlen(contact) + 1;
13423          }
13424          if ((thishop = ast_malloc(sizeof(*thishop) + len))) {
13425             /* ast_calloc is not needed because all fields are initialized in this block */
13426             ast_copy_string(thishop->hop, c, len);
13427             thishop->next = NULL;
13428             /* Goes at the end */
13429             if (tail) {
13430                tail->next = thishop;
13431             } else {
13432                head = thishop;
13433             }
13434          }
13435       }
13436    }
13437 
13438    /* Store as new route */
13439    p->route = head;
13440 
13441    /* For debugging dump what we ended up with */
13442    if (sip_debug_test_pvt(p)) {
13443       list_route(p->route);
13444    }
13445 }
13446 
13447 /*! \brief builds the sip_pvt's randdata field which is used for the nonce
13448  *  challenge.  When forceupdate is not set, the nonce is only updated if
13449  *  the current one is stale.  In this case, a stalenonce is one which
13450  *  has already received a response, if a nonce has not received a response
13451  *  it is not always necessary or beneficial to create a new one. */
13452 
13453 static void set_nonce_randdata(struct sip_pvt *p, int forceupdate)
13454 {
13455    if (p->stalenonce || forceupdate || ast_strlen_zero(p->randdata)) {
13456       ast_string_field_build(p, randdata, "%08lx", ast_random()); /* Create nonce for challenge */
13457       p->stalenonce = 0;
13458    }
13459 }
13460 
13461 AST_THREADSTORAGE(check_auth_buf);
13462 #define CHECK_AUTH_BUF_INITLEN   256
13463 
13464 /*! \brief  Check user authorization from peer definition
13465    Some actions, like REGISTER and INVITEs from peers require
13466    authentication (if peer have secret set)
13467     \return 0 on success, non-zero on error
13468 */
13469 static enum check_auth_result check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
13470                 const char *secret, const char *md5secret, int sipmethod,
13471                 const char *uri, enum xmittype reliable, int ignore)
13472 {
13473    const char *response;
13474    char *reqheader, *respheader;
13475    const char *authtoken;
13476    char a1_hash[256];
13477    char resp_hash[256]="";
13478    char *c;
13479    int  wrongnonce = FALSE;
13480    int  good_response;
13481    const char *usednonce = p->randdata;
13482    struct ast_str *buf;
13483    int res;
13484 
13485    /* table of recognised keywords, and their value in the digest */
13486    enum keys { K_RESP, K_URI, K_USER, K_NONCE, K_LAST };
13487    struct x {
13488       const char *key;
13489       const char *s;
13490    } *i, keys[] = {
13491       [K_RESP] = { "response=", "" },
13492       [K_URI] = { "uri=", "" },
13493       [K_USER] = { "username=", "" },
13494       [K_NONCE] = { "nonce=", "" },
13495       [K_LAST] = { NULL, NULL}
13496    };
13497 
13498    /* Always OK if no secret */
13499    if (ast_strlen_zero(secret) && ast_strlen_zero(md5secret))
13500       return AUTH_SUCCESSFUL;
13501 
13502    /* Always auth with WWW-auth since we're NOT a proxy */
13503    /* Using proxy-auth in a B2BUA may block proxy authorization in the same transaction */
13504    response = "401 Unauthorized";
13505 
13506    /*
13507     * Note the apparent swap of arguments below, compared to other
13508     * usages of auth_headers().
13509     */
13510    auth_headers(WWW_AUTH, &respheader, &reqheader);
13511 
13512    authtoken =  get_header(req, reqheader);  
13513    if (ignore && !ast_strlen_zero(p->randdata) && ast_strlen_zero(authtoken)) {
13514       /* This is a retransmitted invite/register/etc, don't reconstruct authentication
13515          information */
13516       if (!reliable) {
13517          /* Resend message if this was NOT a reliable delivery.   Otherwise the
13518             retransmission should get it */
13519          transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, 0);
13520          /* Schedule auto destroy in 32 seconds (according to RFC 3261) */
13521          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13522       }
13523       return AUTH_CHALLENGE_SENT;
13524    } else if (ast_strlen_zero(p->randdata) || ast_strlen_zero(authtoken)) {
13525       /* We have no auth, so issue challenge and request authentication */
13526       set_nonce_randdata(p, 1); /* Create nonce for challenge */
13527       transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, 0);
13528       /* Schedule auto destroy in 32 seconds */
13529       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13530       return AUTH_CHALLENGE_SENT;
13531    }
13532 
13533    /* --- We have auth, so check it */
13534 
13535    /* Whoever came up with the authentication section of SIP can suck my %&#$&* for not putting
13536       an example in the spec of just what it is you're doing a hash on. */
13537 
13538    if (!(buf = ast_str_thread_get(&check_auth_buf, CHECK_AUTH_BUF_INITLEN))) {
13539       return AUTH_SECRET_FAILED; /*! XXX \todo need a better return code here */
13540    }
13541 
13542    /* Make a copy of the response and parse it */
13543    res = ast_str_set(&buf, 0, "%s", authtoken);
13544 
13545    if (res == AST_DYNSTR_BUILD_FAILED) {
13546       return AUTH_SECRET_FAILED; /*! XXX \todo need a better return code here */
13547    }
13548 
13549    c = buf->str;
13550 
13551    while(c && *(c = ast_skip_blanks(c)) ) { /* lookup for keys */
13552       for (i = keys; i->key != NULL; i++) {
13553          const char *separator = ",";  /* default */
13554 
13555          if (strncasecmp(c, i->key, strlen(i->key)) != 0) {
13556             continue;
13557          }
13558          /* Found. Skip keyword, take text in quotes or up to the separator. */
13559          c += strlen(i->key);
13560          if (*c == '"') { /* in quotes. Skip first and look for last */
13561             c++;
13562             separator = "\"";
13563          }
13564          i->s = c;
13565          strsep(&c, separator);
13566          break;
13567       }
13568       if (i->key == NULL) { /* not found, jump after space or comma */
13569          strsep(&c, " ,");
13570       }
13571    }
13572 
13573    /* Verify that digest username matches  the username we auth as */
13574    if (strcmp(username, keys[K_USER].s)) {
13575       ast_log(LOG_WARNING, "username mismatch, have <%s>, digest has <%s>\n",
13576          username, keys[K_USER].s);
13577       /* Oops, we're trying something here */
13578       return AUTH_USERNAME_MISMATCH;
13579    }
13580 
13581    /* Verify nonce from request matches our nonce, and the nonce has not already been responded to.
13582     * If this check fails, send 401 with new nonce */
13583    if (strcasecmp(p->randdata, keys[K_NONCE].s) || p->stalenonce) { /* XXX it was 'n'casecmp ? */
13584       wrongnonce = TRUE;
13585       usednonce = keys[K_NONCE].s;
13586    } else {
13587       p->stalenonce = 1; /* now, since the nonce has a response, mark it as stale so it can't be sent or responded to again */
13588    }
13589 
13590    if (!ast_strlen_zero(md5secret)) {
13591       ast_copy_string(a1_hash, md5secret, sizeof(a1_hash));
13592    } else {
13593       char a1[256];
13594 
13595       snprintf(a1, sizeof(a1), "%s:%s:%s", username, p->realm, secret);
13596       ast_md5_hash(a1_hash, a1);
13597    }
13598 
13599    /* compute the expected response to compare with what we received */
13600    {
13601       char a2[256];
13602       char a2_hash[256];
13603       char resp[256];
13604 
13605       snprintf(a2, sizeof(a2), "%s:%s", sip_methods[sipmethod].text,
13606             S_OR(keys[K_URI].s, uri));
13607       ast_md5_hash(a2_hash, a2);
13608       snprintf(resp, sizeof(resp), "%s:%s:%s", a1_hash, usednonce, a2_hash);
13609       ast_md5_hash(resp_hash, resp);
13610    }
13611 
13612    good_response = keys[K_RESP].s &&
13613          !strncasecmp(keys[K_RESP].s, resp_hash, strlen(resp_hash));
13614    if (wrongnonce) {
13615       if (good_response) {
13616          if (sipdebug)
13617             ast_log(LOG_NOTICE, "Correct auth, but based on stale nonce received from '%s'\n", get_header(req, "From"));
13618          /* We got working auth token, based on stale nonce . */
13619          set_nonce_randdata(p, 0);
13620          transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, TRUE);
13621       } else {
13622          /* Everything was wrong, so give the device one more try with a new challenge */
13623          if (!req->ignore) {
13624             if (sipdebug) {
13625                ast_log(LOG_NOTICE, "Bad authentication received from '%s'\n", get_header(req, "To"));
13626             }
13627             set_nonce_randdata(p, 1);
13628          } else {
13629             if (sipdebug) {
13630                ast_log(LOG_NOTICE, "Duplicate authentication received from '%s'\n", get_header(req, "To"));
13631             }
13632          }
13633          transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, FALSE);
13634       }
13635 
13636       /* Schedule auto destroy in 32 seconds */
13637       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13638       return AUTH_CHALLENGE_SENT;
13639    }
13640    if (good_response) {
13641       append_history(p, "AuthOK", "Auth challenge successful for %s", username);
13642       return AUTH_SUCCESSFUL;
13643    }
13644 
13645    /* Ok, we have a bad username/secret pair */
13646    /* Tell the UAS not to re-send this authentication data, because
13647       it will continue to fail
13648    */
13649 
13650    return AUTH_SECRET_FAILED;
13651 }
13652 
13653 /*! \brief Change onhold state of a peer using a pvt structure */
13654 static void sip_peer_hold(struct sip_pvt *p, int hold)
13655 {
13656    if (!p->relatedpeer) {
13657       return;
13658    }
13659 
13660    /* If they put someone on hold, increment the value... otherwise decrement it */
13661    ast_atomic_fetchadd_int(&p->relatedpeer->onHold, (hold ? +1 : -1));
13662 
13663    /* Request device state update */
13664    ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", p->relatedpeer->name);
13665    
13666    return;
13667 }
13668 
13669 /*! \brief Receive MWI events that we have subscribed to */
13670 static void mwi_event_cb(const struct ast_event *event, void *userdata)
13671 {
13672    struct sip_peer *peer = userdata;
13673 
13674    ao2_lock(peer);
13675    sip_send_mwi_to_peer(peer, event, 0);
13676    ao2_unlock(peer);
13677 }
13678 
13679 static void network_change_event_subscribe(void)
13680 {
13681    if (!network_change_event_subscription) {
13682       network_change_event_subscription = ast_event_subscribe(AST_EVENT_NETWORK_CHANGE,
13683          network_change_event_cb,
13684          "SIP Network Change ",
13685          NULL, AST_EVENT_IE_END);
13686    }
13687 }
13688 
13689 static void network_change_event_unsubscribe(void)
13690 {
13691    if (network_change_event_subscription) {
13692       network_change_event_subscription = ast_event_unsubscribe(network_change_event_subscription);
13693    }
13694 }
13695 
13696 static int network_change_event_sched_cb(const void *data)
13697 {
13698    network_change_event_sched_id = -1;
13699    sip_send_all_registers();
13700    sip_send_all_mwi_subscriptions();
13701    return 0;
13702 }
13703 
13704 static void network_change_event_cb(const struct ast_event *event, void *userdata)
13705 {
13706    ast_debug(1, "SIP, got a network change event, renewing all SIP registrations.\n");
13707    if (network_change_event_sched_id == -1) {
13708       network_change_event_sched_id = ast_sched_add(sched, 1000, network_change_event_sched_cb, NULL);
13709    }
13710 }
13711 
13712 /*! \brief Callback for the devicestate notification (SUBSCRIBE) support subsystem
13713 \note If you add an "hint" priority to the extension in the dial plan,
13714    you will get notifications on device state changes */
13715 static int cb_extensionstate(char *context, char* exten, int state, void *data)
13716 {
13717    struct sip_pvt *p = data;
13718 
13719    sip_pvt_lock(p);
13720 
13721    switch(state) {
13722    case AST_EXTENSION_DEACTIVATED:  /* Retry after a while */
13723    case AST_EXTENSION_REMOVED:   /* Extension is gone */
13724       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);  /* Delete subscription in 32 secs */
13725       ast_verb(2, "Extension state: Watcher for hint %s %s. Notify User %s\n", exten, state == AST_EXTENSION_DEACTIVATED ? "deactivated" : "removed", p->username);
13726       p->stateid = -1;
13727       p->subscribed = NONE;
13728       append_history(p, "Subscribestatus", "%s", state == AST_EXTENSION_REMOVED ? "HintRemoved" : "Deactivated");
13729       break;
13730    default: /* Tell user */
13731       p->laststate = state;
13732       break;
13733    }
13734    if (p->subscribed != NONE) {  /* Only send state NOTIFY if we know the format */
13735       if (!p->pendinginvite) {
13736          transmit_state_notify(p, state, 1, FALSE);
13737       } else {
13738          /* We already have a NOTIFY sent that is not answered. Queue the state up.
13739             if many state changes happen meanwhile, we will only send a notification of the last one */
13740          ast_set_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE);
13741       }
13742    }
13743    ast_verb(2, "Extension Changed %s[%s] new state %s for Notify User %s %s\n", exten, context, ast_extension_state2str(state), p->username,
13744          ast_test_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE) ? "(queued)" : "");
13745 
13746    sip_pvt_unlock(p);
13747 
13748    return 0;
13749 }
13750 
13751 /*! \brief Send a fake 401 Unauthorized response when the administrator
13752   wants to hide the names of local devices  from fishers
13753  */
13754 static void transmit_fake_auth_response(struct sip_pvt *p, int sipmethod, struct sip_request *req, enum xmittype reliable)
13755 {
13756    /* We have to emulate EXACTLY what we'd get with a good peer
13757     * and a bad password, or else we leak information. */
13758    const char *response = "407 Proxy Authentication Required";
13759    const char *reqheader = "Proxy-Authorization";
13760    const char *respheader = "Proxy-Authenticate";
13761    const char *authtoken;
13762    struct ast_str *buf;
13763    char *c;
13764 
13765    /* table of recognised keywords, and their value in the digest */
13766    enum keys { K_NONCE, K_LAST };
13767    struct x {
13768       const char *key;
13769       const char *s;
13770    } *i, keys[] = {
13771       [K_NONCE] = { "nonce=", "" },
13772       [K_LAST] = { NULL, NULL}
13773    };
13774 
13775    if (sipmethod == SIP_REGISTER || sipmethod == SIP_SUBSCRIBE) {
13776       response = "401 Unauthorized";
13777       reqheader = "Authorization";
13778       respheader = "WWW-Authenticate";
13779    }
13780    authtoken = get_header(req, reqheader);
13781    if (req->ignore && !ast_strlen_zero(p->randdata) && ast_strlen_zero(authtoken)) {
13782       /* This is a retransmitted invite/register/etc, don't reconstruct authentication
13783        * information */
13784       transmit_response_with_auth(p, response, req, p->randdata, 0, respheader, 0);
13785       /* Schedule auto destroy in 32 seconds (according to RFC 3261) */
13786       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13787       return;
13788    } else if (ast_strlen_zero(p->randdata) || ast_strlen_zero(authtoken)) {
13789       /* We have no auth, so issue challenge and request authentication */
13790       set_nonce_randdata(p, 1);
13791       transmit_response_with_auth(p, response, req, p->randdata, 0, respheader, 0);
13792       /* Schedule auto destroy in 32 seconds */
13793       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13794       return;
13795    }
13796 
13797    if (!(buf = ast_str_thread_get(&check_auth_buf, CHECK_AUTH_BUF_INITLEN))) {
13798       transmit_response(p, "403 Forbidden (Bad auth)", &p->initreq);
13799       return;
13800    }
13801 
13802    /* Make a copy of the response and parse it */
13803    if (ast_str_set(&buf, 0, "%s", authtoken) == AST_DYNSTR_BUILD_FAILED) {
13804       transmit_response(p, "403 Forbidden (Bad auth)", &p->initreq);
13805       return;
13806    }
13807 
13808    c = buf->str;
13809 
13810    while (c && *(c = ast_skip_blanks(c))) { /* lookup for keys */
13811       for (i = keys; i->key != NULL; i++) {
13812          const char *separator = ",";  /* default */
13813 
13814          if (strncasecmp(c, i->key, strlen(i->key)) != 0) {
13815             continue;
13816          }
13817          /* Found. Skip keyword, take text in quotes or up to the separator. */
13818          c += strlen(i->key);
13819          if (*c == '"') { /* in quotes. Skip first and look for last */
13820             c++;
13821             separator = "\"";
13822          }
13823          i->s = c;
13824          strsep(&c, separator);
13825          break;
13826       }
13827       if (i->key == NULL) { /* not found, jump after space or comma */
13828          strsep(&c, " ,");
13829       }
13830    }
13831 
13832    /* Verify nonce from request matches our nonce.  If not, send 401 with new nonce */
13833    if (strcasecmp(p->randdata, keys[K_NONCE].s)) {
13834       if (!req->ignore) {
13835          set_nonce_randdata(p, 1);
13836       }
13837       transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, FALSE);
13838 
13839       /* Schedule auto destroy in 32 seconds */
13840       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13841    } else {
13842       transmit_response(p, "403 Forbidden (Bad auth)", &p->initreq);
13843    }
13844 }
13845 
13846 /*!
13847  * Terminate the uri at the first ';' or space.
13848  * Technically we should ignore escaped space per RFC3261 (19.1.1 etc)
13849  * but don't do it for the time being. Remember the uri format is:
13850  * (User-parameters was added after RFC 3261)
13851  *\verbatim
13852  *
13853  * sip:user:password;user-parameters@host:port;uri-parameters?headers
13854  * sips:user:password;user-parameters@host:port;uri-parameters?headers
13855  *
13856  *\endverbatim
13857  * \todo As this function does not support user-parameters, it's considered broken
13858  * and needs fixing.
13859  */
13860 static char *terminate_uri(char *uri)
13861 {
13862    char *t = uri;
13863    while (*t && *t > ' ' && *t != ';') {
13864       t++;
13865    }
13866    *t = '\0';
13867    return uri;
13868 }
13869 
13870 /*! \brief Verify registration of user
13871    - Registration is done in several steps, first a REGISTER without auth
13872      to get a challenge (nonce) then a second one with auth
13873    - Registration requests are only matched with peers that are marked as "dynamic"
13874  */
13875 static enum check_auth_result register_verify(struct sip_pvt *p, struct ast_sockaddr *addr,
13876                      struct sip_request *req, const char *uri)
13877 {
13878    enum check_auth_result res = AUTH_NOT_FOUND;
13879    struct sip_peer *peer;
13880    char tmp[256];
13881    char *name = NULL, *c, *domain = NULL, *dummy = NULL;
13882    char *uri2 = ast_strdupa(uri);
13883 
13884    terminate_uri(uri2);
13885 
13886    ast_copy_string(tmp, get_header(req, "To"), sizeof(tmp));
13887 
13888    c = get_in_brackets(tmp);
13889    c = remove_uri_parameters(c);
13890 
13891    if (parse_uri(c, "sip:,sips:", &name, &dummy, &domain, NULL)) {
13892       ast_log(LOG_NOTICE, "Invalid to address: '%s' from %s (missing sip:) trying to use anyway...\n", c, ast_sockaddr_stringify_addr(addr));
13893       return -1;
13894    }
13895 
13896    SIP_PEDANTIC_DECODE(name);
13897    SIP_PEDANTIC_DECODE(domain);
13898 
13899    /*! \todo XXX here too we interpret a missing @domain as a name-only
13900     * URI, whereas the RFC says this is a domain-only uri.
13901     */
13902    if (!ast_strlen_zero(domain) && !AST_LIST_EMPTY(&domain_list)) {
13903       if (!check_sip_domain(domain, NULL, 0)) {
13904          transmit_response(p, "404 Not found (unknown domain)", &p->initreq);
13905          return AUTH_UNKNOWN_DOMAIN;
13906       }
13907    }
13908 
13909    ast_string_field_set(p, exten, name);
13910    build_contact(p);
13911    if (req->ignore) {
13912       /* Expires is a special case, where we only want to load the peer if this isn't a deregistration attempt */
13913       const char *expires = get_header(req, "Expires");
13914       int expire = atoi(expires);
13915 
13916       if (ast_strlen_zero(expires)) { /* No expires header; look in Contact */
13917          if ((expires = strcasestr(get_header(req, "Contact"), ";expires="))) {
13918             expire = atoi(expires + 9);
13919          }
13920       }
13921       if (!ast_strlen_zero(expires) && expire == 0) {
13922          transmit_response_with_date(p, "200 OK", req);
13923          return 0;
13924       }
13925    }
13926    peer = find_peer(name, NULL, TRUE, FINDPEERS, FALSE, 0);
13927 
13928    if (!(peer && ast_apply_ha(peer->ha, addr))) {
13929       /* Peer fails ACL check */
13930       if (peer) {
13931          unref_peer(peer, "register_verify: unref_peer: from find_peer operation");
13932          peer = NULL;
13933          res = AUTH_ACL_FAILED;
13934       } else {
13935          res = AUTH_NOT_FOUND;
13936       }
13937    }
13938 
13939    if (peer) {
13940       ao2_lock(peer);
13941       if (!peer->host_dynamic) {
13942          ast_log(LOG_ERROR, "Peer '%s' is trying to register, but not configured as host=dynamic\n", peer->name);
13943          res = AUTH_PEER_NOT_DYNAMIC;
13944       } else {
13945          ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_NAT_FORCE_RPORT);
13946          if (ast_test_flag(&p->flags[1], SIP_PAGE2_REGISTERTRYING))
13947             transmit_response(p, "100 Trying", req);
13948          if (!(res = check_auth(p, req, peer->name, peer->secret, peer->md5secret, SIP_REGISTER, uri2, XMIT_UNRELIABLE, req->ignore))) {
13949             if (sip_cancel_destroy(p))
13950                ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
13951 
13952             if (check_request_transport(peer, req)) {
13953                ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
13954                transmit_response_with_date(p, "403 Forbidden", req);
13955                res = AUTH_BAD_TRANSPORT;
13956             } else {
13957 
13958                /* We have a successful registration attempt with proper authentication,
13959                   now, update the peer */
13960                switch (parse_register_contact(p, peer, req)) {
13961                case PARSE_REGISTER_DENIED:
13962                   ast_log(LOG_WARNING, "Registration denied because of contact ACL\n");
13963                   transmit_response_with_date(p, "603 Denied", req);
13964                   peer->lastmsgssent = -1;
13965                   res = 0;
13966                   break;
13967                case PARSE_REGISTER_FAILED:
13968                   ast_log(LOG_WARNING, "Failed to parse contact info\n");
13969                   transmit_response_with_date(p, "400 Bad Request", req);
13970                   peer->lastmsgssent = -1;
13971                   res = 0;
13972                   break;
13973                case PARSE_REGISTER_QUERY:
13974                   ast_string_field_set(p, fullcontact, peer->fullcontact);
13975                   transmit_response_with_date(p, "200 OK", req);
13976                   peer->lastmsgssent = -1;
13977                   res = 0;
13978                   break;
13979                case PARSE_REGISTER_UPDATE:
13980                   ast_string_field_set(p, fullcontact, peer->fullcontact);
13981                   update_peer(peer, p->expiry);
13982                   /* Say OK and ask subsystem to retransmit msg counter */
13983                   transmit_response_with_date(p, "200 OK", req);
13984                   if (!ast_test_flag((&peer->flags[1]), SIP_PAGE2_SUBSCRIBEMWIONLY))
13985                      peer->lastmsgssent = -1;
13986                   res = 0;
13987                   break;
13988                }
13989             }
13990 
13991          }
13992       }
13993       ao2_unlock(peer);
13994    }
13995    if (!peer && sip_cfg.autocreatepeer) {
13996       /* Create peer if we have autocreate mode enabled */
13997       peer = temp_peer(name);
13998       if (peer) {
13999          ao2_t_link(peers, peer, "link peer into peer table");
14000          if (!ast_sockaddr_isnull(&peer->addr)) {
14001             ao2_t_link(peers_by_ip, peer, "link peer into peers-by-ip table");
14002          }
14003          ao2_lock(peer);
14004          if (sip_cancel_destroy(p))
14005             ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
14006          switch (parse_register_contact(p, peer, req)) {
14007          case PARSE_REGISTER_DENIED:
14008             ast_log(LOG_WARNING, "Registration denied because of contact ACL\n");
14009             transmit_response_with_date(p, "403 Forbidden (ACL)", req);
14010             peer->lastmsgssent = -1;
14011             res = 0;
14012             break;
14013          case PARSE_REGISTER_FAILED:
14014             ast_log(LOG_WARNING, "Failed to parse contact info\n");
14015             transmit_response_with_date(p, "400 Bad Request", req);
14016             peer->lastmsgssent = -1;
14017             res = 0;
14018             break;
14019          case PARSE_REGISTER_QUERY:
14020             ast_string_field_set(p, fullcontact, peer->fullcontact);
14021             transmit_response_with_date(p, "200 OK", req);
14022             peer->lastmsgssent = -1;
14023             res = 0;
14024             break;
14025          case PARSE_REGISTER_UPDATE:
14026             ast_string_field_set(p, fullcontact, peer->fullcontact);
14027             /* Say OK and ask subsystem to retransmit msg counter */
14028             transmit_response_with_date(p, "200 OK", req);
14029             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));
14030             peer->lastmsgssent = -1;
14031             res = 0;
14032             break;
14033          }
14034          ao2_unlock(peer);
14035       }
14036    }
14037    if (!peer && sip_cfg.alwaysauthreject) {
14038       /* If we found a peer, we transmit a 100 Trying.  Therefore, if we're
14039        * trying to avoid leaking information, we MUST also transmit the same
14040        * response when we DON'T find a peer. */
14041       transmit_response(p, "100 Trying", req);
14042       /* Insert a fake delay between the 100 and the subsequent failure. */
14043       sched_yield();
14044    }
14045    if (!res) {
14046       ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", peer->name);
14047    }
14048    if (res < 0) {
14049       switch (res) {
14050       case AUTH_SECRET_FAILED:
14051          /* Wrong password in authentication. Go away, don't try again until you fixed it */
14052          transmit_response(p, "403 Forbidden (Bad auth)", &p->initreq);
14053          if (global_authfailureevents) {
14054             const char *peer_addr = ast_strdupa(ast_sockaddr_stringify_addr(addr));
14055             const char *peer_port = ast_strdupa(ast_sockaddr_stringify_port(addr));
14056             manager_event(EVENT_FLAG_SYSTEM, "PeerStatus",
14057                      "ChannelType: SIP\r\n"
14058                      "Peer: SIP/%s\r\n"
14059                      "PeerStatus: Rejected\r\n"
14060                      "Cause: AUTH_SECRET_FAILED\r\n"
14061                      "Address: %s\r\n"
14062                      "Port: %s\r\n",
14063                      name, peer_addr, peer_port);
14064          }
14065          break;
14066       case AUTH_USERNAME_MISMATCH:
14067          /* Username and digest username does not match.
14068             Asterisk uses the From: username for authentication. We need the
14069             devices to use the same authentication user name until we support
14070             proper authentication by digest auth name */
14071       case AUTH_NOT_FOUND:
14072       case AUTH_PEER_NOT_DYNAMIC:
14073       case AUTH_ACL_FAILED:
14074          if (sip_cfg.alwaysauthreject) {
14075             transmit_fake_auth_response(p, SIP_REGISTER, &p->initreq, XMIT_UNRELIABLE);
14076             if (global_authfailureevents) {
14077                const char *peer_addr = ast_strdupa(ast_sockaddr_stringify_addr(addr));
14078                const char *peer_port = ast_strdupa(ast_sockaddr_stringify_port(addr));
14079                manager_event(EVENT_FLAG_SYSTEM, "PeerStatus",
14080                         "ChannelType: SIP\r\n"
14081                         "Peer: SIP/%s\r\n"
14082                         "PeerStatus: Rejected\r\n"
14083                         "Cause: %s\r\n"
14084                         "Address: %s\r\n"
14085                         "Port: %s\r\n",
14086                         name,
14087                         res == AUTH_PEER_NOT_DYNAMIC ? "AUTH_PEER_NOT_DYNAMIC" : "URI_NOT_FOUND",
14088                         peer_addr, peer_port);
14089             }
14090          } else {
14091             /* URI not found */
14092             if (res == AUTH_PEER_NOT_DYNAMIC) {
14093                transmit_response(p, "403 Forbidden", &p->initreq);
14094                if (global_authfailureevents) {
14095                   const char *peer_addr = ast_strdupa(ast_sockaddr_stringify_addr(addr));
14096                   const char *peer_port = ast_strdupa(ast_sockaddr_stringify_port(addr));
14097                   manager_event(EVENT_FLAG_SYSTEM, "PeerStatus",
14098                      "ChannelType: SIP\r\n"
14099                      "Peer: SIP/%s\r\n"
14100                      "PeerStatus: Rejected\r\n"
14101                      "Cause: AUTH_PEER_NOT_DYNAMIC\r\n"
14102                      "Address: %s\r\n"
14103                      "Port: %s\r\n",
14104                      name, peer_addr, peer_port);
14105                }
14106             } else {
14107                transmit_response(p, "404 Not found", &p->initreq);
14108                if (global_authfailureevents) {
14109                   const char *peer_addr = ast_strdupa(ast_sockaddr_stringify_addr(addr));
14110                   const char *peer_port = ast_strdupa(ast_sockaddr_stringify_port(addr));
14111                   manager_event(EVENT_FLAG_SYSTEM, "PeerStatus",
14112                      "ChannelType: SIP\r\n"
14113                      "Peer: SIP/%s\r\n"
14114                      "PeerStatus: Rejected\r\n"
14115                      "Cause: %s\r\n"
14116                      "Address: %s\r\n"
14117                      "Port: %s\r\n",
14118                      name,
14119                      (res == AUTH_USERNAME_MISMATCH) ? "AUTH_USERNAME_MISMATCH" : "URI_NOT_FOUND",
14120                      peer_addr, peer_port);
14121                }
14122             }
14123          }
14124          break;
14125       case AUTH_BAD_TRANSPORT:
14126       default:
14127          break;
14128       }
14129    }
14130    if (peer) {
14131       unref_peer(peer, "register_verify: unref_peer: tossing stack peer pointer at end of func");
14132    }
14133 
14134    return res;
14135 }
14136 
14137 /*! \brief Translate referring cause */
14138 static void sip_set_redirstr(struct sip_pvt *p, char *reason) {
14139 
14140    if (!strcmp(reason, "unknown")) {
14141       ast_string_field_set(p, redircause, "UNKNOWN");
14142    } else if (!strcmp(reason, "user-busy")) {
14143       ast_string_field_set(p, redircause, "BUSY");
14144    } else if (!strcmp(reason, "no-answer")) {
14145       ast_string_field_set(p, redircause, "NOANSWER");
14146    } else if (!strcmp(reason, "unavailable")) {
14147       ast_string_field_set(p, redircause, "UNREACHABLE");
14148    } else if (!strcmp(reason, "unconditional")) {
14149       ast_string_field_set(p, redircause, "UNCONDITIONAL");
14150    } else if (!strcmp(reason, "time-of-day")) {
14151       ast_string_field_set(p, redircause, "UNKNOWN");
14152    } else if (!strcmp(reason, "do-not-disturb")) {
14153       ast_string_field_set(p, redircause, "UNKNOWN");
14154    } else if (!strcmp(reason, "deflection")) {
14155       ast_string_field_set(p, redircause, "UNKNOWN");
14156    } else if (!strcmp(reason, "follow-me")) {
14157       ast_string_field_set(p, redircause, "UNKNOWN");
14158    } else if (!strcmp(reason, "out-of-service")) {
14159       ast_string_field_set(p, redircause, "UNREACHABLE");
14160    } else if (!strcmp(reason, "away")) {
14161       ast_string_field_set(p, redircause, "UNREACHABLE");
14162    } else {
14163       ast_string_field_set(p, redircause, "UNKNOWN");
14164    }
14165 }
14166 
14167 /*! \brief Parse the parts of the P-Asserted-Identity header
14168  * on an incoming packet. Returns 1 if a valid header is found
14169  * and it is different from the current caller id.
14170  */
14171 static int get_pai(struct sip_pvt *p, struct sip_request *req)
14172 {
14173    char pai[256];
14174    char privacy[64];
14175    char *cid_num = "";
14176    char *cid_name = "";
14177    int callingpres = AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
14178    char *start = NULL, *end = NULL, *uri = NULL;
14179 
14180    ast_copy_string(pai, get_header(req, "P-Asserted-Identity"), sizeof(pai));
14181 
14182    if (ast_strlen_zero(pai)) {
14183       return 0;
14184    }
14185 
14186    start = pai;
14187    if (*start == '"') {
14188       *start++ = '\0';
14189       end = strchr(start, '"');
14190       if (!end) {
14191          return 0;
14192       }
14193       *end++ = '\0';
14194       cid_name = start;
14195       start = ast_skip_blanks(end);
14196    }
14197 
14198    if (*start != '<')
14199       return 0;
14200    /* At this point, 'start' points to the URI in brackets.
14201     * We need a copy so that our comparison to the anonymous
14202     * URI is valid.
14203     */
14204    uri = ast_strdupa(start);
14205    *start++ = '\0';
14206    end = strchr(start, '@');
14207    if (!end) {
14208       return 0;
14209    }
14210    *end++ = '\0';
14211    if (!strncasecmp(uri, "sip:anonymous@anonymous.invalid", 31)) {
14212       callingpres = AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED;
14213       /*XXX Assume no change in cid_num. Perhaps it should be
14214        * blanked?
14215        */
14216       cid_num = (char *)p->cid_num;
14217    } else if (!strncasecmp(start, "sip:", 4)) {
14218       cid_num = start + 4;
14219       if (global_shrinkcallerid && ast_is_shrinkable_phonenumber(cid_num))
14220          ast_shrink_phone_number(cid_num);
14221       start = end;
14222 
14223       end = strchr(start, '>');
14224       if (!end) {
14225          return 0;
14226       }
14227       *end = '\0';
14228    } else {
14229       return 0;
14230    }
14231 
14232    ast_copy_string(privacy, get_header(req, "Privacy"), sizeof(privacy));
14233    if (!ast_strlen_zero(privacy) && strncmp(privacy, "id", 2)) {
14234       callingpres = AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED;
14235    }
14236 
14237    /* Only return true if the supplied caller id is different */
14238    if (!strcasecmp(p->cid_num, cid_num) && !strcasecmp(p->cid_name, cid_name) && p->callingpres == callingpres) {
14239       return 0;
14240    }
14241 
14242    ast_string_field_set(p, cid_num, cid_num);
14243    ast_string_field_set(p, cid_name, cid_name);
14244    p->callingpres = callingpres;
14245 
14246    if (p->owner) {
14247       ast_set_callerid(p->owner, cid_num, cid_name, NULL);
14248       p->owner->caller.id.name.presentation = callingpres;
14249       p->owner->caller.id.number.presentation = callingpres;
14250    }
14251 
14252    return 1;
14253 }
14254 
14255 /*! \brief Get name, number and presentation from remote party id header,
14256  *  returns true if a valid header was found and it was different from the
14257  *  current caller id.
14258  */
14259 static int get_rpid(struct sip_pvt *p, struct sip_request *oreq)
14260 {
14261    char tmp[256];
14262    struct sip_request *req;
14263    char *cid_num = "";
14264    char *cid_name = "";
14265    int callingpres = AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
14266    char *privacy = "";
14267    char *screen = "";
14268    char *start, *end;
14269 
14270    if (!ast_test_flag(&p->flags[0], SIP_TRUSTRPID))
14271       return 0;
14272    req = oreq;
14273    if (!req)
14274       req = &p->initreq;
14275    ast_copy_string(tmp, get_header(req, "Remote-Party-ID"), sizeof(tmp));
14276    if (ast_strlen_zero(tmp)) {
14277       return get_pai(p, req);
14278    }
14279 
14280    start = tmp;
14281    if (*start == '"') {
14282       *start++ = '\0';
14283       end = strchr(start, '"');
14284       if (!end)
14285          return 0;
14286       *end++ = '\0';
14287       cid_name = start;
14288       start = ast_skip_blanks(end);
14289    }
14290 
14291    if (*start != '<')
14292       return 0;
14293    *start++ = '\0';
14294    end = strchr(start, '@');
14295    if (!end)
14296       return 0;
14297    *end++ = '\0';
14298    if (strncasecmp(start, "sip:", 4))
14299       return 0;
14300    cid_num = start + 4;
14301    if (global_shrinkcallerid && ast_is_shrinkable_phonenumber(cid_num))
14302       ast_shrink_phone_number(cid_num);
14303    start = end;
14304 
14305    end = strchr(start, '>');
14306    if (!end)
14307       return 0;
14308    *end++ = '\0';
14309    if (*end) {
14310       start = end;
14311       if (*start != ';')
14312          return 0;
14313       *start++ = '\0';
14314       while (!ast_strlen_zero(start)) {
14315          end = strchr(start, ';');
14316          if (end)
14317             *end++ = '\0';
14318          if (!strncasecmp(start, "privacy=", 8))
14319             privacy = start + 8;
14320          else if (!strncasecmp(start, "screen=", 7))
14321             screen = start + 7;
14322          start = end;
14323       }
14324 
14325       if (!strcasecmp(privacy, "full")) {
14326          if (!strcasecmp(screen, "yes"))
14327             callingpres = AST_PRES_PROHIB_USER_NUMBER_PASSED_SCREEN;
14328          else if (!strcasecmp(screen, "no"))
14329             callingpres = AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED;
14330       } else {
14331          if (!strcasecmp(screen, "yes"))
14332             callingpres = AST_PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN;
14333          else if (!strcasecmp(screen, "no"))
14334             callingpres = AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
14335       }
14336    }
14337 
14338    /* Only return true if the supplied caller id is different */
14339    if (!strcasecmp(p->cid_num, cid_num) && !strcasecmp(p->cid_name, cid_name) && p->callingpres == callingpres)
14340       return 0;
14341 
14342    ast_string_field_set(p, cid_num, cid_num);
14343    ast_string_field_set(p, cid_name, cid_name);
14344    p->callingpres = callingpres;
14345 
14346    if (p->owner) {
14347       ast_set_callerid(p->owner, cid_num, cid_name, NULL);
14348       p->owner->caller.id.name.presentation = callingpres;
14349       p->owner->caller.id.number.presentation = callingpres;
14350    }
14351 
14352    return 1;
14353 }
14354 
14355 /*! \brief Get referring dnis */
14356 static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq, char **name, char **number, int *reason)
14357 {
14358    char tmp[256], *exten, *rexten, *rdomain, *rname = NULL;
14359    char *params, *reason_param = NULL;
14360    struct sip_request *req;
14361 
14362    req = oreq ? oreq : &p->initreq;
14363 
14364    ast_copy_string(tmp, get_header(req, "Diversion"), sizeof(tmp));
14365    if (ast_strlen_zero(tmp))
14366       return -1;
14367 
14368    if ((params = strchr(tmp, '>'))) {
14369       params = strchr(params, ';');
14370    }
14371 
14372    exten = get_in_brackets(tmp);
14373    if (!strncasecmp(exten, "sip:", 4)) {
14374       exten += 4;
14375    } else if (!strncasecmp(exten, "sips:", 5)) {
14376       exten += 5;
14377    } else {
14378       ast_log(LOG_WARNING, "Huh?  Not an RDNIS SIP header (%s)?\n", exten);
14379       return -1;
14380    }
14381 
14382    /* Get diversion-reason param if present */
14383    if (params) {
14384       *params = '\0';   /* Cut off parameters  */
14385       params++;
14386       while (*params == ';' || *params == ' ')
14387          params++;
14388       /* Check if we have a reason parameter */
14389       if ((reason_param = strcasestr(params, "reason="))) {
14390          char *end;
14391          reason_param+=7;
14392          if ((end = strchr(reason_param, ';'))) {
14393             *end = '\0';
14394          }
14395          /* Remove enclosing double-quotes */
14396          if (*reason_param == '"')
14397             ast_strip_quoted(reason_param, "\"", "\"");
14398          if (!ast_strlen_zero(reason_param)) {
14399             sip_set_redirstr(p, reason_param);
14400             if (p->owner) {
14401                pbx_builtin_setvar_helper(p->owner, "__PRIREDIRECTREASON", p->redircause);
14402                pbx_builtin_setvar_helper(p->owner, "__SIPREDIRECTREASON", reason_param);
14403             }
14404          }
14405       }
14406    }
14407 
14408    rdomain = exten;
14409    rexten = strsep(&rdomain, "@");  /* trim anything after @ */
14410    if (p->owner)
14411       pbx_builtin_setvar_helper(p->owner, "__SIPRDNISDOMAIN", rdomain);
14412 
14413    if (sip_debug_test_pvt(p))
14414       ast_verbose("RDNIS for this call is %s (reason %s)\n", exten, reason ? reason_param : "");
14415 
14416    /*ast_string_field_set(p, rdnis, rexten);*/
14417 
14418    if (*tmp == '\"') {
14419       char *end_quote;
14420       rname = tmp + 1;
14421       end_quote = strchr(rname, '\"');
14422       *end_quote = '\0';
14423    }
14424 
14425    if (number) {
14426       *number = ast_strdup(rexten);
14427    }
14428 
14429    if (name && rname) {
14430       *name = ast_strdup(rname);
14431    }
14432 
14433    if (reason && !ast_strlen_zero(reason_param)) {
14434       *reason = sip_reason_str_to_code(reason_param);
14435    }
14436 
14437    return 0;
14438 }
14439 
14440 /*! \brief Find out who the call is for.
14441    We use the request uri as a destination.
14442    This code assumes authentication has been done, so that the
14443    device (peer/user) context is already set.
14444    \return 0 on success (found a matching extension), non-zero on failure
14445 
14446   \note If the incoming uri is a SIPS: uri, we are required to carry this across
14447    the dialplan, so that the outbound call also is a sips: call or encrypted
14448    IAX2 call. If that's not available, the call should FAIL.
14449 */
14450 static enum sip_get_dest_result get_destination(struct sip_pvt *p, struct sip_request *oreq, int *cc_recall_core_id)
14451 {
14452    char tmp[256] = "", *uri, *domain, *dummy = NULL;
14453    char tmpf[256] = "", *from = NULL;
14454    struct sip_request *req;
14455    char *decoded_uri;
14456 
14457    req = oreq;
14458    if (!req) {
14459       req = &p->initreq;
14460    }
14461 
14462    /* Find the request URI */
14463    if (req->rlPart2)
14464       ast_copy_string(tmp, REQ_OFFSET_TO_STR(req, rlPart2), sizeof(tmp));
14465    
14466    uri = ast_strdupa(get_in_brackets(tmp));
14467 
14468    if (parse_uri(uri, "sip:,sips:", &uri, &dummy, &domain, NULL)) {
14469       ast_log(LOG_WARNING, "Not a SIP header (%s)?\n", uri);
14470       return SIP_GET_DEST_INVALID_URI;
14471    }
14472 
14473    SIP_PEDANTIC_DECODE(domain);
14474    SIP_PEDANTIC_DECODE(uri);
14475 
14476    ast_string_field_set(p, domain, domain);
14477 
14478    /* Now find the From: caller ID and name */
14479    /* XXX Why is this done in get_destination? Isn't it already done?
14480       Needs to be checked
14481         */
14482    ast_copy_string(tmpf, get_header(req, "From"), sizeof(tmpf));
14483    if (!ast_strlen_zero(tmpf)) {
14484       from = get_in_brackets(tmpf);
14485       if (parse_uri(from, "sip:,sips:", &from, NULL, &domain, NULL)) {
14486          ast_log(LOG_WARNING, "Not a SIP header (%s)?\n", from);
14487          return SIP_GET_DEST_INVALID_URI;
14488       }
14489 
14490       SIP_PEDANTIC_DECODE(from);
14491       SIP_PEDANTIC_DECODE(domain);
14492 
14493       ast_string_field_set(p, fromdomain, domain);
14494    }
14495 
14496    if (!AST_LIST_EMPTY(&domain_list)) {
14497       char domain_context[AST_MAX_EXTENSION];
14498 
14499       domain_context[0] = '\0';
14500       if (!check_sip_domain(p->domain, domain_context, sizeof(domain_context))) {
14501          if (!sip_cfg.allow_external_domains && (req->method == SIP_INVITE || req->method == SIP_REFER)) {
14502             ast_debug(1, "Got SIP %s to non-local domain '%s'; refusing request.\n", sip_methods[req->method].text, p->domain);
14503             return SIP_GET_DEST_REFUSED;
14504          }
14505       }
14506       /* If we don't have a peer (i.e. we're a guest call),
14507        * overwrite the original context */
14508       if (!ast_test_flag(&p->flags[1], SIP_PAGE2_HAVEPEERCONTEXT) && !ast_strlen_zero(domain_context)) {
14509          ast_string_field_set(p, context, domain_context);
14510       }
14511    }
14512 
14513    /* If the request coming in is a subscription and subscribecontext has been specified use it */
14514    if (req->method == SIP_SUBSCRIBE && !ast_strlen_zero(p->subscribecontext)) {
14515       ast_string_field_set(p, context, p->subscribecontext);
14516    }
14517 
14518    if (sip_debug_test_pvt(p)) {
14519       ast_verbose("Looking for %s in %s (domain %s)\n", uri, p->context, p->domain);
14520    }
14521 
14522    /* Since extensions.conf can have unescaped characters, try matching a
14523     * decoded uri in addition to the non-decoded uri. */
14524    decoded_uri = ast_strdupa(uri);
14525    ast_uri_decode(decoded_uri);
14526 
14527    /* If this is a subscription we actually just need to see if a hint exists for the extension */
14528    if (req->method == SIP_SUBSCRIBE) {
14529       char hint[AST_MAX_EXTENSION];
14530       int which = 0;
14531       if (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, p->context, uri) ||
14532           (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, p->context, decoded_uri) && (which = 1))) {
14533          if (!oreq) {
14534             ast_string_field_set(p, exten, which ? decoded_uri : uri);
14535          }
14536          return SIP_GET_DEST_EXTEN_FOUND;
14537       } else {
14538          return SIP_GET_DEST_EXTEN_NOT_FOUND;
14539       }
14540    } else {
14541       struct ast_cc_agent *agent;
14542       int which = 0;
14543       /* Check the dialplan for the username part of the request URI,
14544          the domain will be stored in the SIPDOMAIN variable
14545          Return 0 if we have a matching extension */
14546       if (ast_exists_extension(NULL, p->context, uri, 1, S_OR(p->cid_num, from)) ||
14547           (ast_exists_extension(NULL, p->context, decoded_uri, 1, S_OR(p->cid_num, from)) && (which = 1)) ||
14548           !strcmp(decoded_uri, ast_pickup_ext())) {
14549          if (!oreq) {
14550             ast_string_field_set(p, exten, which ? decoded_uri : uri);
14551          }
14552          return SIP_GET_DEST_EXTEN_FOUND;
14553       } else if ((agent = find_sip_cc_agent_by_notify_uri(tmp))) {
14554          struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
14555          /* This is a CC recall. We can set p's extension to the exten from
14556           * the original INVITE
14557           */
14558          ast_string_field_set(p, exten, agent_pvt->original_exten);
14559          /* And we need to let the CC core know that the caller is attempting
14560           * his recall
14561           */
14562          ast_cc_agent_recalling(agent->core_id, "SIP caller %s is attempting recall",
14563                agent->device_name);
14564          if (cc_recall_core_id) {
14565             *cc_recall_core_id = agent->core_id;
14566          }
14567          ao2_ref(agent, -1);
14568          return SIP_GET_DEST_EXTEN_FOUND;
14569       }
14570    }
14571 
14572    /* Return 1 for pickup extension or overlap dialling support (if we support it) */
14573    if((ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP) &&
14574        ast_canmatch_extension(NULL, p->context, decoded_uri, 1, S_OR(p->cid_num, from))) ||
14575        !strncmp(decoded_uri, ast_pickup_ext(), strlen(decoded_uri))) {
14576       return SIP_GET_DEST_PICKUP_EXTEN_FOUND;
14577    }
14578 
14579    return SIP_GET_DEST_EXTEN_NOT_FOUND;
14580 }
14581 
14582 /*! \brief Lock dialog lock and find matching pvt lock
14583    \return a reference, remember to release it when done
14584 */
14585 static struct sip_pvt *get_sip_pvt_byid_locked(const char *callid, const char *totag, const char *fromtag)
14586 {
14587    struct sip_pvt *sip_pvt_ptr;
14588    struct sip_pvt tmp_dialog = {
14589       .callid = callid,
14590    };
14591 
14592    if (totag) {
14593       ast_debug(4, "Looking for callid %s (fromtag %s totag %s)\n", callid, fromtag ? fromtag : "<no fromtag>", totag ? totag : "<no totag>");
14594    }
14595 
14596    /* Search dialogs and find the match */
14597    
14598    sip_pvt_ptr = ao2_t_find(dialogs, &tmp_dialog, OBJ_POINTER, "ao2_find of dialog in dialogs table");
14599    if (sip_pvt_ptr) {
14600       /* Go ahead and lock it (and its owner) before returning */
14601       sip_pvt_lock(sip_pvt_ptr);
14602       if (sip_cfg.pedanticsipchecking) {
14603          unsigned char frommismatch = 0, tomismatch = 0;
14604 
14605          if (ast_strlen_zero(fromtag)) {
14606             sip_pvt_unlock(sip_pvt_ptr);
14607             ast_debug(4, "Matched %s call for callid=%s - no from tag specified, pedantic check fails\n",
14608                  sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid);
14609             return NULL;
14610          }
14611 
14612          if (ast_strlen_zero(totag)) {
14613             sip_pvt_unlock(sip_pvt_ptr);
14614             ast_debug(4, "Matched %s call for callid=%s - no to tag specified, pedantic check fails\n",
14615                  sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid);
14616             return NULL;
14617          }
14618          /* RFC 3891
14619           * > 3.  User Agent Server Behavior: Receiving a Replaces Header
14620           * > The Replaces header contains information used to match an existing
14621           * > SIP dialog (call-id, to-tag, and from-tag).  Upon receiving an INVITE
14622           * > with a Replaces header, the User Agent (UA) attempts to match this
14623           * > information with a confirmed or early dialog.  The User Agent Server
14624           * > (UAS) matches the to-tag and from-tag parameters as if they were tags
14625           * > present in an incoming request.  In other words, the to-tag parameter
14626           * > is compared to the local tag, and the from-tag parameter is compared
14627           * > to the remote tag.
14628           *
14629           * Thus, the totag is always compared to the local tag, regardless if
14630           * this our call is an incoming or outgoing call.
14631           */
14632          frommismatch = !!strcmp(fromtag, sip_pvt_ptr->theirtag);
14633          tomismatch = !!strcmp(totag, sip_pvt_ptr->tag);
14634 
14635          if (frommismatch || tomismatch) {
14636             sip_pvt_unlock(sip_pvt_ptr);
14637             if (frommismatch) {
14638                ast_debug(4, "Matched %s call for callid=%s - pedantic from tag check fails; their tag is %s our tag is %s\n",
14639                     sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid,
14640                     fromtag, sip_pvt_ptr->theirtag);
14641             }
14642             if (tomismatch) {
14643                ast_debug(4, "Matched %s call for callid=%s - pedantic to tag check fails; their tag is %s our tag is %s\n",
14644                     sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid,
14645                     totag, sip_pvt_ptr->tag);
14646             }
14647             return NULL;
14648          }
14649       }
14650       
14651       if (totag)
14652          ast_debug(4, "Matched %s call - their tag is %s Our tag is %s\n",
14653                  sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING",
14654                  sip_pvt_ptr->theirtag, sip_pvt_ptr->tag);
14655 
14656       /* deadlock avoidance... */
14657       while (sip_pvt_ptr->owner && ast_channel_trylock(sip_pvt_ptr->owner)) {
14658          sip_pvt_unlock(sip_pvt_ptr);
14659          usleep(1);
14660          sip_pvt_lock(sip_pvt_ptr);
14661       }
14662    }
14663    
14664    return sip_pvt_ptr;
14665 }
14666 
14667 /*! \brief Call transfer support (the REFER method)
14668  *    Extracts Refer headers into pvt dialog structure
14669  *
14670  * \note If we get a SIPS uri in the refer-to header, we're required to set up a secure signalling path
14671  * to that extension. As a minimum, this needs to be added to a channel variable, if not a channel
14672  * flag.
14673  */
14674 static int get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req)
14675 {
14676 
14677    const char *p_referred_by = NULL;
14678    char *h_refer_to = NULL;
14679    char *h_referred_by = NULL;
14680    char *refer_to;
14681    const char *p_refer_to;
14682    char *referred_by_uri = NULL;
14683    char *ptr;
14684    struct sip_request *req = NULL;
14685    const char *transfer_context = NULL;
14686    struct sip_refer *referdata;
14687 
14688 
14689    req = outgoing_req;
14690    referdata = transferer->refer;
14691 
14692    if (!req) {
14693       req = &transferer->initreq;
14694    }
14695 
14696    p_refer_to = get_header(req, "Refer-To");
14697    if (ast_strlen_zero(p_refer_to)) {
14698       ast_log(LOG_WARNING, "Refer-To Header missing. Skipping transfer.\n");
14699       return -2;  /* Syntax error */
14700    }
14701    h_refer_to = ast_strdupa(p_refer_to);
14702    refer_to = get_in_brackets(h_refer_to);
14703    if (!strncasecmp(refer_to, "sip:", 4)) {
14704       refer_to += 4;       /* Skip sip: */
14705    } else if (!strncasecmp(refer_to, "sips:", 5)) {
14706       refer_to += 5;
14707    } else {
14708       ast_log(LOG_WARNING, "Can't transfer to non-sip: URI.  (Refer-to: %s)?\n", refer_to);
14709       return -3;
14710    }
14711 
14712    /* Get referred by header if it exists */
14713    p_referred_by = get_header(req, "Referred-By");
14714 
14715    /* Give useful transfer information to the dialplan */
14716    if (transferer->owner) {
14717       struct ast_channel *peer = ast_bridged_channel(transferer->owner);
14718       if (peer) {
14719          pbx_builtin_setvar_helper(peer, "SIPREFERRINGCONTEXT", transferer->context);
14720          pbx_builtin_setvar_helper(peer, "SIPREFERREDBYHDR", p_referred_by);
14721       }
14722    }
14723 
14724    if (!ast_strlen_zero(p_referred_by)) {
14725       char *lessthan;
14726       h_referred_by = ast_strdupa(p_referred_by);
14727 
14728       /* Store referrer's caller ID name */
14729       ast_copy_string(referdata->referred_by_name, h_referred_by, sizeof(referdata->referred_by_name));
14730       if ((lessthan = strchr(referdata->referred_by_name, '<'))) {
14731          *(lessthan - 1) = '\0'; /* Space */
14732       }
14733 
14734       referred_by_uri = get_in_brackets(h_referred_by);
14735 
14736       if (!strncasecmp(referred_by_uri, "sip:", 4)) {
14737          referred_by_uri += 4;      /* Skip sip: */
14738       } else if (!strncasecmp(referred_by_uri, "sips:", 5)) {
14739          referred_by_uri += 5;      /* Skip sips: */
14740       } else {
14741          ast_log(LOG_WARNING, "Huh?  Not a sip: header (Referred-by: %s). Skipping.\n", referred_by_uri);
14742          referred_by_uri = NULL;
14743       }
14744    }
14745 
14746    /* Check for arguments in the refer_to header */
14747    if ((ptr = strcasestr(refer_to, "replaces="))) {
14748       char *to = NULL, *from = NULL;
14749       
14750       /* This is an attended transfer */
14751       referdata->attendedtransfer = 1;
14752       ast_copy_string(referdata->replaces_callid, ptr+9, sizeof(referdata->replaces_callid));
14753       ast_uri_decode(referdata->replaces_callid);
14754       if ((ptr = strchr(referdata->replaces_callid, ';')))  /* Find options */ {
14755          *ptr++ = '\0';
14756       }
14757       
14758       if (ptr) {
14759          /* Find the different tags before we destroy the string */
14760          to = strcasestr(ptr, "to-tag=");
14761          from = strcasestr(ptr, "from-tag=");
14762       }
14763       
14764       /* Grab the to header */
14765       if (to) {
14766          ptr = to + 7;
14767          if ((to = strchr(ptr, '&'))) {
14768             *to = '\0';
14769          }
14770          if ((to = strchr(ptr, ';'))) {
14771             *to = '\0';
14772          }
14773          ast_copy_string(referdata->replaces_callid_totag, ptr, sizeof(referdata->replaces_callid_totag));
14774       }
14775       
14776       if (from) {
14777          ptr = from + 9;
14778          if ((to = strchr(ptr, '&'))) {
14779             *to = '\0';
14780          }
14781          if ((to = strchr(ptr, ';'))) {
14782             *to = '\0';
14783          }
14784          ast_copy_string(referdata->replaces_callid_fromtag, ptr, sizeof(referdata->replaces_callid_fromtag));
14785       }
14786       
14787       if (!sip_cfg.pedanticsipchecking) {
14788          ast_debug(2, "Attended transfer: Will use Replace-Call-ID : %s (No check of from/to tags)\n", referdata->replaces_callid );
14789       } else {
14790          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>" );
14791       }
14792    }
14793    
14794    if ((ptr = strchr(refer_to, '@'))) {   /* Separate domain */
14795       char *urioption = NULL, *domain;
14796       int bracket = 0;
14797       *ptr++ = '\0';
14798 
14799       if ((urioption = strchr(ptr, ';'))) { /* Separate urioptions */
14800          *urioption++ = '\0';
14801       }
14802 
14803       domain = ptr;
14804 
14805       /* Remove :port */
14806       for (; *ptr != '\0'; ++ptr) {
14807          if (*ptr == ':' && bracket == 0) {
14808             *ptr = '\0';
14809             break;
14810          } else if (*ptr == '[') {
14811             ++bracket;
14812          } else if (*ptr == ']') {
14813             --bracket;
14814          }
14815       }
14816 
14817       SIP_PEDANTIC_DECODE(domain);
14818       SIP_PEDANTIC_DECODE(urioption);
14819 
14820       /* Save the domain for the dial plan */
14821       ast_copy_string(referdata->refer_to_domain, domain, sizeof(referdata->refer_to_domain));
14822       if (urioption) {
14823          ast_copy_string(referdata->refer_to_urioption, urioption, sizeof(referdata->refer_to_urioption));
14824       }
14825    }
14826 
14827    if ((ptr = strchr(refer_to, ';')))  /* Remove options */
14828       *ptr = '\0';
14829 
14830    SIP_PEDANTIC_DECODE(refer_to);
14831    ast_copy_string(referdata->refer_to, refer_to, sizeof(referdata->refer_to));
14832    
14833    if (referred_by_uri) {
14834       if ((ptr = strchr(referred_by_uri, ';')))    /* Remove options */
14835          *ptr = '\0';
14836       SIP_PEDANTIC_DECODE(referred_by_uri);
14837       ast_copy_string(referdata->referred_by, referred_by_uri, sizeof(referdata->referred_by));
14838    } else {
14839       referdata->referred_by[0] = '\0';
14840    }
14841 
14842    /* Determine transfer context */
14843    if (transferer->owner)  /* Mimic behaviour in res_features.c */
14844       transfer_context = pbx_builtin_getvar_helper(transferer->owner, "TRANSFER_CONTEXT");
14845 
14846    /* By default, use the context in the channel sending the REFER */
14847    if (ast_strlen_zero(transfer_context)) {
14848       transfer_context = S_OR(transferer->owner->macrocontext,
14849                S_OR(transferer->context, sip_cfg.default_context));
14850    }
14851 
14852    ast_copy_string(referdata->refer_to_context, transfer_context, sizeof(referdata->refer_to_context));
14853    
14854    /* Either an existing extension or the parking extension */
14855    if (referdata->attendedtransfer || ast_exists_extension(NULL, transfer_context, refer_to, 1, NULL) ) {
14856       if (sip_debug_test_pvt(transferer)) {
14857          ast_verbose("SIP transfer to extension %s@%s by %s\n", refer_to, transfer_context, referred_by_uri);
14858       }
14859       /* We are ready to transfer to the extension */
14860       return 0;
14861    }
14862    if (sip_debug_test_pvt(transferer))
14863       ast_verbose("Failed SIP Transfer to non-existing extension %s in context %s\n n", refer_to, transfer_context);
14864 
14865    /* Failure, we can't find this extension */
14866    return -1;
14867 }
14868 
14869 
14870 /*! \brief Call transfer support (old way, deprecated by the IETF)
14871  * \note does not account for SIPS: uri requirements, nor check transport
14872  */
14873 static int get_also_info(struct sip_pvt *p, struct sip_request *oreq)
14874 {
14875    char tmp[256] = "", *c, *a;
14876    struct sip_request *req = oreq ? oreq : &p->initreq;
14877    struct sip_refer *referdata = NULL;
14878    const char *transfer_context = NULL;
14879    
14880    if (!p->refer && !sip_refer_allocate(p))
14881       return -1;
14882 
14883    referdata = p->refer;
14884 
14885    ast_copy_string(tmp, get_header(req, "Also"), sizeof(tmp));
14886    c = get_in_brackets(tmp);
14887 
14888    if (parse_uri(c, "sip:,sips:", &c, NULL, &a, NULL)) {
14889       ast_log(LOG_WARNING, "Huh?  Not a SIP header in Also: transfer (%s)?\n", c);
14890       return -1;
14891    }
14892    
14893    SIP_PEDANTIC_DECODE(c);
14894    SIP_PEDANTIC_DECODE(a);
14895 
14896    if (!ast_strlen_zero(a)) {
14897       ast_copy_string(referdata->refer_to_domain, a, sizeof(referdata->refer_to_domain));
14898    }
14899 
14900    if (sip_debug_test_pvt(p))
14901       ast_verbose("Looking for %s in %s\n", c, p->context);
14902 
14903    if (p->owner)  /* Mimic behaviour in res_features.c */
14904       transfer_context = pbx_builtin_getvar_helper(p->owner, "TRANSFER_CONTEXT");
14905 
14906    /* By default, use the context in the channel sending the REFER */
14907    if (ast_strlen_zero(transfer_context)) {
14908       transfer_context = S_OR(p->owner->macrocontext,
14909                S_OR(p->context, sip_cfg.default_context));
14910    }
14911    if (ast_exists_extension(NULL, transfer_context, c, 1, NULL)) {
14912       /* This is a blind transfer */
14913       ast_debug(1, "SIP Bye-also transfer to Extension %s@%s \n", c, transfer_context);
14914       ast_copy_string(referdata->refer_to, c, sizeof(referdata->refer_to));
14915       ast_copy_string(referdata->referred_by, "", sizeof(referdata->referred_by));
14916       ast_copy_string(referdata->refer_contact, "", sizeof(referdata->refer_contact));
14917       referdata->refer_call = dialog_unref(referdata->refer_call, "unreffing referdata->refer_call");
14918       /* Set new context */
14919       ast_string_field_set(p, context, transfer_context);
14920       return 0;
14921    } else if (ast_canmatch_extension(NULL, p->context, c, 1, NULL)) {
14922       return 1;
14923    }
14924 
14925    return -1;
14926 }
14927 
14928 /*! \brief check received= and rport= in a SIP response.
14929  * If we get a response with received= and/or rport= in the Via:
14930  * line, use them as 'p->ourip' (see RFC 3581 for rport,
14931  * and RFC 3261 for received).
14932  * Using these two fields SIP can produce the correct
14933  * address and port in the SIP headers without the need for STUN.
14934  * The address part is also reused for the media sessions.
14935  * Note that ast_sip_ouraddrfor() still rewrites p->ourip
14936  * if you specify externaddr/seternaddr/.
14937  */
14938 static attribute_unused void check_via_response(struct sip_pvt *p, struct sip_request *req)
14939 {
14940    char via[256];
14941    char *cur, *opts;
14942 
14943    ast_copy_string(via, get_header(req, "Via"), sizeof(via));
14944 
14945    /* Work on the leftmost value of the topmost Via header */
14946    opts = strchr(via, ',');
14947    if (opts)
14948       *opts = '\0';
14949 
14950    /* parse all relevant options */
14951    opts = strchr(via, ';');
14952    if (!opts)
14953       return;  /* no options to parse */
14954    *opts++ = '\0';
14955    while ( (cur = strsep(&opts, ";")) ) {
14956       if (!strncmp(cur, "rport=", 6)) {
14957          int port = strtol(cur+6, NULL, 10);
14958          /* XXX add error checking */
14959          ast_sockaddr_set_port(&p->ourip, port);
14960       } else if (!strncmp(cur, "received=", 9)) {
14961          if (ast_parse_arg(cur + 9, PARSE_ADDR, &p->ourip))
14962             ;  /* XXX add error checking */
14963       }
14964    }
14965 }
14966 
14967 /*! \brief check Via: header for hostname, port and rport request/answer */
14968 static void check_via(struct sip_pvt *p, struct sip_request *req)
14969 {
14970    char via[512];
14971    char *c, *maddr;
14972    struct ast_sockaddr tmp;
14973    uint16_t port;
14974 
14975    ast_copy_string(via, get_header(req, "Via"), sizeof(via));
14976 
14977    /* Work on the leftmost value of the topmost Via header */
14978    c = strchr(via, ',');
14979    if (c)
14980       *c = '\0';
14981 
14982    /* Check for rport */
14983    c = strstr(via, ";rport");
14984    if (c && (c[6] != '=')) { /* rport query, not answer */
14985       ast_set_flag(&p->flags[1], SIP_PAGE2_RPORT_PRESENT);
14986       ast_set_flag(&p->flags[0], SIP_NAT_RPORT_PRESENT);
14987    }
14988 
14989    /* Check for maddr */
14990    maddr = strstr(via, "maddr=");
14991    if (maddr) {
14992       maddr += 6;
14993       c = maddr + strspn(maddr, "abcdefghijklmnopqrstuvwxyz"
14994                       "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-.:[]");
14995       *c = '\0';
14996    }
14997 
14998    c = strchr(via, ';');
14999    if (c)
15000       *c = '\0';
15001 
15002    c = strchr(via, ' ');
15003    if (c) {
15004       *c = '\0';
15005       c = ast_skip_blanks(c+1);
15006       if (strcasecmp(via, "SIP/2.0/UDP") && strcasecmp(via, "SIP/2.0/TCP") && strcasecmp(via, "SIP/2.0/TLS")) {
15007          ast_log(LOG_WARNING, "Don't know how to respond via '%s'\n", via);
15008          return;
15009       }
15010 
15011       if (maddr && ast_sockaddr_resolve_first(&p->sa, maddr, 0)) {
15012          p->sa = p->recv;
15013       }
15014 
15015       ast_sockaddr_resolve_first(&tmp, c, 0);
15016       port = ast_sockaddr_port(&tmp);
15017       ast_sockaddr_set_port(&p->sa,
15018                   port != 0 ? port : STANDARD_SIP_PORT);
15019 
15020       if (sip_debug_test_pvt(p)) {
15021          ast_verbose("Sending to %s (%s)\n",
15022                 ast_sockaddr_stringify(sip_real_dst(p)),
15023                 sip_nat_mode(p));
15024       }
15025    }
15026 }
15027 
15028 /*! \brief Validate device authentication */
15029 static enum check_auth_result check_peer_ok(struct sip_pvt *p, char *of,
15030    struct sip_request *req, int sipmethod, struct ast_sockaddr *addr,
15031    struct sip_peer **authpeer,
15032    enum xmittype reliable, char *calleridname, char *uri2)
15033 {
15034    enum check_auth_result res;
15035    int debug = sip_debug_test_addr(addr);
15036    struct sip_peer *peer;
15037 
15038    if (sipmethod == SIP_SUBSCRIBE) {
15039       /* For subscribes, match on device name only; for other methods,
15040       * match on IP address-port of the incoming request.
15041       */
15042       peer = find_peer(of, NULL, TRUE, FINDALLDEVICES, FALSE, 0);
15043    } else {
15044       /* First find devices based on username (avoid all type=peer's) */
15045       peer = find_peer(of, NULL, TRUE, FINDUSERS, FALSE, 0);
15046 
15047       /* Then find devices based on IP */
15048       if (!peer) {
15049          peer = find_peer(NULL, &p->recv, TRUE, FINDPEERS, FALSE, p->socket.type);
15050       }
15051    }
15052 
15053    if (!peer) {
15054       if (debug) {
15055          ast_verbose("No matching peer for '%s' from '%s'\n",
15056             of, ast_sockaddr_stringify(&p->recv));
15057       }
15058       return AUTH_DONT_KNOW;
15059    }
15060 
15061    if (!ast_apply_ha(peer->ha, addr)) {
15062       ast_debug(2, "Found peer '%s' for '%s', but fails host access\n", peer->name, of);
15063       unref_peer(peer, "unref_peer: check_peer_ok: from find_peer call, early return of AUTH_ACL_FAILED");
15064       return AUTH_ACL_FAILED;
15065    }
15066    if (debug)
15067       ast_verbose("Found peer '%s' for '%s' from %s\n",
15068          peer->name, of, ast_sockaddr_stringify(&p->recv));
15069 
15070    /* XXX what about p->prefs = peer->prefs; ? */
15071    /* Set Frame packetization */
15072    if (p->rtp) {
15073       ast_rtp_codecs_packetization_set(ast_rtp_instance_get_codecs(p->rtp), p->rtp, &peer->prefs);
15074       p->autoframing = peer->autoframing;
15075    }
15076 
15077    /* Take the peer */
15078    ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
15079    ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
15080    ast_copy_flags(&p->flags[2], &peer->flags[2], SIP_PAGE3_FLAGS_TO_COPY);
15081 
15082    if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) && p->udptl) {
15083       p->t38_maxdatagram = peer->t38_maxdatagram;
15084       set_t38_capabilities(p);
15085    }
15086 
15087    /* Copy SIP extensions profile to peer */
15088    /* XXX is this correct before a successful auth ? */
15089    if (p->sipoptions)
15090       peer->sipoptions = p->sipoptions;
15091 
15092    do_setnat(p);
15093 
15094    ast_string_field_set(p, peersecret, peer->secret);
15095    ast_string_field_set(p, peermd5secret, peer->md5secret);
15096    ast_string_field_set(p, subscribecontext, peer->subscribecontext);
15097    ast_string_field_set(p, mohinterpret, peer->mohinterpret);
15098    ast_string_field_set(p, mohsuggest, peer->mohsuggest);
15099    if (!ast_strlen_zero(peer->parkinglot)) {
15100       ast_string_field_set(p, parkinglot, peer->parkinglot);
15101    }
15102    ast_string_field_set(p, engine, peer->engine);
15103    p->disallowed_methods = peer->disallowed_methods;
15104    set_pvt_allowed_methods(p, req);
15105    ast_cc_copy_config_params(p->cc_params, peer->cc_params);
15106    if (peer->callingpres)  /* Peer calling pres setting will override RPID */
15107       p->callingpres = peer->callingpres;
15108    if (peer->maxms && peer->lastms)
15109       p->timer_t1 = peer->lastms < global_t1min ? global_t1min : peer->lastms;
15110    else
15111       p->timer_t1 = peer->timer_t1;
15112 
15113    /* Set timer B to control transaction timeouts */
15114    if (peer->timer_b)
15115       p->timer_b = peer->timer_b;
15116    else
15117       p->timer_b = 64 * p->timer_t1;
15118 
15119    if (ast_test_flag(&peer->flags[0], SIP_INSECURE_INVITE)) {
15120       /* Pretend there is no required authentication */
15121       ast_string_field_set(p, peersecret, NULL);
15122       ast_string_field_set(p, peermd5secret, NULL);
15123    }
15124    if (!(res = check_auth(p, req, peer->name, p->peersecret, p->peermd5secret, sipmethod, uri2, reliable, req->ignore))) {
15125       ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
15126       ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
15127       ast_copy_flags(&p->flags[2], &peer->flags[2], SIP_PAGE3_FLAGS_TO_COPY);
15128       /* If we have a call limit, set flag */
15129       if (peer->call_limit)
15130          ast_set_flag(&p->flags[0], SIP_CALL_LIMIT);
15131       ast_string_field_set(p, peername, peer->name);
15132       ast_string_field_set(p, authname, peer->name);
15133 
15134       if (sipmethod == SIP_INVITE) {
15135          /* copy channel vars */
15136          p->chanvars = copy_vars(peer->chanvars);
15137       }
15138 
15139       if (authpeer) {
15140          ao2_t_ref(peer, 1, "copy pointer into (*authpeer)");
15141          (*authpeer) = peer;  /* Add a ref to the object here, to keep it in memory a bit longer if it is realtime */
15142       }
15143 
15144       if (!ast_strlen_zero(peer->username)) {
15145          ast_string_field_set(p, username, peer->username);
15146          /* Use the default username for authentication on outbound calls */
15147          /* XXX this takes the name from the caller... can we override ? */
15148          ast_string_field_set(p, authname, peer->username);
15149       }
15150       if (!get_rpid(p, req)) {
15151          if (!ast_strlen_zero(peer->cid_num)) {
15152             char *tmp = ast_strdupa(peer->cid_num);
15153             if (global_shrinkcallerid && ast_is_shrinkable_phonenumber(tmp))
15154                ast_shrink_phone_number(tmp);
15155             ast_string_field_set(p, cid_num, tmp);
15156          }
15157          if (!ast_strlen_zero(peer->cid_name))
15158             ast_string_field_set(p, cid_name, peer->cid_name);
15159          if (!ast_strlen_zero(peer->cid_tag))
15160             ast_string_field_set(p, cid_tag, peer->cid_tag);
15161          if (peer->callingpres)
15162             p->callingpres = peer->callingpres;
15163       }
15164       ast_string_field_set(p, fullcontact, peer->fullcontact);
15165       if (!ast_strlen_zero(peer->context))
15166          ast_string_field_set(p, context, peer->context);
15167       ast_string_field_set(p, peersecret, peer->secret);
15168       ast_string_field_set(p, peermd5secret, peer->md5secret);
15169       ast_string_field_set(p, language, peer->language);
15170       ast_string_field_set(p, accountcode, peer->accountcode);
15171       p->amaflags = peer->amaflags;
15172       p->callgroup = peer->callgroup;
15173       p->pickupgroup = peer->pickupgroup;
15174       p->capability = peer->capability;
15175       p->prefs = peer->prefs;
15176       p->jointcapability = peer->capability;
15177       if (peer->maxforwards > 0) {
15178          p->maxforwards = peer->maxforwards;
15179       }
15180       if (p->peercapability)
15181          p->jointcapability &= p->peercapability;
15182       p->maxcallbitrate = peer->maxcallbitrate;
15183       if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
15184           (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
15185          p->noncodeccapability |= AST_RTP_DTMF;
15186       else
15187          p->noncodeccapability &= ~AST_RTP_DTMF;
15188       p->jointnoncodeccapability = p->noncodeccapability;
15189       if (!dialog_initialize_rtp(p)) {
15190          if (p->rtp) {
15191             ast_rtp_codecs_packetization_set(ast_rtp_instance_get_codecs(p->rtp), p->rtp, &peer->prefs);
15192             p->autoframing = peer->autoframing;
15193          }
15194       } else {
15195          res = AUTH_RTP_FAILED;
15196       }
15197    }
15198    unref_peer(peer, "check_peer_ok: unref_peer: tossing temp ptr to peer from find_peer");
15199    return res;
15200 }
15201 
15202 
15203 /*! \brief  Check if matching user or peer is defined
15204    Match user on From: user name and peer on IP/port
15205    This is used on first invite (not re-invites) and subscribe requests
15206     \return 0 on success, non-zero on failure
15207 */
15208 static enum check_auth_result check_user_full(struct sip_pvt *p, struct sip_request *req,
15209                      int sipmethod, const char *uri, enum xmittype reliable,
15210                      struct ast_sockaddr *addr, struct sip_peer **authpeer)
15211 {
15212    char from[256] = { 0, };
15213    char *dummy = NULL;  /* dummy return value for parse_uri */
15214    char *domain = NULL; /* dummy return value for parse_uri */
15215    char *of;
15216    enum check_auth_result res = AUTH_DONT_KNOW;
15217    char calleridname[50];
15218    char *uri2 = ast_strdupa(uri);
15219 
15220    terminate_uri(uri2); /* trim extra stuff */
15221 
15222    ast_copy_string(from, get_header(req, "From"), sizeof(from));
15223    /* XXX here tries to map the username for invite things */
15224    memset(calleridname, 0, sizeof(calleridname));
15225 
15226    /* strip the display-name portion off the beginning of the FROM header. */
15227    if (!(of = (char *) get_calleridname(from, calleridname, sizeof(calleridname)))) {
15228       ast_log(LOG_ERROR, "FROM header can not be parsed \n");
15229       return res;
15230    }
15231 
15232    if (calleridname[0])
15233       ast_string_field_set(p, cid_name, calleridname);
15234 
15235    if (ast_strlen_zero(p->exten)) {
15236       char *t = uri2;
15237       if (!strncasecmp(t, "sip:", 4))
15238          t+= 4;
15239       else if (!strncasecmp(t, "sips:", 5))
15240          t += 5;
15241       ast_string_field_set(p, exten, t);
15242       t = strchr(p->exten, '@');
15243       if (t)
15244          *t = '\0';
15245 
15246       if (ast_strlen_zero(p->our_contact))
15247          build_contact(p);
15248    }
15249 
15250    of = get_in_brackets(of);
15251 
15252    /* save the URI part of the From header */
15253    ast_string_field_set(p, from, of);
15254 
15255    /* ignore all fields but name */
15256    if (parse_uri(of, "sip:,sips:", &of, &dummy, &domain, NULL)) {
15257       ast_log(LOG_NOTICE, "From address missing 'sip:', using it anyway\n");
15258    }
15259 
15260    SIP_PEDANTIC_DECODE(of);
15261    SIP_PEDANTIC_DECODE(domain);
15262 
15263    if (ast_strlen_zero(of)) {
15264       /* XXX note: the original code considered a missing @host
15265        * as a username-only URI. The SIP RFC (19.1.1) says that
15266        * this is wrong, and it should be considered as a domain-only URI.
15267        * For backward compatibility, we keep this block, but it is
15268        * really a mistake and should go away.
15269        */
15270       of = domain;
15271    } else {
15272       char *tmp = ast_strdupa(of);
15273       /* We need to be able to handle auth-headers looking like
15274          <sip:8164444422;phone-context=+1@1.2.3.4:5060;user=phone;tag=SDadkoa01-gK0c3bdb43>
15275       */
15276       tmp = strsep(&tmp, ";");
15277       if (global_shrinkcallerid && ast_is_shrinkable_phonenumber(tmp))
15278          ast_shrink_phone_number(tmp);
15279       ast_string_field_set(p, cid_num, tmp);
15280    }
15281 
15282    if (global_match_auth_username) {
15283       /*
15284        * XXX This is experimental code to grab the search key from the
15285        * Auth header's username instead of the 'From' name, if available.
15286        * Do not enable this block unless you understand the side effects (if any!)
15287        * Note, the search for "username" should be done in a more robust way.
15288        * Note2, at the moment we check both fields, though maybe we should
15289        * pick one or another depending on the request ? XXX
15290        */
15291       const char *hdr = get_header(req, "Authorization");
15292       if (ast_strlen_zero(hdr))
15293          hdr = get_header(req, "Proxy-Authorization");
15294 
15295       if ( !ast_strlen_zero(hdr) && (hdr = strstr(hdr, "username=\"")) ) {
15296          ast_copy_string(from, hdr + strlen("username=\""), sizeof(from));
15297          of = from;
15298          of = strsep(&of, "\"");
15299       }
15300    }
15301 
15302    res = check_peer_ok(p, of, req, sipmethod, addr,
15303          authpeer, reliable, calleridname, uri2);
15304    if (res != AUTH_DONT_KNOW)
15305       return res;
15306 
15307    /* Finally, apply the guest policy */
15308    if (sip_cfg.allowguest) {
15309       get_rpid(p, req);
15310       if (!dialog_initialize_rtp(p)) {
15311          res = AUTH_SUCCESSFUL;
15312       } else {
15313          res = AUTH_RTP_FAILED;
15314       }
15315    } else if (sip_cfg.alwaysauthreject)
15316       res = AUTH_FAKE_AUTH; /* reject with fake authorization request */
15317    else
15318       res = AUTH_SECRET_FAILED; /* we don't want any guests, authentication will fail */
15319 
15320 
15321    if (ast_test_flag(&p->flags[1], SIP_PAGE2_RPORT_PRESENT)) {
15322       ast_set_flag(&p->flags[0], SIP_NAT_RPORT_PRESENT);
15323    }
15324 
15325    return res;
15326 }
15327 
15328 /*! \brief  Find user
15329    If we get a match, this will add a reference pointer to the user object in ASTOBJ, that needs to be unreferenced
15330 */
15331 static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, const char *uri, enum xmittype reliable, struct ast_sockaddr *addr)
15332 {
15333    return check_user_full(p, req, sipmethod, uri, reliable, addr, NULL);
15334 }
15335 
15336 /*! \brief  Get text out of a SIP MESSAGE packet */
15337 static int get_msg_text(char *buf, int len, struct sip_request *req, int addnewline)
15338 {
15339    int x;
15340    int y;
15341 
15342    buf[0] = '\0';
15343    /*XXX isn't strlen(buf) going to always be 0? */
15344    y = len - strlen(buf) - 5;
15345    if (y < 0)
15346       y = 0;
15347    for (x = 0; x < req->lines; x++) {
15348       const char *line = REQ_OFFSET_TO_STR(req, line[x]);
15349       strncat(buf, line, y); /* safe */
15350       y -= strlen(line) + 1;
15351       if (y < 0)
15352          y = 0;
15353       if (y != 0 && addnewline)
15354          strcat(buf, "\n"); /* safe */
15355    }
15356    return 0;
15357 }
15358 
15359 
15360 /*! \brief  Receive SIP MESSAGE method messages
15361 \note We only handle messages within current calls currently
15362    Reference: RFC 3428 */
15363 static void receive_message(struct sip_pvt *p, struct sip_request *req)
15364 {
15365    char buf[1400];   
15366    struct ast_frame f;
15367    const char *content_type = get_header(req, "Content-Type");
15368 
15369    if (strncmp(content_type, "text/plain", strlen("text/plain"))) { /* No text/plain attachment */
15370       transmit_response(p, "415 Unsupported Media Type", req); /* Good enough, or? */
15371       if (!p->owner)
15372          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
15373       return;
15374    }
15375 
15376    if (get_msg_text(buf, sizeof(buf), req, FALSE)) {
15377       ast_log(LOG_WARNING, "Unable to retrieve text from %s\n", p->callid);
15378       transmit_response(p, "202 Accepted", req);
15379       if (!p->owner)
15380          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
15381       return;
15382    }
15383 
15384    if (p->owner) {
15385       if (sip_debug_test_pvt(p))
15386          ast_verbose("SIP Text message received: '%s'\n", buf);
15387       memset(&f, 0, sizeof(f));
15388       f.frametype = AST_FRAME_TEXT;
15389       f.subclass.integer = 0;
15390       f.offset = 0;
15391       f.data.ptr = buf;
15392       f.datalen = strlen(buf);
15393       ast_queue_frame(p->owner, &f);
15394       transmit_response(p, "202 Accepted", req); /* We respond 202 accepted, since we relay the message */
15395       return;
15396    }
15397 
15398    /* Message outside of a call, we do not support that */
15399    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);
15400    transmit_response(p, "405 Method Not Allowed", req);
15401    sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
15402    return;
15403 }
15404 
15405 /*! \brief  CLI Command to show calls within limits set by call_limit */
15406 static char *sip_show_inuse(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15407 {
15408 #define FORMAT "%-25.25s %-15.15s %-15.15s \n"
15409 #define FORMAT2 "%-25.25s %-15.15s %-15.15s \n"
15410    char ilimits[40];
15411    char iused[40];
15412    int showall = FALSE;
15413    struct ao2_iterator i;
15414    struct sip_peer *peer;
15415    
15416    switch (cmd) {
15417    case CLI_INIT:
15418       e->command = "sip show inuse";
15419       e->usage =
15420          "Usage: sip show inuse [all]\n"
15421          "       List all SIP devices usage counters and limits.\n"
15422          "       Add option \"all\" to show all devices, not only those with a limit.\n";
15423       return NULL;
15424    case CLI_GENERATE:
15425       return NULL;
15426    }
15427 
15428    if (a->argc < 3)
15429       return CLI_SHOWUSAGE;
15430 
15431    if (a->argc == 4 && !strcmp(a->argv[3], "all"))
15432       showall = TRUE;
15433    
15434    ast_cli(a->fd, FORMAT, "* Peer name", "In use", "Limit");
15435 
15436    i = ao2_iterator_init(peers, 0);
15437    while ((peer = ao2_t_iterator_next(&i, "iterate thru peer table"))) {
15438       ao2_lock(peer);
15439       if (peer->call_limit)
15440          snprintf(ilimits, sizeof(ilimits), "%d", peer->call_limit);
15441       else
15442          ast_copy_string(ilimits, "N/A", sizeof(ilimits));
15443       snprintf(iused, sizeof(iused), "%d/%d/%d", peer->inUse, peer->inRinging, peer->onHold);
15444       if (showall || peer->call_limit)
15445          ast_cli(a->fd, FORMAT2, peer->name, iused, ilimits);
15446       ao2_unlock(peer);
15447       unref_peer(peer, "toss iterator pointer");
15448    }
15449    ao2_iterator_destroy(&i);
15450 
15451    return CLI_SUCCESS;
15452 #undef FORMAT
15453 #undef FORMAT2
15454 }
15455 
15456 
15457 /*! \brief Convert transfer mode to text string */
15458 static char *transfermode2str(enum transfermodes mode)
15459 {
15460    if (mode == TRANSFER_OPENFORALL)
15461       return "open";
15462    else if (mode == TRANSFER_CLOSED)
15463       return "closed";
15464    return "strict";
15465 }
15466 
15467 /*! \brief  Report Peer status in character string
15468  *  \return 0 if peer is unreachable, 1 if peer is online, -1 if unmonitored
15469  */
15470 
15471 
15472 /* Session-Timer Modes */
15473 static const struct _map_x_s stmodes[] = {
15474         { SESSION_TIMER_MODE_ACCEPT,    "Accept"},
15475         { SESSION_TIMER_MODE_ORIGINATE, "Originate"},
15476         { SESSION_TIMER_MODE_REFUSE,    "Refuse"},
15477         { -1,                           NULL},
15478 };
15479 
15480 static const char *stmode2str(enum st_mode m)
15481 {
15482    return map_x_s(stmodes, m, "Unknown");
15483 }
15484 
15485 static enum st_mode str2stmode(const char *s)
15486 {
15487    return map_s_x(stmodes, s, -1);
15488 }
15489 
15490 /* Session-Timer Refreshers */
15491 static const struct _map_x_s strefreshers[] = {
15492         { SESSION_TIMER_REFRESHER_AUTO,     "auto"},
15493         { SESSION_TIMER_REFRESHER_UAC,      "uac"},
15494         { SESSION_TIMER_REFRESHER_UAS,      "uas"},
15495         { -1,                               NULL},
15496 };
15497 
15498 static const char *strefresher2str(enum st_refresher r)
15499 {
15500    return map_x_s(strefreshers, r, "Unknown");
15501 }
15502 
15503 static enum st_refresher str2strefresher(const char *s)
15504 {
15505    return map_s_x(strefreshers, s, -1);
15506 }
15507 
15508 
15509 static int peer_status(struct sip_peer *peer, char *status, int statuslen)
15510 {
15511    int res = 0;
15512    if (peer->maxms) {
15513       if (peer->lastms < 0) {
15514          ast_copy_string(status, "UNREACHABLE", statuslen);
15515       } else if (peer->lastms > peer->maxms) {
15516          snprintf(status, statuslen, "LAGGED (%d ms)", peer->lastms);
15517          res = 1;
15518       } else if (peer->lastms) {
15519          snprintf(status, statuslen, "OK (%d ms)", peer->lastms);
15520          res = 1;
15521       } else {
15522          ast_copy_string(status, "UNKNOWN", statuslen);
15523       }
15524    } else {
15525       ast_copy_string(status, "Unmonitored", statuslen);
15526       /* Checking if port is 0 */
15527       res = -1;
15528    }
15529    return res;
15530 }
15531 
15532 /*! \brief  Show active TCP connections */
15533 static char *sip_show_tcp(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15534 {
15535    struct sip_threadinfo *th;
15536    struct ao2_iterator i;
15537 
15538 #define FORMAT2 "%-47.47s %9.9s %6.6s\n"
15539 #define FORMAT  "%-47.47s %-9.9s %-6.6s\n"
15540 
15541    switch (cmd) {
15542    case CLI_INIT:
15543       e->command = "sip show tcp";
15544       e->usage =
15545          "Usage: sip show tcp\n"
15546          "       Lists all active TCP/TLS sessions.\n";
15547       return NULL;
15548    case CLI_GENERATE:
15549       return NULL;
15550    }
15551 
15552    if (a->argc != 3)
15553       return CLI_SHOWUSAGE;
15554 
15555    ast_cli(a->fd, FORMAT2, "Address", "Transport", "Type");
15556 
15557    i = ao2_iterator_init(threadt, 0);
15558    while ((th = ao2_t_iterator_next(&i, "iterate through tcp threads for 'sip show tcp'"))) {
15559       ast_cli(a->fd, FORMAT,
15560          ast_sockaddr_stringify(&th->tcptls_session->remote_address),
15561          get_transport(th->type),
15562          (th->tcptls_session->client ? "Client" : "Server"));
15563       ao2_t_ref(th, -1, "decrement ref from iterator");
15564    }
15565    ao2_iterator_destroy(&i);
15566 
15567    return CLI_SUCCESS;
15568 #undef FORMAT
15569 #undef FORMAT2
15570 }
15571 
15572 /*! \brief  CLI Command 'SIP Show Users' */
15573 static char *sip_show_users(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15574 {
15575    regex_t regexbuf;
15576    int havepattern = FALSE;
15577    struct ao2_iterator user_iter;
15578    struct sip_peer *user;
15579 
15580 #define FORMAT  "%-25.25s  %-15.15s  %-15.15s  %-15.15s  %-5.5s%-10.10s\n"
15581 
15582    switch (cmd) {
15583    case CLI_INIT:
15584       e->command = "sip show users";
15585       e->usage =
15586          "Usage: sip show users [like <pattern>]\n"
15587          "       Lists all known SIP users.\n"
15588          "       Optional regular expression pattern is used to filter the user list.\n";
15589       return NULL;
15590    case CLI_GENERATE:
15591       return NULL;
15592    }
15593 
15594    switch (a->argc) {
15595    case 5:
15596       if (!strcasecmp(a->argv[3], "like")) {
15597          if (regcomp(&regexbuf, a->argv[4], REG_EXTENDED | REG_NOSUB))
15598             return CLI_SHOWUSAGE;
15599          havepattern = TRUE;
15600       } else
15601          return CLI_SHOWUSAGE;
15602    case 3:
15603       break;
15604    default:
15605       return CLI_SHOWUSAGE;
15606    }
15607 
15608    ast_cli(a->fd, FORMAT, "Username", "Secret", "Accountcode", "Def.Context", "ACL", "ForcerPort");
15609 
15610    user_iter = ao2_iterator_init(peers, 0);
15611    while ((user = ao2_iterator_next(&user_iter))) {
15612       ao2_lock(user);
15613       if (!(user->type & SIP_TYPE_USER)) {
15614          ao2_unlock(user);
15615          unref_peer(user, "sip show users");
15616          continue;
15617       }
15618 
15619       if (havepattern && regexec(&regexbuf, user->name, 0, NULL, 0)) {
15620          ao2_unlock(user);
15621          unref_peer(user, "sip show users");
15622          continue;
15623       }
15624 
15625       ast_cli(a->fd, FORMAT, user->name,
15626          user->secret,
15627          user->accountcode,
15628          user->context,
15629          AST_CLI_YESNO(user->ha != NULL),
15630          AST_CLI_YESNO(ast_test_flag(&user->flags[0], SIP_NAT_FORCE_RPORT)));
15631       ao2_unlock(user);
15632       unref_peer(user, "sip show users");
15633    }
15634    ao2_iterator_destroy(&user_iter);
15635 
15636    if (havepattern)
15637       regfree(&regexbuf);
15638 
15639    return CLI_SUCCESS;
15640 #undef FORMAT
15641 }
15642 
15643 /*! \brief Show SIP registrations in the manager API */
15644 static int manager_show_registry(struct mansession *s, const struct message *m)
15645 {
15646    const char *id = astman_get_header(m, "ActionID");
15647    char idtext[256] = "";
15648    int total = 0;
15649 
15650    if (!ast_strlen_zero(id))
15651       snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
15652 
15653    astman_send_listack(s, m, "Registrations will follow", "start");
15654 
15655    ASTOBJ_CONTAINER_TRAVERSE(&regl, 1, do {
15656       ASTOBJ_RDLOCK(iterator);
15657       astman_append(s,
15658          "Event: RegistryEntry\r\n"
15659          "%s"
15660          "Host: %s\r\n"
15661          "Port: %d\r\n"
15662          "Username: %s\r\n"
15663          "Domain: %s\r\n"
15664          "DomainPort: %d\r\n"
15665          "Refresh: %d\r\n"
15666          "State: %s\r\n"
15667          "RegistrationTime: %ld\r\n"
15668          "\r\n",
15669          idtext,
15670          iterator->hostname,
15671          iterator->portno ? iterator->portno : STANDARD_SIP_PORT,
15672          iterator->username,
15673          S_OR(iterator->regdomain,iterator->hostname),
15674          iterator->regdomainport ? iterator->regdomainport : STANDARD_SIP_PORT,
15675          iterator->refresh,
15676          regstate2str(iterator->regstate),
15677          (long) iterator->regtime.tv_sec);
15678       ASTOBJ_UNLOCK(iterator);
15679       total++;
15680    } while(0));
15681 
15682    astman_append(s,
15683       "Event: RegistrationsComplete\r\n"
15684       "EventList: Complete\r\n"
15685       "ListItems: %d\r\n"
15686       "%s"
15687       "\r\n", total, idtext);
15688    
15689    return 0;
15690 }
15691 
15692 /*! \brief  Show SIP peers in the manager API */
15693 /*    Inspired from chan_iax2 */
15694 static int manager_sip_show_peers(struct mansession *s, const struct message *m)
15695 {
15696    const char *id = astman_get_header(m, "ActionID");
15697    const char *a[] = {"sip", "show", "peers"};
15698    char idtext[256] = "";
15699    int total = 0;
15700 
15701    if (!ast_strlen_zero(id))
15702       snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
15703 
15704    astman_send_listack(s, m, "Peer status list will follow", "start");
15705    /* List the peers in separate manager events */
15706    _sip_show_peers(-1, &total, s, m, 3, a);
15707    /* Send final confirmation */
15708    astman_append(s,
15709    "Event: PeerlistComplete\r\n"
15710    "EventList: Complete\r\n"
15711    "ListItems: %d\r\n"
15712    "%s"
15713    "\r\n", total, idtext);
15714    return 0;
15715 }
15716 
15717 /*! \brief  CLI Show Peers command */
15718 static char *sip_show_peers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15719 {
15720    switch (cmd) {
15721    case CLI_INIT:
15722       e->command = "sip show peers";
15723       e->usage =
15724          "Usage: sip show peers [like <pattern>]\n"
15725          "       Lists all known SIP peers.\n"
15726          "       Optional regular expression pattern is used to filter the peer list.\n";
15727       return NULL;
15728    case CLI_GENERATE:
15729       return NULL;
15730    }
15731 
15732    return _sip_show_peers(a->fd, NULL, NULL, NULL, a->argc, (const char **) a->argv);
15733 }
15734 
15735 int peercomparefunc(const void *a, const void *b);
15736 
15737 int peercomparefunc(const void *a, const void *b)
15738 {
15739    struct sip_peer **ap = (struct sip_peer **)a;
15740    struct sip_peer **bp = (struct sip_peer **)b;
15741    return strcmp((*ap)->name, (*bp)->name);
15742 }
15743 
15744 
15745 /*! \brief Execute sip show peers command */
15746 static char *_sip_show_peers(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char *argv[])
15747 {
15748    regex_t regexbuf;
15749    int havepattern = FALSE;
15750    struct sip_peer *peer;
15751    struct ao2_iterator i;
15752    
15753 /* the last argument is left-aligned, so we don't need a size anyways */
15754 #define FORMAT2 "%-25.25s  %-39.39s %-3.3s %-10.10s %-3.3s %-8s %-10s %s\n"
15755 #define FORMAT  "%-25.25s  %-39.39s %-3.3s %-3.3s %-3.3s %-8d %-10s %s\n"
15756 
15757    char name[256];
15758    int total_peers = 0;
15759    int peers_mon_online = 0;
15760    int peers_mon_offline = 0;
15761    int peers_unmon_offline = 0;
15762    int peers_unmon_online = 0;
15763    const char *id;
15764    char idtext[256] = "";
15765    int realtimepeers;
15766    int objcount = ao2_container_count(peers);
15767    struct sip_peer **peerarray;
15768    int k;
15769    
15770    
15771    realtimepeers = ast_check_realtime("sippeers");
15772    peerarray = ast_calloc(sizeof(struct sip_peer *), objcount);
15773 
15774    if (s) { /* Manager - get ActionID */
15775       id = astman_get_header(m, "ActionID");
15776       if (!ast_strlen_zero(id))
15777          snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
15778    }
15779 
15780    switch (argc) {
15781    case 5:
15782       if (!strcasecmp(argv[3], "like")) {
15783          if (regcomp(&regexbuf, argv[4], REG_EXTENDED | REG_NOSUB))
15784             return CLI_SHOWUSAGE;
15785          havepattern = TRUE;
15786       } else
15787          return CLI_SHOWUSAGE;
15788    case 3:
15789       break;
15790    default:
15791       return CLI_SHOWUSAGE;
15792    }
15793 
15794    if (!s) /* Normal list */
15795       ast_cli(fd, FORMAT2, "Name/username", "Host", "Dyn", "Forcerport", "ACL", "Port", "Status", (realtimepeers ? "Realtime" : ""));
15796    
15797 
15798    i = ao2_iterator_init(peers, 0);
15799    while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {  
15800       ao2_lock(peer);
15801 
15802       if (!(peer->type & SIP_TYPE_PEER)) {
15803          ao2_unlock(peer);
15804          unref_peer(peer, "unref peer because it's actually a user");
15805          continue;
15806       }
15807 
15808       if (havepattern && regexec(&regexbuf, peer->name, 0, NULL, 0)) {
15809          objcount--;
15810          ao2_unlock(peer);
15811          unref_peer(peer, "toss iterator peer ptr before continue");
15812          continue;
15813       }
15814 
15815       peerarray[total_peers++] = peer;
15816       ao2_unlock(peer);
15817    }
15818    ao2_iterator_destroy(&i);
15819    
15820    qsort(peerarray, total_peers, sizeof(struct sip_peer *), peercomparefunc);
15821 
15822    for(k=0; k < total_peers; k++) {
15823       char status[20] = "";
15824       char srch[2000];
15825       char pstatus;
15826       peer = peerarray[k];
15827       
15828       ao2_lock(peer);
15829       if (havepattern && regexec(&regexbuf, peer->name, 0, NULL, 0)) {
15830          ao2_unlock(peer);
15831          unref_peer(peer, "toss iterator peer ptr before continue");
15832          continue;
15833       }
15834 
15835       if (!ast_strlen_zero(peer->username) && !s)
15836          snprintf(name, sizeof(name), "%s/%s", peer->name, peer->username);
15837       else
15838          ast_copy_string(name, peer->name, sizeof(name));
15839       
15840       pstatus = peer_status(peer, status, sizeof(status));
15841       if (pstatus == 1)
15842          peers_mon_online++;
15843       else if (pstatus == 0)
15844          peers_mon_offline++;
15845       else {
15846          if (ast_sockaddr_isnull(&peer->addr) ||
15847              !ast_sockaddr_port(&peer->addr)) {
15848             peers_unmon_offline++;
15849          } else {
15850             peers_unmon_online++;
15851          }
15852       }
15853 
15854       snprintf(srch, sizeof(srch), FORMAT, name,
15855          ast_sockaddr_isnull(&peer->addr) ? "(Unspecified)" : ast_sockaddr_stringify_addr(&peer->addr),
15856          peer->host_dynamic ? " D " : "   ",    /* Dynamic or not? */
15857          ast_test_flag(&peer->flags[0], SIP_NAT_FORCE_RPORT) ? " N " : "   ", /* NAT=yes? */
15858          peer->ha ? " A " : "   ",  /* permit/deny */
15859          ast_sockaddr_isnull(&peer->addr) ? 0 : ast_sockaddr_port(&peer->addr), status,
15860          realtimepeers ? (peer->is_realtime ? "Cached RT":"") : "");
15861 
15862       if (!s)  {/* Normal CLI list */
15863          ast_cli(fd, FORMAT, name,
15864          ast_sockaddr_isnull(&peer->addr) ? "(Unspecified)" : ast_sockaddr_stringify_addr(&peer->addr),
15865          peer->host_dynamic ? " D " : "   ",    /* Dynamic or not? */
15866          ast_test_flag(&peer->flags[0], SIP_NAT_FORCE_RPORT) ? " N " : "   ", /* NAT=yes? */
15867          peer->ha ? " A " : "   ",       /* permit/deny */
15868          ast_sockaddr_isnull(&peer->addr) ? 0 : ast_sockaddr_port(&peer->addr), status,
15869          realtimepeers ? (peer->is_realtime ? "Cached RT":"") : "");
15870       } else { /* Manager format */
15871          /* The names here need to be the same as other channels */
15872          astman_append(s,
15873          "Event: PeerEntry\r\n%s"
15874          "Channeltype: SIP\r\n"
15875          "ObjectName: %s\r\n"
15876          "ChanObjectType: peer\r\n" /* "peer" or "user" */
15877          "IPaddress: %s\r\n"
15878          "IPport: %d\r\n"
15879          "Dynamic: %s\r\n"
15880          "Forcerport: %s\r\n"
15881          "VideoSupport: %s\r\n"
15882          "TextSupport: %s\r\n"
15883          "ACL: %s\r\n"
15884          "Status: %s\r\n"
15885          "RealtimeDevice: %s\r\n\r\n",
15886          idtext,
15887          peer->name,
15888          ast_sockaddr_isnull(&peer->addr) ? "-none-" : ast_sockaddr_stringify_fmt(&peer->addr, AST_SOCKADDR_STR_HOST),
15889          ast_sockaddr_isnull(&peer->addr) ? 0 : ast_sockaddr_port(&peer->addr),
15890          peer->host_dynamic ? "yes" : "no",  /* Dynamic or not? */
15891          ast_test_flag(&peer->flags[0], SIP_NAT_FORCE_RPORT) ? "yes" : "no",  /* NAT=yes? */
15892          ast_test_flag(&peer->flags[1], SIP_PAGE2_VIDEOSUPPORT) ? "yes" : "no",  /* VIDEOSUPPORT=yes? */
15893          ast_test_flag(&peer->flags[1], SIP_PAGE2_TEXTSUPPORT) ? "yes" : "no",   /* TEXTSUPPORT=yes? */
15894          peer->ha ? "yes" : "no",       /* permit/deny */
15895          status,
15896          realtimepeers ? (peer->is_realtime ? "yes":"no") : "no");
15897       }
15898       ao2_unlock(peer);
15899       unref_peer(peer, "toss iterator peer ptr");
15900    }
15901    
15902    if (!s)
15903       ast_cli(fd, "%d sip peers [Monitored: %d online, %d offline Unmonitored: %d online, %d offline]\n",
15904               total_peers, peers_mon_online, peers_mon_offline, peers_unmon_online, peers_unmon_offline);
15905 
15906    if (havepattern)
15907       regfree(&regexbuf);
15908 
15909    if (total)
15910       *total = total_peers;
15911    
15912    ast_free(peerarray);
15913    
15914    return CLI_SUCCESS;
15915 #undef FORMAT
15916 #undef FORMAT2
15917 }
15918 
15919 static int peer_dump_func(void *userobj, void *arg, int flags)
15920 {
15921    struct sip_peer *peer = userobj;
15922    int refc = ao2_t_ref(userobj, 0, "");
15923    struct ast_cli_args *a = (struct ast_cli_args *) arg;
15924    
15925    ast_cli(a->fd, "name: %s\ntype: peer\nobjflags: %d\nrefcount: %d\n\n",
15926       peer->name, 0, refc);
15927    return 0;
15928 }
15929 
15930 static int dialog_dump_func(void *userobj, void *arg, int flags)
15931 {
15932    struct sip_pvt *pvt = userobj;
15933    int refc = ao2_t_ref(userobj, 0, "");
15934    struct ast_cli_args *a = (struct ast_cli_args *) arg;
15935    
15936    ast_cli(a->fd, "name: %s\ntype: dialog\nobjflags: %d\nrefcount: %d\n\n",
15937       pvt->callid, 0, refc);
15938    return 0;
15939 }
15940 
15941 
15942 /*! \brief List all allocated SIP Objects (realtime or static) */
15943 static char *sip_show_objects(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15944 {
15945    char tmp[256];
15946    
15947    switch (cmd) {
15948    case CLI_INIT:
15949       e->command = "sip show objects";
15950       e->usage =
15951          "Usage: sip show objects\n"
15952          "       Lists status of known SIP objects\n";
15953       return NULL;
15954    case CLI_GENERATE:
15955       return NULL;
15956    }  
15957 
15958    if (a->argc != 3)
15959       return CLI_SHOWUSAGE;
15960    ast_cli(a->fd, "-= Peer objects: %d static, %d realtime, %d autocreate =-\n\n", speerobjs, rpeerobjs, apeerobjs);
15961    ao2_t_callback(peers, OBJ_NODATA, peer_dump_func, a, "initiate ao2_callback to dump peers");
15962    ast_cli(a->fd, "-= Registry objects: %d =-\n\n", regobjs);
15963    ASTOBJ_CONTAINER_DUMP(a->fd, tmp, sizeof(tmp), &regl);
15964    ast_cli(a->fd, "-= Dialog objects:\n\n");
15965    ao2_t_callback(dialogs, OBJ_NODATA, dialog_dump_func, a, "initiate ao2_callback to dump dialogs");
15966    return CLI_SUCCESS;
15967 }
15968 /*! \brief Print call group and pickup group */
15969 static void print_group(int fd, ast_group_t group, int crlf)
15970 {
15971    char buf[256];
15972    ast_cli(fd, crlf ? "%s\r\n" : "%s\n", ast_print_group(buf, sizeof(buf), group) );
15973 }
15974 
15975 /*! \brief mapping between dtmf flags and strings */
15976 static const struct _map_x_s dtmfstr[] = {
15977    { SIP_DTMF_RFC2833,     "rfc2833" },
15978    { SIP_DTMF_INFO,        "info" },
15979    { SIP_DTMF_SHORTINFO,   "shortinfo" },
15980    { SIP_DTMF_INBAND,      "inband" },
15981    { SIP_DTMF_AUTO,        "auto" },
15982    { -1,                   NULL }, /* terminator */
15983 };
15984 
15985 /*! \brief Convert DTMF mode to printable string */
15986 static const char *dtmfmode2str(int mode)
15987 {
15988    return map_x_s(dtmfstr, mode, "<error>");
15989 }
15990 
15991 /*! \brief maps a string to dtmfmode, returns -1 on error */
15992 static int str2dtmfmode(const char *str)
15993 {
15994    return map_s_x(dtmfstr, str, -1);
15995 }
15996 
15997 static const struct _map_x_s insecurestr[] = {
15998    { SIP_INSECURE_PORT,    "port" },
15999    { SIP_INSECURE_INVITE,  "invite" },
16000    { SIP_INSECURE_PORT | SIP_INSECURE_INVITE, "port,invite" },
16001    { 0,                    "no" },
16002    { -1,                   NULL }, /* terminator */
16003 };
16004 
16005 /*! \brief Convert Insecure setting to printable string */
16006 static const char *insecure2str(int mode)
16007 {
16008    return map_x_s(insecurestr, mode, "<error>");
16009 }
16010 
16011 /*! \brief Destroy disused contexts between reloads
16012    Only used in reload_config so the code for regcontext doesn't get ugly
16013 */
16014 static void cleanup_stale_contexts(char *new, char *old)
16015 {
16016    char *oldcontext, *newcontext, *stalecontext, *stringp, newlist[AST_MAX_CONTEXT];
16017 
16018    while ((oldcontext = strsep(&old, "&"))) {
16019       stalecontext = '\0';
16020       ast_copy_string(newlist, new, sizeof(newlist));
16021       stringp = newlist;
16022       while ((newcontext = strsep(&stringp, "&"))) {
16023          if (!strcmp(newcontext, oldcontext)) {
16024             /* This is not the context you're looking for */
16025             stalecontext = '\0';
16026             break;
16027          } else if (strcmp(newcontext, oldcontext)) {
16028             stalecontext = oldcontext;
16029          }
16030          
16031       }
16032       if (stalecontext)
16033          ast_context_destroy(ast_context_find(stalecontext), "SIP");
16034    }
16035 }
16036 
16037 /*!
16038  * \brief Match dialogs that need to be destroyed
16039  *
16040  * \details This is used with ao2_callback to unlink/delete all dialogs that
16041  * are marked needdestroy. It will return CMP_MATCH for candidates, and they
16042  * will be unlinked.
16043  *
16044  * \todo Re-work this to improve efficiency.  Currently, this function is called
16045  * on _every_ dialog after processing _every_ incoming SIP/UDP packet, or
16046  * potentially even more often when the scheduler has entries to run.
16047  */
16048 
16049 static int dialog_needdestroy(void *dialogobj, void *arg, int flags)
16050 {
16051    struct sip_pvt *dialog = dialogobj;
16052    time_t *t = arg;
16053 
16054    if (sip_pvt_trylock(dialog)) {
16055       /* Don't block the monitor thread.  This function is called often enough
16056        * that we can wait for the next time around. */
16057       return 0;
16058    }
16059 
16060    /* We absolutely cannot destroy the rtp struct while a bridge is active or we WILL crash */
16061    if (dialog->rtp && ast_rtp_instance_get_bridged(dialog->rtp)) {
16062       ast_debug(2, "Bridge still active.  Delaying destroy of SIP dialog '%s' Method: %s\n", dialog->callid, sip_methods[dialog->method].text);
16063       sip_pvt_unlock(dialog);
16064       return 0;
16065    }
16066 
16067    if (dialog->vrtp && ast_rtp_instance_get_bridged(dialog->vrtp)) {
16068       ast_debug(2, "Bridge still active.  Delaying destroy of SIP dialog '%s' Method: %s\n", dialog->callid, sip_methods[dialog->method].text);
16069       sip_pvt_unlock(dialog);
16070       return 0;
16071    }
16072 
16073    /* Check RTP timeouts and kill calls if we have a timeout set and do not get RTP */
16074    check_rtp_timeout(dialog, *t);
16075 
16076    /* If we have sessions that needs to be destroyed, do it now */
16077    /* Check if we have outstanding requests not responsed to or an active call
16078       - if that's the case, wait with destruction */
16079    if (dialog->needdestroy && !dialog->packets && !dialog->owner) {
16080       /* We absolutely cannot destroy the rtp struct while a bridge is active or we WILL crash */
16081       if (dialog->rtp && ast_rtp_instance_get_bridged(dialog->rtp)) {
16082          ast_debug(2, "Bridge still active.  Delaying destruction of SIP dialog '%s' Method: %s\n", dialog->callid, sip_methods[dialog->method].text);
16083          sip_pvt_unlock(dialog);
16084          return 0;
16085       }
16086       
16087       if (dialog->vrtp && ast_rtp_instance_get_bridged(dialog->vrtp)) {
16088          ast_debug(2, "Bridge still active.  Delaying destroy of SIP dialog '%s' Method: %s\n", dialog->callid, sip_methods[dialog->method].text);
16089          sip_pvt_unlock(dialog);
16090          return 0;
16091       }
16092 
16093       sip_pvt_unlock(dialog);
16094       /* no, the unlink should handle this: dialog_unref(dialog, "needdestroy: one more refcount decrement to allow dialog to be destroyed"); */
16095       /* the CMP_MATCH will unlink this dialog from the dialog hash table */
16096       dialog_unlink_all(dialog, TRUE, FALSE);
16097       return 0; /* the unlink_all should unlink this from the table, so.... no need to return a match */
16098    }
16099 
16100    sip_pvt_unlock(dialog);
16101 
16102    return 0;
16103 }
16104 
16105 /*! \brief Remove temporary realtime objects from memory (CLI) */
16106 /*! \todo XXXX Propably needs an overhaul after removal of the devices */
16107 static char *sip_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16108 {
16109    struct sip_peer *peer, *pi;
16110    int prunepeer = FALSE;
16111    int multi = FALSE;
16112    const char *name = NULL;
16113    regex_t regexbuf;
16114    struct ao2_iterator i;
16115    static const char * const choices[] = { "all", "like", NULL };
16116    char *cmplt;
16117    
16118    if (cmd == CLI_INIT) {
16119       e->command = "sip prune realtime [peer|all]";
16120       e->usage =
16121          "Usage: sip prune realtime [peer [<name>|all|like <pattern>]|all]\n"
16122          "       Prunes object(s) from the cache.\n"
16123          "       Optional regular expression pattern is used to filter the objects.\n";
16124       return NULL;
16125    } else if (cmd == CLI_GENERATE) {
16126       if (a->pos == 4 && !strcasecmp(a->argv[3], "peer")) {
16127          cmplt = ast_cli_complete(a->word, choices, a->n);
16128          if (!cmplt)
16129             cmplt = complete_sip_peer(a->word, a->n - sizeof(choices), SIP_PAGE2_RTCACHEFRIENDS);
16130          return cmplt;
16131       }
16132       if (a->pos == 5 && !strcasecmp(a->argv[4], "like"))
16133          return complete_sip_peer(a->word, a->n, SIP_PAGE2_RTCACHEFRIENDS);
16134       return NULL;
16135    }
16136    switch (a->argc) {
16137    case 4:
16138       name = a->argv[3];
16139       /* we accept a name in position 3, but keywords are not good. */
16140       if (!strcasecmp(name, "peer") || !strcasecmp(name, "like"))
16141          return CLI_SHOWUSAGE;
16142       prunepeer = TRUE;
16143       if (!strcasecmp(name, "all")) {
16144          multi = TRUE;
16145          name = NULL;
16146       }
16147       /* else a single name, already set */
16148       break;
16149    case 5:
16150       /* sip prune realtime {peer|like} name */
16151       name = a->argv[4];
16152       if (!strcasecmp(a->argv[3], "peer"))
16153          prunepeer = TRUE;
16154       else if (!strcasecmp(a->argv[3], "like")) {
16155          prunepeer = TRUE;
16156          multi = TRUE;
16157       } else
16158          return CLI_SHOWUSAGE;
16159       if (!strcasecmp(name, "like"))
16160          return CLI_SHOWUSAGE;
16161       if (!multi && !strcasecmp(name, "all")) {
16162          multi = TRUE;
16163          name = NULL;
16164       }
16165       break;
16166    case 6:
16167       name = a->argv[5];
16168       multi = TRUE;
16169       /* sip prune realtime {peer} like name */
16170       if (strcasecmp(a->argv[4], "like"))
16171          return CLI_SHOWUSAGE;
16172       if (!strcasecmp(a->argv[3], "peer")) {
16173          prunepeer = TRUE;
16174       } else
16175          return CLI_SHOWUSAGE;
16176       break;
16177    default:
16178       return CLI_SHOWUSAGE;
16179    }
16180 
16181    if (multi && name) {
16182       if (regcomp(&regexbuf, name, REG_EXTENDED | REG_NOSUB))
16183          return CLI_SHOWUSAGE;
16184    }
16185 
16186    if (multi) {
16187       if (prunepeer) {
16188          int pruned = 0;
16189          
16190          i = ao2_iterator_init(peers, 0);
16191          while ((pi = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
16192             ao2_lock(pi);
16193             if (name && regexec(&regexbuf, pi->name, 0, NULL, 0)) {
16194                unref_peer(pi, "toss iterator peer ptr before continue");
16195                ao2_unlock(pi);
16196                continue;
16197             };
16198             if (ast_test_flag(&pi->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
16199                pi->the_mark = 1;
16200                pruned++;
16201             }
16202             ao2_unlock(pi);
16203             unref_peer(pi, "toss iterator peer ptr");
16204          }
16205          ao2_iterator_destroy(&i);
16206          if (pruned) {
16207             unlink_marked_peers_from_tables();
16208             ast_cli(a->fd, "%d peers pruned.\n", pruned);
16209          } else
16210             ast_cli(a->fd, "No peers found to prune.\n");
16211       }
16212    } else {
16213       if (prunepeer) {
16214          struct sip_peer tmp;
16215          ast_copy_string(tmp.name, name, sizeof(tmp.name));
16216          if ((peer = ao2_t_find(peers, &tmp, OBJ_POINTER | OBJ_UNLINK, "finding to unlink from peers"))) {
16217             if (!ast_sockaddr_isnull(&peer->addr)) {
16218                ao2_t_unlink(peers_by_ip, peer, "unlinking peer from peers_by_ip also");
16219             }
16220             if (!ast_test_flag(&peer->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
16221                ast_cli(a->fd, "Peer '%s' is not a Realtime peer, cannot be pruned.\n", name);
16222                /* put it back! */
16223                ao2_t_link(peers, peer, "link peer into peer table");
16224                if (!ast_sockaddr_isnull(&peer->addr)) {
16225                   ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
16226                }
16227             } else
16228                ast_cli(a->fd, "Peer '%s' pruned.\n", name);
16229             unref_peer(peer, "sip_prune_realtime: unref_peer: tossing temp peer ptr");
16230          } else
16231             ast_cli(a->fd, "Peer '%s' not found.\n", name);
16232       }
16233    }
16234 
16235    return CLI_SUCCESS;
16236 }
16237 
16238 /*! \brief Print codec list from preference to CLI/manager */
16239 static void print_codec_to_cli(int fd, struct ast_codec_pref *pref)
16240 {
16241    int x;
16242    format_t codec;
16243 
16244    for(x = 0; x < 64 ; x++) {
16245       codec = ast_codec_pref_index(pref, x);
16246       if (!codec)
16247          break;
16248       ast_cli(fd, "%s", ast_getformatname(codec));
16249       ast_cli(fd, ":%d", pref->framing[x]);
16250       if (x < 31 && ast_codec_pref_index(pref, x + 1))
16251          ast_cli(fd, ",");
16252    }
16253    if (!x)
16254       ast_cli(fd, "none");
16255 }
16256 
16257 /*! \brief Print domain mode to cli */
16258 static const char *domain_mode_to_text(const enum domain_mode mode)
16259 {
16260    switch (mode) {
16261    case SIP_DOMAIN_AUTO:
16262       return "[Automatic]";
16263    case SIP_DOMAIN_CONFIG:
16264       return "[Configured]";
16265    }
16266 
16267    return "";
16268 }
16269 
16270 /*! \brief CLI command to list local domains */
16271 static char *sip_show_domains(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16272 {
16273    struct domain *d;
16274 #define FORMAT "%-40.40s %-20.20s %-16.16s\n"
16275 
16276    switch (cmd) {
16277    case CLI_INIT:
16278       e->command = "sip show domains";
16279       e->usage =
16280          "Usage: sip show domains\n"
16281          "       Lists all configured SIP local domains.\n"
16282          "       Asterisk only responds to SIP messages to local domains.\n";
16283       return NULL;
16284    case CLI_GENERATE:
16285       return NULL;
16286    }
16287 
16288    if (AST_LIST_EMPTY(&domain_list)) {
16289       ast_cli(a->fd, "SIP Domain support not enabled.\n\n");
16290       return CLI_SUCCESS;
16291    } else {
16292       ast_cli(a->fd, FORMAT, "Our local SIP domains:", "Context", "Set by");
16293       AST_LIST_LOCK(&domain_list);
16294       AST_LIST_TRAVERSE(&domain_list, d, list)
16295          ast_cli(a->fd, FORMAT, d->domain, S_OR(d->context, "(default)"),
16296             domain_mode_to_text(d->mode));
16297       AST_LIST_UNLOCK(&domain_list);
16298       ast_cli(a->fd, "\n");
16299       return CLI_SUCCESS;
16300    }
16301 }
16302 #undef FORMAT
16303 
16304 /*! \brief Show SIP peers in the manager API  */
16305 static int manager_sip_show_peer(struct mansession *s, const struct message *m)
16306 {
16307    const char *a[4];
16308    const char *peer;
16309 
16310    peer = astman_get_header(m, "Peer");
16311    if (ast_strlen_zero(peer)) {
16312       astman_send_error(s, m, "Peer: <name> missing.");
16313       return 0;
16314    }
16315    a[0] = "sip";
16316    a[1] = "show";
16317    a[2] = "peer";
16318    a[3] = peer;
16319 
16320    _sip_show_peer(1, -1, s, m, 4, a);
16321    astman_append(s, "\r\n\r\n" );
16322    return 0;
16323 }
16324 
16325 /*! \brief Show one peer in detail */
16326 static char *sip_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16327 {
16328    switch (cmd) {
16329    case CLI_INIT:
16330       e->command = "sip show peer";
16331       e->usage =
16332          "Usage: sip show peer <name> [load]\n"
16333          "       Shows all details on one SIP peer and the current status.\n"
16334          "       Option \"load\" forces lookup of peer in realtime storage.\n";
16335       return NULL;
16336    case CLI_GENERATE:
16337       return complete_sip_show_peer(a->line, a->word, a->pos, a->n);
16338    }
16339    return _sip_show_peer(0, a->fd, NULL, NULL, a->argc, (const char **) a->argv);
16340 }
16341 
16342 /*! \brief Send qualify message to peer from cli or manager. Mostly for debugging. */
16343 static char *_sip_qualify_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[])
16344 {
16345    struct sip_peer *peer;
16346    int load_realtime;
16347 
16348    if (argc < 4)
16349       return CLI_SHOWUSAGE;
16350 
16351    load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? TRUE : FALSE;
16352    if ((peer = find_peer(argv[3], NULL, load_realtime, FINDPEERS, FALSE, 0))) {
16353       sip_poke_peer(peer, 1);
16354       unref_peer(peer, "qualify: done with peer");
16355    } else if (type == 0) {
16356       ast_cli(fd, "Peer '%s' not found\n", argv[3]);
16357    } else {
16358       astman_send_error(s, m, "Peer not found");
16359    }
16360    return CLI_SUCCESS;
16361 }
16362 
16363 /*! \brief Qualify SIP peers in the manager API  */
16364 static int manager_sip_qualify_peer(struct mansession *s, const struct message *m)
16365 {
16366    const char *a[4];
16367    const char *peer;
16368 
16369    peer = astman_get_header(m, "Peer");
16370    if (ast_strlen_zero(peer)) {
16371       astman_send_error(s, m, "Peer: <name> missing.");
16372       return 0;
16373    }
16374    a[0] = "sip";
16375    a[1] = "qualify";
16376    a[2] = "peer";
16377    a[3] = peer;
16378 
16379    _sip_qualify_peer(1, -1, s, m, 4, a);
16380    astman_append(s, "\r\n\r\n" );
16381    return 0;
16382 }
16383 
16384 /*! \brief Send an OPTIONS packet to a SIP peer */
16385 static char *sip_qualify_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16386 {
16387    switch (cmd) {
16388    case CLI_INIT:
16389       e->command = "sip qualify peer";
16390       e->usage =
16391          "Usage: sip qualify peer <name> [load]\n"
16392          "       Requests a response from one SIP peer and the current status.\n"
16393          "       Option \"load\" forces lookup of peer in realtime storage.\n";
16394       return NULL;
16395    case CLI_GENERATE:
16396       return complete_sip_show_peer(a->line, a->word, a->pos, a->n);
16397    }
16398    return _sip_qualify_peer(0, a->fd, NULL, NULL, a->argc, (const char **) a->argv);
16399 }
16400 
16401 /*! \brief list peer mailboxes to CLI */
16402 static void peer_mailboxes_to_str(struct ast_str **mailbox_str, struct sip_peer *peer)
16403 {
16404    struct sip_mailbox *mailbox;
16405 
16406    AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
16407       ast_str_append(mailbox_str, 0, "%s%s%s%s",
16408          mailbox->mailbox,
16409          ast_strlen_zero(mailbox->context) ? "" : "@",
16410          S_OR(mailbox->context, ""),
16411          AST_LIST_NEXT(mailbox, entry) ? "," : "");
16412    }
16413 }
16414 
16415 static struct _map_x_s faxecmodes[] = {
16416    { SIP_PAGE2_T38SUPPORT_UDPTL,       "None"},
16417    { SIP_PAGE2_T38SUPPORT_UDPTL_FEC,      "FEC"},
16418    { SIP_PAGE2_T38SUPPORT_UDPTL_REDUNDANCY,  "Redundancy"},
16419    { -1,                NULL},
16420 };
16421 
16422 static const char *faxec2str(int faxec)
16423 {
16424    return map_x_s(faxecmodes, faxec, "Unknown");
16425 }
16426 
16427 /*! \brief Show one peer in detail (main function) */
16428 static char *_sip_show_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[])
16429 {
16430    char status[30] = "";
16431    char cbuf[256];
16432    struct sip_peer *peer;
16433    char codec_buf[512];
16434    struct ast_codec_pref *pref;
16435    struct ast_variable *v;
16436    struct sip_auth *auth;
16437    int x = 0, load_realtime;
16438    format_t codec = 0;
16439    int realtimepeers;
16440 
16441    realtimepeers = ast_check_realtime("sippeers");
16442 
16443    if (argc < 4)
16444       return CLI_SHOWUSAGE;
16445 
16446    load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? TRUE : FALSE;
16447    peer = find_peer(argv[3], NULL, load_realtime, FINDPEERS, FALSE, 0);
16448 
16449    if (s) {    /* Manager */
16450       if (peer) {
16451          const char *id = astman_get_header(m, "ActionID");
16452 
16453          astman_append(s, "Response: Success\r\n");
16454          if (!ast_strlen_zero(id))
16455             astman_append(s, "ActionID: %s\r\n", id);
16456       } else {
16457          snprintf (cbuf, sizeof(cbuf), "Peer %s not found.", argv[3]);
16458          astman_send_error(s, m, cbuf);
16459          return CLI_SUCCESS;
16460       }
16461    }
16462    if (peer && type==0 ) { /* Normal listing */
16463       struct ast_str *mailbox_str = ast_str_alloca(512);
16464       ast_cli(fd, "\n\n");
16465       ast_cli(fd, "  * Name       : %s\n", peer->name);
16466       if (realtimepeers) { /* Realtime is enabled */
16467          ast_cli(fd, "  Realtime peer: %s\n", peer->is_realtime ? "Yes, cached" : "No");
16468       }
16469       ast_cli(fd, "  Secret       : %s\n", ast_strlen_zero(peer->secret)?"<Not set>":"<Set>");
16470       ast_cli(fd, "  MD5Secret    : %s\n", ast_strlen_zero(peer->md5secret)?"<Not set>":"<Set>");
16471       ast_cli(fd, "  Remote Secret: %s\n", ast_strlen_zero(peer->remotesecret)?"<Not set>":"<Set>");
16472       for (auth = peer->auth; auth; auth = auth->next) {
16473          ast_cli(fd, "  Realm-auth   : Realm %-15.15s User %-10.20s ", auth->realm, auth->username);
16474          ast_cli(fd, "%s\n", !ast_strlen_zero(auth->secret)?"<Secret set>":(!ast_strlen_zero(auth->md5secret)?"<MD5secret set>" : "<Not set>"));
16475       }
16476       ast_cli(fd, "  Context      : %s\n", peer->context);
16477       ast_cli(fd, "  Subscr.Cont. : %s\n", S_OR(peer->subscribecontext, "<Not set>") );
16478       ast_cli(fd, "  Language     : %s\n", peer->language);
16479       if (!ast_strlen_zero(peer->accountcode))
16480          ast_cli(fd, "  Accountcode  : %s\n", peer->accountcode);
16481       ast_cli(fd, "  AMA flags    : %s\n", ast_cdr_flags2str(peer->amaflags));
16482       ast_cli(fd, "  Transfer mode: %s\n", transfermode2str(peer->allowtransfer));
16483       ast_cli(fd, "  CallingPres  : %s\n", ast_describe_caller_presentation(peer->callingpres));
16484       if (!ast_strlen_zero(peer->fromuser))
16485          ast_cli(fd, "  FromUser     : %s\n", peer->fromuser);
16486       if (!ast_strlen_zero(peer->fromdomain))
16487          ast_cli(fd, "  FromDomain   : %s Port %d\n", peer->fromdomain, (peer->fromdomainport) ? peer->fromdomainport : STANDARD_SIP_PORT);
16488       ast_cli(fd, "  Callgroup    : ");
16489       print_group(fd, peer->callgroup, 0);
16490       ast_cli(fd, "  Pickupgroup  : ");
16491       print_group(fd, peer->pickupgroup, 0);
16492       peer_mailboxes_to_str(&mailbox_str, peer);
16493       ast_cli(fd, "  MOH Suggest  : %s\n", peer->mohsuggest);
16494       ast_cli(fd, "  Mailbox      : %s\n", mailbox_str->str);
16495       ast_cli(fd, "  VM Extension : %s\n", peer->vmexten);
16496       ast_cli(fd, "  LastMsgsSent : %d/%d\n", (peer->lastmsgssent & 0x7fff0000) >> 16, peer->lastmsgssent & 0xffff);
16497       ast_cli(fd, "  Call limit   : %d\n", peer->call_limit);
16498       ast_cli(fd, "  Max forwards : %d\n", peer->maxforwards);
16499       if (peer->busy_level)
16500          ast_cli(fd, "  Busy level   : %d\n", peer->busy_level);
16501       ast_cli(fd, "  Dynamic      : %s\n", AST_CLI_YESNO(peer->host_dynamic));
16502       ast_cli(fd, "  Callerid     : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, "<unspecified>"));
16503       ast_cli(fd, "  MaxCallBR    : %d kbps\n", peer->maxcallbitrate);
16504       ast_cli(fd, "  Expire       : %ld\n", ast_sched_when(sched, peer->expire));
16505       ast_cli(fd, "  Insecure     : %s\n", insecure2str(ast_test_flag(&peer->flags[0], SIP_INSECURE)));
16506       ast_cli(fd, "  Force rport  : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[0], SIP_NAT_FORCE_RPORT)));
16507       ast_cli(fd, "  ACL          : %s\n", AST_CLI_YESNO(peer->ha != NULL));
16508       ast_cli(fd, "  DirectMedACL : %s\n", AST_CLI_YESNO(peer->directmediaha != NULL));
16509       ast_cli(fd, "  T.38 support : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)));
16510       ast_cli(fd, "  T.38 EC mode : %s\n", faxec2str(ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)));
16511       ast_cli(fd, "  T.38 MaxDtgrm: %d\n", peer->t38_maxdatagram);
16512       ast_cli(fd, "  DirectMedia  : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[0], SIP_DIRECT_MEDIA)));
16513       ast_cli(fd, "  PromiscRedir : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[0], SIP_PROMISCREDIR)));
16514       ast_cli(fd, "  User=Phone   : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[0], SIP_USEREQPHONE)));
16515       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)));
16516       ast_cli(fd, "  Text Support : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[1], SIP_PAGE2_TEXTSUPPORT)));
16517       ast_cli(fd, "  Ign SDP ver  : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[1], SIP_PAGE2_IGNORESDPVERSION)));
16518       ast_cli(fd, "  Trust RPID   : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[0], SIP_TRUSTRPID)));
16519       ast_cli(fd, "  Send RPID    : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[0], SIP_SENDRPID)));
16520       ast_cli(fd, "  Subscriptions: %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)));
16521       ast_cli(fd, "  Overlap dial : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWOVERLAP)));
16522       if (peer->outboundproxy)
16523          ast_cli(fd, "  Outb. proxy  : %s %s\n", ast_strlen_zero(peer->outboundproxy->name) ? "<not set>" : peer->outboundproxy->name,
16524                      peer->outboundproxy->force ? "(forced)" : "");
16525 
16526       /* - is enumerated */
16527       ast_cli(fd, "  DTMFmode     : %s\n", dtmfmode2str(ast_test_flag(&peer->flags[0], SIP_DTMF)));
16528       ast_cli(fd, "  Timer T1     : %d\n", peer->timer_t1);
16529       ast_cli(fd, "  Timer B      : %d\n", peer->timer_b);
16530       ast_cli(fd, "  ToHost       : %s\n", peer->tohost);
16531       ast_cli(fd, "  Addr->IP     : %s\n", ast_sockaddr_stringify(&peer->addr));
16532       ast_cli(fd, "  Defaddr->IP  : %s\n", ast_sockaddr_stringify(&peer->defaddr));
16533       ast_cli(fd, "  Prim.Transp. : %s\n", get_transport(peer->socket.type));
16534       ast_cli(fd, "  Allowed.Trsp : %s\n", get_transport_list(peer->transports));
16535       if (!ast_strlen_zero(sip_cfg.regcontext))
16536          ast_cli(fd, "  Reg. exten   : %s\n", peer->regexten);
16537       ast_cli(fd, "  Def. Username: %s\n", peer->username);
16538       ast_cli(fd, "  SIP Options  : ");
16539       if (peer->sipoptions) {
16540          int lastoption = -1;
16541          for (x = 0 ; x < ARRAY_LEN(sip_options); x++) {
16542             if (sip_options[x].id != lastoption) {
16543                if (peer->sipoptions & sip_options[x].id)
16544                   ast_cli(fd, "%s ", sip_options[x].text);
16545                lastoption = x;
16546             }
16547          }
16548       } else
16549          ast_cli(fd, "(none)");
16550 
16551       ast_cli(fd, "\n");
16552       ast_cli(fd, "  Codecs       : ");
16553       ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
16554       ast_cli(fd, "%s\n", codec_buf);
16555       ast_cli(fd, "  Codec Order  : (");
16556       print_codec_to_cli(fd, &peer->prefs);
16557       ast_cli(fd, ")\n");
16558 
16559       ast_cli(fd, "  Auto-Framing :  %s \n", AST_CLI_YESNO(peer->autoframing));
16560       ast_cli(fd, "  100 on REG   : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[1], SIP_PAGE2_REGISTERTRYING)));
16561       ast_cli(fd, "  Status       : ");
16562       peer_status(peer, status, sizeof(status));
16563       ast_cli(fd, "%s\n", status);
16564       ast_cli(fd, "  Useragent    : %s\n", peer->useragent);
16565       ast_cli(fd, "  Reg. Contact : %s\n", peer->fullcontact);
16566       ast_cli(fd, "  Qualify Freq : %d ms\n", peer->qualifyfreq);
16567       if (peer->chanvars) {
16568          ast_cli(fd, "  Variables    :\n");
16569          for (v = peer->chanvars ; v ; v = v->next)
16570             ast_cli(fd, "                 %s = %s\n", v->name, v->value);
16571       }
16572 
16573       ast_cli(fd, "  Sess-Timers  : %s\n", stmode2str(peer->stimer.st_mode_oper));
16574       ast_cli(fd, "  Sess-Refresh : %s\n", strefresher2str(peer->stimer.st_ref));
16575       ast_cli(fd, "  Sess-Expires : %d secs\n", peer->stimer.st_max_se);
16576       ast_cli(fd, "  Min-Sess     : %d secs\n", peer->stimer.st_min_se);
16577       ast_cli(fd, "  RTP Engine   : %s\n", peer->engine);
16578       ast_cli(fd, "  Parkinglot   : %s\n", peer->parkinglot);
16579       ast_cli(fd, "  Use Reason   : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[1], SIP_PAGE2_Q850_REASON)));
16580       ast_cli(fd, "  Encryption   : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[1], SIP_PAGE2_USE_SRTP)));
16581       ast_cli(fd, "\n");
16582       peer = unref_peer(peer, "sip_show_peer: unref_peer: done with peer ptr");
16583    } else  if (peer && type == 1) { /* manager listing */
16584       char buffer[256];
16585       struct ast_str *mailbox_str = ast_str_alloca(512);
16586       astman_append(s, "Channeltype: SIP\r\n");
16587       astman_append(s, "ObjectName: %s\r\n", peer->name);
16588       astman_append(s, "ChanObjectType: peer\r\n");
16589       astman_append(s, "SecretExist: %s\r\n", ast_strlen_zero(peer->secret)?"N":"Y");
16590       astman_append(s, "RemoteSecretExist: %s\r\n", ast_strlen_zero(peer->remotesecret)?"N":"Y");
16591       astman_append(s, "MD5SecretExist: %s\r\n", ast_strlen_zero(peer->md5secret)?"N":"Y");
16592       astman_append(s, "Context: %s\r\n", peer->context);
16593       astman_append(s, "Language: %s\r\n", peer->language);
16594       if (!ast_strlen_zero(peer->accountcode))
16595          astman_append(s, "Accountcode: %s\r\n", peer->accountcode);
16596       astman_append(s, "AMAflags: %s\r\n", ast_cdr_flags2str(peer->amaflags));
16597       astman_append(s, "CID-CallingPres: %s\r\n", ast_describe_caller_presentation(peer->callingpres));
16598       if (!ast_strlen_zero(peer->fromuser))
16599          astman_append(s, "SIP-FromUser: %s\r\n", peer->fromuser);
16600       if (!ast_strlen_zero(peer->fromdomain))
16601          astman_append(s, "SIP-FromDomain: %s\r\nSip-FromDomain-Port: %d\r\n", peer->fromdomain, (peer->fromdomainport) ? peer->fromdomainport : STANDARD_SIP_PORT);
16602       astman_append(s, "Callgroup: ");
16603       astman_append(s, "%s\r\n", ast_print_group(buffer, sizeof(buffer), peer->callgroup));
16604       astman_append(s, "Pickupgroup: ");
16605       astman_append(s, "%s\r\n", ast_print_group(buffer, sizeof(buffer), peer->pickupgroup));
16606       astman_append(s, "MOHSuggest: %s\r\n", peer->mohsuggest);
16607       peer_mailboxes_to_str(&mailbox_str, peer);
16608       astman_append(s, "VoiceMailbox: %s\r\n", mailbox_str->str);
16609       astman_append(s, "TransferMode: %s\r\n", transfermode2str(peer->allowtransfer));
16610       astman_append(s, "Maxforwards: %d\r\n", peer->maxforwards);
16611       astman_append(s, "LastMsgsSent: %d\r\n", peer->lastmsgssent);
16612       astman_append(s, "Maxforwards: %d\r\n", peer->maxforwards);
16613       astman_append(s, "Call-limit: %d\r\n", peer->call_limit);
16614       astman_append(s, "Busy-level: %d\r\n", peer->busy_level);
16615       astman_append(s, "MaxCallBR: %d kbps\r\n", peer->maxcallbitrate);
16616       astman_append(s, "Dynamic: %s\r\n", peer->host_dynamic?"Y":"N");
16617       astman_append(s, "Callerid: %s\r\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, ""));
16618       astman_append(s, "RegExpire: %ld seconds\r\n", ast_sched_when(sched, peer->expire));
16619       astman_append(s, "SIP-AuthInsecure: %s\r\n", insecure2str(ast_test_flag(&peer->flags[0], SIP_INSECURE)));
16620       astman_append(s, "SIP-Forcerport: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_NAT_FORCE_RPORT)?"Y":"N"));
16621       astman_append(s, "ACL: %s\r\n", (peer->ha?"Y":"N"));
16622       astman_append(s, "SIP-CanReinvite: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_DIRECT_MEDIA)?"Y":"N"));
16623       astman_append(s, "SIP-DirectMedia: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_DIRECT_MEDIA)?"Y":"N"));
16624       astman_append(s, "SIP-PromiscRedir: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_PROMISCREDIR)?"Y":"N"));
16625       astman_append(s, "SIP-UserPhone: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_USEREQPHONE)?"Y":"N"));
16626       astman_append(s, "SIP-VideoSupport: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_VIDEOSUPPORT)?"Y":"N"));
16627       astman_append(s, "SIP-TextSupport: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_TEXTSUPPORT)?"Y":"N"));
16628       astman_append(s, "SIP-T.38Support: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)?"Y":"N"));
16629       astman_append(s, "SIP-T.38EC: %s\r\n", faxec2str(ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)));
16630       astman_append(s, "SIP-T.38MaxDtgrm: %d\r\n", peer->t38_maxdatagram);
16631       astman_append(s, "SIP-Sess-Timers: %s\r\n", stmode2str(peer->stimer.st_mode_oper));
16632       astman_append(s, "SIP-Sess-Refresh: %s\r\n", strefresher2str(peer->stimer.st_ref));
16633       astman_append(s, "SIP-Sess-Expires: %d\r\n", peer->stimer.st_max_se);
16634       astman_append(s, "SIP-Sess-Min: %d\r\n", peer->stimer.st_min_se);
16635       astman_append(s, "SIP-RTP-Engine: %s\r\n", peer->engine);
16636       astman_append(s, "SIP-Encryption: %s\r\n", ast_test_flag(&peer->flags[1], SIP_PAGE2_USE_SRTP) ? "Y" : "N");
16637 
16638       /* - is enumerated */
16639       astman_append(s, "SIP-DTMFmode: %s\r\n", dtmfmode2str(ast_test_flag(&peer->flags[0], SIP_DTMF)));
16640       astman_append(s, "ToHost: %s\r\n", peer->tohost);
16641       astman_append(s, "Address-IP: %s\r\nAddress-Port: %d\r\n", ast_sockaddr_stringify_addr(&peer->addr), ast_sockaddr_port(&peer->addr));
16642       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));
16643       astman_append(s, "Default-Username: %s\r\n", peer->username);
16644       if (!ast_strlen_zero(sip_cfg.regcontext))
16645          astman_append(s, "RegExtension: %s\r\n", peer->regexten);
16646       astman_append(s, "Codecs: ");
16647       ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
16648       astman_append(s, "%s\r\n", codec_buf);
16649       astman_append(s, "CodecOrder: ");
16650       pref = &peer->prefs;
16651       for(x = 0; x < 64 ; x++) {
16652          codec = ast_codec_pref_index(pref, x);
16653          if (!codec)
16654             break;
16655          astman_append(s, "%s", ast_getformatname(codec));
16656          if (x < 63 && ast_codec_pref_index(pref, x+1))
16657             astman_append(s, ",");
16658       }
16659 
16660       astman_append(s, "\r\n");
16661       astman_append(s, "Status: ");
16662       peer_status(peer, status, sizeof(status));
16663       astman_append(s, "%s\r\n", status);
16664       astman_append(s, "SIP-Useragent: %s\r\n", peer->useragent);
16665       astman_append(s, "Reg-Contact: %s\r\n", peer->fullcontact);
16666       astman_append(s, "QualifyFreq: %d ms\r\n", peer->qualifyfreq);
16667       astman_append(s, "Parkinglot: %s\r\n", peer->parkinglot);
16668       if (peer->chanvars) {
16669          for (v = peer->chanvars ; v ; v = v->next) {
16670             astman_append(s, "ChanVariable: %s=%s\r\n", v->name, v->value);
16671          }
16672       }
16673       astman_append(s, "SIP-Use-Reason-Header : %s\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_Q850_REASON)) ? "Y" : "N");
16674 
16675       peer = unref_peer(peer, "sip_show_peer: unref_peer: done with peer");
16676 
16677    } else {
16678       ast_cli(fd, "Peer %s not found.\n", argv[3]);
16679       ast_cli(fd, "\n");
16680    }
16681 
16682    return CLI_SUCCESS;
16683 }
16684 
16685 /*! \brief Do completion on user name */
16686 static char *complete_sip_user(const char *word, int state)
16687 {
16688    char *result = NULL;
16689    int wordlen = strlen(word);
16690    int which = 0;
16691    struct ao2_iterator user_iter;
16692    struct sip_peer *user;
16693 
16694    user_iter = ao2_iterator_init(peers, 0);
16695    while ((user = ao2_iterator_next(&user_iter))) {
16696       ao2_lock(user);
16697       if (!(user->type & SIP_TYPE_USER)) {
16698          ao2_unlock(user);
16699          unref_peer(user, "complete sip user");
16700          continue;
16701       }
16702       /* locking of the object is not required because only the name and flags are being compared */
16703       if (!strncasecmp(word, user->name, wordlen) && ++which > state) {
16704          result = ast_strdup(user->name);
16705       }
16706       ao2_unlock(user);
16707       unref_peer(user, "complete sip user");
16708    }
16709    ao2_iterator_destroy(&user_iter);
16710    return result;
16711 }
16712 /*! \brief Support routine for 'sip show user' CLI */
16713 static char *complete_sip_show_user(const char *line, const char *word, int pos, int state)
16714 {
16715    if (pos == 3)
16716       return complete_sip_user(word, state);
16717 
16718    return NULL;
16719 }
16720 
16721 /*! \brief Show one user in detail */
16722 static char *sip_show_user(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16723 {
16724    char cbuf[256];
16725    struct sip_peer *user;
16726    struct ast_variable *v;
16727    int load_realtime;
16728 
16729    switch (cmd) {
16730    case CLI_INIT:
16731       e->command = "sip show user";
16732       e->usage =
16733          "Usage: sip show user <name> [load]\n"
16734          "       Shows all details on one SIP user and the current status.\n"
16735          "       Option \"load\" forces lookup of peer in realtime storage.\n";
16736       return NULL;
16737    case CLI_GENERATE:
16738       return complete_sip_show_user(a->line, a->word, a->pos, a->n);
16739    }
16740 
16741    if (a->argc < 4)
16742       return CLI_SHOWUSAGE;
16743 
16744    /* Load from realtime storage? */
16745    load_realtime = (a->argc == 5 && !strcmp(a->argv[4], "load")) ? TRUE : FALSE;
16746 
16747    if ((user = find_peer(a->argv[3], NULL, load_realtime, FINDUSERS, FALSE, 0))) {
16748       ao2_lock(user);
16749       ast_cli(a->fd, "\n\n");
16750       ast_cli(a->fd, "  * Name       : %s\n", user->name);
16751       ast_cli(a->fd, "  Secret       : %s\n", ast_strlen_zero(user->secret)?"<Not set>":"<Set>");
16752       ast_cli(a->fd, "  MD5Secret    : %s\n", ast_strlen_zero(user->md5secret)?"<Not set>":"<Set>");
16753       ast_cli(a->fd, "  Context      : %s\n", user->context);
16754       ast_cli(a->fd, "  Language     : %s\n", user->language);
16755       if (!ast_strlen_zero(user->accountcode))
16756          ast_cli(a->fd, "  Accountcode  : %s\n", user->accountcode);
16757       ast_cli(a->fd, "  AMA flags    : %s\n", ast_cdr_flags2str(user->amaflags));
16758       ast_cli(a->fd, "  Transfer mode: %s\n", transfermode2str(user->allowtransfer));
16759       ast_cli(a->fd, "  MaxCallBR    : %d kbps\n", user->maxcallbitrate);
16760       ast_cli(a->fd, "  CallingPres  : %s\n", ast_describe_caller_presentation(user->callingpres));
16761       ast_cli(a->fd, "  Call limit   : %d\n", user->call_limit);
16762       ast_cli(a->fd, "  Callgroup    : ");
16763       print_group(a->fd, user->callgroup, 0);
16764       ast_cli(a->fd, "  Pickupgroup  : ");
16765       print_group(a->fd, user->pickupgroup, 0);
16766       ast_cli(a->fd, "  Callerid     : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), user->cid_name, user->cid_num, "<unspecified>"));
16767       ast_cli(a->fd, "  ACL          : %s\n", AST_CLI_YESNO(user->ha != NULL));
16768       ast_cli(a->fd, "  Sess-Timers  : %s\n", stmode2str(user->stimer.st_mode_oper));
16769       ast_cli(a->fd, "  Sess-Refresh : %s\n", strefresher2str(user->stimer.st_ref));
16770       ast_cli(a->fd, "  Sess-Expires : %d secs\n", user->stimer.st_max_se);
16771       ast_cli(a->fd, "  Sess-Min-SE  : %d secs\n", user->stimer.st_min_se);
16772       ast_cli(a->fd, "  RTP Engine   : %s\n", user->engine);
16773 
16774       ast_cli(a->fd, "  Codec Order  : (");
16775       print_codec_to_cli(a->fd, &user->prefs);
16776       ast_cli(a->fd, ")\n");
16777 
16778       ast_cli(a->fd, "  Auto-Framing:  %s \n", AST_CLI_YESNO(user->autoframing));
16779       if (user->chanvars) {
16780          ast_cli(a->fd, "  Variables    :\n");
16781          for (v = user->chanvars ; v ; v = v->next)
16782             ast_cli(a->fd, "                 %s = %s\n", v->name, v->value);
16783       }
16784 
16785       ast_cli(a->fd, "\n");
16786 
16787       ao2_unlock(user);
16788       unref_peer(user, "sip show user");
16789    } else {
16790       ast_cli(a->fd, "User %s not found.\n", a->argv[3]);
16791       ast_cli(a->fd, "\n");
16792    }
16793 
16794    return CLI_SUCCESS;
16795 }
16796 
16797 
16798 static char *sip_show_sched(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16799 {
16800    struct ast_str *cbuf;
16801    struct ast_cb_names cbnames = {9, { "retrans_pkt",
16802                                         "__sip_autodestruct",
16803                                         "expire_register",
16804                                         "auto_congest",
16805                                         "sip_reg_timeout",
16806                                         "sip_poke_peer_s",
16807                                         "sip_poke_noanswer",
16808                                         "sip_reregister",
16809                                         "sip_reinvite_retry"},
16810                            { retrans_pkt,
16811                                      __sip_autodestruct,
16812                                      expire_register,
16813                                      auto_congest,
16814                                      sip_reg_timeout,
16815                                      sip_poke_peer_s,
16816                                      sip_poke_noanswer,
16817                                      sip_reregister,
16818                                      sip_reinvite_retry}};
16819    
16820    switch (cmd) {
16821    case CLI_INIT:
16822       e->command = "sip show sched";
16823       e->usage =
16824          "Usage: sip show sched\n"
16825          "       Shows stats on what's in the sched queue at the moment\n";
16826       return NULL;
16827    case CLI_GENERATE:
16828       return NULL;
16829    }
16830 
16831    cbuf = ast_str_alloca(2048);
16832 
16833    ast_cli(a->fd, "\n");
16834    ast_sched_report(sched, &cbuf, &cbnames);
16835    ast_cli(a->fd, "%s", cbuf->str);
16836 
16837    return CLI_SUCCESS;
16838 }
16839 
16840 /*! \brief  Show SIP Registry (registrations with other SIP proxies */
16841 static char *sip_show_registry(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16842 {
16843 #define FORMAT2 "%-39.39s %-6.6s %-12.12s  %8.8s %-20.20s %-25.25s\n"
16844 #define FORMAT  "%-39.39s %-6.6s %-12.12s  %8d %-20.20s %-25.25s\n"
16845    char host[80];
16846    char user[80];
16847    char tmpdat[256];
16848    struct ast_tm tm;
16849    int counter = 0;
16850 
16851    switch (cmd) {
16852    case CLI_INIT:
16853       e->command = "sip show registry";
16854       e->usage =
16855          "Usage: sip show registry\n"
16856          "       Lists all registration requests and status.\n";
16857       return NULL;
16858    case CLI_GENERATE:
16859       return NULL;
16860    }
16861 
16862    if (a->argc != 3)
16863       return CLI_SHOWUSAGE;
16864    ast_cli(a->fd, FORMAT2, "Host", "dnsmgr", "Username", "Refresh", "State", "Reg.Time");
16865    
16866    ASTOBJ_CONTAINER_TRAVERSE(&regl, 1, do {
16867       ASTOBJ_RDLOCK(iterator);
16868       snprintf(host, sizeof(host), "%s:%d", iterator->hostname, iterator->portno ? iterator->portno : STANDARD_SIP_PORT);
16869       snprintf(user, sizeof(user), "%s", iterator->username);
16870       if (!ast_strlen_zero(iterator->regdomain)) {
16871          snprintf(tmpdat, sizeof(tmpdat), "%s", user);
16872          snprintf(user, sizeof(user), "%s@%s", tmpdat, iterator->regdomain);}
16873       if (iterator->regdomainport) {
16874          snprintf(tmpdat, sizeof(tmpdat), "%s", user);
16875          snprintf(user, sizeof(user), "%s:%d", tmpdat, iterator->regdomainport);}
16876       if (iterator->regtime.tv_sec) {
16877          ast_localtime(&iterator->regtime, &tm, NULL);
16878          ast_strftime(tmpdat, sizeof(tmpdat), "%a, %d %b %Y %T", &tm);
16879       } else
16880          tmpdat[0] = '\0';
16881       ast_cli(a->fd, FORMAT, host, (iterator->dnsmgr) ? "Y" : "N", user, iterator->refresh, regstate2str(iterator->regstate), tmpdat);
16882       ASTOBJ_UNLOCK(iterator);
16883       counter++;
16884    } while(0));
16885    ast_cli(a->fd, "%d SIP registrations.\n", counter);
16886    return CLI_SUCCESS;
16887 #undef FORMAT
16888 #undef FORMAT2
16889 }
16890 
16891 /*! \brief Unregister (force expiration) a SIP peer in the registry via CLI
16892    \note This function does not tell the SIP device what's going on,
16893    so use it with great care.
16894 */
16895 static char *sip_unregister(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16896 {
16897    struct sip_peer *peer;
16898    int load_realtime = 0;
16899 
16900    switch (cmd) {
16901    case CLI_INIT:
16902       e->command = "sip unregister";
16903       e->usage =
16904          "Usage: sip unregister <peer>\n"
16905          "       Unregister (force expiration) a SIP peer from the registry\n";
16906       return NULL;
16907    case CLI_GENERATE:
16908       return complete_sip_unregister(a->line, a->word, a->pos, a->n);
16909    }
16910    
16911    if (a->argc != 3)
16912       return CLI_SHOWUSAGE;
16913    
16914    if ((peer = find_peer(a->argv[2], NULL, load_realtime, FINDPEERS, TRUE, 0))) {
16915       if (peer->expire > 0) {
16916          AST_SCHED_DEL_UNREF(sched, peer->expire,
16917             unref_peer(peer, "remove register expire ref"));
16918          expire_register(ref_peer(peer, "ref for expire_register"));
16919          ast_cli(a->fd, "Unregistered peer \'%s\'\n\n", a->argv[2]);
16920       } else {
16921          ast_cli(a->fd, "Peer %s not registered\n", a->argv[2]);
16922       }
16923       unref_peer(peer, "sip_unregister: unref_peer via sip_unregister: done with peer from find_peer call");
16924    } else {
16925       ast_cli(a->fd, "Peer unknown: \'%s\'. Not unregistered.\n", a->argv[2]);
16926    }
16927    
16928    return CLI_SUCCESS;
16929 }
16930 
16931 /*! \brief Callback for show_chanstats */
16932 static int show_chanstats_cb(void *__cur, void *__arg, int flags)
16933 {
16934 #define FORMAT2 "%-15.15s  %-11.11s  %-8.8s %-10.10s  %-10.10s (     %%) %-6.6s %-10.10s  %-10.10s (     %%) %-6.6s\n"
16935 #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"
16936    struct sip_pvt *cur = __cur;
16937    struct ast_rtp_instance_stats stats;
16938    char durbuf[10];
16939    int duration;
16940    int durh, durm, durs;
16941    struct ast_channel *c = cur->owner;
16942    struct __show_chan_arg *arg = __arg;
16943    int fd = arg->fd;
16944 
16945 
16946    if (cur->subscribed != NONE) /* Subscriptions */
16947       return 0;   /* don't care, we scan all channels */
16948 
16949    if (!cur->rtp) {
16950       if (sipdebug) {
16951          ast_cli(fd, "%-15.15s  %-11.11s (inv state: %s) -- %s\n",
16952             ast_sockaddr_stringify_addr(&cur->sa), cur->callid,
16953             invitestate2string[cur->invitestate].desc,
16954             "-- No RTP active");
16955       }
16956       return 0;   /* don't care, we scan all channels */
16957    }
16958 
16959    ast_rtp_instance_get_stats(cur->rtp, &stats, AST_RTP_INSTANCE_STAT_ALL);
16960 
16961    if (c && c->cdr && !ast_tvzero(c->cdr->start)) {
16962       duration = (int)(ast_tvdiff_ms(ast_tvnow(), c->cdr->start) / 1000);
16963       durh = duration / 3600;
16964       durm = (duration % 3600) / 60;
16965       durs = duration % 60;
16966       snprintf(durbuf, sizeof(durbuf), "%02d:%02d:%02d", durh, durm, durs);
16967    } else {
16968       durbuf[0] = '\0';
16969    }
16970 
16971    ast_cli(fd, FORMAT,
16972       ast_sockaddr_stringify_addr(&cur->sa),
16973       cur->callid,
16974       durbuf,
16975       stats.rxcount > (unsigned int) 100000 ? (unsigned int) (stats.rxcount)/(unsigned int) 1000 : stats.rxcount,
16976       stats.rxcount > (unsigned int) 100000 ? "K":" ",
16977       stats.rxploss,
16978       (stats.rxcount + stats.rxploss) > 0 ? (double) stats.rxploss / (stats.rxcount + stats.rxploss) * 100 : 0,
16979       stats.rxjitter,
16980       stats.txcount > (unsigned int) 100000 ? (unsigned int) (stats.txcount)/(unsigned int) 1000 : stats.txcount,
16981       stats.txcount > (unsigned int) 100000 ? "K":" ",
16982       stats.txploss,
16983       stats.txcount > 0 ? (double) stats.txploss / stats.txcount * 100 : 0,
16984       stats.txjitter
16985    );
16986    arg->numchans++;
16987 
16988    return 0;   /* don't care, we scan all channels */
16989 }
16990 
16991 /*! \brief SIP show channelstats CLI (main function) */
16992 static char *sip_show_channelstats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16993 {
16994    struct __show_chan_arg arg = { .fd = a->fd, .numchans = 0 };
16995 
16996    switch (cmd) {
16997    case CLI_INIT:
16998       e->command = "sip show channelstats";
16999       e->usage =
17000          "Usage: sip show channelstats\n"
17001          "       Lists all currently active SIP channel's RTCP statistics.\n"
17002          "       Note that calls in the much optimized RTP P2P bridge mode will not show any packets here.";
17003       return NULL;
17004    case CLI_GENERATE:
17005       return NULL;
17006    }
17007 
17008    if (a->argc != 3)
17009       return CLI_SHOWUSAGE;
17010 
17011    ast_cli(a->fd, FORMAT2, "Peer", "Call ID", "Duration", "Recv: Pack", "Lost", "Jitter", "Send: Pack", "Lost", "Jitter");
17012    /* iterate on the container and invoke the callback on each item */
17013    ao2_t_callback(dialogs, OBJ_NODATA, show_chanstats_cb, &arg, "callback to sip show chanstats");
17014    ast_cli(a->fd, "%d active SIP channel%s\n", arg.numchans, (arg.numchans != 1) ? "s" : "");
17015    return CLI_SUCCESS;
17016 }
17017 #undef FORMAT
17018 #undef FORMAT2
17019 
17020 /*! \brief List global settings for the SIP channel */
17021 static char *sip_show_settings(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
17022 {
17023    int realtimepeers;
17024    int realtimeregs;
17025    char codec_buf[SIPBUFSIZE];
17026    const char *msg;  /* temporary msg pointer */
17027 
17028    switch (cmd) {
17029    case CLI_INIT:
17030       e->command = "sip show settings";
17031       e->usage =
17032          "Usage: sip show settings\n"
17033          "       Provides detailed list of the configuration of the SIP channel.\n";
17034       return NULL;
17035    case CLI_GENERATE:
17036       return NULL;
17037    }
17038 
17039 
17040    realtimepeers = ast_check_realtime("sippeers");
17041    realtimeregs = ast_check_realtime("sipregs");
17042 
17043    if (a->argc != 3)
17044       return CLI_SHOWUSAGE;
17045    ast_cli(a->fd, "\n\nGlobal Settings:\n");
17046    ast_cli(a->fd, "----------------\n");
17047    ast_cli(a->fd, "  UDP Bindaddress:        %s\n", ast_sockaddr_stringify(&bindaddr));
17048    if (ast_sockaddr_is_ipv6(&bindaddr) && ast_sockaddr_is_any(&bindaddr)) {
17049       ast_cli(a->fd, "  ** Additional Info:\n");
17050       ast_cli(a->fd, "     [::] may include IPv4 in addition to IPv6, if such a feature is enabled in the OS.\n");
17051    }
17052    ast_cli(a->fd, "  TCP SIP Bindaddress:    %s\n",
17053       sip_cfg.tcp_enabled != FALSE ?
17054             ast_sockaddr_stringify(&sip_tcp_desc.local_address) :
17055             "Disabled");
17056    ast_cli(a->fd, "  TLS SIP Bindaddress:    %s\n",
17057       default_tls_cfg.enabled != FALSE ?
17058             ast_sockaddr_stringify(&sip_tls_desc.local_address) :
17059             "Disabled");
17060    ast_cli(a->fd, "  Videosupport:           %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_VIDEOSUPPORT)));
17061    ast_cli(a->fd, "  Textsupport:            %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_TEXTSUPPORT)));
17062    ast_cli(a->fd, "  Ignore SDP sess. ver.:  %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_IGNORESDPVERSION)));
17063    ast_cli(a->fd, "  AutoCreate Peer:        %s\n", AST_CLI_YESNO(sip_cfg.autocreatepeer));
17064    ast_cli(a->fd, "  Match Auth Username:    %s\n", AST_CLI_YESNO(global_match_auth_username));
17065    ast_cli(a->fd, "  Allow unknown access:   %s\n", AST_CLI_YESNO(sip_cfg.allowguest));
17066    ast_cli(a->fd, "  Allow subscriptions:    %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)));
17067    ast_cli(a->fd, "  Allow overlap dialing:  %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP)));
17068    ast_cli(a->fd, "  Allow promsic. redir:   %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[0], SIP_PROMISCREDIR)));
17069    ast_cli(a->fd, "  Enable call counters:   %s\n", AST_CLI_YESNO(global_callcounter));
17070    ast_cli(a->fd, "  SIP domain support:     %s\n", AST_CLI_YESNO(!AST_LIST_EMPTY(&domain_list)));
17071    ast_cli(a->fd, "  Realm. auth:            %s\n", AST_CLI_YESNO(authl != NULL));
17072    ast_cli(a->fd, "  Our auth realm          %s\n", sip_cfg.realm);
17073    ast_cli(a->fd, "  Use domains as realms:  %s\n", AST_CLI_YESNO(sip_cfg.domainsasrealm));
17074    ast_cli(a->fd, "  Call to non-local dom.: %s\n", AST_CLI_YESNO(sip_cfg.allow_external_domains));
17075    ast_cli(a->fd, "  URI user is phone no:   %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[0], SIP_USEREQPHONE)));
17076    ast_cli(a->fd, "  Always auth rejects:    %s\n", AST_CLI_YESNO(sip_cfg.alwaysauthreject));
17077    ast_cli(a->fd, "  Direct RTP setup:       %s\n", AST_CLI_YESNO(sip_cfg.directrtpsetup));
17078    ast_cli(a->fd, "  User Agent:             %s\n", global_useragent);
17079    ast_cli(a->fd, "  SDP Session Name:       %s\n", ast_strlen_zero(global_sdpsession) ? "-" : global_sdpsession);
17080    ast_cli(a->fd, "  SDP Owner Name:         %s\n", ast_strlen_zero(global_sdpowner) ? "-" : global_sdpowner);
17081    ast_cli(a->fd, "  Reg. context:           %s\n", S_OR(sip_cfg.regcontext, "(not set)"));
17082    ast_cli(a->fd, "  Regexten on Qualify:    %s\n", AST_CLI_YESNO(sip_cfg.regextenonqualify));
17083    ast_cli(a->fd, "  Caller ID:              %s\n", default_callerid);
17084    if ((default_fromdomainport) && (default_fromdomainport != STANDARD_SIP_PORT)) {
17085       ast_cli(a->fd, "  From: Domain:           %s:%d\n", default_fromdomain, default_fromdomainport);
17086    } else {
17087       ast_cli(a->fd, "  From: Domain:           %s\n", default_fromdomain);
17088    }
17089    ast_cli(a->fd, "  Record SIP history:     %s\n", AST_CLI_ONOFF(recordhistory));
17090    ast_cli(a->fd, "  Call Events:            %s\n", AST_CLI_ONOFF(sip_cfg.callevents));
17091    ast_cli(a->fd, "  Auth. Failure Events:   %s\n", AST_CLI_ONOFF(global_authfailureevents));
17092 
17093    ast_cli(a->fd, "  T.38 support:           %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_T38SUPPORT)));
17094    ast_cli(a->fd, "  T.38 EC mode:           %s\n", faxec2str(ast_test_flag(&global_flags[1], SIP_PAGE2_T38SUPPORT)));
17095    ast_cli(a->fd, "  T.38 MaxDtgrm:          %d\n", global_t38_maxdatagram);
17096    if (!realtimepeers && !realtimeregs)
17097       ast_cli(a->fd, "  SIP realtime:           Disabled\n" );
17098    else
17099       ast_cli(a->fd, "  SIP realtime:           Enabled\n" );
17100    ast_cli(a->fd, "  Qualify Freq :          %d ms\n", global_qualifyfreq);
17101    ast_cli(a->fd, "  Q.850 Reason header:    %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_Q850_REASON)));
17102    ast_cli(a->fd, "\nNetwork QoS Settings:\n");
17103    ast_cli(a->fd, "---------------------------\n");
17104    ast_cli(a->fd, "  IP ToS SIP:             %s\n", ast_tos2str(global_tos_sip));
17105    ast_cli(a->fd, "  IP ToS RTP audio:       %s\n", ast_tos2str(global_tos_audio));
17106    ast_cli(a->fd, "  IP ToS RTP video:       %s\n", ast_tos2str(global_tos_video));
17107    ast_cli(a->fd, "  IP ToS RTP text:        %s\n", ast_tos2str(global_tos_text));
17108    ast_cli(a->fd, "  802.1p CoS SIP:         %d\n", global_cos_sip);
17109    ast_cli(a->fd, "  802.1p CoS RTP audio:   %d\n", global_cos_audio);
17110    ast_cli(a->fd, "  802.1p CoS RTP video:   %d\n", global_cos_video);
17111    ast_cli(a->fd, "  802.1p CoS RTP text:    %d\n", global_cos_text);
17112    ast_cli(a->fd, "  Jitterbuffer enabled:   %s\n", AST_CLI_YESNO(ast_test_flag(&global_jbconf, AST_JB_ENABLED)));
17113    ast_cli(a->fd, "  Jitterbuffer forced:    %s\n", AST_CLI_YESNO(ast_test_flag(&global_jbconf, AST_JB_FORCED)));
17114    ast_cli(a->fd, "  Jitterbuffer max size:  %ld\n", global_jbconf.max_size);
17115    ast_cli(a->fd, "  Jitterbuffer resync:    %ld\n", global_jbconf.resync_threshold);
17116    ast_cli(a->fd, "  Jitterbuffer impl:      %s\n", global_jbconf.impl);
17117    ast_cli(a->fd, "  Jitterbuffer log:       %s\n", AST_CLI_YESNO(ast_test_flag(&global_jbconf, AST_JB_LOG)));
17118 
17119    ast_cli(a->fd, "\nNetwork Settings:\n");
17120    ast_cli(a->fd, "---------------------------\n");
17121    /* determine if/how SIP address can be remapped */
17122    if (localaddr == NULL)
17123       msg = "Disabled, no localnet list";
17124    else if (ast_sockaddr_isnull(&externaddr))
17125       msg = "Disabled";
17126    else if (!ast_strlen_zero(externhost))
17127       msg = "Enabled using externhost";
17128    else
17129       msg = "Enabled using externaddr";
17130    ast_cli(a->fd, "  SIP address remapping:  %s\n", msg);
17131    ast_cli(a->fd, "  Externhost:             %s\n", S_OR(externhost, "<none>"));
17132    ast_cli(a->fd, "  externaddr:               %s\n", ast_sockaddr_stringify(&externaddr));
17133    ast_cli(a->fd, "  Externrefresh:          %d\n", externrefresh);
17134    {
17135       struct ast_ha *d;
17136       const char *prefix = "Localnet:";
17137 
17138       for (d = localaddr; d ; prefix = "", d = d->next) {
17139          const char *addr = ast_strdupa(ast_sockaddr_stringify_addr(&d->addr));
17140          const char *mask = ast_strdupa(ast_sockaddr_stringify_addr(&d->netmask));
17141          ast_cli(a->fd, "  %-24s%s/%s\n", prefix, addr, mask);
17142       }
17143    }
17144    ast_cli(a->fd, "\nGlobal Signalling Settings:\n");
17145    ast_cli(a->fd, "---------------------------\n");
17146    ast_cli(a->fd, "  Codecs:                 ");
17147    ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, sip_cfg.capability);
17148    ast_cli(a->fd, "%s\n", codec_buf);
17149    ast_cli(a->fd, "  Codec Order:            ");
17150    print_codec_to_cli(a->fd, &default_prefs);
17151    ast_cli(a->fd, "\n");
17152    ast_cli(a->fd, "  Relax DTMF:             %s\n", AST_CLI_YESNO(global_relaxdtmf));
17153    ast_cli(a->fd, "  RFC2833 Compensation:   %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_RFC2833_COMPENSATE)));
17154    ast_cli(a->fd, "  Symmetric RTP:          %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_SYMMETRICRTP)));
17155    ast_cli(a->fd, "  Compact SIP headers:    %s\n", AST_CLI_YESNO(sip_cfg.compactheaders));
17156    ast_cli(a->fd, "  RTP Keepalive:          %d %s\n", global_rtpkeepalive, global_rtpkeepalive ? "" : "(Disabled)" );
17157    ast_cli(a->fd, "  RTP Timeout:            %d %s\n", global_rtptimeout, global_rtptimeout ? "" : "(Disabled)" );
17158    ast_cli(a->fd, "  RTP Hold Timeout:       %d %s\n", global_rtpholdtimeout, global_rtpholdtimeout ? "" : "(Disabled)");
17159    ast_cli(a->fd, "  MWI NOTIFY mime type:   %s\n", default_notifymime);
17160    ast_cli(a->fd, "  DNS SRV lookup:         %s\n", AST_CLI_YESNO(sip_cfg.srvlookup));
17161    ast_cli(a->fd, "  Pedantic SIP support:   %s\n", AST_CLI_YESNO(sip_cfg.pedanticsipchecking));
17162    ast_cli(a->fd, "  Reg. min duration       %d secs\n", min_expiry);
17163    ast_cli(a->fd, "  Reg. max duration:      %d secs\n", max_expiry);
17164    ast_cli(a->fd, "  Reg. default duration:  %d secs\n", default_expiry);
17165    ast_cli(a->fd, "  Outbound reg. timeout:  %d secs\n", global_reg_timeout);
17166    ast_cli(a->fd, "  Outbound reg. attempts: %d\n", global_regattempts_max);
17167    ast_cli(a->fd, "  Notify ringing state:   %s\n", AST_CLI_YESNO(sip_cfg.notifyringing));
17168    if (sip_cfg.notifyringing) {
17169       ast_cli(a->fd, "    Include CID:          %s%s\n",
17170             AST_CLI_YESNO(sip_cfg.notifycid),
17171             sip_cfg.notifycid == IGNORE_CONTEXT ? " (Ignoring context)" : "");
17172    }
17173    ast_cli(a->fd, "  Notify hold state:      %s\n", AST_CLI_YESNO(sip_cfg.notifyhold));
17174    ast_cli(a->fd, "  SIP Transfer mode:      %s\n", transfermode2str(sip_cfg.allowtransfer));
17175    ast_cli(a->fd, "  Max Call Bitrate:       %d kbps\n", default_maxcallbitrate);
17176    ast_cli(a->fd, "  Auto-Framing:           %s\n", AST_CLI_YESNO(global_autoframing));
17177    ast_cli(a->fd, "  Outb. proxy:            %s %s\n", ast_strlen_zero(sip_cfg.outboundproxy.name) ? "<not set>" : sip_cfg.outboundproxy.name,
17178                      sip_cfg.outboundproxy.force ? "(forced)" : "");
17179    ast_cli(a->fd, "  Session Timers:         %s\n", stmode2str(global_st_mode));
17180    ast_cli(a->fd, "  Session Refresher:      %s\n", strefresher2str (global_st_refresher));
17181    ast_cli(a->fd, "  Session Expires:        %d secs\n", global_max_se);
17182    ast_cli(a->fd, "  Session Min-SE:         %d secs\n", global_min_se);
17183    ast_cli(a->fd, "  Timer T1:               %d\n", global_t1);
17184    ast_cli(a->fd, "  Timer T1 minimum:       %d\n", global_t1min);
17185    ast_cli(a->fd, "  Timer B:                %d\n", global_timer_b);
17186    ast_cli(a->fd, "  No premature media:     %s\n", AST_CLI_YESNO(global_prematuremediafilter));
17187    ast_cli(a->fd, "  Max forwards:           %d\n", sip_cfg.default_max_forwards);
17188 
17189    ast_cli(a->fd, "\nDefault Settings:\n");
17190    ast_cli(a->fd, "-----------------\n");
17191    ast_cli(a->fd, "  Allowed transports:     %s\n", get_transport_list(default_transports));
17192    ast_cli(a->fd, "  Outbound transport:    %s\n", get_transport(default_primary_transport));
17193    ast_cli(a->fd, "  Context:                %s\n", sip_cfg.default_context);
17194    ast_cli(a->fd, "  Force rport:            %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[0], SIP_NAT_FORCE_RPORT)));
17195    ast_cli(a->fd, "  DTMF:                   %s\n", dtmfmode2str(ast_test_flag(&global_flags[0], SIP_DTMF)));
17196    ast_cli(a->fd, "  Qualify:                %d\n", default_qualify);
17197    ast_cli(a->fd, "  Use ClientCode:         %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[0], SIP_USECLIENTCODE)));
17198    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)));
17199    ast_cli(a->fd, "  Language:               %s\n", default_language);
17200    ast_cli(a->fd, "  MOH Interpret:          %s\n", default_mohinterpret);
17201    ast_cli(a->fd, "  MOH Suggest:            %s\n", default_mohsuggest);
17202    ast_cli(a->fd, "  Voice Mail Extension:   %s\n", default_vmexten);
17203 
17204    
17205    if (realtimepeers || realtimeregs) {
17206       ast_cli(a->fd, "\nRealtime SIP Settings:\n");
17207       ast_cli(a->fd, "----------------------\n");
17208       ast_cli(a->fd, "  Realtime Peers:         %s\n", AST_CLI_YESNO(realtimepeers));
17209       ast_cli(a->fd, "  Realtime Regs:          %s\n", AST_CLI_YESNO(realtimeregs));
17210       ast_cli(a->fd, "  Cache Friends:          %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)));
17211       ast_cli(a->fd, "  Update:                 %s\n", AST_CLI_YESNO(sip_cfg.peer_rtupdate));
17212       ast_cli(a->fd, "  Ignore Reg. Expire:     %s\n", AST_CLI_YESNO(sip_cfg.ignore_regexpire));
17213       ast_cli(a->fd, "  Save sys. name:         %s\n", AST_CLI_YESNO(sip_cfg.rtsave_sysname));
17214       ast_cli(a->fd, "  Auto Clear:             %d (%s)\n", sip_cfg.rtautoclear, ast_test_flag(&global_flags[1], SIP_PAGE2_RTAUTOCLEAR) ? "Enabled" : "Disabled");
17215    }
17216    ast_cli(a->fd, "\n----\n");
17217    return CLI_SUCCESS;
17218 }
17219 
17220 static char *sip_show_mwi(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
17221 {
17222 #define FORMAT  "%-30.30s  %-12.12s  %-10.10s  %-10.10s\n"
17223    char host[80];
17224    
17225    switch (cmd) {
17226    case CLI_INIT:
17227       e->command = "sip show mwi";
17228       e->usage =
17229          "Usage: sip show mwi\n"
17230          "       Provides a list of MWI subscriptions and status.\n";
17231       return NULL;
17232    case CLI_GENERATE:
17233       return NULL;
17234    }
17235    
17236    ast_cli(a->fd, FORMAT, "Host", "Username", "Mailbox", "Subscribed");
17237    
17238    ASTOBJ_CONTAINER_TRAVERSE(&submwil, 1, do {
17239       ASTOBJ_RDLOCK(iterator);
17240       snprintf(host, sizeof(host), "%s:%d", iterator->hostname, iterator->portno ? iterator->portno : STANDARD_SIP_PORT);
17241       ast_cli(a->fd, FORMAT, host, iterator->username, iterator->mailbox, AST_CLI_YESNO(iterator->subscribed));
17242       ASTOBJ_UNLOCK(iterator);
17243    } while(0));
17244 
17245    return CLI_SUCCESS;
17246 #undef FORMAT
17247 }
17248 
17249 
17250 /*! \brief Show subscription type in string format */
17251 static const char *subscription_type2str(enum subscriptiontype subtype)
17252 {
17253    int i;
17254 
17255    for (i = 1; i < ARRAY_LEN(subscription_types); i++) {
17256       if (subscription_types[i].type == subtype) {
17257          return subscription_types[i].text;
17258       }
17259    }
17260    return subscription_types[0].text;
17261 }
17262 
17263 /*! \brief Find subscription type in array */
17264 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype)
17265 {
17266    int i;
17267 
17268    for (i = 1; i < ARRAY_LEN(subscription_types); i++) {
17269       if (subscription_types[i].type == subtype) {
17270          return &subscription_types[i];
17271       }
17272    }
17273    return &subscription_types[0];
17274 }
17275 
17276 /*
17277  * We try to structure all functions that loop on data structures as
17278  * a handler for individual entries, and a mainloop that iterates
17279  * on the main data structure. This way, moving the code to containers
17280  * that support iteration through callbacks will be a lot easier.
17281  */
17282 
17283 #define FORMAT4 "%-15.15s  %-15.15s  %-15.15s  %-15.15s  %-13.13s  %-15.15s %-10.10s %-6.6d\n"
17284 #define FORMAT3 "%-15.15s  %-15.15s  %-15.15s  %-15.15s  %-13.13s  %-15.15s %-10.10s %-6.6s\n"
17285 #define FORMAT2 "%-15.15s  %-15.15s  %-15.15s  %-15.15s  %-7.7s  %-15.15s %-10.10s %-10.10s\n"
17286 #define FORMAT  "%-15.15s  %-15.15s  %-15.15s  %-15.15s  %-3.3s %-3.3s  %-15.15s %-10.10s %-10.10s\n"
17287 
17288 /*! \brief callback for show channel|subscription */
17289 static int show_channels_cb(void *__cur, void *__arg, int flags)
17290 {
17291    struct sip_pvt *cur = __cur;
17292    struct __show_chan_arg *arg = __arg;
17293    const struct ast_sockaddr *dst = sip_real_dst(cur);
17294    
17295    /* XXX indentation preserved to reduce diff. Will be fixed later */
17296    if (cur->subscribed == NONE && !arg->subscriptions) {
17297       /* set if SIP transfer in progress */
17298       const char *referstatus = cur->refer ? referstatus2str(cur->refer->status) : "";
17299       char formatbuf[SIPBUFSIZE/2];
17300       
17301       ast_cli(arg->fd, FORMAT, ast_sockaddr_stringify_addr(dst),
17302             S_OR(cur->username, S_OR(cur->cid_num, "(None)")),
17303             cur->callid,
17304             ast_getformatname_multiple(formatbuf, sizeof(formatbuf), cur->owner ? cur->owner->nativeformats : 0),
17305             AST_CLI_YESNO(ast_test_flag(&cur->flags[1], SIP_PAGE2_CALL_ONHOLD)),
17306             cur->needdestroy ? "(d)" : "",
17307             cur->lastmsg ,
17308             referstatus,
17309             cur->relatedpeer ? cur->relatedpeer->name : "<guest>"
17310          );
17311       arg->numchans++;
17312    }
17313    if (cur->subscribed != NONE && arg->subscriptions) {
17314       struct ast_str *mailbox_str = ast_str_alloca(512);
17315       if (cur->subscribed == MWI_NOTIFICATION && cur->relatedpeer)
17316          peer_mailboxes_to_str(&mailbox_str, cur->relatedpeer);
17317       ast_cli(arg->fd, FORMAT4, ast_sockaddr_stringify_addr(dst),
17318             S_OR(cur->username, S_OR(cur->cid_num, "(None)")),
17319                cur->callid,
17320             /* the 'complete' exten/context is hidden in the refer_to field for subscriptions */
17321             cur->subscribed == MWI_NOTIFICATION ? "--" : cur->subscribeuri,
17322             cur->subscribed == MWI_NOTIFICATION ? "<none>" : ast_extension_state2str(cur->laststate),
17323             subscription_type2str(cur->subscribed),
17324             cur->subscribed == MWI_NOTIFICATION ? S_OR(mailbox_str->str, "<none>") : "<none>",
17325             cur->expiry
17326          );
17327       arg->numchans++;
17328    }
17329    return 0;   /* don't care, we scan all channels */
17330 }
17331 
17332 /*! \brief CLI for show channels or subscriptions.
17333  * This is a new-style CLI handler so a single function contains
17334  * the prototype for the function, the 'generator' to produce multiple
17335  * entries in case it is required, and the actual handler for the command.
17336  */
17337 static char *sip_show_channels(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
17338 {
17339    struct __show_chan_arg arg = { .fd = a->fd, .numchans = 0 };
17340 
17341 
17342    if (cmd == CLI_INIT) {
17343       e->command = "sip show {channels|subscriptions}";
17344       e->usage =
17345          "Usage: sip show channels\n"
17346          "       Lists all currently active SIP calls (dialogs).\n"
17347          "Usage: sip show subscriptions\n"
17348          "       Lists active SIP subscriptions.\n";
17349       return NULL;
17350    } else if (cmd == CLI_GENERATE)
17351       return NULL;
17352 
17353    if (a->argc != e->args)
17354       return CLI_SHOWUSAGE;
17355    arg.subscriptions = !strcasecmp(a->argv[e->args - 1], "subscriptions");
17356    if (!arg.subscriptions)
17357       ast_cli(arg.fd, FORMAT2, "Peer", "User/ANR", "Call ID", "Format", "Hold", "Last Message", "Expiry", "Peer");
17358    else
17359       ast_cli(arg.fd, FORMAT3, "Peer", "User", "Call ID", "Extension", "Last state", "Type", "Mailbox", "Expiry");
17360 
17361    /* iterate on the container and invoke the callback on each item */
17362    ao2_t_callback(dialogs, OBJ_NODATA, show_channels_cb, &arg, "callback to show channels");
17363    
17364    /* print summary information */
17365    ast_cli(arg.fd, "%d active SIP %s%s\n", arg.numchans,
17366       (arg.subscriptions ? "subscription" : "dialog"),
17367       ESS(arg.numchans));  /* ESS(n) returns an "s" if n>1 */
17368    return CLI_SUCCESS;
17369 #undef FORMAT
17370 #undef FORMAT2
17371 #undef FORMAT3
17372 }
17373 
17374 /*! \brief Support routine for 'sip show channel' and 'sip show history' CLI
17375  * This is in charge of generating all strings that match a prefix in the
17376  * given position. As many functions of this kind, each invokation has
17377  * O(state) time complexity so be careful in using it.
17378  */
17379 static char *complete_sipch(const char *line, const char *word, int pos, int state)
17380 {
17381    int which=0;
17382    struct sip_pvt *cur;
17383    char *c = NULL;
17384    int wordlen = strlen(word);
17385    struct ao2_iterator i;
17386 
17387    if (pos != 3) {
17388       return NULL;
17389    }
17390 
17391    i = ao2_iterator_init(dialogs, 0);
17392    while ((cur = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
17393       sip_pvt_lock(cur);
17394       if (!strncasecmp(word, cur->callid, wordlen) && ++which > state) {
17395          c = ast_strdup(cur->callid);
17396          sip_pvt_unlock(cur);
17397          dialog_unref(cur, "drop ref in iterator loop break");
17398          break;
17399       }
17400       sip_pvt_unlock(cur);
17401       dialog_unref(cur, "drop ref in iterator loop");
17402    }
17403    ao2_iterator_destroy(&i);
17404    return c;
17405 }
17406 
17407 
17408 /*! \brief Do completion on peer name */
17409 static char *complete_sip_peer(const char *word, int state, int flags2)
17410 {
17411    char *result = NULL;
17412    int wordlen = strlen(word);
17413    int which = 0;
17414    struct ao2_iterator i = ao2_iterator_init(peers, 0);
17415    struct sip_peer *peer;
17416 
17417    while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
17418       /* locking of the object is not required because only the name and flags are being compared */
17419       if (!strncasecmp(word, peer->name, wordlen) &&
17420             (!flags2 || ast_test_flag(&peer->flags[1], flags2)) &&
17421             ++which > state)
17422          result = ast_strdup(peer->name);
17423       unref_peer(peer, "toss iterator peer ptr before break");
17424       if (result) {
17425          break;
17426       }
17427    }
17428    ao2_iterator_destroy(&i);
17429    return result;
17430 }
17431 
17432 /*! \brief Do completion on registered peer name */
17433 static char *complete_sip_registered_peer(const char *word, int state, int flags2)
17434 {
17435        char *result = NULL;
17436        int wordlen = strlen(word);
17437        int which = 0;
17438        struct ao2_iterator i;
17439        struct sip_peer *peer;
17440        
17441        i = ao2_iterator_init(peers, 0);
17442        while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
17443           if (!strncasecmp(word, peer->name, wordlen) &&
17444          (!flags2 || ast_test_flag(&peer->flags[1], flags2)) &&
17445          ++which > state && peer->expire > 0)
17446              result = ast_strdup(peer->name);
17447           if (result) {
17448              unref_peer(peer, "toss iterator peer ptr before break");
17449              break;
17450           }
17451           unref_peer(peer, "toss iterator peer ptr");
17452        }
17453        ao2_iterator_destroy(&i);
17454        return result;
17455 }
17456 
17457 /*! \brief Support routine for 'sip show history' CLI */
17458 static char *complete_sip_show_history(const char *line, const char *word, int pos, int state)
17459 {
17460    if (pos == 3)
17461       return complete_sipch(line, word, pos, state);
17462 
17463    return NULL;
17464 }
17465 
17466 /*! \brief Support routine for 'sip show peer' CLI */
17467 static char *complete_sip_show_peer(const char *line, const char *word, int pos, int state)
17468 {
17469    if (pos == 3) {
17470       return complete_sip_peer(word, state, 0);
17471    }
17472 
17473    return NULL;
17474 }
17475 
17476 /*! \brief Support routine for 'sip unregister' CLI */
17477 static char *complete_sip_unregister(const char *line, const char *word, int pos, int state)
17478 {
17479        if (pos == 2)
17480                return complete_sip_registered_peer(word, state, 0);
17481 
17482        return NULL;
17483 }
17484 
17485 /*! \brief Support routine for 'sip notify' CLI */
17486 static char *complete_sipnotify(const char *line, const char *word, int pos, int state)
17487 {
17488    char *c = NULL;
17489 
17490    if (pos == 2) {
17491       int which = 0;
17492       char *cat = NULL;
17493       int wordlen = strlen(word);
17494 
17495       /* do completion for notify type */
17496 
17497       if (!notify_types)
17498          return NULL;
17499       
17500       while ( (cat = ast_category_browse(notify_types, cat)) ) {
17501          if (!strncasecmp(word, cat, wordlen) && ++which > state) {
17502             c = ast_strdup(cat);
17503             break;
17504          }
17505       }
17506       return c;
17507    }
17508 
17509    if (pos > 2)
17510       return complete_sip_peer(word, state, 0);
17511 
17512    return NULL;
17513 }
17514 
17515 /*! \brief Show details of one active dialog */
17516 static char *sip_show_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
17517 {
17518    struct sip_pvt *cur;
17519    size_t len;
17520    int found = 0;
17521    struct ao2_iterator i;
17522 
17523    switch (cmd) {
17524    case CLI_INIT:
17525       e->command = "sip show channel";
17526       e->usage =
17527          "Usage: sip show channel <call-id>\n"
17528          "       Provides detailed status on a given SIP dialog (identified by SIP call-id).\n";
17529       return NULL;
17530    case CLI_GENERATE:
17531       return complete_sipch(a->line, a->word, a->pos, a->n);
17532    }
17533 
17534    if (a->argc != 4)
17535       return CLI_SHOWUSAGE;
17536    len = strlen(a->argv[3]);
17537    
17538    i = ao2_iterator_init(dialogs, 0);
17539    while ((cur = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
17540       sip_pvt_lock(cur);
17541 
17542       if (!strncasecmp(cur->callid, a->argv[3], len)) {
17543          char formatbuf[SIPBUFSIZE/2];
17544          ast_cli(a->fd, "\n");
17545          if (cur->subscribed != NONE)
17546             ast_cli(a->fd, "  * Subscription (type: %s)\n", subscription_type2str(cur->subscribed));
17547          else
17548             ast_cli(a->fd, "  * SIP Call\n");
17549          ast_cli(a->fd, "  Curr. trans. direction:  %s\n", ast_test_flag(&cur->flags[0], SIP_OUTGOING) ? "Outgoing" : "Incoming");
17550          ast_cli(a->fd, "  Call-ID:                %s\n", cur->callid);
17551          ast_cli(a->fd, "  Owner channel ID:       %s\n", cur->owner ? cur->owner->name : "<none>");
17552          ast_cli(a->fd, "  Our Codec Capability:   %s\n", ast_getformatname_multiple(formatbuf, sizeof(formatbuf), cur->capability));
17553          ast_cli(a->fd, "  Non-Codec Capability (DTMF):   %d\n", cur->noncodeccapability);
17554          ast_cli(a->fd, "  Their Codec Capability:   %s\n", ast_getformatname_multiple(formatbuf, sizeof(formatbuf), cur->peercapability));
17555          ast_cli(a->fd, "  Joint Codec Capability:   %s\n", ast_getformatname_multiple(formatbuf, sizeof(formatbuf), cur->jointcapability));
17556          ast_cli(a->fd, "  Format:                 %s\n", ast_getformatname_multiple(formatbuf, sizeof(formatbuf), cur->owner ? cur->owner->nativeformats : 0) );
17557          ast_cli(a->fd, "  T.38 support            %s\n", AST_CLI_YESNO(cur->udptl != NULL));
17558          ast_cli(a->fd, "  Video support           %s\n", AST_CLI_YESNO(cur->vrtp != NULL));
17559          ast_cli(a->fd, "  MaxCallBR:              %d kbps\n", cur->maxcallbitrate);
17560          ast_cli(a->fd, "  Theoretical Address:    %s\n", ast_sockaddr_stringify(&cur->sa));
17561          ast_cli(a->fd, "  Received Address:       %s\n", ast_sockaddr_stringify(&cur->recv));
17562          ast_cli(a->fd, "  SIP Transfer mode:      %s\n", transfermode2str(cur->allowtransfer));
17563          ast_cli(a->fd, "  Force rport:            %s\n", AST_CLI_YESNO(ast_test_flag(&cur->flags[0], SIP_NAT_FORCE_RPORT)));
17564          if (ast_sockaddr_isnull(&cur->redirip)) {
17565             ast_cli(a->fd,
17566                "  Audio IP:               %s (local)\n",
17567                ast_sockaddr_stringify_addr(&cur->ourip));
17568          } else {
17569             ast_cli(a->fd,
17570                "  Audio IP:               %s (Outside bridge)\n",
17571                ast_sockaddr_stringify_addr(&cur->redirip));
17572          }
17573          ast_cli(a->fd, "  Our Tag:                %s\n", cur->tag);
17574          ast_cli(a->fd, "  Their Tag:              %s\n", cur->theirtag);
17575          ast_cli(a->fd, "  SIP User agent:         %s\n", cur->useragent);
17576          if (!ast_strlen_zero(cur->username))
17577             ast_cli(a->fd, "  Username:               %s\n", cur->username);
17578          if (!ast_strlen_zero(cur->peername))
17579             ast_cli(a->fd, "  Peername:               %s\n", cur->peername);
17580          if (!ast_strlen_zero(cur->uri))
17581             ast_cli(a->fd, "  Original uri:           %s\n", cur->uri);
17582          if (!ast_strlen_zero(cur->cid_num))
17583             ast_cli(a->fd, "  Caller-ID:              %s\n", cur->cid_num);
17584          ast_cli(a->fd, "  Need Destroy:           %s\n", AST_CLI_YESNO(cur->needdestroy));
17585          ast_cli(a->fd, "  Last Message:           %s\n", cur->lastmsg);
17586          ast_cli(a->fd, "  Promiscuous Redir:      %s\n", AST_CLI_YESNO(ast_test_flag(&cur->flags[0], SIP_PROMISCREDIR)));
17587          ast_cli(a->fd, "  Route:                  %s\n", cur->route ? cur->route->hop : "N/A");
17588          ast_cli(a->fd, "  DTMF Mode:              %s\n", dtmfmode2str(ast_test_flag(&cur->flags[0], SIP_DTMF)));
17589          ast_cli(a->fd, "  SIP Options:            ");
17590          if (cur->sipoptions) {
17591             int x;
17592             for (x = 0 ; x < ARRAY_LEN(sip_options); x++) {
17593                if (cur->sipoptions & sip_options[x].id)
17594                   ast_cli(a->fd, "%s ", sip_options[x].text);
17595             }
17596             ast_cli(a->fd, "\n");
17597          } else
17598             ast_cli(a->fd, "(none)\n");
17599 
17600          if (!cur->stimer)
17601             ast_cli(a->fd, "  Session-Timer:          Uninitiallized\n");
17602          else {
17603             ast_cli(a->fd, "  Session-Timer:          %s\n", cur->stimer->st_active ? "Active" : "Inactive");
17604             if (cur->stimer->st_active == TRUE) {
17605                ast_cli(a->fd, "  S-Timer Interval:       %d\n", cur->stimer->st_interval);
17606                ast_cli(a->fd, "  S-Timer Refresher:      %s\n", strefresher2str(cur->stimer->st_ref));
17607                ast_cli(a->fd, "  S-Timer Expirys:        %d\n", cur->stimer->st_expirys);
17608                ast_cli(a->fd, "  S-Timer Sched Id:       %d\n", cur->stimer->st_schedid);
17609                ast_cli(a->fd, "  S-Timer Peer Sts:       %s\n", cur->stimer->st_active_peer_ua ? "Active" : "Inactive");
17610                ast_cli(a->fd, "  S-Timer Cached Min-SE:  %d\n", cur->stimer->st_cached_min_se);
17611                ast_cli(a->fd, "  S-Timer Cached SE:      %d\n", cur->stimer->st_cached_max_se);
17612                ast_cli(a->fd, "  S-Timer Cached Ref:     %s\n", strefresher2str(cur->stimer->st_cached_ref));
17613                ast_cli(a->fd, "  S-Timer Cached Mode:    %s\n", stmode2str(cur->stimer->st_cached_mode));
17614             }
17615          }
17616 
17617          ast_cli(a->fd, "\n\n");
17618 
17619          found++;
17620       }
17621 
17622       sip_pvt_unlock(cur);
17623 
17624       ao2_t_ref(cur, -1, "toss dialog ptr set by iterator_next");
17625    }
17626    ao2_iterator_destroy(&i);
17627 
17628    if (!found)
17629       ast_cli(a->fd, "No such SIP Call ID starting with '%s'\n", a->argv[3]);
17630 
17631    return CLI_SUCCESS;
17632 }
17633 
17634 /*! \brief Show history details of one dialog */
17635 static char *sip_show_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
17636 {
17637    struct sip_pvt *cur;
17638    size_t len;
17639    int found = 0;
17640    struct ao2_iterator i;
17641 
17642    switch (cmd) {
17643    case CLI_INIT:
17644       e->command = "sip show history";
17645       e->usage =
17646          "Usage: sip show history <call-id>\n"
17647          "       Provides detailed dialog history on a given SIP call (specified by call-id).\n";
17648       return NULL;
17649    case CLI_GENERATE:
17650       return complete_sip_show_history(a->line, a->word, a->pos, a->n);
17651    }
17652 
17653    if (a->argc != 4)
17654       return CLI_SHOWUSAGE;
17655 
17656    if (!recordhistory)
17657       ast_cli(a->fd, "\n***Note: History recording is currently DISABLED.  Use 'sip set history on' to ENABLE.\n");
17658 
17659    len = strlen(a->argv[3]);
17660 
17661    i = ao2_iterator_init(dialogs, 0);
17662    while ((cur = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
17663       sip_pvt_lock(cur);
17664       if (!strncasecmp(cur->callid, a->argv[3], len)) {
17665          struct sip_history *hist;
17666          int x = 0;
17667 
17668          ast_cli(a->fd, "\n");
17669          if (cur->subscribed != NONE)
17670             ast_cli(a->fd, "  * Subscription\n");
17671          else
17672             ast_cli(a->fd, "  * SIP Call\n");
17673          if (cur->history)
17674             AST_LIST_TRAVERSE(cur->history, hist, list)
17675                ast_cli(a->fd, "%d. %s\n", ++x, hist->event);
17676          if (x == 0)
17677             ast_cli(a->fd, "Call '%s' has no history\n", cur->callid);
17678          found++;
17679       }
17680       sip_pvt_unlock(cur);
17681       ao2_t_ref(cur, -1, "toss dialog ptr from iterator_next");
17682    }
17683    ao2_iterator_destroy(&i);
17684 
17685    if (!found)
17686       ast_cli(a->fd, "No such SIP Call ID starting with '%s'\n", a->argv[3]);
17687 
17688    return CLI_SUCCESS;
17689 }
17690 
17691 /*! \brief Dump SIP history to debug log file at end of lifespan for SIP dialog */
17692 static void sip_dump_history(struct sip_pvt *dialog)
17693 {
17694    int x = 0;
17695    struct sip_history *hist;
17696    static int errmsg = 0;
17697 
17698    if (!dialog)
17699       return;
17700 
17701    if (!option_debug && !sipdebug) {
17702       if (!errmsg) {
17703          ast_log(LOG_NOTICE, "You must have debugging enabled (SIP or Asterisk) in order to dump SIP history.\n");
17704          errmsg = 1;
17705       }
17706       return;
17707    }
17708 
17709    ast_debug(1, "\n---------- SIP HISTORY for '%s' \n", dialog->callid);
17710    if (dialog->subscribed)
17711       ast_debug(1, "  * Subscription\n");
17712    else
17713       ast_debug(1, "  * SIP Call\n");
17714    if (dialog->history)
17715       AST_LIST_TRAVERSE(dialog->history, hist, list)
17716          ast_debug(1, "  %-3.3d. %s\n", ++x, hist->event);
17717    if (!x)
17718       ast_debug(1, "Call '%s' has no history\n", dialog->callid);
17719    ast_debug(1, "\n---------- END SIP HISTORY for '%s' \n", dialog->callid);
17720 }
17721 
17722 
17723 /*! \brief  Receive SIP INFO Message */
17724 static void handle_request_info(struct sip_pvt *p, struct sip_request *req)
17725 {
17726    char buf[1024];
17727    unsigned int event;
17728    const char *c = get_header(req, "Content-Type");
17729 
17730    /* Need to check the media/type */
17731    if (!strcasecmp(c, "application/dtmf-relay") ||
17732        !strcasecmp(c, "application/vnd.nortelnetworks.digits")) {
17733       unsigned int duration = 0;
17734 
17735       if (!p->owner) {  /* not a PBX call */
17736          transmit_response(p, "481 Call leg/transaction does not exist", req);
17737          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
17738          return;
17739       }
17740 
17741       /* Try getting the "signal=" part */
17742       if (ast_strlen_zero(c = get_body(req, "Signal", '=')) && ast_strlen_zero(c = get_body(req, "d", '='))) {
17743          ast_log(LOG_WARNING, "Unable to retrieve DTMF signal from INFO message from %s\n", p->callid);
17744          transmit_response(p, "200 OK", req); /* Should return error */
17745          return;
17746       } else {
17747          ast_copy_string(buf, c, sizeof(buf));
17748       }
17749 
17750       if (!ast_strlen_zero((c = get_body(req, "Duration", '='))))
17751          duration = atoi(c);
17752       if (!duration)
17753          duration = 100; /* 100 ms */
17754 
17755 
17756       if (ast_strlen_zero(buf)) {
17757          transmit_response(p, "200 OK", req);
17758          return;
17759       }
17760 
17761       if (buf[0] == '*')
17762          event = 10;
17763       else if (buf[0] == '#')
17764          event = 11;
17765       else if ((buf[0] >= 'A') && (buf[0] <= 'D'))
17766          event = 12 + buf[0] - 'A';
17767       else if (buf[0] == '!')
17768          event = 16;
17769       else
17770          event = atoi(buf);
17771       if (event == 16) {
17772          /* send a FLASH event */
17773          struct ast_frame f = { AST_FRAME_CONTROL, { AST_CONTROL_FLASH, } };
17774          ast_queue_frame(p->owner, &f);
17775          if (sipdebug)
17776             ast_verbose("* DTMF-relay event received: FLASH\n");
17777       } else {
17778          /* send a DTMF event */
17779          struct ast_frame f = { AST_FRAME_DTMF, };
17780          if (event < 10) {
17781             f.subclass.integer = '0' + event;
17782          } else if (event == 10) {
17783             f.subclass.integer = '*';
17784          } else if (event == 11) {
17785             f.subclass.integer = '#';
17786          } else if (event < 16) {
17787             f.subclass.integer = 'A' + (event - 12);
17788          }
17789          f.len = duration;
17790          ast_queue_frame(p->owner, &f);
17791          if (sipdebug)
17792             ast_verbose("* DTMF-relay event received: %c\n", (int) f.subclass.integer);
17793       }
17794       transmit_response(p, "200 OK", req);
17795       return;
17796    } else if (!strcasecmp(c, "application/dtmf")) {
17797       /*! \todo Note: Doesn't read the duration of the DTMF. Should be fixed. */
17798       unsigned int duration = 0;
17799 
17800       if (!p->owner) {  /* not a PBX call */
17801          transmit_response(p, "481 Call leg/transaction does not exist", req);
17802          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
17803          return;
17804       }
17805 
17806       get_msg_text(buf, sizeof(buf), req, TRUE);
17807       duration = 100; /* 100 ms */
17808 
17809       if (ast_strlen_zero(buf)) {
17810          transmit_response(p, "200 OK", req);
17811          return;
17812       }
17813       event = atoi(buf);
17814       if (event == 16) {
17815          /* send a FLASH event */
17816          struct ast_frame f = { AST_FRAME_CONTROL, { AST_CONTROL_FLASH }, };
17817          ast_queue_frame(p->owner, &f);
17818          if (sipdebug)
17819             ast_verbose("* DTMF-relay event received: FLASH\n");
17820       } else {
17821          /* send a DTMF event */
17822          struct ast_frame f = { AST_FRAME_DTMF, };
17823          if (event < 10) {
17824             f.subclass.integer = '0' + event;
17825          } else if (event == 10) {
17826             f.subclass.integer = '*';
17827          } else if (event == 11) {
17828             f.subclass.integer = '#';
17829          } else if (event < 16) {
17830             f.subclass.integer = 'A' + (event - 12);
17831          }
17832          f.len = duration;
17833          ast_queue_frame(p->owner, &f);
17834          if (sipdebug)
17835             ast_verbose("* DTMF-relay event received: %c\n", (int) f.subclass.integer);
17836       }
17837       transmit_response(p, "200 OK", req);
17838       return;
17839 
17840    } else if (!strcasecmp(c, "application/media_control+xml")) {
17841       /* Eh, we'll just assume it's a fast picture update for now */
17842       if (p->owner)
17843          ast_queue_control(p->owner, AST_CONTROL_VIDUPDATE);
17844       transmit_response(p, "200 OK", req);
17845       return;
17846    } else if (!ast_strlen_zero(c = get_header(req, "X-ClientCode"))) {
17847       /* Client code (from SNOM phone) */
17848       if (ast_test_flag(&p->flags[0], SIP_USECLIENTCODE)) {
17849          if (p->owner && p->owner->cdr)
17850             ast_cdr_setuserfield(p->owner, c);
17851          if (p->owner && ast_bridged_channel(p->owner) && ast_bridged_channel(p->owner)->cdr)
17852             ast_cdr_setuserfield(ast_bridged_channel(p->owner), c);
17853          transmit_response(p, "200 OK", req);
17854       } else {
17855          transmit_response(p, "403 Forbidden", req);
17856       }
17857       return;
17858    } else if (!ast_strlen_zero(c = get_header(req, "Record"))) {
17859       /* INFO messages generated by some phones to start/stop recording
17860          on phone calls.
17861          OEJ: I think this should be something that is enabled/disabled
17862          per device. I don't want incoming callers to record calls in my
17863          pbx.
17864       */
17865       /* first, get the feature string, if it exists */
17866       struct ast_call_feature *feat;
17867       int j;
17868       struct ast_frame f = { AST_FRAME_DTMF, };
17869 
17870       ast_rdlock_call_features();
17871       feat = ast_find_call_feature("automon");
17872       if (!feat || ast_strlen_zero(feat->exten)) {
17873          ast_log(LOG_WARNING, "Recording requested, but no One Touch Monitor registered. (See features.conf)\n");
17874          /* 403 means that we don't support this feature, so don't request it again */
17875          transmit_response(p, "403 Forbidden", req);
17876          ast_unlock_call_features();
17877          return;
17878       }
17879       /* Send the feature code to the PBX as DTMF, just like the handset had sent it */
17880       f.len = 100;
17881       for (j=0; j < strlen(feat->exten); j++) {
17882          f.subclass.integer = feat->exten[j];
17883          ast_queue_frame(p->owner, &f);
17884          if (sipdebug)
17885             ast_verbose("* DTMF-relay event faked: %c\n", f.subclass.integer);
17886       }
17887       ast_unlock_call_features();
17888 
17889       ast_debug(1, "Got a Request to Record the channel, state %s\n", c);
17890       transmit_response(p, "200 OK", req);
17891       return;
17892    } else if (ast_strlen_zero(c = get_header(req, "Content-Length")) || !strcasecmp(c, "0")) {
17893       /* This is probably just a packet making sure the signalling is still up, just send back a 200 OK */
17894       transmit_response(p, "200 OK", req);
17895       return;
17896    }
17897 
17898    /* Other type of INFO message, not really understood by Asterisk */
17899    /* if (get_msg_text(buf, sizeof(buf), req)) { */
17900 
17901    ast_log(LOG_WARNING, "Unable to parse INFO message from %s. Content %s\n", p->callid, buf);
17902    transmit_response(p, "415 Unsupported media type", req);
17903    return;
17904 }
17905 
17906 /*! \brief Enable SIP Debugging for a single IP */
17907 static char *sip_do_debug_ip(int fd, const char *arg)
17908 {
17909    if (ast_sockaddr_resolve_first(&debugaddr, arg, 0)) {
17910       return CLI_SHOWUSAGE;
17911    }
17912 
17913    ast_cli(fd, "SIP Debugging Enabled for IP: %s\n", ast_sockaddr_stringify_addr(&debugaddr));
17914    sipdebug |= sip_debug_console;
17915 
17916    return CLI_SUCCESS;
17917 }
17918 
17919 /*! \brief  Turn on SIP debugging for a given peer */
17920 static char *sip_do_debug_peer(int fd, const char *arg)
17921 {
17922    struct sip_peer *peer = find_peer(arg, NULL, TRUE, FINDPEERS, FALSE, 0);
17923    if (!peer)
17924       ast_cli(fd, "No such peer '%s'\n", arg);
17925    else if (ast_sockaddr_isnull(&peer->addr))
17926       ast_cli(fd, "Unable to get IP address of peer '%s'\n", arg);
17927    else {
17928       ast_sockaddr_copy(&debugaddr, &peer->addr);
17929       ast_cli(fd, "SIP Debugging Enabled for IP: %s\n", ast_sockaddr_stringify_addr(&debugaddr));
17930       sipdebug |= sip_debug_console;
17931    }
17932    if (peer)
17933       unref_peer(peer, "sip_do_debug_peer: unref_peer, from find_peer call");
17934    return CLI_SUCCESS;
17935 }
17936 
17937 /*! \brief Turn on SIP debugging (CLI command) */
17938 static char *sip_do_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
17939 {
17940    int oldsipdebug = sipdebug & sip_debug_console;
17941    const char *what;
17942 
17943    if (cmd == CLI_INIT) {
17944       e->command = "sip set debug {on|off|ip|peer}";
17945       e->usage =
17946          "Usage: sip set debug {off|on|ip addr[:port]|peer peername}\n"
17947          "       Globally disables dumping of SIP packets,\n"
17948          "       or enables it either globally or for a (single)\n"
17949          "       IP address or registered peer.\n";
17950       return NULL;
17951    } else if (cmd == CLI_GENERATE) {
17952       if (a->pos == 4 && !strcasecmp(a->argv[3], "peer"))
17953          return complete_sip_peer(a->word, a->n, 0);
17954       return NULL;
17955         }
17956 
17957    what = a->argv[e->args-1];      /* guaranteed to exist */
17958    if (a->argc == e->args) {       /* on/off */
17959       if (!strcasecmp(what, "on")) {
17960          sipdebug |= sip_debug_console;
17961          sipdebug_text = 1;   /*! \note this can be a special debug command - "sip debug text" or something */
17962          memset(&debugaddr, 0, sizeof(debugaddr));
17963          ast_cli(a->fd, "SIP Debugging %senabled\n", oldsipdebug ? "re-" : "");
17964          return CLI_SUCCESS;
17965       } else if (!strcasecmp(what, "off")) {
17966          sipdebug &= ~sip_debug_console;
17967          sipdebug_text = 0;
17968          ast_cli(a->fd, "SIP Debugging Disabled\n");
17969          return CLI_SUCCESS;
17970       }
17971    } else if (a->argc == e->args +1) {/* ip/peer */
17972       if (!strcasecmp(what, "ip"))
17973          return sip_do_debug_ip(a->fd, a->argv[e->args]);
17974       else if (!strcasecmp(what, "peer"))
17975          return sip_do_debug_peer(a->fd, a->argv[e->args]);
17976    }
17977    return CLI_SHOWUSAGE;   /* default, failure */
17978 }
17979 
17980 /*! \brief Cli command to send SIP notify to peer */
17981 static char *sip_cli_notify(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
17982 {
17983    struct ast_variable *varlist;
17984    int i;
17985 
17986    switch (cmd) {
17987    case CLI_INIT:
17988       e->command = "sip notify";
17989       e->usage =
17990          "Usage: sip notify <type> <peer> [<peer>...]\n"
17991          "       Send a NOTIFY message to a SIP peer or peers\n"
17992          "       Message types are defined in sip_notify.conf\n";
17993       return NULL;
17994    case CLI_GENERATE:
17995       return complete_sipnotify(a->line, a->word, a->pos, a->n);
17996    }
17997 
17998    if (a->argc < 4)
17999       return CLI_SHOWUSAGE;
18000 
18001    if (!notify_types) {
18002       ast_cli(a->fd, "No %s file found, or no types listed there\n", notify_config);
18003       return CLI_FAILURE;
18004    }
18005 
18006    varlist = ast_variable_browse(notify_types, a->argv[2]);
18007 
18008    if (!varlist) {
18009       ast_cli(a->fd, "Unable to find notify type '%s'\n", a->argv[2]);
18010       return CLI_FAILURE;
18011    }
18012 
18013    for (i = 3; i < a->argc; i++) {
18014       struct sip_pvt *p;
18015       char buf[512];
18016       struct ast_variable *header, *var;
18017 
18018       if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY, NULL))) {
18019          ast_log(LOG_WARNING, "Unable to build sip pvt data for notify (memory/socket error)\n");
18020          return CLI_FAILURE;
18021       }
18022 
18023       if (create_addr(p, a->argv[i], NULL, 1, NULL)) {
18024          /* Maybe they're not registered, etc. */
18025          dialog_unlink_all(p, TRUE, TRUE);
18026          dialog_unref(p, "unref dialog inside for loop" );
18027          /* sip_destroy(p); */
18028          ast_cli(a->fd, "Could not create address for '%s'\n", a->argv[i]);
18029          continue;
18030       }
18031 
18032       /* Notify is outgoing call */
18033       ast_set_flag(&p->flags[0], SIP_OUTGOING);
18034       sip_notify_allocate(p);
18035       p->notify->headers = header = ast_variable_new("Subscription-State", "terminated", "");
18036 
18037       for (var = varlist; var; var = var->next) {
18038          ast_copy_string(buf, var->value, sizeof(buf));
18039          ast_unescape_semicolon(buf);
18040 
18041          if (!strcasecmp(var->name, "Content")) {
18042             if (ast_str_strlen(p->notify->content))
18043                ast_str_append(&p->notify->content, 0, "\r\n");
18044             ast_str_append(&p->notify->content, 0, "%s", buf);
18045          } else if (!strcasecmp(var->name, "Content-Length")) {
18046             ast_log(LOG_WARNING, "it is not necessary to specify Content-Length in sip_notify.conf, ignoring");
18047          } else {
18048             header->next = ast_variable_new(var->name, buf, "");
18049             header = header->next;
18050          }
18051       }
18052 
18053       /* Recalculate our side, and recalculate Call ID */
18054       ast_cli(a->fd, "Sending NOTIFY of type '%s' to '%s'\n", a->argv[2], a->argv[i]);
18055       dialog_ref(p, "bump the count of p, which transmit_sip_request will decrement.");
18056       sip_scheddestroy(p, SIP_TRANS_TIMEOUT);
18057       transmit_invite(p, SIP_NOTIFY, 0, 2, NULL);
18058    }
18059 
18060    return CLI_SUCCESS;
18061 }
18062 
18063 /*! \brief Enable/Disable SIP History logging (CLI) */
18064 static char *sip_set_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
18065 {
18066    switch (cmd) {
18067    case CLI_INIT:
18068       e->command = "sip set history {on|off}";
18069       e->usage =
18070          "Usage: sip set history {on|off}\n"
18071          "       Enables/Disables recording of SIP dialog history for debugging purposes.\n"
18072          "       Use 'sip show history' to view the history of a call number.\n";
18073       return NULL;
18074    case CLI_GENERATE:
18075       return NULL;
18076    }
18077 
18078    if (a->argc != e->args)
18079       return CLI_SHOWUSAGE;
18080 
18081    if (!strncasecmp(a->argv[e->args - 1], "on", 2)) {
18082       recordhistory = TRUE;
18083       ast_cli(a->fd, "SIP History Recording Enabled (use 'sip show history')\n");
18084    } else if (!strncasecmp(a->argv[e->args - 1], "off", 3)) {
18085       recordhistory = FALSE;
18086       ast_cli(a->fd, "SIP History Recording Disabled\n");
18087    } else {
18088       return CLI_SHOWUSAGE;
18089    }
18090    return CLI_SUCCESS;
18091 }
18092 
18093 /*! \brief Authenticate for outbound registration */
18094 static int do_register_auth(struct sip_pvt *p, struct sip_request *req, enum sip_auth_type code)
18095 {
18096    char *header, *respheader;
18097    char digest[1024];
18098 
18099    p->authtries++;
18100    auth_headers(code, &header, &respheader);
18101    memset(digest, 0, sizeof(digest));
18102    if (reply_digest(p, req, header, SIP_REGISTER, digest, sizeof(digest))) {
18103       /* There's nothing to use for authentication */
18104       /* No digest challenge in request */
18105       if (sip_debug_test_pvt(p) && p->registry)
18106          ast_verbose("No authentication challenge, sending blank registration to domain/host name %s\n", p->registry->hostname);
18107          /* No old challenge */
18108       return -1;
18109    }
18110    if (p->do_history)
18111       append_history(p, "RegistryAuth", "Try: %d", p->authtries);
18112    if (sip_debug_test_pvt(p) && p->registry)
18113       ast_verbose("Responding to challenge, registration to domain/host name %s\n", p->registry->hostname);
18114    return transmit_register(p->registry, SIP_REGISTER, digest, respheader);
18115 }
18116 
18117 /*! \brief Add authentication on outbound SIP packet */
18118 static int do_proxy_auth(struct sip_pvt *p, struct sip_request *req, enum sip_auth_type code, int sipmethod, int init)
18119 {
18120    char *header, *respheader;
18121    char digest[1024];
18122 
18123    if (!p->options && !(p->options = ast_calloc(1, sizeof(*p->options))))
18124       return -2;
18125 
18126    p->authtries++;
18127    auth_headers(code, &header, &respheader);
18128    ast_debug(2, "Auth attempt %d on %s\n", p->authtries, sip_methods[sipmethod].text);
18129    memset(digest, 0, sizeof(digest));
18130    if (reply_digest(p, req, header, sipmethod, digest, sizeof(digest) )) {
18131       /* No way to authenticate */
18132       return -1;
18133    }
18134    /* Now we have a reply digest */
18135    p->options->auth = digest;
18136    p->options->authheader = respheader;
18137    return transmit_invite(p, sipmethod, sipmethod == SIP_INVITE, init, NULL);
18138 }
18139 
18140 /*! \brief  reply to authentication for outbound registrations
18141 \return  Returns -1 if we have no auth
18142 \note This is used for register= servers in sip.conf, SIP proxies we register
18143    with  for receiving calls from.  */
18144 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod,  char *digest, int digest_len)
18145 {
18146    char tmp[512];
18147    char *c;
18148    char oldnonce[256];
18149 
18150    /* table of recognised keywords, and places where they should be copied */
18151    const struct x {
18152       const char *key;
18153       const ast_string_field *field;
18154    } *i, keys[] = {
18155       { "realm=", &p->realm },
18156       { "nonce=", &p->nonce },
18157       { "opaque=", &p->opaque },
18158       { "qop=", &p->qop },
18159       { "domain=", &p->domain },
18160       { NULL, 0 },
18161    };
18162 
18163    ast_copy_string(tmp, get_header(req, header), sizeof(tmp));
18164    if (ast_strlen_zero(tmp))
18165       return -1;
18166    if (strncasecmp(tmp, "Digest ", strlen("Digest "))) {
18167       ast_log(LOG_WARNING, "missing Digest.\n");
18168       return -1;
18169    }
18170    c = tmp + strlen("Digest ");
18171    ast_copy_string(oldnonce, p->nonce, sizeof(oldnonce));
18172    while (c && *(c = ast_skip_blanks(c))) {  /* lookup for keys */
18173       for (i = keys; i->key != NULL; i++) {
18174          char *src, *separator;
18175          if (strncasecmp(c, i->key, strlen(i->key)) != 0)
18176             continue;
18177          /* Found. Skip keyword, take text in quotes or up to the separator. */
18178          c += strlen(i->key);
18179          if (*c == '"') {
18180             src = ++c;
18181             separator = "\"";
18182          } else {
18183             src = c;
18184             separator = ",";
18185          }
18186          strsep(&c, separator); /* clear separator and move ptr */
18187          ast_string_field_ptr_set(p, i->field, src);
18188          break;
18189       }
18190       if (i->key == NULL) /* not found, try ',' */
18191          strsep(&c, ",");
18192    }
18193    /* Reset nonce count */
18194    if (strcmp(p->nonce, oldnonce))
18195       p->noncecount = 0;
18196 
18197    /* Save auth data for following registrations */
18198    if (p->registry) {
18199       struct sip_registry *r = p->registry;
18200 
18201       if (strcmp(r->nonce, p->nonce)) {
18202          ast_string_field_set(r, realm, p->realm);
18203          ast_string_field_set(r, nonce, p->nonce);
18204          ast_string_field_set(r, authdomain, p->domain);
18205          ast_string_field_set(r, opaque, p->opaque);
18206          ast_string_field_set(r, qop, p->qop);
18207          r->noncecount = 0;
18208       }
18209    }
18210    return build_reply_digest(p, sipmethod, digest, digest_len);
18211 }
18212 
18213 /*! \brief  Build reply digest
18214 \return  Returns -1 if we have no auth
18215 \note Build digest challenge for authentication of registrations and calls
18216    Also used for authentication of BYE
18217 */
18218 static int build_reply_digest(struct sip_pvt *p, int method, char* digest, int digest_len)
18219 {
18220    char a1[256];
18221    char a2[256];
18222    char a1_hash[256];
18223    char a2_hash[256];
18224    char resp[256];
18225    char resp_hash[256];
18226    char uri[256];
18227    char opaque[256] = "";
18228    char cnonce[80];
18229    const char *username;
18230    const char *secret;
18231    const char *md5secret;
18232    struct sip_auth *auth = NULL; /* Realm authentication */
18233 
18234    if (!ast_strlen_zero(p->domain))
18235       ast_copy_string(uri, p->domain, sizeof(uri));
18236    else if (!ast_strlen_zero(p->uri))
18237       ast_copy_string(uri, p->uri, sizeof(uri));
18238    else
18239       snprintf(uri, sizeof(uri), "sip:%s@%s", p->username, ast_sockaddr_stringify_host(&p->sa));
18240 
18241    snprintf(cnonce, sizeof(cnonce), "%08lx", ast_random());
18242 
18243    /* Check if we have separate auth credentials */
18244    if(!(auth = find_realm_authentication(p->peerauth, p->realm))) /* Start with peer list */
18245       auth = find_realm_authentication(authl, p->realm); /* If not, global list */
18246 
18247    if (auth) {
18248       ast_debug(3, "use realm [%s] from peer [%s][%s]\n", auth->username, p->peername, p->username);
18249       username = auth->username;
18250       secret = auth->secret;
18251       md5secret = auth->md5secret;
18252       if (sipdebug)
18253          ast_debug(1, "Using realm %s authentication for call %s\n", p->realm, p->callid);
18254    } else {
18255       /* No authentication, use peer or register= config */
18256       username = p->authname;
18257       secret =  p->peersecret;
18258       md5secret = p->peermd5secret;
18259    }
18260    if (ast_strlen_zero(username))   /* We have no authentication */
18261       return -1;
18262 
18263    /* Calculate SIP digest response */
18264    snprintf(a1, sizeof(a1), "%s:%s:%s", username, p->realm, secret);
18265    snprintf(a2, sizeof(a2), "%s:%s", sip_methods[method].text, uri);
18266    if (!ast_strlen_zero(md5secret))
18267       ast_copy_string(a1_hash, md5secret, sizeof(a1_hash));
18268    else
18269       ast_md5_hash(a1_hash, a1);
18270    ast_md5_hash(a2_hash, a2);
18271 
18272    p->noncecount++;
18273    if (!ast_strlen_zero(p->qop))
18274       snprintf(resp, sizeof(resp), "%s:%s:%08x:%s:%s:%s", a1_hash, p->nonce, p->noncecount, cnonce, "auth", a2_hash);
18275    else
18276       snprintf(resp, sizeof(resp), "%s:%s:%s", a1_hash, p->nonce, a2_hash);
18277    ast_md5_hash(resp_hash, resp);
18278 
18279    /* only include the opaque string if it's set */
18280    if (!ast_strlen_zero(p->opaque)) {
18281      snprintf(opaque, sizeof(opaque), ", opaque=\"%s\"", p->opaque);
18282    }
18283 
18284    /* XXX We hard code our qop to "auth" for now.  XXX */
18285    if (!ast_strlen_zero(p->qop))
18286       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);
18287    else
18288       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);
18289 
18290    append_history(p, "AuthResp", "Auth response sent for %s in realm %s - nc %d", username, p->realm, p->noncecount);
18291 
18292    return 0;
18293 }
18294    
18295 /*! \brief Read SIP header (dialplan function) */
18296 static int func_header_read(struct ast_channel *chan, const char *function, char *data, char *buf, size_t len)
18297 {
18298    struct sip_pvt *p;
18299    const char *content = NULL;
18300    AST_DECLARE_APP_ARGS(args,
18301       AST_APP_ARG(header);
18302       AST_APP_ARG(number);
18303    );
18304    int i, number, start = 0;
18305 
18306    if (ast_strlen_zero(data)) {
18307       ast_log(LOG_WARNING, "This function requires a header name.\n");
18308       return -1;
18309    }
18310 
18311    ast_channel_lock(chan);
18312    if (!IS_SIP_TECH(chan->tech)) {
18313       ast_log(LOG_WARNING, "This function can only be used on SIP channels.\n");
18314       ast_channel_unlock(chan);
18315       return -1;
18316    }
18317 
18318    AST_STANDARD_APP_ARGS(args, data);
18319    if (!args.number) {
18320       number = 1;
18321    } else {
18322       sscanf(args.number, "%30d", &number);
18323       if (number < 1)
18324          number = 1;
18325    }
18326 
18327    p = chan->tech_pvt;
18328 
18329    /* If there is no private structure, this channel is no longer alive */
18330    if (!p) {
18331       ast_channel_unlock(chan);
18332       return -1;
18333    }
18334 
18335    for (i = 0; i < number; i++)
18336       content = __get_header(&p->initreq, args.header, &start);
18337 
18338    if (ast_strlen_zero(content)) {
18339       ast_channel_unlock(chan);
18340       return -1;
18341    }
18342 
18343    ast_copy_string(buf, content, len);
18344    ast_channel_unlock(chan);
18345 
18346    return 0;
18347 }
18348 
18349 static struct ast_custom_function sip_header_function = {
18350    .name = "SIP_HEADER",
18351    .read = func_header_read,
18352 };
18353 
18354 /*! \brief  Dial plan function to check if domain is local */
18355 static int func_check_sipdomain(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
18356 {
18357    if (ast_strlen_zero(data)) {
18358       ast_log(LOG_WARNING, "CHECKSIPDOMAIN requires an argument - A domain name\n");
18359       return -1;
18360    }
18361    if (check_sip_domain(data, NULL, 0))
18362       ast_copy_string(buf, data, len);
18363    else
18364       buf[0] = '\0';
18365    return 0;
18366 }
18367 
18368 static struct ast_custom_function checksipdomain_function = {
18369    .name = "CHECKSIPDOMAIN",
18370    .read = func_check_sipdomain,
18371 };
18372 
18373 /*! \brief  ${SIPPEER()} Dialplan function - reads peer data */
18374 static int function_sippeer(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
18375 {
18376    struct sip_peer *peer;
18377    char *colname;
18378 
18379    if ((colname = strchr(data, ':'))) {   /*! \todo Will be deprecated after 1.4 */
18380       static int deprecation_warning = 0;
18381       *colname++ = '\0';
18382       if (deprecation_warning++ % 10 == 0)
18383          ast_log(LOG_WARNING, "SIPPEER(): usage of ':' to separate arguments is deprecated.  Please use ',' instead.\n");
18384    } else if ((colname = strchr(data, ',')))
18385       *colname++ = '\0';
18386    else
18387       colname = "ip";
18388 
18389    if (!(peer = find_peer(data, NULL, TRUE, FINDPEERS, FALSE, 0)))
18390       return -1;
18391 
18392    if (!strcasecmp(colname, "ip")) {
18393       ast_copy_string(buf, ast_sockaddr_stringify_addr(&peer->addr), len);
18394    } else  if (!strcasecmp(colname, "port")) {
18395       snprintf(buf, len, "%d", ast_sockaddr_port(&peer->addr));
18396    } else  if (!strcasecmp(colname, "status")) {
18397       peer_status(peer, buf, len);
18398    } else  if (!strcasecmp(colname, "language")) {
18399       ast_copy_string(buf, peer->language, len);
18400    } else  if (!strcasecmp(colname, "regexten")) {
18401       ast_copy_string(buf, peer->regexten, len);
18402    } else  if (!strcasecmp(colname, "limit")) {
18403       snprintf(buf, len, "%d", peer->call_limit);
18404    } else  if (!strcasecmp(colname, "busylevel")) {
18405       snprintf(buf, len, "%d", peer->busy_level);
18406    } else  if (!strcasecmp(colname, "curcalls")) {
18407       snprintf(buf, len, "%d", peer->inUse);
18408    } else if (!strcasecmp(colname, "maxforwards")) {
18409       snprintf(buf, len, "%d", peer->maxforwards);
18410    } else  if (!strcasecmp(colname, "accountcode")) {
18411       ast_copy_string(buf, peer->accountcode, len);
18412    } else  if (!strcasecmp(colname, "callgroup")) {
18413       ast_print_group(buf, len, peer->callgroup);
18414    } else  if (!strcasecmp(colname, "pickupgroup")) {
18415       ast_print_group(buf, len, peer->pickupgroup);
18416    } else  if (!strcasecmp(colname, "useragent")) {
18417       ast_copy_string(buf, peer->useragent, len);
18418    } else  if (!strcasecmp(colname, "mailbox")) {
18419       struct ast_str *mailbox_str = ast_str_alloca(512);
18420       peer_mailboxes_to_str(&mailbox_str, peer);
18421       ast_copy_string(buf, mailbox_str->str, len);
18422    } else  if (!strcasecmp(colname, "context")) {
18423       ast_copy_string(buf, peer->context, len);
18424    } else  if (!strcasecmp(colname, "expire")) {
18425       snprintf(buf, len, "%d", peer->expire);
18426    } else  if (!strcasecmp(colname, "dynamic")) {
18427       ast_copy_string(buf, peer->host_dynamic ? "yes" : "no", len);
18428    } else  if (!strcasecmp(colname, "callerid_name")) {
18429       ast_copy_string(buf, peer->cid_name, len);
18430    } else  if (!strcasecmp(colname, "callerid_num")) {
18431       ast_copy_string(buf, peer->cid_num, len);
18432    } else  if (!strcasecmp(colname, "codecs")) {
18433       ast_getformatname_multiple(buf, len -1, peer->capability);
18434    } else if (!strcasecmp(colname, "encryption")) {
18435       snprintf(buf, len, "%d", ast_test_flag(&peer->flags[1], SIP_PAGE2_USE_SRTP));
18436    } else  if (!strncasecmp(colname, "chanvar[", 8)) {
18437       char *chanvar=colname + 8;
18438       struct ast_variable *v;
18439    
18440       chanvar = strsep(&chanvar, "]");
18441       for (v = peer->chanvars ; v ; v = v->next) {
18442          if (!strcasecmp(v->name, chanvar)) {
18443             ast_copy_string(buf, v->value, len);
18444          }
18445       }
18446    } else  if (!strncasecmp(colname, "codec[", 6)) {
18447       char *codecnum;
18448       format_t codec = 0;
18449       
18450       codecnum = colname + 6; /* move past the '[' */
18451       codecnum = strsep(&codecnum, "]"); /* trim trailing ']' if any */
18452       if((codec = ast_codec_pref_index(&peer->prefs, atoi(codecnum)))) {
18453          ast_copy_string(buf, ast_getformatname(codec), len);
18454       } else {
18455          buf[0] = '\0';
18456       }
18457    } else {
18458       buf[0] = '\0';
18459    }
18460 
18461    unref_peer(peer, "unref_peer from function_sippeer, just before return");
18462 
18463    return 0;
18464 }
18465 
18466 /*! \brief Structure to declare a dialplan function: SIPPEER */
18467 static struct ast_custom_function sippeer_function = {
18468    .name = "SIPPEER",
18469    .read = function_sippeer,
18470 };
18471 
18472 /*! \brief ${SIPCHANINFO()} Dialplan function - reads sip channel data */
18473 static int function_sipchaninfo_read(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
18474 {
18475    struct sip_pvt *p;
18476    static int deprecated = 0;
18477 
18478    *buf = 0;
18479    
18480    if (!data) {
18481       ast_log(LOG_WARNING, "This function requires a parameter name.\n");
18482       return -1;
18483    }
18484 
18485    ast_channel_lock(chan);
18486    if (!IS_SIP_TECH(chan->tech)) {
18487       ast_log(LOG_WARNING, "This function can only be used on SIP channels.\n");
18488       ast_channel_unlock(chan);
18489       return -1;
18490    }
18491 
18492    if (deprecated++ % 20 == 0) {
18493       /* Deprecated in 1.6.1 */
18494       ast_log(LOG_WARNING, "SIPCHANINFO() is deprecated.  Please transition to using CHANNEL().\n");
18495    }
18496 
18497    p = chan->tech_pvt;
18498 
18499    /* If there is no private structure, this channel is no longer alive */
18500    if (!p) {
18501       ast_channel_unlock(chan);
18502       return -1;
18503    }
18504 
18505    if (!strcasecmp(data, "peerip")) {
18506       ast_copy_string(buf, ast_sockaddr_stringify_addr(&p->sa), len);
18507    } else  if (!strcasecmp(data, "recvip")) {
18508       ast_copy_string(buf, ast_sockaddr_stringify_addr(&p->recv), len);
18509    } else  if (!strcasecmp(data, "from")) {
18510       ast_copy_string(buf, p->from, len);
18511    } else  if (!strcasecmp(data, "uri")) {
18512       ast_copy_string(buf, p->uri, len);
18513    } else  if (!strcasecmp(data, "useragent")) {
18514       ast_copy_string(buf, p->useragent, len);
18515    } else  if (!strcasecmp(data, "peername")) {
18516       ast_copy_string(buf, p->peername, len);
18517    } else if (!strcasecmp(data, "t38passthrough")) {
18518       if (p->t38.state == T38_DISABLED) {
18519          ast_copy_string(buf, "0", len);
18520       } else { /* T38 is offered or enabled in this call */
18521          ast_copy_string(buf, "1", len);
18522       }
18523    } else {
18524       ast_channel_unlock(chan);
18525       return -1;
18526    }
18527    ast_channel_unlock(chan);
18528 
18529    return 0;
18530 }
18531 
18532 /*! \brief Structure to declare a dialplan function: SIPCHANINFO */
18533 static struct ast_custom_function sipchaninfo_function = {
18534    .name = "SIPCHANINFO",
18535    .read = function_sipchaninfo_read,
18536 };
18537 
18538 /*! \brief update redirecting information for a channel based on headers
18539  *
18540  */
18541 static void change_redirecting_information(struct sip_pvt *p, struct sip_request *req,
18542    struct ast_party_redirecting *redirecting,
18543    struct ast_set_party_redirecting *update_redirecting, int set_call_forward)
18544 {
18545    char *redirecting_from_name = NULL;
18546    char *redirecting_from_number = NULL;
18547    char *redirecting_to_name = NULL;
18548    char *redirecting_to_number = NULL;
18549    int reason = AST_REDIRECTING_REASON_UNCONDITIONAL;
18550    int is_response = req->method == SIP_RESPONSE;
18551    int res = 0;
18552 
18553    res = get_rdnis(p, req, &redirecting_from_name, &redirecting_from_number, &reason);
18554    if (res == -1) {
18555       if (is_response) {
18556          get_name_and_number(get_header(req, "TO"), &redirecting_from_name, &redirecting_from_number);
18557       } else {
18558          return;
18559       }
18560    }
18561 
18562    /* At this point, all redirecting "from" info should be filled in appropriately
18563     * on to the "to" info
18564     */
18565 
18566    if (is_response) {
18567       parse_moved_contact(p, req, &redirecting_to_name, &redirecting_to_number, set_call_forward);
18568    } else {
18569       get_name_and_number(get_header(req, "TO"), &redirecting_to_name, &redirecting_to_number);
18570    }
18571 
18572    if (!ast_strlen_zero(redirecting_from_number)) {
18573       ast_debug(3, "Got redirecting from number %s\n", redirecting_from_number);
18574       update_redirecting->from.number = 1;
18575       redirecting->from.number.valid = 1;
18576       ast_free(redirecting->from.number.str);
18577       redirecting->from.number.str = redirecting_from_number;
18578    }
18579    if (!ast_strlen_zero(redirecting_from_name)) {
18580       ast_debug(3, "Got redirecting from name %s\n", redirecting_from_name);
18581       update_redirecting->from.name = 1;
18582       redirecting->from.name.valid = 1;
18583       ast_free(redirecting->from.name.str);
18584       redirecting->from.name.str = redirecting_from_name;
18585    }
18586    if (!ast_strlen_zero(p->cid_tag)) {
18587       ast_free(redirecting->from.tag);
18588       redirecting->from.tag = ast_strdup(p->cid_tag);
18589       ast_free(redirecting->to.tag);
18590       redirecting->to.tag = ast_strdup(p->cid_tag);
18591    }
18592    if (!ast_strlen_zero(redirecting_to_number)) {
18593       ast_debug(3, "Got redirecting to number %s\n", redirecting_to_number);
18594       update_redirecting->to.number = 1;
18595       redirecting->to.number.valid = 1;
18596       ast_free(redirecting->to.number.str);
18597       redirecting->to.number.str = redirecting_to_number;
18598    }
18599    if (!ast_strlen_zero(redirecting_to_name)) {
18600       ast_debug(3, "Got redirecting to name %s\n", redirecting_from_number);
18601       update_redirecting->to.name = 1;
18602       redirecting->to.name.valid = 1;
18603       ast_free(redirecting->to.name.str);
18604       redirecting->to.name.str = redirecting_to_name;
18605    }
18606    redirecting->reason = reason;
18607 }
18608 
18609 /*! \brief Parse 302 Moved temporalily response
18610    \todo XXX Doesn't redirect over TLS on sips: uri's.
18611       If we get a redirect to a SIPS: uri, this needs to be going back to the
18612       dialplan (this is a request for a secure signalling path).
18613       Note that transport=tls is deprecated, but we need to support it on incoming requests.
18614 */
18615 static void parse_moved_contact(struct sip_pvt *p, struct sip_request *req, char **name, char **number, int set_call_forward)
18616 {
18617    char contact[SIPBUFSIZE];
18618    char *contact_name = NULL;
18619    char *contact_number = NULL;
18620    char *separator, *trans;
18621    char *domain;
18622    enum sip_transport transport = SIP_TRANSPORT_UDP;
18623 
18624    ast_copy_string(contact, get_header(req, "Contact"), sizeof(contact));
18625    if ((separator = strchr(contact, ',')))
18626       *separator = '\0';
18627 
18628    contact_number = get_in_brackets(contact);
18629    if ((trans = strcasestr(contact_number, ";transport="))) {
18630       trans += 11;
18631 
18632       if ((separator = strchr(trans, ';')))
18633          *separator = '\0';
18634 
18635       if (!strncasecmp(trans, "tcp", 3))
18636          transport = SIP_TRANSPORT_TCP;
18637       else if (!strncasecmp(trans, "tls", 3))
18638          transport = SIP_TRANSPORT_TLS;
18639       else {
18640          if (strncasecmp(trans, "udp", 3))
18641             ast_debug(1, "received contact with an invalid transport, '%s'\n", contact_number);
18642          /* This will assume UDP for all unknown transports */
18643          transport = SIP_TRANSPORT_UDP;
18644       }
18645    }
18646    contact_number = remove_uri_parameters(contact_number);
18647 
18648    if (p->socket.tcptls_session) {
18649       ao2_ref(p->socket.tcptls_session, -1);
18650       p->socket.tcptls_session = NULL;
18651    }
18652 
18653    set_socket_transport(&p->socket, transport);
18654 
18655    if (set_call_forward && ast_test_flag(&p->flags[0], SIP_PROMISCREDIR)) {
18656       char *host = NULL;
18657       if (!strncasecmp(contact_number, "sip:", 4))
18658          contact_number += 4;
18659       else if (!strncasecmp(contact_number, "sips:", 5))
18660          contact_number += 5;
18661       separator = strchr(contact_number, '/');
18662       if (separator)
18663          *separator = '\0';
18664       if ((host = strchr(contact_number, '@'))) {
18665          *host++ = '\0';
18666          ast_debug(2, "Found promiscuous redirection to 'SIP/%s::::%s@%s'\n", contact_number, get_transport(transport), host);
18667          if (p->owner)
18668             ast_string_field_build(p->owner, call_forward, "SIP/%s::::%s@%s", contact_number, get_transport(transport), host);
18669       } else {
18670          ast_debug(2, "Found promiscuous redirection to 'SIP/::::%s@%s'\n", get_transport(transport), contact_number);
18671          if (p->owner)
18672             ast_string_field_build(p->owner, call_forward, "SIP/::::%s@%s", get_transport(transport), contact_number);
18673       }
18674    } else {
18675       separator = strchr(contact, '@');
18676       if (separator) {
18677          *separator++ = '\0';
18678          domain = separator;
18679       } else {
18680          /* No username part */
18681          domain = contact;
18682       }
18683       separator = strchr(contact, '/');   /* WHEN do we hae a forward slash in the URI? */
18684       if (separator)
18685          *separator = '\0';
18686 
18687       if (!strncasecmp(contact_number, "sip:", 4))
18688          contact_number += 4;
18689       else if (!strncasecmp(contact_number, "sips:", 5))
18690          contact_number += 5;
18691       separator = strchr(contact_number, ';');  /* And username ; parameters? */
18692       if (separator)
18693          *separator = '\0';
18694       ast_uri_decode(contact_number);
18695       if (set_call_forward) {
18696          ast_debug(2, "Received 302 Redirect to extension '%s' (domain %s)\n", contact_number, domain);
18697          if (p->owner) {
18698             pbx_builtin_setvar_helper(p->owner, "SIPDOMAIN", domain);
18699             ast_string_field_set(p->owner, call_forward, contact_number);
18700          }
18701       }
18702    }
18703 
18704    /* We've gotten the number for the contact, now get the name */
18705 
18706    if (*contact == '\"') {
18707       contact_name = contact + 1;
18708       if (!(separator = (char *)find_closing_quote(contact_name, NULL))) {
18709          ast_log(LOG_NOTICE, "No closing quote on name in Contact header? %s\n", contact);
18710       }
18711       *separator = '\0';
18712    }
18713 
18714    if (name && !ast_strlen_zero(contact_name)) {
18715       *name = ast_strdup(contact_name);
18716    }
18717    if (number) {
18718       *number = ast_strdup(contact_number);
18719    }
18720 }
18721 
18722 /*! \brief Check pending actions on SIP call 
18723  *
18724  * \note both sip_pvt and sip_pvt's owner channel (if present)
18725  *  must be locked for this function.
18726  */
18727 static void check_pendings(struct sip_pvt *p)
18728 {
18729    if (ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
18730       /* if we can't BYE, then this is really a pending CANCEL */
18731       if (p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA) {
18732          p->invitestate = INV_CANCELLED;
18733          transmit_request(p, SIP_CANCEL, p->lastinvite, XMIT_RELIABLE, FALSE);
18734          /* Actually don't destroy us yet, wait for the 487 on our original
18735             INVITE, but do set an autodestruct just in case we never get it. */
18736       } else {
18737          /* We have a pending outbound invite, don't send something
18738             new in-transaction */
18739          if (p->pendinginvite)
18740             return;
18741 
18742          if (p->owner) {
18743             ast_softhangup_nolock(p->owner, AST_SOFTHANGUP_DEV);
18744          }
18745          /* Perhaps there is an SD change INVITE outstanding */
18746          transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, TRUE);
18747       }
18748       ast_clear_flag(&p->flags[0], SIP_PENDINGBYE);   
18749       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
18750    } else if (ast_test_flag(&p->flags[0], SIP_NEEDREINVITE)) {
18751       /* if we can't REINVITE, hold it for later */
18752       if (p->pendinginvite || p->invitestate == INV_CALLING || p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA || p->waitid > 0) {
18753          ast_debug(2, "NOT Sending pending reinvite (yet) on '%s'\n", p->callid);
18754       } else {
18755          ast_debug(2, "Sending pending reinvite on '%s'\n", p->callid);
18756          /* Didn't get to reinvite yet, so do it now */
18757          transmit_reinvite_with_sdp(p, (p->t38.state == T38_LOCAL_REINVITE ? TRUE : FALSE), FALSE);
18758          ast_clear_flag(&p->flags[0], SIP_NEEDREINVITE); 
18759       }
18760    }
18761 }
18762 
18763 /*! \brief Reset the NEEDREINVITE flag after waiting when we get 491 on a Re-invite
18764    to avoid race conditions between asterisk servers.
18765    Called from the scheduler.
18766 */
18767 static int sip_reinvite_retry(const void *data)
18768 {
18769    struct sip_pvt *p = (struct sip_pvt *) data;
18770    struct ast_channel *owner;
18771 
18772    sip_pvt_lock(p); /* called from schedule thread which requires a lock */
18773    while ((owner = p->owner) && ast_channel_trylock(owner)) {
18774       sip_pvt_unlock(p);
18775       usleep(1);
18776       sip_pvt_lock(p);
18777    }
18778    ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
18779    p->waitid = -1;
18780    check_pendings(p);
18781    sip_pvt_unlock(p);
18782    if (owner) {
18783       ast_channel_unlock(owner);
18784    }
18785    dialog_unref(p, "unref the dialog ptr from sip_reinvite_retry, because it held a dialog ptr");
18786    return 0;
18787 }
18788 
18789 /*!
18790  * \brief Handle authentication challenge for SIP UPDATE
18791  *
18792  * This function is only called upon the receipt of a 401/407 response to an UPDATE.
18793  */
18794 static void handle_response_update(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno)
18795 {
18796    if (p->options) {
18797       p->options->auth_type = (resp == 401 ? WWW_AUTH : PROXY_AUTH);
18798    }
18799    if ((p->authtries == MAX_AUTHTRIES) || do_proxy_auth(p, req, resp, SIP_UPDATE, 1)) {
18800       ast_log(LOG_NOTICE, "Failed to authenticate on UPDATE to '%s'\n", get_header(&p->initreq, "From"));
18801    }
18802 }
18803 
18804 static void cc_handle_publish_error(struct sip_pvt *pvt, const int resp, struct sip_request *req, struct sip_epa_entry *epa_entry)
18805 {
18806    struct cc_epa_entry *cc_entry = epa_entry->instance_data;
18807    struct sip_monitor_instance *monitor_instance = ao2_callback(sip_monitor_instances, 0,
18808          find_sip_monitor_instance_by_suspension_entry, epa_entry);
18809    const char *min_expires;
18810 
18811    if (!monitor_instance) {
18812       ast_log(LOG_WARNING, "Can't find monitor_instance corresponding to epa_entry %p.\n", epa_entry);
18813       return;
18814    }
18815 
18816    if (resp != 423) {
18817       ast_cc_monitor_failed(cc_entry->core_id, monitor_instance->device_name,
18818             "Received error response to our PUBLISH");
18819       ao2_ref(monitor_instance, -1);
18820       return;
18821    }
18822 
18823    /* Allrighty, the other end doesn't like our Expires value. They think it's
18824     * too small, so let's see if they've provided a more sensible value. If they
18825     * haven't, then we'll just double our Expires value and see if they like that
18826     * instead.
18827     *
18828     * XXX Ideally this logic could be placed into its own function so that SUBSCRIBE,
18829     * PUBLISH, and REGISTER could all benefit from the same shared code.
18830     */
18831    min_expires = get_header(req, "Min-Expires");
18832    if (ast_strlen_zero(min_expires)) {
18833       pvt->expiry *= 2;
18834       if (pvt->expiry < 0) {
18835          /* You dork! You overflowed! */
18836          ast_cc_monitor_failed(cc_entry->core_id, monitor_instance->device_name,
18837                "PUBLISH expiry overflowed");
18838          ao2_ref(monitor_instance, -1);
18839          return;
18840       }
18841    } else if (sscanf(min_expires, "%d", &pvt->expiry) != 1) {
18842       ast_cc_monitor_failed(cc_entry->core_id, monitor_instance->device_name,
18843             "Min-Expires has non-numeric value");
18844       ao2_ref(monitor_instance, -1);
18845       return;
18846    }
18847    /* At this point, we have most certainly changed pvt->expiry, so try transmitting
18848     * again
18849     */
18850    transmit_invite(pvt, SIP_PUBLISH, FALSE, 0, NULL);
18851    ao2_ref(monitor_instance, -1);
18852 }
18853 
18854 static void handle_response_publish(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno)
18855 {
18856    struct sip_epa_entry *epa_entry = p->epa_entry;
18857    const char *etag = get_header(req, "Sip-ETag");
18858 
18859    ast_assert(epa_entry != NULL);
18860 
18861    if (resp == 401 || resp == 407) {
18862       ast_string_field_set(p, theirtag, NULL);
18863       if (p->options) {
18864          p->options->auth_type = (resp == 401 ? WWW_AUTH : PROXY_AUTH);
18865       }
18866       if ((p->authtries == MAX_AUTHTRIES) || do_proxy_auth(p, req, resp, SIP_PUBLISH, 0)) {
18867          ast_log(LOG_NOTICE, "Failed to authenticate on PUBLISH to '%s'\n", get_header(&p->initreq, "From"));
18868          pvt_set_needdestroy(p, "Failed to authenticate on PUBLISH");
18869          sip_alreadygone(p);
18870       }
18871       return;
18872    }
18873 
18874    if (resp == 501 || resp == 405) {
18875       mark_method_unallowed(&p->allowed_methods, SIP_PUBLISH);
18876    }
18877 
18878    if (resp == 200) {
18879       p->authtries = 0;
18880       /* If I've read section 6, item 6 of RFC 3903 correctly,
18881        * an ESC will only generate a new etag when it sends a 200 OK
18882        */
18883       if (!ast_strlen_zero(etag)) {
18884          ast_copy_string(epa_entry->entity_tag, etag, sizeof(epa_entry->entity_tag));
18885       }
18886       /* The nominal case. Everything went well. Everybody is happy.
18887        * Each EPA will have a specific action to take as a result of this
18888        * development, so ... callbacks!
18889        */
18890       if (epa_entry->static_data->handle_ok) {
18891          epa_entry->static_data->handle_ok(p, req, epa_entry);
18892       }
18893    } else {
18894       /* Rather than try to make individual callbacks for each error
18895        * type, there is just a single error callback. The callback
18896        * can distinguish between error messages and do what it needs to
18897        */
18898       if (epa_entry->static_data->handle_error) {
18899          epa_entry->static_data->handle_error(p, resp, req, epa_entry);
18900       }
18901    }
18902 }
18903 
18904 /*! \brief Handle SIP response to INVITE dialogue */
18905 static void handle_response_invite(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno)
18906 {
18907    int outgoing = ast_test_flag(&p->flags[0], SIP_OUTGOING);
18908    int res = 0;
18909    int xmitres = 0;
18910    int reinvite = (p->owner && p->owner->_state == AST_STATE_UP);
18911    char *p_hdrval;
18912    int rtn;
18913    struct ast_party_connected_line connected;
18914    struct ast_set_party_connected_line update_connected;
18915 
18916    if (reinvite)
18917       ast_debug(4, "SIP response %d to RE-invite on %s call %s\n", resp, outgoing ? "outgoing" : "incoming", p->callid);
18918    else
18919       ast_debug(4, "SIP response %d to standard invite\n", resp);
18920 
18921    if (p->alreadygone) { /* This call is already gone */
18922       ast_debug(1, "Got response on call that is already terminated: %s (ignoring)\n", p->callid);
18923       return;
18924    }
18925 
18926    /* Acknowledge sequence number - This only happens on INVITE from SIP-call */
18927    /* Don't auto congest anymore since we've gotten something useful back */
18928    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"));
18929 
18930    /* RFC3261 says we must treat every 1xx response (but not 100)
18931       that we don't recognize as if it was 183.
18932    */
18933    if (resp > 100 && resp < 200 && resp!=101 && resp != 180 && resp != 181 && resp != 182 && resp != 183)
18934       resp = 183;
18935 
18936    /* Any response between 100 and 199 is PROCEEDING */
18937    if (resp >= 100 && resp < 200 && p->invitestate == INV_CALLING)
18938       p->invitestate = INV_PROCEEDING;
18939 
18940    /* Final response, not 200 ? */
18941    if (resp >= 300 && (p->invitestate == INV_CALLING || p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA ))
18942       p->invitestate = INV_COMPLETED;
18943    
18944    /* Final response, clear out pending invite */
18945    if ((resp == 200 || resp >= 300) && p->pendinginvite && seqno == p->pendinginvite)
18946       p->pendinginvite = 0;
18947 
18948    /* If this is a response to our initial INVITE, we need to set what we can use
18949     * for this peer.
18950     */
18951    if (!reinvite) {
18952       set_pvt_allowed_methods(p, req);
18953    }     
18954 
18955    switch (resp) {
18956    case 100:   /* Trying */
18957    case 101:   /* Dialog establishment */
18958       if (!req->ignore && p->invitestate != INV_CANCELLED && sip_cancel_destroy(p))
18959          ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
18960       check_pendings(p);
18961       break;
18962 
18963    case 180:   /* 180 Ringing */
18964    case 182:       /* 182 Queued */
18965       if (!req->ignore && p->invitestate != INV_CANCELLED && sip_cancel_destroy(p))
18966          ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
18967       if (!req->ignore && p->owner) {
18968          if (get_rpid(p, req)) {
18969             ast_party_connected_line_init(&connected);
18970             memset(&update_connected, 0, sizeof(update_connected));
18971             if (p->cid_num) {
18972                update_connected.id.number = 1;
18973                connected.id.number.valid = 1;
18974                connected.id.number.str = (char *) p->cid_num;
18975                connected.id.number.presentation = p->callingpres;
18976             }
18977             if (p->cid_name) {
18978                update_connected.id.name = 1;
18979                connected.id.name.valid = 1;
18980                connected.id.name.str = (char *) p->cid_name;
18981                connected.id.name.presentation = p->callingpres;
18982             }
18983             connected.id.tag = (char *) p->cid_tag;
18984             connected.source = AST_CONNECTED_LINE_UPDATE_SOURCE_ANSWER;
18985             ast_channel_queue_connected_line_update(p->owner, &connected,
18986                &update_connected);
18987          }
18988          sip_handle_cc(p, req, AST_CC_CCNR);
18989          ast_queue_control(p->owner, AST_CONTROL_RINGING);
18990          if (p->owner->_state != AST_STATE_UP) {
18991             ast_setstate(p->owner, AST_STATE_RINGING);
18992          }
18993       }
18994       if (find_sdp(req)) {
18995          if (p->invitestate != INV_CANCELLED)
18996             p->invitestate = INV_EARLY_MEDIA;
18997          res = process_sdp(p, req, SDP_T38_NONE);
18998          if (!req->ignore && p->owner) {
18999             /* Queue a progress frame only if we have SDP in 180 or 182 */
19000             ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
19001          }
19002          ast_rtp_instance_activate(p->rtp);
19003       }
19004       check_pendings(p);
19005       break;
19006 
19007    case 181:   /* Call Is Being Forwarded */
19008       if (!req->ignore && (p->invitestate != INV_CANCELLED) && sip_cancel_destroy(p))
19009          ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
19010       if (!req->ignore && p->owner) {
19011          struct ast_party_redirecting redirecting;
19012          struct ast_set_party_redirecting update_redirecting;
19013 
19014          ast_party_redirecting_init(&redirecting);
19015          memset(&update_redirecting, 0, sizeof(update_redirecting));
19016          change_redirecting_information(p, req, &redirecting, &update_redirecting,
19017             FALSE);
19018          ast_channel_queue_redirecting_update(p->owner, &redirecting,
19019             &update_redirecting);
19020          ast_party_redirecting_free(&redirecting);
19021          sip_handle_cc(p, req, AST_CC_CCNR);
19022       }
19023       check_pendings(p);
19024       break;
19025 
19026    case 183:   /* Session progress */
19027       if (!req->ignore && (p->invitestate != INV_CANCELLED) && sip_cancel_destroy(p))
19028          ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
19029       if (!req->ignore && p->owner) {
19030          if (get_rpid(p, req)) {
19031             /* Queue a connected line update */
19032             ast_party_connected_line_init(&connected);
19033             memset(&update_connected, 0, sizeof(update_connected));
19034             if (p->cid_num) {
19035                update_connected.id.number = 1;
19036                connected.id.number.valid = 1;
19037                connected.id.number.str = (char *) p->cid_num;
19038                connected.id.number.presentation = p->callingpres;
19039             }
19040             if (p->cid_name) {
19041                update_connected.id.name = 1;
19042                connected.id.name.valid = 1;
19043                connected.id.name.str = (char *) p->cid_name;
19044                connected.id.name.presentation = p->callingpres;
19045             }
19046             connected.id.tag = (char *) p->cid_tag;
19047             connected.source = AST_CONNECTED_LINE_UPDATE_SOURCE_ANSWER;
19048             ast_channel_queue_connected_line_update(p->owner, &connected,
19049                &update_connected);
19050          }
19051          sip_handle_cc(p, req, AST_CC_CCNR);
19052       }
19053       if (find_sdp(req)) {
19054          if (p->invitestate != INV_CANCELLED)
19055             p->invitestate = INV_EARLY_MEDIA;
19056          res = process_sdp(p, req, SDP_T38_NONE);
19057          if (!req->ignore && p->owner) {
19058             /* Queue a progress frame */
19059             ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
19060          }
19061          ast_rtp_instance_activate(p->rtp);
19062       } else {
19063          /* Alcatel PBXs are known to send 183s with no SDP after sending
19064           * a 100 Trying response. We're just going to treat this sort of thing
19065           * the same as we would treat a 180 Ringing
19066           */
19067          if (!req->ignore && p->owner) {
19068             ast_queue_control(p->owner, AST_CONTROL_RINGING);
19069          }
19070       }
19071       check_pendings(p);
19072       break;
19073 
19074    case 200:   /* 200 OK on invite - someone's answering our call */
19075       if (!req->ignore && (p->invitestate != INV_CANCELLED) && sip_cancel_destroy(p))
19076          ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
19077       p->authtries = 0;
19078       if (find_sdp(req)) {
19079          if ((res = process_sdp(p, req, SDP_T38_ACCEPT)) && !req->ignore)
19080             if (!reinvite)
19081                /* This 200 OK's SDP is not acceptable, so we need to ack, then hangup */
19082                /* For re-invites, we try to recover */
19083                ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
19084          ast_rtp_instance_activate(p->rtp);
19085       }
19086 
19087       if (!req->ignore && p->owner && (get_rpid(p, req) || !reinvite)) {
19088          /* Queue a connected line update */
19089          ast_party_connected_line_init(&connected);
19090          memset(&update_connected, 0, sizeof(update_connected));
19091          if (p->cid_num) {
19092             update_connected.id.number = 1;
19093             connected.id.number.valid = 1;
19094             connected.id.number.str = (char *) p->cid_num;
19095             connected.id.number.presentation = p->callingpres;
19096          }
19097          if (p->cid_name) {
19098             update_connected.id.name = 1;
19099             connected.id.name.valid = 1;
19100             connected.id.name.str = (char *) p->cid_name;
19101             connected.id.name.presentation = p->callingpres;
19102          }
19103          connected.id.tag = (char *) p->cid_tag;
19104          connected.source = AST_CONNECTED_LINE_UPDATE_SOURCE_ANSWER;
19105          ast_channel_queue_connected_line_update(p->owner, &connected,
19106             &update_connected);
19107       }
19108 
19109       /* Parse contact header for continued conversation */
19110       /* When we get 200 OK, we know which device (and IP) to contact for this call */
19111       /* This is important when we have a SIP proxy between us and the phone */
19112       if (outgoing) {
19113          update_call_counter(p, DEC_CALL_RINGING);
19114          parse_ok_contact(p, req);
19115          /* Save Record-Route for any later requests we make on this dialogue */
19116          if (!reinvite)
19117             build_route(p, req, 1);
19118 
19119          if(set_address_from_contact(p)) {
19120             /* Bad contact - we don't know how to reach this device */
19121             /* We need to ACK, but then send a bye */
19122             if (!p->route && !req->ignore)
19123                ast_set_flag(&p->flags[0], SIP_PENDINGBYE);  
19124          }
19125 
19126       }
19127 
19128       if (!req->ignore && p->owner) {
19129          if (!reinvite) {
19130             ast_queue_control(p->owner, AST_CONTROL_ANSWER);
19131             if (sip_cfg.callevents)
19132                manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
19133                   "Channel: %s\r\nChanneltype: %s\r\nUniqueid: %s\r\nSIPcallid: %s\r\nSIPfullcontact: %s\r\nPeername: %s\r\n",
19134                   p->owner->name, "SIP", p->owner->uniqueid, p->callid, p->fullcontact, p->peername);
19135          } else { /* RE-invite */
19136             ast_queue_frame(p->owner, &ast_null_frame);
19137          }
19138       } else {
19139           /* It's possible we're getting an 200 OK after we've tried to disconnect
19140               by sending CANCEL */
19141          /* First send ACK, then send bye */
19142          if (!req->ignore)
19143             ast_set_flag(&p->flags[0], SIP_PENDINGBYE);  
19144       }
19145 
19146       /* Check for Session-Timers related headers */
19147       if (st_get_mode(p) != SESSION_TIMER_MODE_REFUSE && p->outgoing_call == TRUE && !reinvite) {
19148          p_hdrval = (char*)get_header(req, "Session-Expires");
19149          if (!ast_strlen_zero(p_hdrval)) {
19150             /* UAS supports Session-Timers */
19151             enum st_refresher tmp_st_ref = SESSION_TIMER_REFRESHER_AUTO;
19152             int tmp_st_interval = 0;
19153             rtn = parse_session_expires(p_hdrval, &tmp_st_interval, &tmp_st_ref);
19154             if (rtn != 0) {
19155                ast_set_flag(&p->flags[0], SIP_PENDINGBYE);  
19156             }
19157             if (tmp_st_ref == SESSION_TIMER_REFRESHER_UAC ||
19158                tmp_st_ref == SESSION_TIMER_REFRESHER_UAS) {
19159                p->stimer->st_ref = tmp_st_ref;
19160             }
19161             if (tmp_st_interval) {
19162                p->stimer->st_interval = tmp_st_interval;
19163             }
19164             p->stimer->st_active = TRUE;
19165             p->stimer->st_active_peer_ua = TRUE;
19166             start_session_timer(p);
19167          } else {
19168             /* UAS doesn't support Session-Timers */
19169             if (st_get_mode(p) == SESSION_TIMER_MODE_ORIGINATE) {
19170                p->stimer->st_ref = SESSION_TIMER_REFRESHER_UAC;
19171                p->stimer->st_active_peer_ua = FALSE;
19172                start_session_timer(p);
19173             }
19174          }
19175       }
19176 
19177 
19178       /* If I understand this right, the branch is different for a non-200 ACK only */
19179       p->invitestate = INV_TERMINATED;
19180       ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
19181       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, TRUE);
19182       check_pendings(p);
19183       break;
19184 
19185    case 407: /* Proxy authentication */
19186    case 401: /* Www auth */
19187       /* First we ACK */
19188       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
19189       if (p->options)
19190          p->options->auth_type = resp;
19191 
19192       /* Then we AUTH */
19193       ast_string_field_set(p, theirtag, NULL);  /* forget their old tag, so we don't match tags when getting response */
19194       if (!req->ignore) {
19195          if (p->authtries < MAX_AUTHTRIES)
19196             p->invitestate = INV_CALLING;
19197          if (p->authtries == MAX_AUTHTRIES || do_proxy_auth(p, req, resp, SIP_INVITE, 1)) {
19198             ast_log(LOG_NOTICE, "Failed to authenticate on INVITE to '%s'\n", get_header(&p->initreq, "From"));
19199             pvt_set_needdestroy(p, "failed to authenticate on INVITE");
19200             sip_alreadygone(p);
19201             if (p->owner)
19202                ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
19203          }
19204       }
19205       break;
19206 
19207    case 403: /* Forbidden */
19208       /* First we ACK */
19209       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
19210       ast_log(LOG_WARNING, "Received response: \"Forbidden\" from '%s'\n", get_header(&p->initreq, "From"));
19211       if (!req->ignore && p->owner) {
19212          ast_set_hangupsource(p->owner, p->owner->name, 0);
19213          ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
19214       }
19215       pvt_set_needdestroy(p, "received 403 response");
19216       sip_alreadygone(p);
19217       break;
19218 
19219    case 404: /* Not found */
19220       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
19221       if (p->owner && !req->ignore) {
19222          ast_set_hangupsource(p->owner, p->owner->name, 0);
19223          ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
19224       }
19225       sip_alreadygone(p);
19226       break;
19227 
19228    case 408: /* Request timeout */
19229    case 481: /* Call leg does not exist */
19230       /* Could be REFER caused INVITE with replaces */
19231       ast_log(LOG_WARNING, "Re-invite to non-existing call leg on other UA. SIP dialog '%s'. Giving up.\n", p->callid);
19232       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
19233       if (p->owner)
19234          ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
19235       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19236       break;
19237 
19238    case 422: /* Session-Timers: Session interval too small */
19239       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
19240       ast_string_field_set(p, theirtag, NULL);
19241       proc_422_rsp(p, req);
19242       break;
19243 
19244    case 428: /* Use identity header - rfc 4474 - not supported by Asterisk yet */
19245       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
19246       append_history(p, "Identity", "SIP identity is required. Not supported by Asterisk.");
19247       ast_log(LOG_WARNING, "SIP identity required by proxy. SIP dialog '%s'. Giving up.\n", p->callid);
19248       if (p->owner)
19249          ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
19250       break;
19251 
19252       
19253 
19254    case 487: /* Cancelled transaction */
19255       /* We have sent CANCEL on an outbound INVITE
19256          This transaction is already scheduled to be killed by sip_hangup().
19257       */
19258       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
19259       if (p->owner && !req->ignore) {
19260          ast_queue_hangup_with_cause(p->owner, AST_CAUSE_NORMAL_CLEARING);
19261          append_history(p, "Hangup", "Got 487 on CANCEL request from us. Queued AST hangup request");
19262       } else if (!req->ignore) {
19263          update_call_counter(p, DEC_CALL_LIMIT);
19264          append_history(p, "Hangup", "Got 487 on CANCEL request from us on call without owner. Killing this dialog.");
19265          pvt_set_needdestroy(p, "received 487 response");
19266          sip_alreadygone(p);
19267       }
19268       break;
19269    case 415: /* Unsupported media type */
19270    case 488: /* Not acceptable here */
19271    case 606: /* Not Acceptable */
19272       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
19273       if (p->udptl && p->t38.state == T38_LOCAL_REINVITE) {
19274          change_t38_state(p, T38_DISABLED);
19275          /* Try to reset RTP timers */
19276          //ast_rtp_set_rtptimers_onhold(p->rtp);
19277 
19278          /* Trigger a reinvite back to audio */
19279          transmit_reinvite_with_sdp(p, FALSE, FALSE);
19280       } else {
19281          /* We can't set up this call, so give up */
19282          if (p->owner && !req->ignore)
19283             ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
19284          pvt_set_needdestroy(p, "received 488 response");
19285          /* If there's no dialog to end, then mark p as already gone */
19286          if (!reinvite)
19287             sip_alreadygone(p);
19288       }
19289       break;
19290    case 491: /* Pending */
19291       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
19292       if (p->owner && !req->ignore) {
19293          if (p->owner->_state != AST_STATE_UP) {
19294             ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
19295             pvt_set_needdestroy(p, "received 491 response");
19296          } else {
19297             /* This is a re-invite that failed. */
19298             /* Reset the flag after a while
19299              */
19300             int wait;
19301             /* RFC 3261, if owner of call, wait between 2.1 to 4 seconds,
19302              * if not owner of call, wait 0 to 2 seconds */
19303             if (p->outgoing_call) {
19304                wait = 2100 + ast_random() % 2000;
19305             } else {
19306                wait = ast_random() % 2000;
19307             }
19308             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."));
19309             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);
19310             ast_debug(2, "Reinvite race. Waiting %d secs before retry\n", wait);
19311          }
19312       }
19313       break;
19314 
19315    case 405: /* Not allowed */
19316    case 501: /* Not implemented */
19317       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
19318       if (p->owner)
19319          ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
19320       break;
19321    }
19322    if (xmitres == XMIT_ERROR)
19323       ast_log(LOG_WARNING, "Could not transmit message in dialog %s\n", p->callid);
19324 }
19325 
19326 /* \brief Handle SIP response in NOTIFY transaction
19327        We've sent a NOTIFY, now handle responses to it
19328   */
19329 static void handle_response_notify(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno)
19330 {
19331    switch (resp) {
19332    case 200:   /* Notify accepted */
19333       /* They got the notify, this is the end */
19334       if (p->owner) {
19335          if (!p->refer) {
19336             ast_log(LOG_WARNING, "Notify answer on an owned channel? - %s\n", p->owner->name);
19337             ast_queue_hangup_with_cause(p->owner, AST_CAUSE_NORMAL_UNSPECIFIED);
19338          } else {
19339             ast_debug(4, "Got OK on REFER Notify message\n");
19340          }
19341       } else {
19342          if (p->subscribed == NONE) {
19343             ast_debug(4, "Got 200 accepted on NOTIFY\n");
19344             pvt_set_needdestroy(p, "received 200 response");
19345          }
19346          if (ast_test_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE)) {
19347             /* Ready to send the next state we have on queue */
19348             ast_clear_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE);
19349             cb_extensionstate((char *)p->context, (char *)p->exten, p->laststate, (void *) p);
19350          }
19351       }
19352       break;
19353    case 401:   /* Not www-authorized on SIP method */
19354    case 407:   /* Proxy auth */
19355       if (!p->notify) {
19356          break; /* Only device notify can use NOTIFY auth */
19357       }
19358       ast_string_field_set(p, theirtag, NULL);
19359       if (ast_strlen_zero(p->authname)) {
19360          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));
19361          pvt_set_needdestroy(p, "unable to authenticate NOTIFY");
19362       }
19363       if (p->authtries > 1 || do_proxy_auth(p, req, resp, SIP_NOTIFY, 0)) {
19364          ast_log(LOG_NOTICE, "Failed to authenticate on NOTIFY to '%s'\n", get_header(&p->initreq, "From"));
19365          pvt_set_needdestroy(p, "failed to authenticate NOTIFY");
19366       }
19367       break;
19368    }
19369 }
19370 
19371 /* \brief Handle SIP response in SUBSCRIBE transaction */
19372 static void handle_response_subscribe(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno)
19373 {
19374    if (!p->mwi) {
19375       return;
19376    }
19377 
19378    switch (resp) {
19379    case 200: /* Subscription accepted */
19380       ast_debug(3, "Got 200 OK on subscription for MWI\n");
19381       set_pvt_allowed_methods(p, req);
19382       if (p->options) {
19383          ast_free(p->options);
19384          p->options = NULL;
19385       }
19386       p->mwi->subscribed = 1;
19387       if ((p->mwi->resub = ast_sched_add(sched, mwi_expiry * 1000, sip_subscribe_mwi_do, ASTOBJ_REF(p->mwi))) < 0) {
19388          ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
19389       }
19390       break;
19391    case 401:
19392    case 407:
19393       ast_string_field_set(p, theirtag, NULL);
19394       if (p->authtries > 1 || do_proxy_auth(p, req, resp, SIP_SUBSCRIBE, 0)) {
19395          ast_log(LOG_NOTICE, "Failed to authenticate on SUBSCRIBE to '%s'\n", get_header(&p->initreq, "From"));
19396          p->mwi->call = NULL;
19397          ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
19398          pvt_set_needdestroy(p, "failed to authenticate SUBSCRIBE");
19399       }
19400       break;
19401    case 403:
19402       transmit_response_with_date(p, "200 OK", req);
19403       ast_log(LOG_WARNING, "Authentication failed while trying to subscribe for MWI.\n");
19404       p->mwi->call = NULL;
19405       ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
19406       pvt_set_needdestroy(p, "received 403 response");
19407       sip_alreadygone(p);
19408       break;
19409    case 404:
19410       ast_log(LOG_WARNING, "Subscription failed for MWI. The remote side said that a mailbox may not have been configured.\n");
19411       p->mwi->call = NULL;
19412       ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
19413       pvt_set_needdestroy(p, "received 404 response");
19414       break;
19415    case 481:
19416       ast_log(LOG_WARNING, "Subscription failed for MWI. The remote side said that our dialog did not exist.\n");
19417       p->mwi->call = NULL;
19418       ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
19419       pvt_set_needdestroy(p, "received 481 response");
19420       break;
19421    case 500:
19422    case 501:
19423       ast_log(LOG_WARNING, "Subscription failed for MWI. The remote side may have suffered a heart attack.\n");
19424       p->mwi->call = NULL;
19425       ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
19426       pvt_set_needdestroy(p, "received 500/501 response");
19427       break;
19428    }
19429 }
19430 
19431 /* \brief Handle SIP response in REFER transaction
19432    We've sent a REFER, now handle responses to it
19433   */
19434 static void handle_response_refer(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno)
19435 {
19436    enum ast_control_transfer message = AST_TRANSFER_FAILED;
19437 
19438    /* If no refer structure exists, then do nothing */
19439    if (!p->refer)
19440       return;
19441 
19442    switch (resp) {
19443    case 202:   /* Transfer accepted */
19444       /* We need  to do something here */
19445       /* The transferee is now sending INVITE to target */
19446       p->refer->status = REFER_ACCEPTED;
19447       /* Now wait for next message */
19448       ast_debug(3, "Got 202 accepted on transfer\n");
19449       /* We should hang along, waiting for NOTIFY's here */
19450       break;
19451 
19452    case 401:   /* Not www-authorized on SIP method */
19453    case 407:   /* Proxy auth */
19454       if (ast_strlen_zero(p->authname)) {
19455          ast_log(LOG_WARNING, "Asked to authenticate REFER to %s but we have no matching peer or realm auth!\n",
19456             ast_sockaddr_stringify(&p->recv));
19457          if (p->owner) {
19458             ast_queue_control_data(p->owner, AST_CONTROL_TRANSFER, &message, sizeof(message));
19459          }
19460          pvt_set_needdestroy(p, "unable to authenticate REFER");
19461       }
19462       if (p->authtries > 1 || do_proxy_auth(p, req, resp, SIP_REFER, 0)) {
19463          ast_log(LOG_NOTICE, "Failed to authenticate on REFER to '%s'\n", get_header(&p->initreq, "From"));
19464          p->refer->status = REFER_NOAUTH;
19465          if (p->owner) {
19466             ast_queue_control_data(p->owner, AST_CONTROL_TRANSFER, &message, sizeof(message));
19467          }
19468          pvt_set_needdestroy(p, "failed to authenticate REFER");
19469       }
19470       break;
19471    
19472    case 405:   /* Method not allowed */
19473       /* Return to the current call onhold */
19474       /* Status flag needed to be reset */
19475       ast_log(LOG_NOTICE, "SIP transfer to %s failed, REFER not allowed. \n", p->refer->refer_to);
19476       pvt_set_needdestroy(p, "received 405 response");
19477       p->refer->status = REFER_FAILED;
19478       if (p->owner) {
19479          ast_queue_control_data(p->owner, AST_CONTROL_TRANSFER, &message, sizeof(message));
19480       }
19481       break;
19482 
19483    case 481: /* Call leg does not exist */
19484 
19485       /* A transfer with Replaces did not work */
19486       /* OEJ: We should Set flag, cancel the REFER, go back
19487       to original call - but right now we can't */
19488       ast_log(LOG_WARNING, "Remote host can't match REFER request to call '%s'. Giving up.\n", p->callid);
19489       if (p->owner)
19490          ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
19491       pvt_set_needdestroy(p, "received 481 response");
19492       break;
19493 
19494    case 500:   /* Server error */
19495    case 501:   /* Method not implemented */
19496       /* Return to the current call onhold */
19497       /* Status flag needed to be reset */
19498       ast_log(LOG_NOTICE, "SIP transfer to %s failed, call miserably fails. \n", p->refer->refer_to);
19499       pvt_set_needdestroy(p, "received 500/501 response");
19500       p->refer->status = REFER_FAILED;
19501       if (p->owner) {
19502          ast_queue_control_data(p->owner, AST_CONTROL_TRANSFER, &message, sizeof(message));
19503       }
19504       break;
19505    case 603:   /* Transfer declined */
19506       ast_log(LOG_NOTICE, "SIP transfer to %s declined, call miserably fails. \n", p->refer->refer_to);
19507       p->refer->status = REFER_FAILED;
19508       pvt_set_needdestroy(p, "received 603 response");
19509       if (p->owner) {
19510          ast_queue_control_data(p->owner, AST_CONTROL_TRANSFER, &message, sizeof(message));
19511       }
19512       break;
19513    default:
19514       /* We should treat unrecognized 9xx as 900.  400 is actually
19515          specified as a possible response, but any 4-6xx is 
19516          theoretically possible. */
19517 
19518       if (resp < 299) { /* 1xx cases don't get here */
19519          ast_log(LOG_WARNING, "SIP transfer to %s had unxpected 2xx response (%d), confusion is possible. \n", p->refer->refer_to, resp);
19520       } else {
19521          ast_log(LOG_WARNING, "SIP transfer to %s with response (%d). \n", p->refer->refer_to, resp);
19522       }
19523 
19524       p->refer->status = REFER_FAILED;
19525       pvt_set_needdestroy(p, "received failure response");
19526       if (p->owner) {
19527          ast_queue_control_data(p->owner, AST_CONTROL_TRANSFER, &message, sizeof(message));
19528       }
19529       break;
19530    }
19531 }
19532 
19533 /*! \brief Handle responses on REGISTER to services */
19534 static int handle_response_register(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno)
19535 {
19536    int expires, expires_ms;
19537    struct sip_registry *r;
19538    r=p->registry;
19539    
19540    switch (resp) {
19541    case 401:   /* Unauthorized */
19542       if (p->authtries == MAX_AUTHTRIES || do_register_auth(p, req, resp)) {
19543          ast_log(LOG_NOTICE, "Failed to authenticate on REGISTER to '%s@%s' (Tries %d)\n", p->registry->username, p->registry->hostname, p->authtries);
19544          pvt_set_needdestroy(p, "failed to authenticate REGISTER");
19545       }
19546       break;
19547    case 403:   /* Forbidden */
19548       ast_log(LOG_WARNING, "Forbidden - wrong password on authentication for REGISTER for '%s' to '%s'\n", p->registry->username, p->registry->hostname);
19549       AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 403"));
19550       r->regstate = REG_STATE_NOAUTH;
19551       pvt_set_needdestroy(p, "received 403 response");
19552       break;
19553    case 404:   /* Not found */
19554       ast_log(LOG_WARNING, "Got 404 Not found on SIP register to service %s@%s, giving up\n", p->registry->username, p->registry->hostname);
19555       pvt_set_needdestroy(p, "received 404 response");
19556       if (r->call)
19557          r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 404");
19558       r->regstate = REG_STATE_REJECTED;
19559       AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 404"));
19560       break;
19561    case 407:   /* Proxy auth */
19562       if (p->authtries == MAX_AUTHTRIES || do_register_auth(p, req, resp)) {
19563          ast_log(LOG_NOTICE, "Failed to authenticate on REGISTER to '%s' (tries '%d')\n", get_header(&p->initreq, "From"), p->authtries);
19564          pvt_set_needdestroy(p, "failed to authenticate REGISTER");
19565       }
19566       break;
19567    case 408:   /* Request timeout */
19568       /* Got a timeout response, so reset the counter of failed responses */
19569       if (r) {
19570          r->regattempts = 0;
19571       } else {
19572          ast_log(LOG_WARNING, "Got a 408 response to our REGISTER on call %s after we had destroyed the registry object\n", p->callid);
19573       }
19574       break;
19575    case 423:   /* Interval too brief */
19576       r->expiry = atoi(get_header(req, "Min-Expires"));
19577       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);
19578       AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 423"));
19579       if (r->call) {
19580          r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 423");
19581          pvt_set_needdestroy(p, "received 423 response");
19582       }
19583       if (r->expiry > max_expiry) {
19584          ast_log(LOG_WARNING, "Required expiration time from %s@%s is too high, giving up\n", p->registry->username, p->registry->hostname);
19585          r->expiry = r->configured_expiry;
19586          r->regstate = REG_STATE_REJECTED;
19587       } else {
19588          r->regstate = REG_STATE_UNREGISTERED;
19589          transmit_register(r, SIP_REGISTER, NULL, NULL);
19590       }
19591       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));
19592       break;
19593    case 479:   /* SER: Not able to process the URI - address is wrong in register*/
19594       ast_log(LOG_WARNING, "Got error 479 on register to %s@%s, giving up (check config)\n", p->registry->username, p->registry->hostname);
19595       pvt_set_needdestroy(p, "received 479 response");
19596       if (r->call)
19597          r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 479");
19598       r->regstate = REG_STATE_REJECTED;
19599       AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 479"));
19600       break;
19601    case 200:   /* 200 OK */
19602       if (!r) {
19603          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));
19604          pvt_set_needdestroy(p, "received erroneous 200 response");
19605          return 0;
19606       }
19607       
19608       r->regstate = REG_STATE_REGISTERED;
19609       r->regtime = ast_tvnow();     /* Reset time of last successful registration */
19610       manager_event(EVENT_FLAG_SYSTEM, "Registry", "ChannelType: SIP\r\nDomain: %s\r\nStatus: %s\r\n", r->hostname, regstate2str(r->regstate));
19611       r->regattempts = 0;
19612       ast_debug(1, "Registration successful\n");
19613       if (r->timeout > -1) {
19614          ast_debug(1, "Cancelling timeout %d\n", r->timeout);
19615       }
19616       AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 200"));
19617       if (r->call)
19618          r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 200");
19619       p->registry = registry_unref(p->registry, "unref registry entry p->registry");
19620       /* Let this one hang around until we have all the responses */
19621       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19622       /* p->needdestroy = 1; */
19623       
19624       /* set us up for re-registering
19625        * figure out how long we got registered for
19626        * according to section 6.13 of RFC, contact headers override
19627        * expires headers, so check those first */
19628       expires = 0;
19629 
19630       /* XXX todo: try to save the extra call */
19631       if (!ast_strlen_zero(get_header(req, "Contact"))) {
19632          const char *contact = NULL;
19633          const char *tmptmp = NULL;
19634          int start = 0;
19635          for(;;) {
19636             contact = __get_header(req, "Contact", &start);
19637             /* this loop ensures we get a contact header about our register request */
19638             if(!ast_strlen_zero(contact)) {
19639                if( (tmptmp=strstr(contact, p->our_contact))) {
19640                   contact=tmptmp;
19641                   break;
19642                }
19643             } else
19644                break;
19645          }
19646          tmptmp = strcasestr(contact, "expires=");
19647          if (tmptmp) {
19648             if (sscanf(tmptmp + 8, "%30d;", &expires) != 1)
19649                expires = 0;
19650          }
19651          
19652       }
19653       if (!expires)
19654          expires=atoi(get_header(req, "expires"));
19655       if (!expires)
19656          expires=default_expiry;
19657       
19658       expires_ms = expires * 1000;
19659       if (expires <= EXPIRY_GUARD_LIMIT)
19660          expires_ms -= MAX((expires_ms * EXPIRY_GUARD_PCT), EXPIRY_GUARD_MIN);
19661       else
19662          expires_ms -= EXPIRY_GUARD_SECS * 1000;
19663       if (sipdebug)
19664          ast_log(LOG_NOTICE, "Outbound Registration: Expiry for %s is %d sec (Scheduling reregistration in %d s)\n", r->hostname, expires, expires_ms/1000);
19665       
19666       r->refresh= (int) expires_ms / 1000;
19667       
19668       /* Schedule re-registration before we expire */
19669       AST_SCHED_REPLACE_UNREF(r->expire, sched, expires_ms, sip_reregister, r,
19670                         registry_unref(_data,"unref in REPLACE del fail"),
19671                         registry_unref(r,"unref in REPLACE add fail"),
19672                         registry_addref(r,"The Addition side of REPLACE"));
19673    }
19674    return 1;
19675 }
19676 
19677 /*! \brief Handle qualification responses (OPTIONS) */
19678 static void handle_response_peerpoke(struct sip_pvt *p, int resp, struct sip_request *req)
19679 {
19680    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! */
19681    int statechanged, is_reachable, was_reachable;
19682    int pingtime = ast_tvdiff_ms(ast_tvnow(), peer->ps);
19683 
19684    /*
19685     * Compute the response time to a ping (goes in peer->lastms.)
19686     * -1 means did not respond, 0 means unknown,
19687     * 1..maxms is a valid response, >maxms means late response.
19688     */
19689    if (pingtime < 1) /* zero = unknown, so round up to 1 */
19690       pingtime = 1;
19691 
19692    /* Now determine new state and whether it has changed.
19693     * Use some helper variables to simplify the writing
19694     * of the expressions.
19695     */
19696    was_reachable = peer->lastms > 0 && peer->lastms <= peer->maxms;
19697    is_reachable = pingtime <= peer->maxms;
19698    statechanged = peer->lastms == 0 /* yes, unknown before */
19699       || was_reachable != is_reachable;
19700 
19701    peer->lastms = pingtime;
19702    peer->call = dialog_unref(peer->call, "unref dialog peer->call");
19703    if (statechanged) {
19704       const char *s = is_reachable ? "Reachable" : "Lagged";
19705       char str_lastms[20];
19706       snprintf(str_lastms, sizeof(str_lastms), "%d", pingtime);
19707 
19708       ast_log(LOG_NOTICE, "Peer '%s' is now %s. (%dms / %dms)\n",
19709          peer->name, s, pingtime, peer->maxms);
19710       ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", peer->name);
19711       if (sip_cfg.peer_rtupdate) {
19712          ast_update_realtime(ast_check_realtime("sipregs") ? "sipregs" : "sippeers", "name", peer->name, "lastms", str_lastms, SENTINEL);
19713       }
19714       manager_event(EVENT_FLAG_SYSTEM, "PeerStatus",
19715          "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: %s\r\nTime: %d\r\n",
19716          peer->name, s, pingtime);
19717       if (is_reachable && sip_cfg.regextenonqualify)
19718          register_peer_exten(peer, TRUE);
19719    }
19720 
19721    pvt_set_needdestroy(p, "got OPTIONS response");
19722 
19723    /* Try again eventually */
19724    AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched,
19725          is_reachable ? peer->qualifyfreq : DEFAULT_FREQ_NOTOK,
19726          sip_poke_peer_s, peer,
19727          unref_peer(_data, "removing poke peer ref"),
19728          unref_peer(peer, "removing poke peer ref"),
19729          ref_peer(peer, "adding poke peer ref"));
19730 }
19731 
19732 /*! \brief Immediately stop RTP, VRTP and UDPTL as applicable */
19733 static void stop_media_flows(struct sip_pvt *p)
19734 {
19735    /* Immediately stop RTP, VRTP and UDPTL as applicable */
19736    if (p->rtp)
19737       ast_rtp_instance_stop(p->rtp);
19738    if (p->vrtp)
19739       ast_rtp_instance_stop(p->vrtp);
19740    if (p->trtp)
19741       ast_rtp_instance_stop(p->trtp);
19742    if (p->udptl)
19743       ast_udptl_stop(p->udptl);
19744 }
19745 
19746 /*! \brief Handle SIP response in dialogue
19747    \note only called by handle_incoming */
19748 static void handle_response(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno)
19749 {
19750    struct ast_channel *owner;
19751    int sipmethod;
19752    int res = 1;
19753    const char *c = get_header(req, "Cseq");
19754    /* 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 */
19755    char *c_copy = ast_strdupa(c);
19756    /* Skip the Cseq and its subsequent spaces */
19757    const char *msg = ast_skip_blanks(ast_skip_nonblanks(c_copy));
19758 
19759    if (!msg)
19760       msg = "";
19761 
19762    sipmethod = find_sip_method(msg);
19763 
19764    owner = p->owner;
19765    if (owner) {
19766       const char *rp = NULL, *rh = NULL;
19767 
19768       owner->hangupcause = 0;
19769       if (ast_test_flag(&p->flags[1], SIP_PAGE2_Q850_REASON) && (rh = get_header(req, "Reason"))) {
19770          rh = ast_skip_blanks(rh);
19771          if (!strncasecmp(rh, "Q.850", 5)) {
19772             rp = strstr(rh, "cause=");
19773             if (rp && sscanf(rp + 6, "%30d", &owner->hangupcause) == 1) {
19774                owner->hangupcause &= 0x7f;
19775                if (req->debug)
19776                   ast_verbose("Using Reason header for cause code: %d\n", owner->hangupcause);
19777             }
19778          }
19779       }
19780 
19781       if (!owner->hangupcause)
19782          owner->hangupcause = hangup_sip2cause(resp);
19783    }
19784 
19785    if (p->socket.type == SIP_TRANSPORT_UDP) {
19786       int ack_res = FALSE;
19787 
19788       /* Acknowledge whatever it is destined for */
19789       if ((resp >= 100) && (resp <= 199)) {
19790          /* NON-INVITE messages do not ack a 1XX response. RFC 3261 section 17.1.2.2 */
19791          if (sipmethod == SIP_INVITE) {
19792             ack_res = __sip_semi_ack(p, seqno, 0, sipmethod);
19793          }
19794       } else {
19795          ack_res = __sip_ack(p, seqno, 0, sipmethod);
19796       }
19797 
19798       if (ack_res == FALSE) {
19799          /* RFC 3261 13.2.2.4 and 17.1.1.2 - We must re-send ACKs to re-transmitted final responses */
19800          if (sipmethod == SIP_INVITE && resp >= 200) {
19801             transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, resp < 300 ? TRUE: FALSE);
19802          }
19803 
19804          append_history(p, "Ignore", "Ignoring this retransmit\n");
19805          return;
19806       }
19807    }
19808 
19809    /* If this is a NOTIFY for a subscription clear the flag that indicates that we have a NOTIFY pending */
19810    if (!p->owner && sipmethod == SIP_NOTIFY && p->pendinginvite)
19811       p->pendinginvite = 0;
19812 
19813    /* Get their tag if we haven't already */
19814    if (ast_strlen_zero(p->theirtag) || (resp >= 200)) {
19815       char tag[128];
19816 
19817       gettag(req, "To", tag, sizeof(tag));
19818       ast_string_field_set(p, theirtag, tag);
19819    }
19820    /* This needs to be configurable on a channel/peer level,
19821       not mandatory for all communication. Sadly enough, NAT implementations
19822       are not so stable so we can always rely on these headers.
19823       Temporarily disabled, while waiting for fix.
19824       Fix assigned to Rizzo :-)
19825    */
19826    /* check_via_response(p, req); */
19827 
19828    /* RFC 3261 Section 15 specifies that if we receive a 408 or 481
19829     * in response to a BYE, then we should end the current dialog
19830     * and session.  It is known that at least one phone manufacturer
19831     * potentially will send a 404 in response to a BYE, so we'll be
19832     * liberal in what we accept and end the dialog and session if we
19833     * receive any of those responses to a BYE.
19834     */
19835    if ((resp == 404 || resp == 408 || resp == 481) && sipmethod == SIP_BYE) {
19836       pvt_set_needdestroy(p, "received 4XX response to a BYE");
19837       return;
19838    }
19839 
19840    if (p->relatedpeer && p->method == SIP_OPTIONS) {
19841       /* We don't really care what the response is, just that it replied back.
19842          Well, as long as it's not a 100 response...  since we might
19843          need to hang around for something more "definitive" */
19844       if (resp != 100)
19845          handle_response_peerpoke(p, resp, req);
19846    } else if (sipmethod == SIP_REFER && resp >= 200) {
19847       handle_response_refer(p, resp, rest, req, seqno);
19848    } else if (sipmethod == SIP_PUBLISH) {
19849       /* SIP PUBLISH transcends this morass of doodoo and instead
19850        * we just always call the response handler. Good gravy!
19851        */
19852       handle_response_publish(p, resp, rest, req, seqno);
19853    } else if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
19854       switch(resp) {
19855       case 100:   /* 100 Trying */
19856       case 101:   /* 101 Dialog establishment */
19857       case 183:   /* 183 Session Progress */
19858       case 180:   /* 180 Ringing */
19859       case 182:   /* 182 Queued */
19860       case 181:   /* 181 Call Is Being Forwarded */
19861          if (sipmethod == SIP_INVITE)
19862             handle_response_invite(p, resp, rest, req, seqno);
19863          break;
19864       case 200:   /* 200 OK */
19865          p->authtries = 0; /* Reset authentication counter */
19866          if (sipmethod == SIP_MESSAGE || sipmethod == SIP_INFO) {
19867             /* We successfully transmitted a message
19868                or a video update request in INFO */
19869             /* Nothing happens here - the message is inside a dialog */
19870          } else if (sipmethod == SIP_INVITE) {
19871             handle_response_invite(p, resp, rest, req, seqno);
19872          } else if (sipmethod == SIP_NOTIFY) {
19873             handle_response_notify(p, resp, rest, req, seqno);
19874          } else if (sipmethod == SIP_REGISTER) {
19875             res = handle_response_register(p, resp, rest, req, seqno);
19876          } else if (sipmethod == SIP_SUBSCRIBE) {
19877             ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
19878             handle_response_subscribe(p, resp, rest, req, seqno);
19879          } else if (sipmethod == SIP_BYE) {     /* Ok, we're ready to go */
19880             pvt_set_needdestroy(p, "received 200 response");
19881             ast_clear_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
19882          }
19883          break;
19884       case 401: /* Not www-authorized on SIP method */
19885       case 407: /* Proxy auth required */
19886          if (sipmethod == SIP_INVITE)
19887             handle_response_invite(p, resp, rest, req, seqno);
19888          else if (sipmethod == SIP_NOTIFY)
19889             handle_response_notify(p, resp, rest, req, seqno);
19890          else if (sipmethod == SIP_SUBSCRIBE)
19891             handle_response_subscribe(p, resp, rest, req, seqno);
19892          else if (p->registry && sipmethod == SIP_REGISTER)
19893             res = handle_response_register(p, resp, rest, req, seqno);
19894          else if (sipmethod == SIP_UPDATE) {
19895             handle_response_update(p, resp, rest, req, seqno);
19896          } else if (sipmethod == SIP_BYE) {
19897             if (p->options)
19898                p->options->auth_type = resp;
19899             if (ast_strlen_zero(p->authname)) {
19900                ast_log(LOG_WARNING, "Asked to authenticate %s, to %s but we have no matching peer!\n",
19901                      msg, ast_sockaddr_stringify(&p->recv));
19902                pvt_set_needdestroy(p, "unable to authenticate BYE");
19903             } else if ((p->authtries == MAX_AUTHTRIES) || do_proxy_auth(p, req, resp,  sipmethod, 0)) {
19904                ast_log(LOG_NOTICE, "Failed to authenticate on %s to '%s'\n", msg, get_header(&p->initreq, "From"));
19905                pvt_set_needdestroy(p, "failed to authenticate BYE");
19906             }
19907          } else {
19908             ast_log(LOG_WARNING, "Got authentication request (%d) on %s to '%s'\n", resp, sip_methods[sipmethod].text, get_header(req, "To"));
19909             pvt_set_needdestroy(p, "received 407 response");
19910          }
19911          break;
19912       case 403: /* Forbidden - we failed authentication */
19913          if (sipmethod == SIP_INVITE)
19914             handle_response_invite(p, resp, rest, req, seqno);
19915          else if (sipmethod == SIP_SUBSCRIBE)
19916             handle_response_subscribe(p, resp, rest, req, seqno);
19917          else if (p->registry && sipmethod == SIP_REGISTER)
19918             res = handle_response_register(p, resp, rest, req, seqno);
19919          else {
19920             ast_log(LOG_WARNING, "Forbidden - maybe wrong password on authentication for %s\n", msg);
19921             pvt_set_needdestroy(p, "received 403 response");
19922          }
19923          break;
19924       case 404: /* Not found */
19925          if (p->registry && sipmethod == SIP_REGISTER)
19926             res = handle_response_register(p, resp, rest, req, seqno);
19927          else if (sipmethod == SIP_INVITE)
19928             handle_response_invite(p, resp, rest, req, seqno);
19929          else if (sipmethod == SIP_SUBSCRIBE)
19930             handle_response_subscribe(p, resp, rest, req, seqno);
19931          else if (owner)
19932             ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
19933          break;
19934       case 423: /* Interval too brief */
19935          if (sipmethod == SIP_REGISTER)
19936             res = handle_response_register(p, resp, rest, req, seqno);
19937          break;
19938       case 408: /* Request timeout - terminate dialog */
19939          if (sipmethod == SIP_INVITE)
19940             handle_response_invite(p, resp, rest, req, seqno);
19941          else if (sipmethod == SIP_REGISTER)
19942             res = handle_response_register(p, resp, rest, req, seqno);
19943          else if (sipmethod == SIP_BYE) {
19944             pvt_set_needdestroy(p, "received 408 response");
19945             ast_debug(4, "Got timeout on bye. Thanks for the answer. Now, kill this call\n");
19946          } else {
19947             if (owner)
19948                ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
19949             pvt_set_needdestroy(p, "received 408 response");
19950          }
19951          break;
19952 
19953       case 422: /* Session-Timers: Session Interval Too Small */
19954          if (sipmethod == SIP_INVITE) {
19955             handle_response_invite(p, resp, rest, req, seqno);
19956          }
19957          break;
19958 
19959       case 481: /* Call leg does not exist */
19960          if (sipmethod == SIP_INVITE) {
19961             handle_response_invite(p, resp, rest, req, seqno);
19962          } else if (sipmethod == SIP_SUBSCRIBE) {
19963             handle_response_subscribe(p, resp, rest, req, seqno);
19964          } else if (sipmethod == SIP_NOTIFY) {
19965             pvt_set_needdestroy(p, "received 481 response");
19966          } else if (sipmethod == SIP_BYE) {
19967             /* The other side has no transaction to bye,
19968             just assume it's all right then */
19969             ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
19970          } else if (sipmethod == SIP_CANCEL) {
19971             /* The other side has no transaction to cancel,
19972             just assume it's all right then */
19973             ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
19974          } else {
19975             ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
19976             /* Guessing that this is not an important request */
19977          }
19978          break;
19979       case 487:
19980          if (sipmethod == SIP_INVITE)
19981             handle_response_invite(p, resp, rest, req, seqno);
19982          break;
19983       case 415: /* Unsupported media type */
19984       case 488: /* Not acceptable here - codec error */
19985       case 606: /* Not Acceptable */
19986          if (sipmethod == SIP_INVITE)
19987             handle_response_invite(p, resp, rest, req, seqno);
19988          break;
19989       case 491: /* Pending */
19990          if (sipmethod == SIP_INVITE)
19991             handle_response_invite(p, resp, rest, req, seqno);
19992          else {
19993             ast_debug(1, "Got 491 on %s, unsupported. Call ID %s\n", sip_methods[sipmethod].text, p->callid);
19994             pvt_set_needdestroy(p, "received 491 response");
19995          }
19996          break;
19997       case 405:
19998       case 501: /* Not Implemented */
19999          mark_method_unallowed(&p->allowed_methods, sipmethod);
20000          if (p->relatedpeer) {
20001             mark_method_allowed(&p->relatedpeer->disallowed_methods, sipmethod);
20002          }
20003          if (sipmethod == SIP_INVITE)
20004             handle_response_invite(p, resp, rest, req, seqno);
20005          else
20006             ast_log(LOG_WARNING, "Host '%s' does not implement '%s'\n", ast_sockaddr_stringify(&p->sa), msg);
20007          break;
20008          /* Fallthrough */
20009       default:
20010          if ((resp >= 300) && (resp < 700)) {
20011             /* Fatal response */
20012             if ((resp != 487))
20013                ast_verb(3, "Got SIP response %d \"%s\" back from %s\n", resp, rest, ast_sockaddr_stringify(&p->sa));
20014    
20015             if (sipmethod == SIP_INVITE)
20016                stop_media_flows(p); /* Immediately stop RTP, VRTP and UDPTL as applicable */
20017 
20018             /* XXX Locking issues?? XXX */
20019             switch(resp) {
20020             case 300: /* Multiple Choices */
20021             case 301: /* Moved permanently */
20022             case 302: /* Moved temporarily */
20023             case 305: /* Use Proxy */
20024             if (p->owner) {
20025                struct ast_party_redirecting redirecting;
20026                struct ast_set_party_redirecting update_redirecting;
20027 
20028                ast_party_redirecting_init(&redirecting);
20029                change_redirecting_information(p, req, &redirecting,
20030                   &update_redirecting, TRUE);
20031                ast_channel_set_redirecting(p->owner, &redirecting,
20032                   &update_redirecting);
20033                ast_party_redirecting_free(&redirecting);
20034             }
20035                /* Fall through */
20036             case 486: /* Busy here */
20037             case 600: /* Busy everywhere */
20038             case 603: /* Decline */
20039                if (p->owner) {
20040                   sip_handle_cc(p, req, AST_CC_CCBS);
20041                   ast_queue_control(p->owner, AST_CONTROL_BUSY);
20042                }
20043                break;
20044             case 482: /* Loop Detected */
20045             case 480: /* Temporarily Unavailable */
20046             case 404: /* Not Found */
20047             case 410: /* Gone */
20048             case 400: /* Bad Request */
20049             case 500: /* Server error */
20050                if (sipmethod == SIP_SUBSCRIBE) {
20051                   handle_response_subscribe(p, resp, rest, req, seqno);
20052                   break;
20053                }
20054                /* Fall through */
20055             case 502: /* Bad gateway */
20056             case 503: /* Service Unavailable */
20057             case 504: /* Server Timeout */
20058                if (owner)
20059                   ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
20060                break;
20061             default:
20062                /* Send hangup */ 
20063                if (owner && sipmethod != SIP_MESSAGE && sipmethod != SIP_INFO && sipmethod != SIP_BYE)
20064                   ast_queue_hangup_with_cause(p->owner, AST_CAUSE_PROTOCOL_ERROR);
20065                break;
20066             }
20067             /* ACK on invite */
20068             if (sipmethod == SIP_INVITE)
20069                transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
20070             if (sipmethod != SIP_MESSAGE && sipmethod != SIP_INFO)
20071                sip_alreadygone(p);
20072             if (!p->owner) {
20073                pvt_set_needdestroy(p, "transaction completed");
20074             }
20075          } else if ((resp >= 100) && (resp < 200)) {
20076             if (sipmethod == SIP_INVITE) {
20077                if (!req->ignore && sip_cancel_destroy(p))
20078                   ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
20079                if (find_sdp(req))
20080                   process_sdp(p, req, SDP_T38_NONE);
20081                if (p->owner) {
20082                   /* Queue a progress frame */
20083                   ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
20084                }
20085             }
20086          } else
20087             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));
20088       }
20089    } else { 
20090       /* Responses to OUTGOING SIP requests on INCOMING calls
20091          get handled here. As well as out-of-call message responses */
20092       if (req->debug)
20093          ast_verbose("SIP Response message for INCOMING dialog %s arrived\n", msg);
20094 
20095       if (sipmethod == SIP_INVITE && resp == 200) {
20096          /* Tags in early session is replaced by the tag in 200 OK, which is
20097          the final reply to our INVITE */
20098          char tag[128];
20099 
20100          gettag(req, "To", tag, sizeof(tag));
20101          ast_string_field_set(p, theirtag, tag);
20102       }
20103 
20104       if (sipmethod == SIP_SUBSCRIBE && resp >= 400) {
20105          struct sip_monitor_instance *monitor_instance = ao2_callback(sip_monitor_instances,
20106                0, find_sip_monitor_instance_by_subscription_pvt, p);
20107          if (monitor_instance) {
20108             ast_cc_monitor_failed(monitor_instance->core_id, monitor_instance->device_name,
20109                   "Received error response to our SUBSCRIBE");
20110             return;
20111          }
20112       }
20113 
20114       switch(resp) {
20115       case 200:
20116          if (sipmethod == SIP_INVITE) {
20117             handle_response_invite(p, resp, rest, req, seqno);
20118          } else if (sipmethod == SIP_CANCEL) {
20119             ast_debug(1, "Got 200 OK on CANCEL\n");
20120 
20121             /* Wait for 487, then destroy */
20122          } else if (sipmethod == SIP_NOTIFY) {
20123             /* They got the notify, this is the end */
20124             if (p->owner) {
20125                if (p->refer) {
20126                   ast_debug(1, "Got 200 OK on NOTIFY for transfer\n");
20127                } else
20128                   ast_log(LOG_WARNING, "Notify answer on an owned channel?\n");
20129                /* ast_queue_hangup(p->owner); Disabled */
20130             } else {
20131                if (!p->subscribed && !p->refer) {
20132                   pvt_set_needdestroy(p, "transaction completed");
20133                }
20134                if (ast_test_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE)) {
20135                   /* Ready to send the next state we have on queue */
20136                   ast_clear_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE);
20137                   cb_extensionstate((char *)p->context, (char *)p->exten, p->laststate, (void *) p);
20138                }
20139             }
20140          } else if (sipmethod == SIP_BYE) {
20141             pvt_set_needdestroy(p, "transaction completed");
20142          } else if (sipmethod == SIP_MESSAGE || sipmethod == SIP_INFO) {
20143             /* We successfully transmitted a message or
20144                a video update request in INFO */
20145             ;
20146          }
20147          break;
20148       case 401:   /* www-auth */
20149       case 407:
20150          if (sipmethod == SIP_INVITE)
20151             handle_response_invite(p, resp, rest, req, seqno);
20152          else if (sipmethod == SIP_BYE) {
20153             if (p->authtries == MAX_AUTHTRIES || do_proxy_auth(p, req, resp, sipmethod, 0)) {
20154                ast_log(LOG_NOTICE, "Failed to authenticate on %s to '%s'\n", msg, get_header(&p->initreq, "From"));
20155                pvt_set_needdestroy(p, "failed to authenticate BYE");
20156             }
20157          }
20158          break;
20159       case 481:   /* Call leg does not exist */
20160          if (sipmethod == SIP_INVITE) {
20161             /* Re-invite failed */
20162             handle_response_invite(p, resp, rest, req, seqno);
20163          } else if (sipmethod == SIP_BYE) {
20164             pvt_set_needdestroy(p, "received 481 response");
20165          } else if (sipmethod == SIP_NOTIFY) {
20166             pvt_set_needdestroy(p, "received 481 response");
20167          } else if (sipdebug) {
20168             ast_debug(1, "Remote host can't match request %s to call '%s'. Giving up\n", sip_methods[sipmethod].text, p->callid);
20169          }
20170          break;
20171       case 501: /* Not Implemented */
20172          if (sipmethod == SIP_INVITE)
20173             handle_response_invite(p, resp, rest, req, seqno);
20174          break;
20175       default: /* Errors without handlers */
20176          if ((resp >= 100) && (resp < 200)) {
20177             if (sipmethod == SIP_INVITE) {   /* re-invite */
20178                if (!req->ignore && sip_cancel_destroy(p))
20179                   ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
20180             }
20181          }
20182          if ((resp >= 300) && (resp < 700)) {
20183             if ((resp != 487))
20184                ast_verb(3, "Incoming call: Got SIP response %d \"%s\" back from %s\n", resp, rest, ast_sockaddr_stringify(&p->sa));
20185             switch(resp) {
20186             case 415: /* Unsupported media type */
20187             case 488: /* Not acceptable here - codec error */
20188             case 603: /* Decline */
20189             case 500: /* Server error */
20190             case 502: /* Bad gateway */
20191             case 503: /* Service Unavailable */
20192             case 504: /* Server timeout */
20193 
20194                /* re-invite failed */
20195                if (sipmethod == SIP_INVITE && sip_cancel_destroy(p))
20196                   ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
20197                break;
20198             }
20199          }
20200          break;
20201       }
20202    }
20203 }
20204 
20205 
20206 /*! \brief Park SIP call support function
20207    Starts in a new thread, then parks the call
20208    XXX Should we add a wait period after streaming audio and before hangup?? Sometimes the
20209       audio can't be heard before hangup
20210 */
20211 static void *sip_park_thread(void *stuff)
20212 {
20213    struct ast_channel *transferee, *transferer; /* Chan1: The transferee, Chan2: The transferer */
20214    struct sip_dual *d;
20215    struct sip_request req = {0,};
20216    int ext;
20217    int res;
20218 
20219    d = stuff;
20220    transferee = d->chan1;
20221    transferer = d->chan2;
20222    copy_request(&req, &d->req);
20223 
20224    if (!transferee || !transferer) {
20225       ast_log(LOG_ERROR, "Missing channels for parking! Transferer %s Transferee %s\n", transferer ? "<available>" : "<missing>", transferee ? "<available>" : "<missing>" );
20226       deinit_req(&d->req);
20227       ast_free(d);
20228       return NULL;
20229    }
20230    ast_debug(4, "SIP Park: Transferer channel %s, Transferee %s\n", transferer->name, transferee->name);
20231 
20232    if (ast_do_masquerade(transferee)) {
20233       ast_log(LOG_WARNING, "Masquerade failed.\n");
20234       transmit_response(transferer->tech_pvt, "503 Internal error", &req);
20235       deinit_req(&d->req);
20236       ast_free(d);
20237       return NULL;
20238    }
20239 
20240    res = ast_park_call(transferee, transferer, 0, d->parkexten, &ext);
20241    
20242 
20243 #ifdef WHEN_WE_KNOW_THAT_THE_CLIENT_SUPPORTS_MESSAGE
20244    if (!res) {
20245       transmit_message_with_text(transferer->tech_pvt, "Unable to park call.\n");
20246    } else {
20247       /* Then tell the transferer what happened */
20248       sprintf(buf, "Call parked on extension '%d'", ext);
20249       transmit_message_with_text(transferer->tech_pvt, buf);
20250    }
20251 #endif
20252 
20253    /* Any way back to the current call??? */
20254    /* Transmit response to the REFER request */
20255    if (!res)   {
20256       /* Transfer succeeded */
20257       append_history(transferer->tech_pvt, "SIPpark", "Parked call on %d", ext);
20258       transmit_notify_with_sipfrag(transferer->tech_pvt, d->seqno, "200 OK", TRUE);
20259       transferer->hangupcause = AST_CAUSE_NORMAL_CLEARING;
20260       ast_hangup(transferer); /* This will cause a BYE */
20261       ast_debug(1, "SIP Call parked on extension '%d'\n", ext);
20262    } else {
20263       transmit_notify_with_sipfrag(transferer->tech_pvt, d->seqno, "503 Service Unavailable", TRUE);
20264       append_history(transferer->tech_pvt, "SIPpark", "Parking failed\n");
20265       ast_debug(1, "SIP Call parked failed \n");
20266       /* Do not hangup call */
20267    }
20268    deinit_req(&d->req);
20269    ast_free(d);
20270    return NULL;
20271 }
20272 
20273 /*! \brief Park a call using the subsystem in res_features.c
20274    This is executed in a separate thread
20275 */
20276 static int sip_park(struct ast_channel *chan1, struct ast_channel *chan2, struct sip_request *req, int seqno, char *parkexten)
20277 {
20278    struct sip_dual *d;
20279    struct ast_channel *transferee, *transferer;
20280       /* Chan2m: The transferer, chan1m: The transferee */
20281    pthread_t th;
20282 
20283    transferee = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, chan1->accountcode, chan1->exten, chan1->context, chan1->linkedid, chan1->amaflags, "Parking/%s", chan1->name);
20284    transferer = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, chan2->accountcode, chan2->exten, chan2->context, chan2->linkedid, chan2->amaflags, "SIPPeer/%s", chan2->name);
20285    if ((!transferer) || (!transferee)) {
20286       if (transferee) {
20287          transferee->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
20288          ast_hangup(transferee);
20289       }
20290       if (transferer) {
20291          transferer->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
20292          ast_hangup(transferer);
20293       }
20294       return -1;
20295    }
20296 
20297    /* Make formats okay */
20298    transferee->readformat = chan1->readformat;
20299    transferee->writeformat = chan1->writeformat;
20300 
20301    /* Prepare for taking over the channel */
20302    ast_channel_masquerade(transferee, chan1);
20303 
20304    /* Setup the extensions and such */
20305    ast_copy_string(transferee->context, chan1->context, sizeof(transferee->context));
20306    ast_copy_string(transferee->exten, chan1->exten, sizeof(transferee->exten));
20307    transferee->priority = chan1->priority;
20308       
20309    /* We make a clone of the peer channel too, so we can play
20310       back the announcement */
20311 
20312    /* Make formats okay */
20313    transferer->readformat = chan2->readformat;
20314    transferer->writeformat = chan2->writeformat;
20315    if (!ast_strlen_zero(chan2->parkinglot))
20316       ast_string_field_set(transferer, parkinglot, chan2->parkinglot);
20317 
20318    /* Prepare for taking over the channel.  Go ahead and grab this channel
20319     * lock here to avoid a deadlock with callbacks into the channel driver
20320     * that hold the channel lock and want the pvt lock.  */
20321    while (ast_channel_trylock(chan2)) {
20322       struct sip_pvt *pvt = chan2->tech_pvt;
20323       sip_pvt_unlock(pvt);
20324       usleep(1);
20325       sip_pvt_lock(pvt);
20326    }
20327    ast_channel_masquerade(transferer, chan2);
20328    ast_channel_unlock(chan2);
20329 
20330    /* Setup the extensions and such */
20331    ast_copy_string(transferer->context, chan2->context, sizeof(transferer->context));
20332    ast_copy_string(transferer->exten, chan2->exten, sizeof(transferer->exten));
20333    transferer->priority = chan2->priority;
20334 
20335    if (ast_do_masquerade(transferer)) {
20336       ast_log(LOG_WARNING, "Masquerade failed :(\n");
20337       transferer->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
20338       ast_hangup(transferer);
20339       return -1;
20340    }
20341    if (!transferer || !transferee) {
20342       if (!transferer) {
20343          ast_debug(1, "No transferer channel, giving up parking\n");
20344       }
20345       if (!transferee) {
20346          ast_debug(1, "No transferee channel, giving up parking\n");
20347       }
20348       return -1;
20349    }
20350    if (!(d = ast_calloc(1, sizeof(*d)))) {
20351       return -1;
20352    }
20353 
20354    /* Save original request for followup */
20355    copy_request(&d->req, req);
20356    d->chan1 = transferee;  /* Transferee */
20357    d->chan2 = transferer;  /* Transferer */
20358    d->seqno = seqno;
20359    d->parkexten = parkexten;
20360    if (ast_pthread_create_detached_background(&th, NULL, sip_park_thread, d) < 0) {
20361       /* Could not start thread */
20362       deinit_req(&d->req);
20363       ast_free(d);   /* We don't need it anymore. If thread is created, d will be free'd
20364                by sip_park_thread() */
20365       return -1;
20366    }
20367    return 0;
20368 }
20369 
20370 /*! \brief Turn off generator data
20371    XXX Does this function belong in the SIP channel?
20372 */
20373 static void ast_quiet_chan(struct ast_channel *chan)
20374 {
20375    if (chan && chan->_state == AST_STATE_UP) {
20376       if (ast_test_flag(chan, AST_FLAG_MOH))
20377          ast_moh_stop(chan);
20378       else if (chan->generatordata)
20379          ast_deactivate_generator(chan);
20380    }
20381 }
20382 
20383 /*! \brief Attempt transfer of SIP call
20384    This fix for attended transfers on a local PBX */
20385 static int attempt_transfer(struct sip_dual *transferer, struct sip_dual *target)
20386 {
20387    int res = 0;
20388    struct ast_channel *peera = NULL,   
20389       *peerb = NULL,
20390       *peerc = NULL,
20391       *peerd = NULL;
20392 
20393 
20394    /* We will try to connect the transferee with the target and hangup
20395       all channels to the transferer */   
20396    ast_debug(4, "Sip transfer:--------------------\n");
20397    if (transferer->chan1)
20398       ast_debug(4, "-- Transferer to PBX channel: %s State %s\n", transferer->chan1->name, ast_state2str(transferer->chan1->_state));
20399    else
20400       ast_debug(4, "-- No transferer first channel - odd??? \n");
20401    if (target->chan1)
20402       ast_debug(4, "-- Transferer to PBX second channel (target): %s State %s\n", target->chan1->name, ast_state2str(target->chan1->_state));
20403    else
20404       ast_debug(4, "-- No target first channel ---\n");
20405    if (transferer->chan2)
20406       ast_debug(4, "-- Bridged call to transferee: %s State %s\n", transferer->chan2->name, ast_state2str(transferer->chan2->_state));
20407    else
20408       ast_debug(4, "-- No bridged call to transferee\n");
20409    if (target->chan2)
20410       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)");
20411    else
20412       ast_debug(4, "-- No target second channel ---\n");
20413    ast_debug(4, "-- END Sip transfer:--------------------\n");
20414    if (transferer->chan2) { /* We have a bridge on the transferer's channel */
20415       peera = transferer->chan1; /* Transferer - PBX -> transferee channel * the one we hangup */
20416       peerb = target->chan1;     /* Transferer - PBX -> target channel - This will get lost in masq */
20417       peerc = transferer->chan2; /* Asterisk to Transferee */
20418       peerd = target->chan2;     /* Asterisk to Target */
20419       ast_debug(3, "SIP transfer: Four channels to handle\n");
20420    } else if (target->chan2) {   /* Transferer has no bridge (IVR), but transferee */
20421       peera = target->chan1;     /* Transferer to PBX -> target channel */
20422       peerb = transferer->chan1; /* Transferer to IVR*/
20423       peerc = target->chan2;     /* Asterisk to Target */
20424       peerd = transferer->chan2; /* Nothing */
20425       ast_debug(3, "SIP transfer: Three channels to handle\n");
20426    }
20427 
20428    if (peera && peerb && peerc && (peerb != peerc)) {
20429       ast_quiet_chan(peera);     /* Stop generators */
20430       ast_quiet_chan(peerb);  
20431       ast_quiet_chan(peerc);
20432       if (peerd)
20433          ast_quiet_chan(peerd);
20434 
20435       ast_debug(4, "SIP transfer: trying to masquerade %s into %s\n", peerc->name, peerb->name);
20436       if (ast_channel_masquerade(peerb, peerc)) {
20437          ast_log(LOG_WARNING, "Failed to masquerade %s into %s\n", peerb->name, peerc->name);
20438          res = -1;
20439       } else
20440          ast_debug(4, "SIP transfer: Succeeded to masquerade channels.\n");
20441       return res;
20442    } else {
20443       ast_log(LOG_NOTICE, "SIP Transfer attempted with no appropriate bridged calls to transfer\n");
20444       if (transferer->chan1)
20445          ast_softhangup_nolock(transferer->chan1, AST_SOFTHANGUP_DEV);
20446       if (target->chan1)
20447          ast_softhangup_nolock(target->chan1, AST_SOFTHANGUP_DEV);
20448       return -1;
20449    }
20450    return 0;
20451 }
20452 
20453 /*! \brief Get tag from packet
20454  *
20455  * \return Returns the pointer to the provided tag buffer,
20456  *         or NULL if the tag was not found.
20457  */
20458 static const char *gettag(const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize)
20459 {
20460    const char *thetag;
20461 
20462    if (!tagbuf)
20463       return NULL;
20464    tagbuf[0] = '\0';    /* reset the buffer */
20465    thetag = get_header(req, header);
20466    thetag = strcasestr(thetag, ";tag=");
20467    if (thetag) {
20468       thetag += 5;
20469       ast_copy_string(tagbuf, thetag, tagbufsize);
20470       return strsep(&tagbuf, ";");
20471    }
20472    return NULL;
20473 }
20474 
20475 static int handle_cc_notify(struct sip_pvt *pvt, struct sip_request *req)
20476 {
20477    struct sip_monitor_instance *monitor_instance = ao2_callback(sip_monitor_instances, 0,
20478          find_sip_monitor_instance_by_subscription_pvt, pvt);
20479    const char *status = get_body(req, "cc-state", ':');
20480    struct cc_epa_entry *cc_entry;
20481    char *uri;
20482 
20483    if (!monitor_instance) {
20484       transmit_response(pvt, "400 Bad Request", req);
20485       return -1;
20486    }
20487 
20488    if (ast_strlen_zero(status)) {
20489       ao2_ref(monitor_instance, -1);
20490       transmit_response(pvt, "400 Bad Request", req);
20491       return -1;
20492    }
20493 
20494    if (!strcmp(status, "queued")) {
20495       /* We've been told that we're queued. This is the endpoint's way of telling
20496        * us that it has accepted our CC request. We need to alert the core of this
20497        * development
20498        */
20499       ast_cc_monitor_request_acked(monitor_instance->core_id, "SIP endpoint %s accepted request", monitor_instance->device_name);
20500       transmit_response(pvt, "200 OK", req);
20501       ao2_ref(monitor_instance, -1);
20502       return 0;
20503    }
20504 
20505    /* It's open! Yay! */
20506    uri = get_body(req, "cc-URI", ':');
20507    if (ast_strlen_zero(uri)) {
20508       uri = get_in_brackets((char *)get_header(req, "From"));
20509    }
20510 
20511    ast_string_field_set(monitor_instance, notify_uri, uri);
20512    if (monitor_instance->suspension_entry) {
20513       cc_entry = monitor_instance->suspension_entry->instance_data;
20514       if (cc_entry->current_state == CC_CLOSED) {
20515          /* If we've created a suspension entry and the current state is closed, then that means
20516           * we got a notice from the CC core earlier to suspend monitoring, but because this particular
20517           * call leg had not yet notified us that it was ready for recall, it meant that we
20518           * could not yet send a PUBLISH. Now, however, we can.
20519           */
20520          construct_pidf_body(CC_CLOSED, monitor_instance->suspension_entry->body,
20521                sizeof(monitor_instance->suspension_entry->body), monitor_instance->peername);
20522          transmit_publish(monitor_instance->suspension_entry, SIP_PUBLISH_INITIAL, monitor_instance->notify_uri);
20523       } else {
20524          ast_cc_monitor_callee_available(monitor_instance->core_id, "SIP monitored callee has become available");
20525       }
20526    } else {
20527       ast_cc_monitor_callee_available(monitor_instance->core_id, "SIP monitored callee has become available");
20528    }
20529    ao2_ref(monitor_instance, -1);
20530    transmit_response(pvt, "200 OK", req);
20531 
20532    return 0;
20533 }
20534 
20535 /*! \brief Handle incoming notifications */
20536 static int handle_request_notify(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, int seqno, const char *e)
20537 {
20538    /* This is mostly a skeleton for future improvements */
20539    /* Mostly created to return proper answers on notifications on outbound REFER's */
20540    int res = 0;
20541    const char *event = get_header(req, "Event");
20542    char *eventid = NULL;
20543    char *sep;
20544 
20545    if( (sep = strchr(event, ';')) ) {  /* XXX bug here - overwriting string ? */
20546       *sep++ = '\0';
20547       eventid = sep;
20548    }
20549    
20550    if (sipdebug)
20551       ast_debug(2, "Got NOTIFY Event: %s\n", event);
20552 
20553    if (!strcmp(event, "refer")) {
20554       /* Save nesting depth for now, since there might be other events we will
20555          support in the future */
20556 
20557       /* Handle REFER notifications */
20558 
20559       char buf[1024];
20560       char *cmd, *code;
20561       int respcode;
20562       int success = TRUE;
20563 
20564       /* EventID for each transfer... EventID is basically the REFER cseq
20565 
20566        We are getting notifications on a call that we transfered
20567        We should hangup when we are getting a 200 OK in a sipfrag
20568        Check if we have an owner of this event */
20569       
20570       /* Check the content type */
20571       if (strncasecmp(get_header(req, "Content-Type"), "message/sipfrag", strlen("message/sipfrag"))) {
20572          /* We need a sipfrag */
20573          transmit_response(p, "400 Bad request", req);
20574          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20575          return -1;
20576       }
20577 
20578       /* Get the text of the attachment */
20579       if (get_msg_text(buf, sizeof(buf), req, TRUE)) {
20580          ast_log(LOG_WARNING, "Unable to retrieve attachment from NOTIFY %s\n", p->callid);
20581          transmit_response(p, "400 Bad request", req);
20582          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20583          return -1;
20584       }
20585 
20586       /*
20587       From the RFC...
20588       A minimal, but complete, implementation can respond with a single
20589       NOTIFY containing either the body:
20590          SIP/2.0 100 Trying
20591       
20592       if the subscription is pending, the body:
20593          SIP/2.0 200 OK
20594       if the reference was successful, the body:
20595          SIP/2.0 503 Service Unavailable
20596       if the reference failed, or the body:
20597          SIP/2.0 603 Declined
20598 
20599       if the REFER request was accepted before approval to follow the
20600       reference could be obtained and that approval was subsequently denied
20601       (see Section 2.4.7).
20602       
20603       If there are several REFERs in the same dialog, we need to
20604       match the ID of the event header...
20605       */
20606       ast_debug(3, "* SIP Transfer NOTIFY Attachment: \n---%s\n---\n", buf);
20607       cmd = ast_skip_blanks(buf);
20608       code = cmd;
20609       /* We are at SIP/2.0 */
20610       while(*code && (*code > 32)) {   /* Search white space */
20611          code++;
20612       }
20613       *code++ = '\0';
20614       code = ast_skip_blanks(code);
20615       sep = code;
20616       sep++;
20617       while(*sep && (*sep > 32)) {  /* Search white space */
20618          sep++;
20619       }
20620       *sep++ = '\0';       /* Response string */
20621       respcode = atoi(code);
20622       switch (respcode) {
20623       case 200:   /* OK: The new call is up, hangup this call */
20624          /* Hangup the call that we are replacing */
20625          break;
20626       case 301: /* Moved permenantly */
20627       case 302: /* Moved temporarily */
20628          /* Do we get the header in the packet in this case? */
20629          success = FALSE;
20630          break;
20631       case 503:   /* Service Unavailable: The new call failed */
20632       case 603:   /* Declined: Not accepted */
20633             /* Cancel transfer, continue the current call */
20634          success = FALSE;
20635          break;
20636       case 0:     /* Parse error */
20637             /* Cancel transfer, continue the current call */
20638          ast_log(LOG_NOTICE, "Error parsing sipfrag in NOTIFY in response to REFER.\n");
20639          success = FALSE;
20640          break;
20641       default:
20642          if (respcode < 200) {
20643             /* ignore provisional responses */
20644             success = -1;
20645          } else {
20646             ast_log(LOG_NOTICE, "Got unknown code '%d' in NOTIFY in response to REFER.\n", respcode);
20647             success = FALSE;
20648          }
20649          break;
20650       }
20651       if (success == FALSE) {
20652          ast_log(LOG_NOTICE, "Transfer failed. Sorry. Nothing further to do with this call\n");
20653       }
20654 
20655       if (p->owner && success != -1) {
20656          enum ast_control_transfer message = success ? AST_TRANSFER_SUCCESS : AST_TRANSFER_FAILED;
20657          ast_queue_control_data(p->owner, AST_CONTROL_TRANSFER, &message, sizeof(message));
20658       }
20659       /* Confirm that we received this packet */
20660       transmit_response(p, "200 OK", req);
20661    } else if (!strcmp(event, "message-summary")) {
20662       const char *mailbox = NULL;
20663       char *c = ast_strdupa(get_body(req, "Voice-Message", ':'));
20664 
20665       if (!p->mwi) {
20666          struct sip_peer *peer = find_peer(NULL, &p->recv, TRUE, FINDPEERS, FALSE, p->socket.type);
20667 
20668          if (peer) {
20669             mailbox = ast_strdupa(peer->unsolicited_mailbox);
20670             unref_peer(peer, "removing unsolicited mwi ref");
20671          }
20672       } else {
20673          mailbox = p->mwi->mailbox;
20674       }
20675 
20676       if (!ast_strlen_zero(mailbox) && !ast_strlen_zero(c)) {
20677          char *old = strsep(&c, " ");
20678          char *new = strsep(&old, "/");
20679          struct ast_event *event;
20680 
20681          if ((event = ast_event_new(AST_EVENT_MWI,
20682                      AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, mailbox,
20683                      AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, "SIP_Remote",
20684                      AST_EVENT_IE_NEWMSGS, AST_EVENT_IE_PLTYPE_UINT, atoi(new),
20685                      AST_EVENT_IE_OLDMSGS, AST_EVENT_IE_PLTYPE_UINT, atoi(old),
20686                      AST_EVENT_IE_END))) {
20687             ast_event_queue_and_cache(event);
20688          }
20689          transmit_response(p, "200 OK", req);
20690       } else {
20691          transmit_response(p, "489 Bad event", req);
20692          res = -1;
20693       }
20694    } else if (!strcmp(event, "keep-alive")) {
20695        /* Used by Sipura/Linksys for NAT pinhole,
20696         * just confirm that we received the packet. */
20697       transmit_response(p, "200 OK", req);
20698    } else if (!strcmp(event, "call-completion")) {
20699       res = handle_cc_notify(p, req);
20700    } else {
20701       /* We don't understand this event. */
20702       transmit_response(p, "489 Bad event", req);
20703       res = -1;
20704    }
20705 
20706    if (!p->lastinvite)
20707       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20708 
20709    return res;
20710 }
20711 
20712 /*! \brief Handle incoming OPTIONS request
20713    An OPTIONS request should be answered like an INVITE from the same UA, including SDP
20714 */
20715 static int handle_request_options(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, const char *e)
20716 {
20717    int res;
20718 
20719    if (p->lastinvite) {
20720       /* if this is a request in an active dialog, just confirm that the dialog exists. */
20721       transmit_response_with_allow(p, "200 OK", req, 0);
20722       return 0;
20723    }
20724 
20725    if (sip_cfg.auth_options_requests) {
20726       /* Do authentication if this OPTIONS request began the dialog */
20727       copy_request(&p->initreq, req);
20728       set_pvt_allowed_methods(p, req);
20729       res = check_user(p, req, SIP_OPTIONS, e, XMIT_UNRELIABLE, addr);
20730       if (res == AUTH_CHALLENGE_SENT) {
20731          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20732          return 0;
20733       }
20734       if (res < 0) { /* Something failed in authentication */
20735          if (res == AUTH_FAKE_AUTH) {
20736             ast_log(LOG_NOTICE, "Sending fake auth rejection for device %s\n", get_header(req, "From"));
20737             transmit_fake_auth_response(p, SIP_OPTIONS, req, XMIT_UNRELIABLE);
20738          } else {
20739             ast_log(LOG_NOTICE, "Failed to authenticate device %s\n", get_header(req, "From"));
20740             transmit_response(p, "403 Forbidden", req);
20741          }
20742          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20743          return 0;
20744       }
20745    }
20746 
20747    /* must go through authentication before getting here */
20748    res = (get_destination(p, req, NULL) == SIP_GET_DEST_EXTEN_FOUND ? 0 : -1);
20749    build_contact(p);
20750 
20751    if (ast_strlen_zero(p->context))
20752       ast_string_field_set(p, context, sip_cfg.default_context);
20753 
20754    if (ast_shutting_down())
20755       transmit_response_with_allow(p, "503 Unavailable", req, 0);
20756    else if (res < 0)
20757       transmit_response_with_allow(p, "404 Not Found", req, 0);
20758    else
20759       transmit_response_with_allow(p, "200 OK", req, 0);
20760 
20761    /* Destroy if this OPTIONS was the opening request, but not if
20762       it's in the middle of a normal call flow. */
20763    sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20764 
20765    return res;
20766 }
20767 
20768 /*! \brief Handle the transfer part of INVITE with a replaces: header,
20769     meaning a target pickup or an attended transfer.
20770     Used only once.
20771    XXX 'ignore' is unused.
20772 
20773    \note this function is called by handle_request_invite(). Four locks
20774    held at the beginning of this function, p, p->owner, p->refer->refer_call and
20775    p->refere->refer_call->owner.  only p's lock should remain at the end of this
20776    function.  p's lock as well as the channel p->owner's lock are held by
20777    handle_request_do(), we unlock p->owner before the masq.  By setting nounlock
20778    we are indicating to handle_request_do() that we have already unlocked the owner.
20779  */
20780 static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, struct ast_sockaddr *addr, int *nounlock)
20781 {
20782    int earlyreplace = 0;
20783    int oneleggedreplace = 0;     /* Call with no bridge, propably IVR or voice message */
20784    struct ast_channel *c = p->owner;   /* Our incoming call */
20785    struct ast_channel *replacecall = p->refer->refer_call->owner; /* The channel we're about to take over */
20786    struct ast_channel *targetcall;     /* The bridge to the take-over target */
20787 
20788    /* Check if we're in ring state */
20789    if (replacecall->_state == AST_STATE_RING)
20790       earlyreplace = 1;
20791 
20792    /* Check if we have a bridge */
20793    if (!(targetcall = ast_bridged_channel(replacecall))) {
20794       /* We have no bridge */
20795       if (!earlyreplace) {
20796          ast_debug(2, " Attended transfer attempted to replace call with no bridge (maybe ringing). Channel %s!\n", replacecall->name);
20797          oneleggedreplace = 1;
20798       }
20799    }
20800    if (targetcall && targetcall->_state == AST_STATE_RINGING)
20801       ast_debug(4, "SIP transfer: Target channel is in ringing state\n");
20802 
20803    if (targetcall)
20804       ast_debug(4, "SIP transfer: Invite Replace incoming channel should bridge to channel %s while hanging up channel %s\n", targetcall->name, replacecall->name);
20805    else
20806       ast_debug(4, "SIP transfer: Invite Replace incoming channel should replace and hang up channel %s (one call leg)\n", replacecall->name);
20807 
20808    if (req->ignore) {
20809       ast_log(LOG_NOTICE, "Ignoring this INVITE with replaces in a stupid way.\n");
20810       /* We should answer something here. If we are here, the
20811          call we are replacing exists, so an accepted
20812          can't harm */
20813       transmit_response_with_sdp(p, "200 OK", req, XMIT_RELIABLE, FALSE, FALSE);
20814       /* Do something more clever here */
20815       if (c) {
20816          *nounlock = 1;
20817          ast_channel_unlock(c);
20818       }
20819       ast_channel_unlock(replacecall);
20820       sip_pvt_unlock(p->refer->refer_call);
20821       return 1;
20822    }
20823    if (!c) {
20824       /* What to do if no channel ??? */
20825       ast_log(LOG_ERROR, "Unable to create new channel.  Invite/replace failed.\n");
20826       transmit_response_reliable(p, "503 Service Unavailable", req);
20827       append_history(p, "Xfer", "INVITE/Replace Failed. No new channel.");
20828       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20829       ast_channel_unlock(replacecall);
20830       sip_pvt_unlock(p->refer->refer_call);
20831       return 1;
20832    }
20833    append_history(p, "Xfer", "INVITE/Replace received");
20834    /* We have three channels to play with
20835       channel c: New incoming call
20836       targetcall: Call from PBX to target
20837       p->refer->refer_call: SIP pvt dialog from transferer to pbx.
20838       replacecall: The owner of the previous
20839       We need to masq C into refer_call to connect to
20840       targetcall;
20841       If we are talking to internal audio stream, target call is null.
20842    */
20843 
20844    /* Fake call progress */
20845    transmit_response(p, "100 Trying", req);
20846    ast_setstate(c, AST_STATE_RING);
20847 
20848    /* Masquerade the new call into the referred call to connect to target call
20849       Targetcall is not touched by the masq */
20850 
20851    /* Answer the incoming call and set channel to UP state */
20852    transmit_response_with_sdp(p, "200 OK", req, XMIT_RELIABLE, FALSE, FALSE);
20853 
20854    ast_setstate(c, AST_STATE_UP);
20855 
20856    /* Stop music on hold and other generators */
20857    ast_quiet_chan(replacecall);
20858    ast_quiet_chan(targetcall);
20859    ast_debug(4, "Invite/Replaces: preparing to masquerade %s into %s\n", c->name, replacecall->name);
20860 
20861    /* Make sure that the masq does not free our PVT for the old call */
20862    if (! earlyreplace && ! oneleggedreplace )
20863       ast_set_flag(&p->refer->refer_call->flags[0], SIP_DEFER_BYE_ON_TRANSFER);  /* Delay hangup */
20864 
20865    /* Prepare the masquerade - if this does not happen, we will be gone */
20866    if(ast_channel_masquerade(replacecall, c))
20867       ast_log(LOG_ERROR, "Failed to masquerade C into Replacecall\n");
20868    else
20869       ast_debug(4, "Invite/Replaces: Going to masquerade %s into %s\n", c->name, replacecall->name);
20870 
20871    /* C should now be in place of replacecall. all channel locks and pvt locks should be removed
20872     * before issuing the masq.  Since we are unlocking both the pvt (p) and its owner channel (c)
20873     * it is possible for channel c to be destroyed on us.  To prevent this, we must give c a reference
20874     * before any unlocking takes place and remove it only once we are completely done with it */
20875    ast_channel_ref(c);
20876    ast_channel_unlock(replacecall);
20877    ast_channel_unlock(c);
20878    sip_pvt_unlock(p->refer->refer_call);
20879    sip_pvt_unlock(p);
20880    if (ast_do_masquerade(replacecall)) {
20881       ast_log(LOG_WARNING, "Failed to perform masquerade with INVITE replaces\n");
20882    }
20883    ast_channel_lock(c);
20884    if (earlyreplace || oneleggedreplace ) {
20885       c->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
20886    }
20887    ast_setstate(c, AST_STATE_DOWN);
20888    ast_channel_unlock(c);
20889 
20890    /* The call should be down with no ast_channel, so hang it up */
20891    c->tech_pvt = dialog_unref(c->tech_pvt, "unref dialog c->tech_pvt");
20892 
20893    /* c and c's tech pvt must be unlocked at this point for ast_hangup */
20894    ast_hangup(c);
20895    /* this indicates to handle_request_do that the owner channel has already been unlocked */
20896    *nounlock = 1;
20897    /* lock PVT structure again after hangup */
20898    sip_pvt_lock(p);
20899    ast_channel_unref(c);
20900    return 0;
20901 }
20902 
20903 /*! \note No channel or pvt locks should be held while calling this function. */
20904 static int do_magic_pickup(struct ast_channel *channel, const char *extension, const char *context)
20905 {
20906    struct ast_str *str = ast_str_alloca(AST_MAX_EXTENSION + AST_MAX_CONTEXT + 2);
20907    struct ast_app *pickup = pbx_findapp("Pickup");
20908 
20909    if (!pickup) {
20910       ast_log(LOG_ERROR, "Unable to perform pickup: Application 'Pickup' not loaded (app_directed_pickup.so).\n");
20911       return -1;
20912    }
20913 
20914    ast_str_set(&str, 0, "%s@%s", extension, sip_cfg.notifycid == IGNORE_CONTEXT ? "PICKUPMARK" : context);
20915 
20916    ast_debug(2, "About to call Pickup(%s)\n", str->str);
20917 
20918    /* There is no point in capturing the return value since pickup_exec
20919       doesn't return anything meaningful unless the passed data is an empty
20920       string (which in our case it will not be) */
20921    pbx_exec(channel, pickup, str->str);
20922 
20923    return 0;
20924 }
20925 
20926 /*! \brief Called to deny a T38 reinvite if the core does not respond to our request */
20927 static int sip_t38_abort(const void *data)
20928 {
20929    struct sip_pvt *p = (struct sip_pvt *) data;
20930 
20931    sip_pvt_lock(p);
20932    /* an application may have taken ownership of the T.38 negotiation on this
20933     * channel while we were waiting to grab the lock... if it did, the scheduler
20934     * id will have been reset to -1, which is our indication that we do *not*
20935     * want to abort the negotiation process
20936     */
20937    if (p->t38id != -1) {
20938       change_t38_state(p, T38_DISABLED);
20939       transmit_response_reliable(p, "488 Not acceptable here", &p->initreq);
20940       p->t38id = -1;
20941       dialog_unref(p, "unref the dialog ptr from sip_t38_abort, because it held a dialog ptr");
20942    }
20943    sip_pvt_unlock(p);
20944    return 0;
20945 }
20946 
20947 /*!
20948  * \brief bare-bones support for SIP UPDATE
20949  *
20950  * XXX This is not even close to being RFC 3311-compliant. We don't advertise
20951  * that we support the UPDATE method, so no one should ever try sending us
20952  * an UPDATE anyway. However, Asterisk can send an UPDATE to change connected
20953  * line information, so we need to be prepared to handle this. The way we distinguish
20954  * such an UPDATE is through the X-Asterisk-rpid-update header.
20955  *
20956  * Actually updating the media session may be some future work.
20957  */
20958 static int handle_request_update(struct sip_pvt *p, struct sip_request *req)
20959 {
20960    if (ast_strlen_zero(get_header(req, "X-Asterisk-rpid-update"))) {
20961       transmit_response(p, "501 Method Not Implemented", req);
20962       return 0;
20963    }
20964    if (get_rpid(p, req)) {
20965       struct ast_party_connected_line connected;
20966       struct ast_set_party_connected_line update_connected;
20967       ast_party_connected_line_init(&connected);
20968       memset(&update_connected, 0, sizeof(update_connected));
20969       if (p->cid_num) {
20970          update_connected.id.number = 1;
20971          connected.id.number.valid = 1;
20972          connected.id.number.str = (char *) p->cid_num;
20973          connected.id.number.presentation = p->callingpres;
20974       }
20975       if (p->cid_name) {
20976          update_connected.id.name = 1;
20977          connected.id.name.valid = 1;
20978          connected.id.name.str = (char *) p->cid_name;
20979          connected.id.name.presentation = p->callingpres;
20980       }
20981       connected.id.tag = (char *) p->cid_tag;
20982       connected.source = AST_CONNECTED_LINE_UPDATE_SOURCE_TRANSFER;
20983       ast_channel_queue_connected_line_update(p->owner, &connected, &update_connected);
20984    }
20985    transmit_response(p, "200 OK", req);
20986    return 0;
20987 }
20988 
20989 /*!
20990  * \brief Handle incoming INVITE request
20991  * \note If the INVITE has a Replaces header, it is part of an
20992  * attended transfer. If so, we do not go through the dial
20993  * plan but try to find the active call and masquerade
20994  * into it
20995  */
20996 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)
20997 {
20998    int res = 1;
20999    int gotdest;
21000    const char *p_replaces;
21001    char *replace_id = NULL;
21002    int refer_locked = 0;
21003    const char *required;
21004    unsigned int required_profile = 0;
21005    struct ast_channel *c = NULL;    /* New channel */
21006    struct sip_peer *authpeer = NULL;   /* Matching Peer */
21007    int reinvite = 0;
21008    int rtn;
21009    struct ast_party_redirecting redirecting;
21010    struct ast_set_party_redirecting update_redirecting;
21011 
21012    const char *p_uac_se_hdr;       /* UAC's Session-Expires header string                      */
21013    const char *p_uac_min_se;       /* UAC's requested Min-SE interval (char string)            */
21014    int uac_max_se = -1;            /* UAC's Session-Expires in integer format                  */
21015    int uac_min_se = -1;            /* UAC's Min-SE in integer format                           */
21016    int st_active = FALSE;          /* Session-Timer on/off boolean                             */
21017    int st_interval = 0;            /* Session-Timer negotiated refresh interval                */
21018    enum st_refresher st_ref;       /* Session-Timer session refresher                          */
21019    int dlg_min_se = -1;
21020    struct {
21021       char exten[AST_MAX_EXTENSION];
21022       char context[AST_MAX_CONTEXT];
21023    } pickup = {
21024          .exten = "",
21025    };
21026    st_ref = SESSION_TIMER_REFRESHER_AUTO;
21027 
21028    /* Find out what they support */
21029    if (!p->sipoptions) {
21030       const char *supported = get_header(req, "Supported");
21031       if (!ast_strlen_zero(supported)) {
21032          p->sipoptions = parse_sip_options(supported, NULL, 0);
21033       }
21034    }
21035 
21036    /* Find out what they require */
21037    required = get_header(req, "Require");
21038    if (!ast_strlen_zero(required)) {
21039       char unsupported[256] = { 0, };
21040       required_profile = parse_sip_options(required, unsupported, ARRAY_LEN(unsupported));
21041 
21042       /* If there are any options required that we do not support,
21043        * then send a 420 with only those unsupported options listed */
21044       if (!ast_strlen_zero(unsupported)) {
21045          transmit_response_with_unsupported(p, "420 Bad extension (unsupported)", req, unsupported);
21046          ast_log(LOG_WARNING, "Received SIP INVITE with unsupported required extension: required:%s unsupported:%s\n", required, unsupported);
21047          p->invitestate = INV_COMPLETED;
21048          if (!p->lastinvite)
21049             sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
21050          res = -1;
21051          goto request_invite_cleanup;
21052       }
21053    }
21054 
21055    /* The option tags may be present in Supported: or Require: headers.
21056    Include the Require: option tags for further processing as well */
21057    p->sipoptions |= required_profile;
21058    p->reqsipoptions = required_profile;
21059 
21060    /* Check if this is a loop */
21061    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) {
21062       /* This is a call to ourself.  Send ourselves an error code and stop
21063          processing immediately, as SIP really has no good mechanism for
21064          being able to call yourself */
21065       /* If pedantic is on, we need to check the tags. If they're different, this is
21066          in fact a forked call through a SIP proxy somewhere. */
21067       int different;
21068       const char *initial_rlPart2 = REQ_OFFSET_TO_STR(&p->initreq, rlPart2);
21069       const char *this_rlPart2 = REQ_OFFSET_TO_STR(req, rlPart2);
21070       if (sip_cfg.pedanticsipchecking)
21071          different = sip_uri_cmp(initial_rlPart2, this_rlPart2);
21072       else
21073          different = strcmp(initial_rlPart2, this_rlPart2);
21074       if (!different) {
21075          transmit_response(p, "482 Loop Detected", req);
21076          p->invitestate = INV_COMPLETED;
21077          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
21078          res = 0;
21079          goto request_invite_cleanup;
21080       } else {
21081          /*! This is a spiral. What we need to do is to just change the outgoing INVITE
21082           * so that it now routes to the new Request URI. Since we created the INVITE ourselves
21083           * that should be all we need to do.
21084           *
21085           * \todo XXX This needs to be reviewed.  YOu don't change the request URI really, you route the packet
21086           * correctly instead...
21087           */
21088          char *uri = ast_strdupa(this_rlPart2);
21089          char *at = strchr(uri, '@');
21090          char *peerorhost;
21091          ast_debug(2, "Potential spiral detected. Original RURI was %s, new RURI is %s\n", initial_rlPart2, this_rlPart2);
21092          transmit_response(p, "100 Trying", req);
21093          if (at) {
21094             *at = '\0';
21095          }
21096          /* Parse out "sip:" */
21097          if ((peerorhost = strchr(uri, ':'))) {
21098             *peerorhost++ = '\0';
21099          }
21100          ast_string_field_set(p, theirtag, NULL);
21101          /* Treat this as if there were a call forward instead...
21102           */
21103          ast_string_field_set(p->owner, call_forward, peerorhost);
21104          ast_queue_control(p->owner, AST_CONTROL_BUSY);
21105          res = 0;
21106          goto request_invite_cleanup;
21107       }
21108    }
21109 
21110    if (!req->ignore && p->pendinginvite) {
21111       if (!ast_test_flag(&p->flags[0], SIP_OUTGOING) && (p->invitestate == INV_COMPLETED || p->invitestate == INV_TERMINATED)) {
21112          /* What do these circumstances mean? We have received an INVITE for an "incoming" dialog for which we
21113           * have sent a final response. We have not yet received an ACK, though (which is why p->pendinginvite is non-zero).
21114           * We also know that the INVITE is not a retransmission, because otherwise the "ignore" flag would be set.
21115           * This means that either we are receiving a reinvite for a terminated dialog, or we are receiving an INVITE with
21116           * credentials based on one we challenged earlier.
21117           *
21118           * The action to take in either case is to treat the INVITE as though it contains an implicit ACK for the previous
21119           * transaction. Calling __sip_ack will take care of this by clearing the p->pendinginvite and removing the response
21120           * from the previous transaction from the list of outstanding packets.
21121           */
21122          __sip_ack(p, p->pendinginvite, 1, 0);
21123       } else {
21124          /* We already have a pending invite. Sorry. You are on hold. */
21125          p->glareinvite = seqno;
21126          if (p->rtp && find_sdp(req)) {
21127             struct ast_sockaddr addr;
21128             if (get_ip_and_port_from_sdp(req, SDP_AUDIO, &addr)) {
21129                ast_log(LOG_WARNING, "Failed to set an alternate media source on glared reinvite. Audio may not work properly on this call.\n");
21130             } else {
21131                ast_rtp_instance_set_alt_remote_address(p->rtp, &addr);
21132             }
21133             if (p->vrtp) {
21134                if (get_ip_and_port_from_sdp(req, SDP_VIDEO, &addr)) {
21135                   ast_log(LOG_WARNING, "Failed to set an alternate media source on glared reinvite. Video may not work properly on this call.\n");
21136                } else {
21137                   ast_rtp_instance_set_alt_remote_address(p->vrtp, &addr);
21138                }
21139             }
21140          }
21141          transmit_response_reliable(p, "491 Request Pending", req);
21142          ast_debug(1, "Got INVITE on call where we already have pending INVITE, deferring that - %s\n", p->callid);
21143          /* Don't destroy dialog here */
21144          res = 0;
21145          goto request_invite_cleanup;
21146       }
21147    }
21148 
21149    p_replaces = get_header(req, "Replaces");
21150    if (!ast_strlen_zero(p_replaces)) {
21151       /* We have a replaces header */
21152       char *ptr;
21153       char *fromtag = NULL;
21154       char *totag = NULL;
21155       char *start, *to;
21156       int error = 0;
21157 
21158       if (p->owner) {
21159          ast_debug(3, "INVITE w Replaces on existing call? Refusing action. [%s]\n", p->callid);
21160          transmit_response_reliable(p, "400 Bad request", req);   /* The best way to not not accept the transfer */
21161          /* Do not destroy existing call */
21162          res = -1;
21163          goto request_invite_cleanup;
21164       }
21165 
21166       if (sipdebug)
21167          ast_debug(3, "INVITE part of call transfer. Replaces [%s]\n", p_replaces);
21168       /* Create a buffer we can manipulate */
21169       replace_id = ast_strdupa(p_replaces);
21170       ast_uri_decode(replace_id);
21171 
21172       if (!p->refer && !sip_refer_allocate(p)) {
21173          transmit_response_reliable(p, "500 Server Internal Error", req);
21174          append_history(p, "Xfer", "INVITE/Replace Failed. Out of memory.");
21175          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
21176          p->invitestate = INV_COMPLETED;
21177          res = -1;
21178          goto request_invite_cleanup;
21179       }
21180 
21181       /*  Todo: (When we find phones that support this)
21182          if the replaces header contains ";early-only"
21183          we can only replace the call in early
21184          stage, not after it's up.
21185 
21186          If it's not in early mode, 486 Busy.
21187       */
21188 
21189       /* Skip leading whitespace */
21190       replace_id = ast_skip_blanks(replace_id);
21191 
21192       start = replace_id;
21193       while ( (ptr = strsep(&start, ";")) ) {
21194          ptr = ast_skip_blanks(ptr); /* XXX maybe unnecessary ? */
21195          if ( (to = strcasestr(ptr, "to-tag=") ) )
21196             totag = to + 7;   /* skip the keyword */
21197          else if ( (to = strcasestr(ptr, "from-tag=") ) ) {
21198             fromtag = to + 9; /* skip the keyword */
21199             fromtag = strsep(&fromtag, "&"); /* trim what ? */
21200          }
21201       }
21202 
21203       if (sipdebug)
21204          ast_debug(4, "Invite/replaces: Will use Replace-Call-ID : %s Fromtag: %s Totag: %s\n",
21205                  replace_id,
21206                  fromtag ? fromtag : "<no from tag>",
21207                  totag ? totag : "<no to tag>");
21208 
21209       /* Try to find call that we are replacing.
21210          If we have a Replaces header, we need to cancel that call if we succeed with this call.
21211          First we cheat a little and look for a magic call-id from phones that support
21212          dialog-info+xml so we can do technology independent pickup... */
21213       if (strncmp(replace_id, "pickup-", 7) == 0) {
21214          struct sip_pvt *subscription = NULL;
21215          replace_id += 7; /* Worst case we are looking at \0 */
21216 
21217          if ((subscription = get_sip_pvt_byid_locked(replace_id, totag, fromtag)) == NULL) {
21218             ast_log(LOG_NOTICE, "Unable to find subscription with call-id: %s\n", replace_id);
21219             transmit_response_reliable(p, "481 Call Leg Does Not Exist (Replaces)", req);
21220             error = 1;
21221          } else {
21222             ast_log(LOG_NOTICE, "Trying to pick up %s@%s\n", subscription->exten, subscription->context);
21223             ast_copy_string(pickup.exten, subscription->exten, sizeof(pickup.exten));
21224             ast_copy_string(pickup.context, subscription->context, sizeof(pickup.context));
21225             sip_pvt_unlock(subscription);
21226             if (subscription->owner) {
21227                ast_channel_unlock(subscription->owner);
21228             }
21229          }
21230       }
21231 
21232       /* This locks both refer_call pvt and refer_call pvt's owner!!!*/
21233       if (!error && ast_strlen_zero(pickup.exten) && (p->refer->refer_call = get_sip_pvt_byid_locked(replace_id, totag, fromtag)) == NULL) {
21234          ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-existent call id (%s)!\n", replace_id);
21235          transmit_response_reliable(p, "481 Call Leg Does Not Exist (Replaces)", req);
21236          error = 1;
21237       } else {
21238          refer_locked = 1;
21239       }
21240 
21241       /* The matched call is the call from the transferer to Asterisk .
21242          We want to bridge the bridged part of the call to the
21243          incoming invite, thus taking over the refered call */
21244 
21245       if (p->refer->refer_call == p) {
21246          ast_log(LOG_NOTICE, "INVITE with replaces into it's own call id (%s == %s)!\n", replace_id, p->callid);
21247          p->refer->refer_call = dialog_unref(p->refer->refer_call, "unref dialog p->refer->refer_call");
21248          transmit_response_reliable(p, "400 Bad request", req);   /* The best way to not not accept the transfer */
21249          error = 1;
21250       }
21251 
21252       if (!error && ast_strlen_zero(pickup.exten) && !p->refer->refer_call->owner) {
21253          /* Oops, someting wrong anyway, no owner, no call */
21254          ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-existing call id (%s)!\n", replace_id);
21255          /* Check for better return code */
21256          transmit_response_reliable(p, "481 Call Leg Does Not Exist (Replace)", req);
21257          error = 1;
21258       }
21259 
21260       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) {
21261          ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-ringing or active call id (%s)!\n", replace_id);
21262          transmit_response_reliable(p, "603 Declined (Replaces)", req);
21263          error = 1;
21264       }
21265 
21266       if (error) {   /* Give up this dialog */
21267          append_history(p, "Xfer", "INVITE/Replace Failed.");
21268          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
21269          sip_pvt_unlock(p);
21270          if (p->refer->refer_call) {
21271             sip_pvt_unlock(p->refer->refer_call);
21272             if (p->refer->refer_call->owner) {
21273                ast_channel_unlock(p->refer->refer_call->owner);
21274             }
21275          }
21276          refer_locked = 0;
21277          p->invitestate = INV_COMPLETED;
21278          res = -1;
21279          goto request_invite_cleanup;
21280       }
21281    }
21282 
21283    /* Check if this is an INVITE that sets up a new dialog or
21284       a re-invite in an existing dialog */
21285 
21286    if (!req->ignore) {
21287       int newcall = (p->initreq.headers ? TRUE : FALSE);
21288 
21289       if (sip_cancel_destroy(p))
21290          ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
21291       /* This also counts as a pending invite */
21292       p->pendinginvite = seqno;
21293       check_via(p, req);
21294 
21295       copy_request(&p->initreq, req);     /* Save this INVITE as the transaction basis */
21296       if (sipdebug)
21297          ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
21298       if (!p->owner) {  /* Not a re-invite */
21299          if (debug)
21300             ast_verbose("Using INVITE request as basis request - %s\n", p->callid);
21301          if (newcall)
21302             append_history(p, "Invite", "New call: %s", p->callid);
21303          parse_ok_contact(p, req);
21304       } else { /* Re-invite on existing call */
21305          ast_clear_flag(&p->flags[0], SIP_OUTGOING);  /* This is now an inbound dialog */
21306          if (get_rpid(p, req)) {
21307             struct ast_party_connected_line connected;
21308             struct ast_set_party_connected_line update_connected;
21309 
21310             ast_party_connected_line_init(&connected);
21311             memset(&update_connected, 0, sizeof(update_connected));
21312             if (p->cid_num) {
21313                update_connected.id.number = 1;
21314                connected.id.number.valid = 1;
21315                connected.id.number.str = (char *) p->cid_num;
21316                connected.id.number.presentation = p->callingpres;
21317             }
21318             if (p->cid_name) {
21319                update_connected.id.name = 1;
21320                connected.id.name.valid = 1;
21321                connected.id.name.str = (char *) p->cid_name;
21322                connected.id.name.presentation = p->callingpres;
21323             }
21324             connected.id.tag = (char *) p->cid_tag;
21325             connected.source = AST_CONNECTED_LINE_UPDATE_SOURCE_TRANSFER;
21326             ast_channel_queue_connected_line_update(p->owner, &connected,
21327                &update_connected);
21328          }
21329          /* Handle SDP here if we already have an owner */
21330          if (find_sdp(req)) {
21331             if (process_sdp(p, req, SDP_T38_INITIATE)) {
21332                if (!ast_strlen_zero(get_header(req, "Content-Encoding"))) {
21333                   /* Asterisk does not yet support any Content-Encoding methods.  Always
21334                    * attempt to process the sdp, but return a 415 if a Content-Encoding header
21335                    * was present after processing failed.  */
21336                   transmit_response_reliable(p, "415 Unsupported Media type", req);
21337                } else {
21338                   transmit_response_reliable(p, "488 Not acceptable here", req);
21339                }
21340                if (!p->lastinvite)
21341                   sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
21342                res = -1;
21343                goto request_invite_cleanup;
21344             }
21345             ast_queue_control(p->owner, AST_CONTROL_SRCUPDATE);
21346          } else {
21347             p->jointcapability = p->capability;
21348             ast_debug(1, "Hm....  No sdp for the moment\n");
21349             /* Some devices signal they want to be put off hold by sending a re-invite
21350                *without* an SDP, which is supposed to mean "Go back to your state"
21351                and since they put os on remote hold, we go back to off hold */
21352             if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
21353                ast_queue_control(p->owner, AST_CONTROL_UNHOLD);
21354                /* Activate a re-invite */
21355                ast_queue_frame(p->owner, &ast_null_frame);
21356                change_hold_state(p, req, FALSE, 0);
21357             }
21358          }
21359          if (p->do_history) /* This is a response, note what it was for */
21360             append_history(p, "ReInv", "Re-invite received");
21361       }
21362    } else if (debug)
21363       ast_verbose("Ignoring this INVITE request\n");
21364 
21365    if (!p->lastinvite && !req->ignore && !p->owner) {
21366       /* This is a new invite */
21367       /* Handle authentication if this is our first invite */
21368       int cc_recall_core_id = -1;
21369       set_pvt_allowed_methods(p, req);
21370       res = check_user_full(p, req, SIP_INVITE, e, XMIT_RELIABLE, addr, &authpeer);
21371       if (res == AUTH_CHALLENGE_SENT) {
21372          p->invitestate = INV_COMPLETED;     /* Needs to restart in another INVITE transaction */
21373          res = 0;
21374          goto request_invite_cleanup;
21375       }
21376       if (res < 0) { /* Something failed in authentication */
21377          if (res == AUTH_FAKE_AUTH) {
21378             ast_log(LOG_NOTICE, "Sending fake auth rejection for device %s\n", get_header(req, "From"));
21379             transmit_fake_auth_response(p, SIP_INVITE, req, XMIT_RELIABLE);
21380          } else {
21381             ast_log(LOG_NOTICE, "Failed to authenticate device %s\n", get_header(req, "From"));
21382             transmit_response_reliable(p, "403 Forbidden", req);
21383          }
21384          p->invitestate = INV_COMPLETED;
21385          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
21386          ast_string_field_set(p, theirtag, NULL);
21387          res = 0;
21388          goto request_invite_cleanup;
21389       }
21390 
21391       /* Successful authentication and peer matching so record the peer related to this pvt (for easy access to peer settings) */
21392       if (p->relatedpeer) {
21393          p->relatedpeer = unref_peer(p->relatedpeer,"unsetting the relatedpeer field in the dialog, before it is set to something else.");
21394       }
21395       if (authpeer) {
21396          p->relatedpeer = ref_peer(authpeer, "setting dialog's relatedpeer pointer");
21397       }
21398       /* If T38 is needed but not present, then make it magically appear */
21399       if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) && !p->udptl) {
21400          if ((p->udptl = ast_udptl_new_with_bindaddr(sched, io, 0, &bindaddr))) {
21401             p->t38_maxdatagram = global_t38_maxdatagram;
21402             set_t38_capabilities(p);
21403          } else {
21404             /* udptl creation failed, T38 can not be supported on this dialog */
21405             ast_debug(1, "UDPTL creation failed on dialog.\n");
21406             ast_clear_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT);
21407          }
21408       }
21409 
21410       req->authenticated = 1;
21411 
21412       /* We have a successful authentication, process the SDP portion if there is one */
21413       if (find_sdp(req)) {
21414          if (process_sdp(p, req, SDP_T38_INITIATE)) {
21415             /* Asterisk does not yet support any Content-Encoding methods.  Always
21416              * attempt to process the sdp, but return a 415 if a Content-Encoding header
21417              * was present after processing fails. */
21418             if (!ast_strlen_zero(get_header(req, "Content-Encoding"))) {
21419                transmit_response_reliable(p, "415 Unsupported Media type", req);
21420             } else {
21421                /* Unacceptable codecs */
21422                transmit_response_reliable(p, "488 Not acceptable here", req);
21423             }
21424             p->invitestate = INV_COMPLETED;
21425             sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
21426             ast_debug(1, "No compatible codecs for this SIP call.\n");
21427             res = -1;
21428             goto request_invite_cleanup;
21429          }
21430       } else { /* No SDP in invite, call control session */
21431          p->jointcapability = p->capability;
21432          ast_debug(2, "No SDP in Invite, third party call control\n");
21433       }
21434 
21435       /* Queue NULL frame to prod ast_rtp_bridge if appropriate */
21436       /* This seems redundant ... see !p-owner above */
21437       if (p->owner)
21438          ast_queue_frame(p->owner, &ast_null_frame);
21439 
21440 
21441       /* Initialize the context if it hasn't been already */
21442       if (ast_strlen_zero(p->context))
21443          ast_string_field_set(p, context, sip_cfg.default_context);
21444 
21445 
21446       /* Check number of concurrent calls -vs- incoming limit HERE */
21447       ast_debug(1, "Checking SIP call limits for device %s\n", p->username);
21448       if ((res = update_call_counter(p, INC_CALL_LIMIT))) {
21449          if (res < 0) {
21450             ast_log(LOG_NOTICE, "Failed to place call for device %s, too many calls\n", p->username);
21451             transmit_response_reliable(p, "480 Temporarily Unavailable (Call limit) ", req);
21452             sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
21453             p->invitestate = INV_COMPLETED;
21454          }
21455          res = 0;
21456          goto request_invite_cleanup;
21457       }
21458       gotdest = get_destination(p, NULL, &cc_recall_core_id);  /* Get destination right away */
21459       extract_uri(p, req);       /* Get the Contact URI */
21460       build_contact(p);       /* Build our contact header */
21461 
21462       if (p->rtp) {
21463          ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_DTMF, ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
21464          ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_DTMF_COMPENSATE, ast_test_flag(&p->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
21465       }
21466 
21467       if (!replace_id && (gotdest != SIP_GET_DEST_EXTEN_FOUND)) { /* No matching extension found */
21468          switch(gotdest) {
21469          case SIP_GET_DEST_INVALID_URI:
21470             transmit_response_reliable(p, "416 Unsupported URI scheme", req);
21471             break;
21472          case SIP_GET_DEST_PICKUP_EXTEN_FOUND:
21473             if (ast_test_flag(&p->flags[1], SIP_PAGE2_ALLOWOVERLAP)) {
21474                transmit_response_reliable(p, "484 Address Incomplete", req);
21475                break;
21476             }
21477          /* INTENTIONAL FALL THROUGH */
21478          case SIP_GET_DEST_EXTEN_NOT_FOUND:
21479          case SIP_GET_DEST_REFUSED:
21480          default:
21481             {
21482                char *decoded_exten = ast_strdupa(p->exten);
21483                transmit_response_reliable(p, "404 Not Found", req);
21484                ast_uri_decode(decoded_exten);
21485                ast_log(LOG_NOTICE, "Call from '%s' to extension"
21486                   " '%s' rejected because extension not found in context '%s'.\n",
21487                   S_OR(p->username, p->peername), decoded_exten, p->context);
21488             }
21489          } /* end switch */
21490 
21491          p->invitestate = INV_COMPLETED;
21492          update_call_counter(p, DEC_CALL_LIMIT);
21493          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
21494          res = 0;
21495          goto request_invite_cleanup;
21496       } else {
21497 
21498          /* If no extension was specified, use the s one */
21499          /* Basically for calling to IP/Host name only */
21500          if (ast_strlen_zero(p->exten))
21501             ast_string_field_set(p, exten, "s");
21502          /* Initialize our tag */
21503 
21504          make_our_tag(p->tag, sizeof(p->tag));
21505          /* First invitation - create the channel.  Allocation
21506           * failures are handled below. */
21507          c = sip_new(p, AST_STATE_DOWN, S_OR(p->peername, NULL), NULL);
21508          if (cc_recall_core_id != -1) {
21509             ast_setup_cc_recall_datastore(c, cc_recall_core_id);
21510             ast_cc_agent_set_interfaces_chanvar(c);
21511          }
21512          *recount = 1;
21513 
21514          /* Save Record-Route for any later requests we make on this dialogue */
21515          build_route(p, req, 0);
21516 
21517          if (c) {
21518             ast_party_redirecting_init(&redirecting);
21519             memset(&update_redirecting, 0, sizeof(update_redirecting));
21520             /* Pre-lock the call */
21521             ast_channel_lock(c);
21522             change_redirecting_information(p, req, &redirecting, &update_redirecting,
21523                FALSE); /*Will return immediately if no Diversion header is present */
21524             ast_channel_set_redirecting(c, &redirecting, &update_redirecting);
21525             ast_party_redirecting_free(&redirecting);
21526          }
21527       }
21528    } else {
21529       ast_party_redirecting_init(&redirecting);
21530       memset(&update_redirecting, 0, sizeof(update_redirecting));
21531       if (sipdebug) {
21532          if (!req->ignore)
21533             ast_debug(2, "Got a SIP re-invite for call %s\n", p->callid);
21534          else
21535             ast_debug(2, "Got a SIP re-transmit of INVITE for call %s\n", p->callid);
21536       }
21537       if (!req->ignore)
21538          reinvite = 1;
21539       c = p->owner;
21540       change_redirecting_information(p, req, &redirecting, &update_redirecting, FALSE); /*Will return immediately if no Diversion header is present */
21541       if (c) {
21542          ast_channel_set_redirecting(c, &redirecting, &update_redirecting);
21543       }
21544       ast_party_redirecting_free(&redirecting);
21545    }
21546 
21547    /* Session-Timers */
21548    if ((p->sipoptions & SIP_OPT_TIMER) && !ast_strlen_zero(get_header(req, "Session-Expires"))) {
21549       /* The UAC has requested session-timers for this session. Negotiate
21550       the session refresh interval and who will be the refresher */
21551       ast_debug(2, "Incoming INVITE with 'timer' option supported and \"Session-Expires\" header.\n");
21552 
21553       /* Allocate Session-Timers struct w/in the dialog */
21554       if (!p->stimer)
21555          sip_st_alloc(p);
21556 
21557       /* Parse the Session-Expires header */
21558       p_uac_se_hdr = get_header(req, "Session-Expires");
21559       rtn = parse_session_expires(p_uac_se_hdr, &uac_max_se, &st_ref);
21560       if (rtn != 0) {
21561          transmit_response_reliable(p, "400 Session-Expires Invalid Syntax", req);
21562          p->invitestate = INV_COMPLETED;
21563          if (!p->lastinvite) {
21564             sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
21565          }
21566          res = -1;
21567          goto request_invite_cleanup;
21568       }
21569 
21570       /* Parse the Min-SE header */
21571       p_uac_min_se = get_header(req, "Min-SE");
21572       if (!ast_strlen_zero(p_uac_min_se)) {
21573          rtn = parse_minse(p_uac_min_se, &uac_min_se);
21574          if (rtn != 0) {
21575             transmit_response_reliable(p, "400 Min-SE Invalid Syntax", req);
21576             p->invitestate = INV_COMPLETED;
21577             if (!p->lastinvite) {
21578                sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
21579             }
21580             res = -1;
21581             goto request_invite_cleanup;
21582          }
21583       }
21584 
21585       dlg_min_se = st_get_se(p, FALSE);
21586       switch (st_get_mode(p)) {
21587       case SESSION_TIMER_MODE_ACCEPT:
21588       case SESSION_TIMER_MODE_ORIGINATE:
21589          if (uac_max_se > 0 && uac_max_se < dlg_min_se) {
21590             transmit_response_with_minse(p, "422 Session Interval Too Small", req, dlg_min_se);
21591             p->invitestate = INV_COMPLETED;
21592             if (!p->lastinvite) {
21593                sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
21594             }
21595             res = -1;
21596             goto request_invite_cleanup;
21597          }
21598 
21599          p->stimer->st_active_peer_ua = TRUE;
21600          st_active = TRUE;
21601          if (st_ref == SESSION_TIMER_REFRESHER_AUTO) {
21602             st_ref = st_get_refresher(p);
21603          }
21604 
21605          if (uac_max_se > 0) {
21606             int dlg_max_se = st_get_se(p, TRUE);
21607             if (dlg_max_se >= uac_min_se) {
21608                st_interval = (uac_max_se < dlg_max_se) ? uac_max_se : dlg_max_se;
21609             } else {
21610                st_interval = uac_max_se;
21611             }
21612          } else {
21613             /* Set to default max value */
21614             st_interval = global_max_se;
21615          }
21616          break;
21617 
21618       case SESSION_TIMER_MODE_REFUSE:
21619          if (p->reqsipoptions & SIP_OPT_TIMER) {
21620             transmit_response_with_unsupported(p, "420 Option Disabled", req, required);
21621             ast_log(LOG_WARNING, "Received SIP INVITE with supported but disabled option: %s\n", required);
21622             p->invitestate = INV_COMPLETED;
21623             if (!p->lastinvite) {
21624                sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
21625             }
21626             res = -1;
21627             goto request_invite_cleanup;
21628          }
21629          break;
21630 
21631       default:
21632          ast_log(LOG_ERROR, "Internal Error %d at %s:%d\n", st_get_mode(p), __FILE__, __LINE__);
21633          break;
21634       }
21635    } else {
21636       /* The UAC did not request session-timers.  Asterisk (UAS), will now decide
21637       (based on session-timer-mode in sip.conf) whether to run session-timers for
21638       this session or not. */
21639       switch (st_get_mode(p)) {
21640       case SESSION_TIMER_MODE_ORIGINATE:
21641          st_active = TRUE;
21642          st_interval = st_get_se(p, TRUE);
21643          st_ref = SESSION_TIMER_REFRESHER_UAS;
21644          p->stimer->st_active_peer_ua = FALSE;
21645          break;
21646 
21647       default:
21648          break;
21649       }
21650    }
21651 
21652    if (reinvite == 0) {
21653       /* Session-Timers: Start session refresh timer based on negotiation/config */
21654       if (st_active == TRUE) {
21655          p->stimer->st_active   = TRUE;
21656          p->stimer->st_interval = st_interval;
21657          p->stimer->st_ref      = st_ref;
21658          start_session_timer(p);
21659       }
21660    } else {
21661       if (p->stimer->st_active == TRUE) {
21662          /* Session-Timers:  A re-invite request sent within a dialog will serve as
21663          a refresh request, no matter whether the re-invite was sent for refreshing
21664          the session or modifying it.*/
21665          ast_debug (2, "Restarting session-timers on a refresh - %s\n", p->callid);
21666 
21667          /* The UAC may be adjusting the session-timers mid-session */
21668          if (st_interval > 0) {
21669             p->stimer->st_interval = st_interval;
21670             p->stimer->st_ref      = st_ref;
21671          }
21672 
21673          restart_session_timer(p);
21674          if (p->stimer->st_expirys > 0) {
21675             p->stimer->st_expirys--;
21676          }
21677       }
21678    }
21679 
21680    if (!req->ignore && p)
21681       p->lastinvite = seqno;
21682 
21683    if (c && replace_id) {  /* Attended transfer or call pickup - we're the target */
21684       if (!ast_strlen_zero(pickup.exten)) {
21685          append_history(p, "Xfer", "INVITE/Replace received");
21686 
21687          /* Let the caller know we're giving it a shot */
21688          transmit_response(p, "100 Trying", req);
21689          p->invitestate = INV_PROCEEDING;
21690          ast_setstate(c, AST_STATE_RING);
21691 
21692          /* Do the pickup itself */
21693          ast_channel_unlock(c);
21694          *nounlock = 1;
21695 
21696          /* since p->owner (c) is unlocked, we need to go ahead and unlock pvt for both
21697           * magic pickup and ast_hangup.  Both of these functions will attempt to lock
21698           * p->owner again, which can cause a deadlock if we already hold a lock on p.
21699           * Locking order is, channel then pvt.  Dead lock avoidance must be used if
21700           * called the other way around. */
21701          sip_pvt_unlock(p);
21702          do_magic_pickup(c, pickup.exten, pickup.context);
21703          /* Now we're either masqueraded or we failed to pickup, in either case we... */
21704          ast_hangup(c);
21705          sip_pvt_lock(p); /* pvt is expected to remain locked on return, so re-lock it */
21706 
21707          res = 0;
21708          goto request_invite_cleanup;
21709       } else {
21710          /* Go and take over the target call */
21711          if (sipdebug)
21712             ast_debug(4, "Sending this call to the invite/replcaes handler %s\n", p->callid);
21713          res = handle_invite_replaces(p, req, debug, seqno, addr, nounlock);
21714          refer_locked = 0;
21715          goto request_invite_cleanup;
21716       }
21717    }
21718 
21719 
21720    if (c) { /* We have a call  -either a new call or an old one (RE-INVITE) */
21721       enum ast_channel_state c_state = c->_state;
21722 
21723       if (c_state != AST_STATE_UP && reinvite &&
21724          (p->invitestate == INV_TERMINATED || p->invitestate == INV_CONFIRMED)) {
21725          /* If these conditions are true, and the channel is still in the 'ringing'
21726           * state, then this likely means that we have a situation where the initial
21727           * INVITE transaction has completed *but* the channel's state has not yet been
21728           * changed to UP. The reason this could happen is if the reinvite is received
21729           * on the SIP socket prior to an application calling ast_read on this channel
21730           * to read the answer frame we earlier queued on it. In this case, the reinvite
21731           * is completely legitimate so we need to handle this the same as if the channel
21732           * were already UP. Thus we are purposely falling through to the AST_STATE_UP case.
21733           */
21734          c_state = AST_STATE_UP;
21735       }
21736 
21737       switch(c_state) {
21738       case AST_STATE_DOWN:
21739          ast_debug(2, "%s: New call is still down.... Trying... \n", c->name);
21740          transmit_provisional_response(p, "100 Trying", req, 0);
21741          p->invitestate = INV_PROCEEDING;
21742          ast_setstate(c, AST_STATE_RING);
21743          if (strcmp(p->exten, ast_pickup_ext())) { /* Call to extension -start pbx on this call */
21744             enum ast_pbx_result result;
21745 
21746             result = ast_pbx_start(c);
21747 
21748             switch(result) {
21749             case AST_PBX_FAILED:
21750                ast_log(LOG_WARNING, "Failed to start PBX :(\n");
21751                p->invitestate = INV_COMPLETED;
21752                transmit_response_reliable(p, "503 Unavailable", req);
21753                break;
21754             case AST_PBX_CALL_LIMIT:
21755                ast_log(LOG_WARNING, "Failed to start PBX (call limit reached) \n");
21756                p->invitestate = INV_COMPLETED;
21757                transmit_response_reliable(p, "480 Temporarily Unavailable", req);
21758                break;
21759             case AST_PBX_SUCCESS:
21760                /* nothing to do */
21761                break;
21762             }
21763 
21764             if (result) {
21765 
21766                /* Unlock locks so ast_hangup can do its magic */
21767                ast_channel_unlock(c);
21768                sip_pvt_unlock(p);
21769                ast_hangup(c);
21770                sip_pvt_lock(p);
21771                c = NULL;
21772             }
21773          } else { /* Pickup call in call group */
21774             ast_channel_unlock(c);
21775             *nounlock = 1;
21776             if (ast_pickup_call(c)) {
21777                ast_log(LOG_NOTICE, "Nothing to pick up for %s\n", p->callid);
21778                transmit_response_reliable(p, "503 Unavailable", req);
21779                sip_alreadygone(p);
21780                /* Unlock locks so ast_hangup can do its magic */
21781                sip_pvt_unlock(p);
21782                c->hangupcause = AST_CAUSE_CALL_REJECTED;
21783             } else {
21784                sip_pvt_unlock(p);
21785                c->hangupcause = AST_CAUSE_NORMAL_CLEARING;
21786             }
21787             p->invitestate = INV_COMPLETED;
21788             ast_hangup(c);
21789             sip_pvt_lock(p);
21790             c = NULL;
21791          }
21792          break;
21793       case AST_STATE_RING:
21794          transmit_provisional_response(p, "100 Trying", req, 0);
21795          p->invitestate = INV_PROCEEDING;
21796          break;
21797       case AST_STATE_RINGING:
21798          transmit_provisional_response(p, "180 Ringing", req, 0);
21799          p->invitestate = INV_PROCEEDING;
21800          break;
21801       case AST_STATE_UP:
21802          ast_debug(2, "%s: This call is UP.... \n", c->name);
21803 
21804          transmit_response(p, "100 Trying", req);
21805 
21806          if (p->t38.state == T38_PEER_REINVITE) {
21807             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."));
21808          } else if (p->t38.state == T38_ENABLED) {
21809             ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
21810             transmit_response_with_t38_sdp(p, "200 OK", req, (reinvite ? XMIT_RELIABLE : (req->ignore ?  XMIT_UNRELIABLE : XMIT_CRITICAL)));
21811          } else if (p->t38.state == T38_DISABLED) {
21812             /* If this is not a re-invite or something to ignore - it's critical */
21813             if (p->srtp && !ast_test_flag(p->srtp, SRTP_CRYPTO_OFFER_OK)) {
21814                ast_log(LOG_WARNING, "Target does not support required crypto\n");
21815                transmit_response_reliable(p, "488 Not Acceptable Here (crypto)", req);
21816             } else {
21817                ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
21818                transmit_response_with_sdp(p, "200 OK", req, (reinvite ? XMIT_RELIABLE : (req->ignore ?  XMIT_UNRELIABLE : XMIT_CRITICAL)), p->session_modify == TRUE ? FALSE : TRUE, FALSE);
21819             }
21820          }
21821 
21822          p->invitestate = INV_TERMINATED;
21823          break;
21824       default:
21825          ast_log(LOG_WARNING, "Don't know how to handle INVITE in state %d\n", c->_state);
21826          transmit_response(p, "100 Trying", req);
21827          break;
21828       }
21829    } else {
21830       if (p && (p->autokillid == -1)) {
21831          const char *msg;
21832 
21833          if (!p->jointcapability)
21834             msg = "488 Not Acceptable Here (codec error)";
21835          else {
21836             ast_log(LOG_NOTICE, "Unable to create/find SIP channel for this INVITE\n");
21837             msg = "503 Unavailable";
21838          }
21839          transmit_response_reliable(p, msg, req);
21840          p->invitestate = INV_COMPLETED;
21841          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
21842       }
21843    }
21844 
21845 request_invite_cleanup:
21846 
21847    if (refer_locked && p->refer && p->refer->refer_call) {
21848       sip_pvt_unlock(p->refer->refer_call);
21849       if (p->refer->refer_call->owner) {
21850          ast_channel_unlock(p->refer->refer_call->owner);
21851       }
21852    }
21853    if (authpeer) {
21854       authpeer = unref_peer(authpeer, "unref_peer, from handle_request_invite authpeer");
21855    }
21856 
21857    return res;
21858 }
21859 
21860 /*! \brief  Find all call legs and bridge transferee with target
21861  * called from handle_request_refer
21862  *
21863  * \note this function assumes two locks to begin with, sip_pvt transferer and current.chan1 (the pvt's owner)... 
21864  * 2 additional locks are held at the beginning of the function, targetcall_pvt, and targetcall_pvt's owner
21865  * channel (which is stored in target.chan1).  These 2 locks _MUST_ be let go by the end of the function.  Do
21866  * not be confused into thinking a pvt's owner is the same thing as the channels locked at the beginning of
21867  * this function, after the masquerade this may not be true.  Be consistent and unlock only the exact same
21868  * pointers that were locked to begin with.
21869  *
21870  * If this function is successful, only the transferer pvt lock will remain on return.  Setting nounlock indicates
21871  * to handle_request_do() that the pvt's owner it locked does not require an unlock.
21872  */
21873 static int local_attended_transfer(struct sip_pvt *transferer, struct sip_dual *current, struct sip_request *req, int seqno, int *nounlock)
21874 {
21875    struct sip_dual target;    /* Chan 1: Call from tranferer to Asterisk */
21876                /* Chan 2: Call from Asterisk to target */
21877    int res = 0;
21878    struct sip_pvt *targetcall_pvt;
21879    struct ast_party_connected_line connected_to_transferee;
21880    struct ast_party_connected_line connected_to_target;
21881    char transferer_linkedid[32];
21882    struct ast_channel *chans[2];
21883 
21884    /* Check if the call ID of the replaces header does exist locally */
21885    if (!(targetcall_pvt = get_sip_pvt_byid_locked(transferer->refer->replaces_callid, transferer->refer->replaces_callid_totag,
21886       transferer->refer->replaces_callid_fromtag))) {
21887       if (transferer->refer->localtransfer) {
21888          /* We did not find the refered call. Sorry, can't accept then */
21889          /* Let's fake a response from someone else in order
21890             to follow the standard */
21891          transmit_notify_with_sipfrag(transferer, seqno, "481 Call leg/transaction does not exist", TRUE);
21892          append_history(transferer, "Xfer", "Refer failed");
21893          ast_clear_flag(&transferer->flags[0], SIP_GOTREFER);
21894          transferer->refer->status = REFER_FAILED;
21895          return -1;
21896       }
21897       /* Fall through for remote transfers that we did not find locally */
21898       ast_debug(3, "SIP attended transfer: Not our call - generating INVITE with replaces\n");
21899       return 0;
21900    }
21901 
21902    /* Ok, we can accept this transfer */
21903    append_history(transferer, "Xfer", "Refer accepted");
21904    if (!targetcall_pvt->owner) { /* No active channel */
21905       ast_debug(4, "SIP attended transfer: Error: No owner of target call\n");
21906       /* Cancel transfer */
21907       transmit_notify_with_sipfrag(transferer, seqno, "503 Service Unavailable", TRUE);
21908       append_history(transferer, "Xfer", "Refer failed");
21909       ast_clear_flag(&transferer->flags[0], SIP_GOTREFER);
21910       transferer->refer->status = REFER_FAILED;
21911       sip_pvt_unlock(targetcall_pvt);
21912       if (targetcall_pvt)
21913          ao2_t_ref(targetcall_pvt, -1, "Drop targetcall_pvt pointer");
21914       return -1;
21915    }
21916 
21917    /* We have a channel, find the bridge */
21918    target.chan1 = targetcall_pvt->owner;           /* Transferer to Asterisk */
21919    target.chan2 = ast_bridged_channel(targetcall_pvt->owner);  /* Asterisk to target */
21920 
21921    if (!target.chan2 || !(target.chan2->_state == AST_STATE_UP || target.chan2->_state == AST_STATE_RINGING) ) {
21922       /* Wrong state of new channel */
21923       if (target.chan2)
21924          ast_debug(4, "SIP attended transfer: Error: Wrong state of target call: %s\n", ast_state2str(target.chan2->_state));
21925       else if (target.chan1->_state != AST_STATE_RING)
21926          ast_debug(4, "SIP attended transfer: Error: No target channel\n");
21927       else
21928          ast_debug(4, "SIP attended transfer: Attempting transfer in ringing state\n");
21929    }
21930 
21931    /* Transfer */
21932    if (sipdebug) {
21933       if (current->chan2)  /* We have two bridges */
21934          ast_debug(4, "SIP attended transfer: trying to bridge %s and %s\n", target.chan1->name, current->chan2->name);
21935       else        /* One bridge, propably transfer of IVR/voicemail etc */
21936          ast_debug(4, "SIP attended transfer: trying to make %s take over (masq) %s\n", target.chan1->name, current->chan1->name);
21937    }
21938 
21939    ast_set_flag(&transferer->flags[0], SIP_DEFER_BYE_ON_TRANSFER);   /* Delay hangup */
21940 
21941    ast_copy_string(transferer_linkedid, transferer->owner->linkedid, sizeof(transferer_linkedid));
21942 
21943    /* Perform the transfer */
21944    chans[0] = transferer->owner;
21945    chans[1] = target.chan1;
21946    ast_manager_event_multichan(EVENT_FLAG_CALL, "Transfer", 2, chans,
21947       "TransferMethod: SIP\r\n"
21948       "TransferType: Attended\r\n"
21949       "Channel: %s\r\n"
21950       "Uniqueid: %s\r\n"
21951       "SIP-Callid: %s\r\n"
21952       "TargetChannel: %s\r\n"
21953       "TargetUniqueid: %s\r\n",
21954       transferer->owner->name,
21955       transferer->owner->uniqueid,
21956       transferer->callid,
21957       target.chan1->name,
21958       target.chan1->uniqueid);
21959    ast_party_connected_line_init(&connected_to_transferee);
21960    ast_party_connected_line_init(&connected_to_target);
21961    /* No need to lock current->chan1 here since it was locked in sipsock_read */
21962    ast_party_connected_line_copy(&connected_to_transferee, &current->chan1->connected);
21963    /* No need to lock target.chan1 here since it was locked in get_sip_pvt_byid_locked */
21964    ast_party_connected_line_copy(&connected_to_target, &target.chan1->connected);
21965    connected_to_target.source = connected_to_transferee.source = AST_CONNECTED_LINE_UPDATE_SOURCE_TRANSFER;
21966    res = attempt_transfer(current, &target);
21967    if (res) {
21968       /* Failed transfer */
21969       transmit_notify_with_sipfrag(transferer, seqno, "486 Busy Here", TRUE);
21970       append_history(transferer, "Xfer", "Refer failed");
21971       ast_clear_flag(&transferer->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
21972       /* if transfer failed, go ahead and unlock targetcall_pvt and it's owner channel */
21973       sip_pvt_unlock(targetcall_pvt);
21974       ast_channel_unlock(target.chan1);
21975    } else {
21976       /* Transfer succeeded! */
21977       const char *xfersound = pbx_builtin_getvar_helper(target.chan1, "ATTENDED_TRANSFER_COMPLETE_SOUND");
21978 
21979       /* target.chan1 was locked in get_sip_pvt_byid_locked, do not unlock target.chan1 before this */
21980       ast_cel_report_event(target.chan1, AST_CEL_ATTENDEDTRANSFER, NULL, transferer_linkedid, target.chan2);
21981 
21982       /* Tell transferer that we're done. */
21983       transmit_notify_with_sipfrag(transferer, seqno, "200 OK", TRUE);
21984       append_history(transferer, "Xfer", "Refer succeeded");
21985       transferer->refer->status = REFER_200OK;
21986       if (target.chan2 && !ast_strlen_zero(xfersound) && ast_streamfile(target.chan2, xfersound, target.chan2->language) >= 0) {
21987          ast_waitstream(target.chan2, "");
21988       }
21989 
21990       /* By forcing the masquerade, we know that target.chan1 and target.chan2 are bridged. We then
21991        * can queue connected line updates where they need to go.
21992        *
21993        * before a masquerade, all channel and pvt locks must be unlocked.  Any recursive
21994        * channel locks held before this function invalidates channel container locking order.
21995        * Since we are unlocking both the pvt (transferer) and its owner channel (current.chan1)
21996        * it is possible for current.chan1 to be destroyed in the pbx thread.  To prevent this
21997        * we must give c a reference before any unlocking takes place.
21998        */
21999 
22000       ast_channel_ref(current->chan1);
22001       ast_channel_unlock(current->chan1); /* current.chan1 is p->owner before the masq, it was locked by socket_read()*/
22002       ast_channel_unlock(target.chan1);
22003       *nounlock = 1;  /* we just unlocked the dialog's channel and have no plans of locking it again. */
22004       sip_pvt_unlock(targetcall_pvt);
22005       sip_pvt_unlock(transferer);
22006 
22007       ast_do_masquerade(target.chan1);
22008 
22009       sip_pvt_lock(transferer); /* the transferer pvt is expected to remain locked on return */
22010 
22011       ast_indicate(target.chan1, AST_CONTROL_UNHOLD);
22012 
22013       if (current->chan2 && current->chan2->_state == AST_STATE_RING) {
22014          ast_indicate(target.chan1, AST_CONTROL_RINGING);
22015       }
22016 
22017       if (target.chan2) {
22018          ast_channel_queue_connected_line_update(target.chan1, &connected_to_transferee, NULL);
22019          ast_channel_queue_connected_line_update(target.chan2, &connected_to_target, NULL);
22020       } else {
22021          /* Since target.chan1 isn't actually connected to another channel, there is no way for us
22022           * to queue a frame so that its connected line status will be updated.
22023           *
22024           * Instead, we use the somewhat hackish approach of using a special control frame type that
22025           * instructs ast_read to perform a specific action. In this case, the frame we queue tells
22026           * ast_read to call the connected line interception macro configured for target.chan1.
22027           */
22028          struct ast_control_read_action_payload *frame_payload;
22029          int payload_size;
22030          int frame_size;
22031          unsigned char connected_line_data[1024];
22032          payload_size = ast_connected_line_build_data(connected_line_data,
22033             sizeof(connected_line_data), &connected_to_target, NULL);
22034          frame_size = payload_size + sizeof(*frame_payload);
22035          if (payload_size != -1 && (frame_payload = alloca(frame_size))) {
22036             frame_payload->payload_size = payload_size;
22037             memcpy(frame_payload->payload, connected_line_data, payload_size);
22038             frame_payload->action = AST_FRAME_READ_ACTION_CONNECTED_LINE_MACRO;
22039             ast_queue_control_data(target.chan1, AST_CONTROL_READ_ACTION, frame_payload, frame_size);
22040          }
22041          /* In addition to queueing the read action frame so that target.chan1's connected line info
22042           * will be updated, we also are going to queue a plain old connected line update on target.chan1. This
22043           * way, either Dial or Queue can apply this connected line update to the outgoing ringing channel.
22044           */
22045          ast_channel_queue_connected_line_update(target.chan1, &connected_to_transferee, NULL);
22046 
22047       }
22048       ast_channel_unref(current->chan1);
22049    }
22050 
22051    /* at this point if the transfer is successful only the transferer pvt should be locked. */
22052    ast_party_connected_line_free(&connected_to_target);
22053    ast_party_connected_line_free(&connected_to_transferee);
22054    if (targetcall_pvt)
22055       ao2_t_ref(targetcall_pvt, -1, "drop targetcall_pvt");
22056    return 1;
22057 }
22058 
22059 
22060 /*! \brief Handle incoming REFER request */
22061 /*! \page SIP_REFER SIP transfer Support (REFER)
22062 
22063    REFER is used for call transfer in SIP. We get a REFER
22064    to place a new call with an INVITE somwhere and then
22065    keep the transferor up-to-date of the transfer. If the
22066    transfer fails, get back on line with the orginal call.
22067 
22068    - REFER can be sent outside or inside of a dialog.
22069      Asterisk only accepts REFER inside of a dialog.
22070 
22071    - If we get a replaces header, it is an attended transfer
22072 
22073    \par Blind transfers
22074    The transferor provides the transferee
22075    with the transfer targets contact. The signalling between
22076    transferer or transferee should not be cancelled, so the
22077    call is recoverable if the transfer target can not be reached
22078    by the transferee.
22079 
22080    In this case, Asterisk receives a TRANSFER from
22081    the transferor, thus is the transferee. We should
22082    try to set up a call to the contact provided
22083    and if that fails, re-connect the current session.
22084    If the new call is set up, we issue a hangup.
22085    In this scenario, we are following section 5.2
22086    in the SIP CC Transfer draft. (Transfer without
22087    a GRUU)
22088 
22089    \par Transfer with consultation hold
22090    In this case, the transferor
22091    talks to the transfer target before the transfer takes place.
22092    This is implemented with SIP hold and transfer.
22093    Note: The invite From: string could indicate a transfer.
22094    (Section 6. Transfer with consultation hold)
22095    The transferor places the transferee on hold, starts a call
22096    with the transfer target to alert them to the impending
22097    transfer, terminates the connection with the target, then
22098    proceeds with the transfer (as in Blind transfer above)
22099 
22100    \par Attended transfer
22101    The transferor places the transferee
22102    on hold, calls the transfer target to alert them,
22103    places the target on hold, then proceeds with the transfer
22104    using a Replaces header field in the Refer-to header. This
22105    will force the transfee to send an Invite to the target,
22106    with a replaces header that instructs the target to
22107    hangup the call between the transferor and the target.
22108    In this case, the Refer/to: uses the AOR address. (The same
22109    URI that the transferee used to establish the session with
22110    the transfer target (To: ). The Require: replaces header should
22111    be in the INVITE to avoid the wrong UA in a forked SIP proxy
22112    scenario to answer and have no call to replace with.
22113 
22114    The referred-by header is *NOT* required, but if we get it,
22115    can be copied into the INVITE to the transfer target to
22116    inform the target about the transferor
22117 
22118    "Any REFER request has to be appropriately authenticated.".
22119    
22120    We can't destroy dialogs, since we want the call to continue.
22121    
22122    */
22123 static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, int *nounlock)
22124 {
22125    struct sip_dual current;   /* Chan1: Call between asterisk and transferer */
22126                /* Chan2: Call between asterisk and transferee */
22127 
22128    int res = 0;
22129    struct ast_channel *chans[2];
22130    current.req.data = NULL;
22131 
22132    if (req->debug)
22133       ast_verbose("Call %s got a SIP call transfer from %s: (REFER)!\n", p->callid, ast_test_flag(&p->flags[0], SIP_OUTGOING) ? "callee" : "caller");
22134 
22135    if (!p->owner) {
22136       /* This is a REFER outside of an existing SIP dialog */
22137       /* We can't handle that, so decline it */
22138       ast_debug(3, "Call %s: Declined REFER, outside of dialog...\n", p->callid);
22139       transmit_response(p, "603 Declined (No dialog)", req);
22140       if (!req->ignore) {
22141          append_history(p, "Xfer", "Refer failed. Outside of dialog.");
22142          sip_alreadygone(p);
22143          pvt_set_needdestroy(p, "outside of dialog");
22144       }
22145       return 0;
22146    }
22147 
22148 
22149    /* Check if transfer is allowed from this device */
22150    if (p->allowtransfer == TRANSFER_CLOSED ) {
22151       /* Transfer not allowed, decline */
22152       transmit_response(p, "603 Declined (policy)", req);
22153       append_history(p, "Xfer", "Refer failed. Allowtransfer == closed.");
22154       /* Do not destroy SIP session */
22155       return 0;
22156    }
22157 
22158    if (!req->ignore && ast_test_flag(&p->flags[0], SIP_GOTREFER)) {
22159       /* Already have a pending REFER */
22160       transmit_response(p, "491 Request pending", req);
22161       append_history(p, "Xfer", "Refer failed. Request pending.");
22162       return 0;
22163    }
22164 
22165    /* Allocate memory for call transfer data */
22166    if (!p->refer && !sip_refer_allocate(p)) {
22167       transmit_response(p, "500 Internal Server Error", req);
22168       append_history(p, "Xfer", "Refer failed. Memory allocation error.");
22169       return -3;
22170    }
22171 
22172    res = get_refer_info(p, req); /* Extract headers */
22173 
22174    p->refer->status = REFER_SENT;
22175 
22176    if (res != 0) {
22177       switch (res) {
22178       case -2: /* Syntax error */
22179          transmit_response(p, "400 Bad Request (Refer-to missing)", req);
22180          append_history(p, "Xfer", "Refer failed. Refer-to missing.");
22181          if (req->debug)
22182             ast_debug(1, "SIP transfer to black hole can't be handled (no refer-to: )\n");
22183          break;
22184       case -3:
22185          transmit_response(p, "603 Declined (Non sip: uri)", req);
22186          append_history(p, "Xfer", "Refer failed. Non SIP uri");
22187          if (req->debug)
22188             ast_debug(1, "SIP transfer to non-SIP uri denied\n");
22189          break;
22190       default:
22191          /* Refer-to extension not found, fake a failed transfer */
22192          transmit_response(p, "202 Accepted", req);
22193          append_history(p, "Xfer", "Refer failed. Bad extension.");
22194          transmit_notify_with_sipfrag(p, seqno, "404 Not found", TRUE);
22195          ast_clear_flag(&p->flags[0], SIP_GOTREFER);  
22196          if (req->debug)
22197             ast_debug(1, "SIP transfer to bad extension: %s\n", p->refer->refer_to);
22198          break;
22199       }
22200       return 0;
22201    }
22202    if (ast_strlen_zero(p->context))
22203       ast_string_field_set(p, context, sip_cfg.default_context);
22204 
22205    /* If we do not support SIP domains, all transfers are local */
22206    if (sip_cfg.allow_external_domains && check_sip_domain(p->refer->refer_to_domain, NULL, 0)) {
22207       p->refer->localtransfer = 1;
22208       if (sipdebug)
22209          ast_debug(3, "This SIP transfer is local : %s\n", p->refer->refer_to_domain);
22210    } else if (AST_LIST_EMPTY(&domain_list) || check_sip_domain(p->refer->refer_to_domain, NULL, 0)) {
22211       /* This PBX doesn't bother with SIP domains or domain is local, so this transfer is local */
22212       p->refer->localtransfer = 1;
22213    } else if (sipdebug)
22214          ast_debug(3, "This SIP transfer is to a remote SIP extension (remote domain %s)\n", p->refer->refer_to_domain);
22215 
22216    /* Is this a repeat of a current request? Ignore it */
22217    /* Don't know what else to do right now. */
22218    if (req->ignore)
22219       return res;
22220 
22221    /* If this is a blind transfer, we have the following
22222    channels to work with:
22223    - chan1, chan2: The current call between transferer and transferee (2 channels)
22224    - target_channel: A new call from the transferee to the target (1 channel)
22225    We need to stay tuned to what happens in order to be able
22226    to bring back the call to the transferer */
22227 
22228    /* If this is a attended transfer, we should have all call legs within reach:
22229    - chan1, chan2: The call between the transferer and transferee (2 channels)
22230    - target_channel, targetcall_pvt: The call between the transferer and the target (2 channels)
22231    We want to bridge chan2 with targetcall_pvt!
22232    
22233    The replaces call id in the refer message points
22234    to the call leg between Asterisk and the transferer.
22235    So we need to connect the target and the transferee channel
22236    and hangup the two other channels silently
22237    
22238    If the target is non-local, the call ID could be on a remote
22239    machine and we need to send an INVITE with replaces to the
22240    target. We basically handle this as a blind transfer
22241    and let the sip_call function catch that we need replaces
22242    header in the INVITE.
22243    */
22244 
22245 
22246    /* Get the transferer's channel */
22247    chans[0] = current.chan1 = p->owner;
22248 
22249    /* Find the other part of the bridge (2) - transferee */
22250    chans[1] = current.chan2 = ast_bridged_channel(current.chan1);
22251 
22252    if (sipdebug)
22253       ast_debug(3, "SIP %s transfer: Transferer channel %s, transferee channel %s\n", p->refer->attendedtransfer ? "attended" : "blind", current.chan1->name, current.chan2 ? current.chan2->name : "<none>");
22254 
22255    if (!current.chan2 && !p->refer->attendedtransfer) {
22256       /* No bridged channel, propably IVR or echo or similar... */
22257       /* Guess we should masquerade or something here */
22258       /* Until we figure it out, refuse transfer of such calls */
22259       if (sipdebug)
22260          ast_debug(3, "Refused SIP transfer on non-bridged channel.\n");
22261       p->refer->status = REFER_FAILED;
22262       append_history(p, "Xfer", "Refer failed. Non-bridged channel.");
22263       transmit_response(p, "603 Declined", req);
22264       return -1;
22265    }
22266 
22267    if (current.chan2) {
22268       if (sipdebug)
22269          ast_debug(4, "Got SIP transfer, applying to bridged peer '%s'\n", current.chan2->name);
22270 
22271       ast_queue_control(current.chan1, AST_CONTROL_UNHOLD);
22272    }
22273 
22274    ast_set_flag(&p->flags[0], SIP_GOTREFER);
22275 
22276    /* From here on failures will be indicated with NOTIFY requests */
22277    transmit_response(p, "202 Accepted", req);
22278 
22279    /* Attended transfer: Find all call legs and bridge transferee with target*/
22280    if (p->refer->attendedtransfer) {
22281       if ((res = local_attended_transfer(p, &current, req, seqno, nounlock)))
22282          return res; /* We're done with the transfer */
22283       /* Fall through for remote transfers that we did not find locally */
22284       if (sipdebug)
22285          ast_debug(4, "SIP attended transfer: Still not our call - generating INVITE with replaces\n");
22286       /* Fallthrough if we can't find the call leg internally */
22287    }
22288 
22289    /* Must release lock now, because it will not longer
22290       be accessible after the transfer! */
22291    *nounlock = 1;
22292    /*
22293     * Increase ref count so that we can delay channel destruction until after
22294     * we get a chance to fire off some events.
22295     */
22296    ast_channel_ref(current.chan1);
22297    sip_pvt_unlock(p);
22298    ast_channel_unlock(current.chan1);
22299 
22300    /* Parking a call */
22301    if (p->refer->localtransfer && ast_parking_ext_valid(p->refer->refer_to, p->owner, p->owner->context)) {
22302       sip_pvt_lock(p);
22303       copy_request(&current.req, req);
22304       ast_clear_flag(&p->flags[0], SIP_GOTREFER);
22305       p->refer->status = REFER_200OK;
22306       append_history(p, "Xfer", "REFER to call parking.");
22307       ast_manager_event_multichan(EVENT_FLAG_CALL, "Transfer", 2, chans,
22308          "TransferMethod: SIP\r\n"
22309          "TransferType: Blind\r\n"
22310          "Channel: %s\r\n"
22311          "Uniqueid: %s\r\n"
22312          "SIP-Callid: %s\r\n"
22313          "TargetChannel: %s\r\n"
22314          "TargetUniqueid: %s\r\n"
22315          "TransferExten: %s\r\n"
22316          "Transfer2Parking: Yes\r\n",
22317          current.chan1->name,
22318          current.chan1->uniqueid,
22319          p->callid,
22320          current.chan2->name,
22321          current.chan2->uniqueid,
22322          p->refer->refer_to);
22323       if (sipdebug)
22324          ast_debug(4, "SIP transfer to parking: trying to park %s. Parked by %s\n", current.chan2->name, current.chan1->name);
22325       if (sip_park(current.chan2, current.chan1, req, seqno, p->refer->refer_to)) {
22326          transmit_notify_with_sipfrag(p, seqno, "500 Internal Server Error", TRUE);
22327       }
22328       ast_channel_unref(current.chan1);
22329       return res;
22330    }
22331 
22332    /* Blind transfers and remote attended xfers */
22333    if (current.chan1 && current.chan2) {
22334       ast_debug(3, "chan1->name: %s\n", current.chan1->name);
22335       pbx_builtin_setvar_helper(current.chan1, "BLINDTRANSFER", current.chan2->name);
22336    }
22337 
22338    sip_pvt_lock(p);
22339 
22340    if (current.chan2) {
22341       pbx_builtin_setvar_helper(current.chan2, "BLINDTRANSFER", current.chan1->name);
22342       pbx_builtin_setvar_helper(current.chan2, "SIPDOMAIN", p->refer->refer_to_domain);
22343       pbx_builtin_setvar_helper(current.chan2, "SIPTRANSFER", "yes");
22344       /* One for the new channel */
22345       pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER", "yes");
22346       /* Attended transfer to remote host, prepare headers for the INVITE */
22347       if (p->refer->referred_by)
22348          pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER_REFERER", p->refer->referred_by);
22349    }
22350    /* Generate a Replaces string to be used in the INVITE during attended transfer */
22351    if (!ast_strlen_zero(p->refer->replaces_callid)) {
22352       char tempheader[SIPBUFSIZE];
22353       snprintf(tempheader, sizeof(tempheader), "%s%s%s%s%s", p->refer->replaces_callid,
22354             p->refer->replaces_callid_totag ? ";to-tag=" : "",
22355             p->refer->replaces_callid_totag,
22356             p->refer->replaces_callid_fromtag ? ";from-tag=" : "",
22357             p->refer->replaces_callid_fromtag);
22358       if (current.chan2)
22359          pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER_REPLACES", tempheader);
22360    }
22361 
22362    /* Connect the call */
22363 
22364    /* FAKE ringing if not attended transfer */
22365    if (!p->refer->attendedtransfer)
22366       transmit_notify_with_sipfrag(p, seqno, "183 Ringing", FALSE);
22367 
22368    /* For blind transfer, this will lead to a new call */
22369    /* For attended transfer to remote host, this will lead to
22370       a new SIP call with a replaces header, if the dial plan allows it
22371    */
22372    if (!current.chan2) {
22373       /* We have no bridge, so we're talking with Asterisk somehow */
22374       /* We need to masquerade this call */
22375       /* What to do to fix this situation:
22376          * Set up the new call in a new channel
22377          * Let the new channel masq into this channel
22378          Please add that code here :-)
22379       */
22380       p->refer->status = REFER_FAILED;
22381       transmit_notify_with_sipfrag(p, seqno, "503 Service Unavailable (can't handle one-legged xfers)", TRUE);
22382       ast_clear_flag(&p->flags[0], SIP_GOTREFER);  
22383       append_history(p, "Xfer", "Refer failed (only bridged calls).");
22384       ast_channel_unref(current.chan1);
22385       return -1;
22386    }
22387    ast_set_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER);   /* Delay hangup */
22388 
22389 
22390    /* For blind transfers, move the call to the new extensions. For attended transfers on multiple
22391       servers - generate an INVITE with Replaces. Either way, let the dial plan decided  */
22392    /* indicate before masquerade so the indication actually makes it to the real channel
22393       when using local channels with MOH passthru */
22394    ast_indicate(current.chan2, AST_CONTROL_UNHOLD);
22395    res = ast_async_goto(current.chan2, p->refer->refer_to_context, p->refer->refer_to, 1);
22396 
22397    if (!res) {
22398       ast_manager_event_multichan(EVENT_FLAG_CALL, "Transfer", 2, chans,
22399          "TransferMethod: SIP\r\n"
22400          "TransferType: Blind\r\n"
22401          "Channel: %s\r\n"
22402          "Uniqueid: %s\r\n"
22403          "SIP-Callid: %s\r\n"
22404          "TargetChannel: %s\r\n"
22405          "TargetUniqueid: %s\r\n"
22406          "TransferExten: %s\r\n"
22407          "TransferContext: %s\r\n",
22408          current.chan1->name,
22409          current.chan1->uniqueid,
22410          p->callid,
22411          current.chan2->name,
22412          current.chan2->uniqueid,
22413          p->refer->refer_to, p->refer->refer_to_context);
22414       /* Success  - we have a new channel */
22415       ast_debug(3, "%s transfer succeeded. Telling transferer.\n", p->refer->attendedtransfer? "Attended" : "Blind");
22416 
22417       while (ast_channel_trylock(current.chan1)) {
22418          sip_pvt_unlock(p);
22419          sched_yield();
22420          sip_pvt_lock(p);
22421       }
22422 
22423       /* XXX - what to we put in CEL 'extra' for attended transfers to external systems? NULL for now */
22424       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);
22425       ast_channel_unlock(current.chan1);
22426 
22427       transmit_notify_with_sipfrag(p, seqno, "200 Ok", TRUE);
22428       if (p->refer->localtransfer)
22429          p->refer->status = REFER_200OK;
22430       if (p->owner)
22431          p->owner->hangupcause = AST_CAUSE_NORMAL_CLEARING;
22432       append_history(p, "Xfer", "Refer succeeded.");
22433       ast_clear_flag(&p->flags[0], SIP_GOTREFER);  
22434       /* Do not hangup call, the other side do that when we say 200 OK */
22435       /* We could possibly implement a timer here, auto congestion */
22436       res = 0;
22437    } else {
22438       ast_clear_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER); /* Don't delay hangup */
22439       ast_debug(3, "%s transfer failed. Resuming original call.\n", p->refer->attendedtransfer? "Attended" : "Blind");
22440       append_history(p, "Xfer", "Refer failed.");
22441       /* Failure of some kind */
22442       p->refer->status = REFER_FAILED;
22443       transmit_notify_with_sipfrag(p, seqno, "503 Service Unavailable", TRUE);
22444       ast_clear_flag(&p->flags[0], SIP_GOTREFER);  
22445       res = -1;
22446    }
22447 
22448    ast_channel_unref(current.chan1);
22449 
22450    return res;
22451 }
22452 
22453 /*! \brief Handle incoming CANCEL request */
22454 static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req)
22455 {
22456 
22457    check_via(p, req);
22458    sip_alreadygone(p);
22459 
22460    if (p->owner && p->owner->_state == AST_STATE_UP) {
22461       /* This call is up, cancel is ignored, we need a bye */
22462       transmit_response(p, "200 OK", req);
22463       ast_debug(1, "Got CANCEL on an answered call. Ignoring... \n");
22464       return 0;
22465    }
22466 
22467    /* At this point, we could have cancelled the invite at the same time
22468       as the other side sends a CANCEL. Our final reply with error code
22469       might not have been received by the other side before the CANCEL
22470       was sent, so let's just give up retransmissions and waiting for
22471       ACK on our error code. The call is hanging up any way. */
22472    if (p->invitestate == INV_TERMINATED || p->invitestate == INV_COMPLETED) {
22473       __sip_pretend_ack(p);
22474    }
22475    if (p->invitestate != INV_TERMINATED)
22476       p->invitestate = INV_CANCELLED;
22477 
22478    if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD))
22479       update_call_counter(p, DEC_CALL_LIMIT);
22480 
22481    stop_media_flows(p); /* Immediately stop RTP, VRTP and UDPTL as applicable */
22482    if (p->owner) {
22483       ast_set_hangupsource(p->owner, p->owner->name, 0);
22484       ast_queue_hangup(p->owner);
22485    }
22486    else
22487       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
22488    if (p->initreq.len > 0) {
22489       struct sip_pkt *pkt, *prev_pkt;
22490       /* If the CANCEL we are receiving is a retransmission, and we already have scheduled
22491        * a reliable 487, then we don't want to schedule another one on top of the previous
22492        * one.
22493        *
22494        * As odd as this may sound, we can't rely on the previously-transmitted "reliable"
22495        * response in this situation. What if we've sent all of our reliable responses
22496        * already and now all of a sudden, we get this second CANCEL?
22497        *
22498        * The only way to do this correctly is to cancel our previously-scheduled reliably-
22499        * transmitted response and send a new one in its place.
22500        */
22501       for (pkt = p->packets, prev_pkt = NULL; pkt; prev_pkt = pkt, pkt = pkt->next) {
22502          if (pkt->seqno == p->lastinvite && pkt->response_code == 487) {
22503             AST_SCHED_DEL(sched, pkt->retransid);
22504             UNLINK(pkt, p->packets, prev_pkt);
22505             ast_free(pkt);
22506             break;
22507          }
22508       }
22509       transmit_response_reliable(p, "487 Request Terminated", &p->initreq);
22510       transmit_response(p, "200 OK", req);
22511       return 1;
22512    } else {
22513       transmit_response(p, "481 Call Leg Does Not Exist", req);
22514       return 0;
22515    }
22516 }
22517 
22518 /*! \brief Handle incoming BYE request */
22519 static int handle_request_bye(struct sip_pvt *p, struct sip_request *req)
22520 {
22521    struct ast_channel *c=NULL;
22522    int res;
22523    struct ast_channel *bridged_to;
22524    const char *required;
22525 
22526    /* If we have an INCOMING invite that we haven't answered, terminate that transaction */
22527    if (p->pendinginvite && !ast_test_flag(&p->flags[0], SIP_OUTGOING) && !req->ignore) {
22528       transmit_response_reliable(p, "487 Request Terminated", &p->initreq);
22529    }
22530 
22531    __sip_pretend_ack(p);
22532 
22533    p->invitestate = INV_TERMINATED;
22534 
22535    copy_request(&p->initreq, req);
22536    if (sipdebug)
22537       ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
22538    check_via(p, req);
22539    sip_alreadygone(p);
22540 
22541    /* Get RTCP quality before end of call */
22542    if (p->do_history || p->owner) {
22543       char quality_buf[AST_MAX_USER_FIELD], *quality;
22544       struct ast_channel *bridge = p->owner ? ast_bridged_channel(p->owner) : NULL;
22545 
22546       /* We need to get the lock on bridge because ast_rtp_instance_set_stats_vars will attempt
22547        * to lock the bridge. This may get hairy...
22548        */
22549       while (bridge && ast_channel_trylock(bridge)) {
22550          ast_channel_unlock(p->owner);
22551          do {
22552             /* Can't use DEADLOCK_AVOIDANCE since p is an ao2 object */
22553             sip_pvt_unlock(p);
22554             usleep(1);
22555             sip_pvt_lock(p);
22556          } while (p->owner && ast_channel_trylock(p->owner));
22557          bridge = p->owner ? ast_bridged_channel(p->owner) : NULL;
22558       }
22559 
22560 
22561       if (p->rtp && (quality = ast_rtp_instance_get_quality(p->rtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY, quality_buf, sizeof(quality_buf)))) {
22562          if (p->do_history) {
22563             append_history(p, "RTCPaudio", "Quality:%s", quality);
22564 
22565             if ((quality = ast_rtp_instance_get_quality(p->rtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY_JITTER, quality_buf, sizeof(quality_buf)))) {
22566                append_history(p, "RTCPaudioJitter", "Quality:%s", quality);
22567             }
22568             if ((quality = ast_rtp_instance_get_quality(p->rtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY_LOSS, quality_buf, sizeof(quality_buf)))) {
22569                append_history(p, "RTCPaudioLoss", "Quality:%s", quality);
22570             }
22571             if ((quality = ast_rtp_instance_get_quality(p->rtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY_RTT, quality_buf, sizeof(quality_buf)))) {
22572                append_history(p, "RTCPaudioRTT", "Quality:%s", quality);
22573             }
22574          }
22575 
22576          if (p->owner) {
22577             ast_rtp_instance_set_stats_vars(p->owner, p->rtp);
22578          }
22579 
22580       }
22581 
22582       if (bridge) {
22583          struct sip_pvt *q = bridge->tech_pvt;
22584 
22585          if (IS_SIP_TECH(bridge->tech) && q && q->rtp) {
22586             ast_rtp_instance_set_stats_vars(bridge, q->rtp);
22587          }
22588          ast_channel_unlock(bridge);
22589       }
22590 
22591       if (p->vrtp && (quality = ast_rtp_instance_get_quality(p->vrtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY, quality_buf, sizeof(quality_buf)))) {
22592          if (p->do_history) {
22593             append_history(p, "RTCPvideo", "Quality:%s", quality);
22594          }
22595          if (p->owner) {
22596             pbx_builtin_setvar_helper(p->owner, "RTPVIDEOQOS", quality);
22597          }
22598       }
22599       if (p->trtp && (quality = ast_rtp_instance_get_quality(p->trtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY, quality_buf, sizeof(quality_buf)))) {
22600          if (p->do_history) {
22601             append_history(p, "RTCPtext", "Quality:%s", quality);
22602          }
22603          if (p->owner) {
22604             pbx_builtin_setvar_helper(p->owner, "RTPTEXTQOS", quality);
22605          }
22606       }
22607    }
22608 
22609    stop_media_flows(p); /* Immediately stop RTP, VRTP and UDPTL as applicable */
22610    stop_session_timer(p); /* Stop Session-Timer */
22611 
22612    if (!ast_strlen_zero(get_header(req, "Also"))) {
22613       ast_log(LOG_NOTICE, "Client '%s' using deprecated BYE/Also transfer method.  Ask vendor to support REFER instead\n",
22614          ast_sockaddr_stringify(&p->recv));
22615       if (ast_strlen_zero(p->context))
22616          ast_string_field_set(p, context, sip_cfg.default_context);
22617       res = get_also_info(p, req);
22618       if (!res) {
22619          c = p->owner;
22620          if (c) {
22621             bridged_to = ast_bridged_channel(c);
22622             if (bridged_to) {
22623                /* Don't actually hangup here... */
22624                ast_queue_control(c, AST_CONTROL_UNHOLD);
22625                ast_channel_unlock(c);  /* async_goto can do a masquerade, no locks can be held during a masq */
22626                ast_async_goto(bridged_to, p->context, p->refer->refer_to, 1);
22627                ast_channel_lock(c);
22628             } else
22629                ast_queue_hangup(p->owner);
22630          }
22631       } else {
22632          ast_log(LOG_WARNING, "Invalid transfer information from '%s'\n", ast_sockaddr_stringify(&p->recv));
22633          if (p->owner)
22634             ast_queue_hangup_with_cause(p->owner, AST_CAUSE_PROTOCOL_ERROR);
22635       }
22636    } else if (p->owner) {
22637       ast_set_hangupsource(p->owner, p->owner->name, 0);
22638       ast_queue_hangup(p->owner);
22639       sip_scheddestroy_final(p, DEFAULT_TRANS_TIMEOUT);
22640       ast_debug(3, "Received bye, issuing owner hangup\n");
22641    } else {
22642       sip_scheddestroy_final(p, DEFAULT_TRANS_TIMEOUT);
22643       ast_debug(3, "Received bye, no owner, selfdestruct soon.\n");
22644    }
22645    ast_clear_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
22646 
22647    /* Find out what they require */
22648    required = get_header(req, "Require");
22649    if (!ast_strlen_zero(required)) {
22650       char unsupported[256] = { 0, };
22651       parse_sip_options(required, unsupported, ARRAY_LEN(unsupported));
22652       /* If there are any options required that we do not support,
22653        * then send a 420 with only those unsupported options listed */
22654       if (!ast_strlen_zero(unsupported)) {
22655          transmit_response_with_unsupported(p, "420 Bad extension (unsupported)", req, unsupported);
22656          ast_log(LOG_WARNING, "Received SIP BYE with unsupported required extension: required:%s unsupported:%s\n", required, unsupported);
22657       } else {
22658          transmit_response(p, "200 OK", req);
22659       }
22660    } else {
22661       transmit_response(p, "200 OK", req);
22662    }
22663 
22664    return 1;
22665 }
22666 
22667 /*! \brief Handle incoming MESSAGE request */
22668 static int handle_request_message(struct sip_pvt *p, struct sip_request *req)
22669 {
22670    if (!req->ignore) {
22671       if (req->debug)
22672          ast_verbose("Receiving message!\n");
22673       receive_message(p, req);
22674    } else
22675       transmit_response(p, "202 Accepted", req);
22676    return 1;
22677 }
22678 
22679 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)
22680 {
22681    int etag_present = !ast_strlen_zero(etag);
22682    int body_present = req->lines > 0;
22683 
22684    ast_assert(expires_int != NULL);
22685 
22686    if (ast_strlen_zero(expires)) {
22687       /* Section 6, item 4, second bullet point of RFC 3903 says to
22688        * use a locally-configured default expiration if none is provided
22689        * in the request
22690        */
22691       *expires_int = DEFAULT_PUBLISH_EXPIRES;
22692    } else if (sscanf(expires, "%30d", expires_int) != 1) {
22693       return SIP_PUBLISH_UNKNOWN;
22694    }
22695 
22696    if (*expires_int == 0) {
22697       return SIP_PUBLISH_REMOVE;
22698    } else if (!etag_present && body_present) {
22699       return SIP_PUBLISH_INITIAL;
22700    } else if (etag_present && !body_present) {
22701       return SIP_PUBLISH_REFRESH;
22702    } else if (etag_present && body_present) {
22703       return SIP_PUBLISH_MODIFY;
22704    }
22705 
22706    return SIP_PUBLISH_UNKNOWN;
22707 }
22708 
22709 #ifdef HAVE_LIBXML2
22710 static void get_pidf_body(struct sip_request *req, char *pidf_body, size_t size)
22711 {
22712    int i;
22713    struct ast_str *str = ast_str_alloca(size);
22714    for (i = 0; i < req->lines; ++i) {
22715       ast_str_append(&str, 0, "%s", REQ_OFFSET_TO_STR(req, line[i]));
22716    }
22717    ast_copy_string(pidf_body, ast_str_buffer(str), size);
22718 }
22719 
22720 static int pidf_validate_tuple(struct ast_xml_node *tuple_node)
22721 {
22722    const char *id;
22723    int status_found = FALSE;
22724    struct ast_xml_node *tuple_children;
22725    struct ast_xml_node *tuple_children_iterator;
22726    /* Tuples have to have an id attribute or they're invalid */
22727    if (!(id = ast_xml_get_attribute(tuple_node, "id"))) {
22728       ast_log(LOG_WARNING, "Tuple XML element has no attribute 'id'\n");
22729       return FALSE;
22730    }
22731    /* We don't care what it actually is, just that it's there */
22732    ast_xml_free_attr(id);
22733    /* This is a tuple. It must have a status element */
22734    if (!(tuple_children = ast_xml_node_get_children(tuple_node))) {
22735       /* The tuple has no children. It sucks */
22736       ast_log(LOG_WARNING, "Tuple XML element has no child elements\n");
22737       return FALSE;
22738    }
22739    for (tuple_children_iterator = tuple_children; tuple_children_iterator;
22740          tuple_children_iterator = ast_xml_node_get_next(tuple_children_iterator)) {
22741       /* Similar to the wording used regarding tuples, the status element should appear
22742        * first. However, we will once again relax things and accept the status at any
22743        * position. We will enforce that only a single status element can be present.
22744        */
22745       if (strcmp(ast_xml_node_get_name(tuple_children_iterator), "status")) {
22746          /* Not the status, we don't care */
22747          continue;
22748       }
22749       if (status_found == TRUE) {
22750          /* THERE CAN BE ONLY ONE!!! */
22751          ast_log(LOG_WARNING, "Multiple status elements found in tuple. Only one allowed\n");
22752          return FALSE;
22753       }
22754       status_found = TRUE;
22755    }
22756    return status_found;
22757 }
22758 
22759 
22760 static int pidf_validate_presence(struct ast_xml_doc *doc)
22761 {
22762    struct ast_xml_node *presence_node = ast_xml_get_root(doc);
22763    struct ast_xml_node *child_nodes;
22764    struct ast_xml_node *node_iterator;
22765    struct ast_xml_ns *ns;
22766    const char *entity;
22767    const char *namespace;
22768    const char presence_namespace[] = "urn:ietf:params:xml:ns:pidf";
22769 
22770    if (!presence_node) {
22771       ast_log(LOG_WARNING, "Unable to retrieve root node of the XML document\n");
22772       return FALSE;
22773    }
22774    /* Okay, we managed to open the document! YAY! Now, let's start making sure it's all PIDF-ified
22775     * correctly.
22776     */
22777    if (strcmp(ast_xml_node_get_name(presence_node), "presence")) {
22778       ast_log(LOG_WARNING, "Root node of PIDF document is not 'presence'. Invalid\n");
22779       return FALSE;
22780    }
22781 
22782    /* The presence element must have an entity attribute and an xmlns attribute. Furthermore
22783     * the xmlns attribute must be "urn:ietf:params:xml:ns:pidf"
22784     */
22785    if (!(entity = ast_xml_get_attribute(presence_node, "entity"))) {
22786       ast_log(LOG_WARNING, "Presence element of PIDF document has no 'entity' attribute\n");
22787       return FALSE;
22788    }
22789    /* We're not interested in what the entity is, just that it exists */
22790    ast_xml_free_attr(entity);
22791 
22792    if (!(ns = ast_xml_find_namespace(doc, presence_node, NULL))) {
22793       ast_log(LOG_WARNING, "Couldn't find default namespace...\n");
22794       return FALSE;
22795    }
22796 
22797    namespace = ast_xml_get_ns_href(ns);
22798    if (ast_strlen_zero(namespace) || strcmp(namespace, presence_namespace)) {
22799       ast_log(LOG_WARNING, "PIDF document has invalid namespace value %s\n", namespace);
22800       return FALSE;
22801    }
22802 
22803    if (!(child_nodes = ast_xml_node_get_children(presence_node))) {
22804       ast_log(LOG_WARNING, "PIDF document has no elements as children of 'presence'. Invalid\n");
22805       return FALSE;
22806    }
22807 
22808    /* Check for tuple elements. RFC 3863 says that PIDF documents can have any number of
22809     * tuples, including 0. The big thing here is that if there are tuple elements present,
22810     * they have to have a single status element within.
22811     *
22812     * The RFC is worded such that tuples should appear as the first elements as children of
22813     * the presence element. However, we'll be accepting of documents which may place other elements
22814     * before the tuple(s).
22815     */
22816    for (node_iterator = child_nodes; node_iterator;
22817          node_iterator = ast_xml_node_get_next(node_iterator)) {
22818       if (strcmp(ast_xml_node_get_name(node_iterator), "tuple")) {
22819          /* Not a tuple. We don't give a rat's hind quarters */
22820          continue;
22821       }
22822       if (pidf_validate_tuple(node_iterator) == FALSE) {
22823          ast_log(LOG_WARNING, "Unable to validate tuple\n");
22824          return FALSE;
22825       }
22826    }
22827 
22828    return TRUE;
22829 }
22830 
22831 /*!
22832  * \brief Makes sure that body is properly formatted PIDF
22833  *
22834  * Specifically, we check that the document has a "presence" element
22835  * at the root and that within that, there is at least one "tuple" element
22836  * that contains a "status" element.
22837  *
22838  * XXX This function currently assumes a default namespace is used. Of course
22839  * if you're not using a default namespace, you're probably a stupid jerk anyway.
22840  *
22841  * \param req The SIP request to check
22842  * \param[out] pidf_doc The validated PIDF doc.
22843  * \retval FALSE The XML was malformed or the basic PIDF structure was marred
22844  * \retval TRUE The PIDF document is of a valid format
22845  */
22846 static int sip_pidf_validate(struct sip_request *req, struct ast_xml_doc **pidf_doc)
22847 {
22848    struct ast_xml_doc *doc;
22849    int content_length;
22850    const char *content_length_str = get_header(req, "Content-Length");
22851    const char *content_type = get_header(req, "Content-Type");
22852    char pidf_body[SIPBUFSIZE];
22853    int res;
22854 
22855    if (ast_strlen_zero(content_type) || strcmp(content_type, "application/pidf+xml")) {
22856       ast_log(LOG_WARNING, "Content type is not PIDF\n");
22857       return FALSE;
22858    }
22859 
22860    if (ast_strlen_zero(content_length_str)) {
22861       ast_log(LOG_WARNING, "No content length. Can't determine bounds of PIDF document\n");
22862       return FALSE;
22863    }
22864 
22865    if (sscanf(content_length_str, "%30d", &content_length) != 1) {
22866       ast_log(LOG_WARNING, "Invalid content length provided\n");
22867       return FALSE;
22868    }
22869 
22870    if (content_length > sizeof(pidf_body)) {
22871       ast_log(LOG_WARNING, "Content length of PIDF document truncated to %d bytes\n", (int) sizeof(pidf_body));
22872       content_length = sizeof(pidf_body);
22873    }
22874 
22875    get_pidf_body(req, pidf_body, content_length);
22876 
22877    if (!(doc = ast_xml_read_memory(pidf_body, content_length))) {
22878       ast_log(LOG_WARNING, "Unable to open XML PIDF document. Is it malformed?\n");
22879       return FALSE;
22880    }
22881 
22882    res = pidf_validate_presence(doc);
22883    if (res == TRUE) {
22884       *pidf_doc = doc;
22885    } else {
22886       ast_xml_close(doc);
22887    }
22888    return res;
22889 }
22890 
22891 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)
22892 {
22893    const char *uri = REQ_OFFSET_TO_STR(req, rlPart2);
22894    struct ast_cc_agent *agent = find_sip_cc_agent_by_notify_uri(uri);
22895    struct sip_cc_agent_pvt *agent_pvt;
22896    struct ast_xml_doc *pidf_doc = NULL;
22897    const char *basic_status = NULL;
22898    struct ast_xml_node *presence_node;
22899    struct ast_xml_node *presence_children;
22900    struct ast_xml_node *tuple_node;
22901    struct ast_xml_node *tuple_children;
22902    struct ast_xml_node *status_node;
22903    struct ast_xml_node *status_children;
22904    struct ast_xml_node *basic_node;
22905    int res = 0;
22906 
22907    if (!agent) {
22908       ast_log(LOG_WARNING, "Could not find agent using uri '%s'\n", uri);
22909       transmit_response(pvt, "412 Conditional Request Failed", req);
22910       return -1;
22911    }
22912 
22913    agent_pvt = agent->private_data;
22914 
22915    if (sip_pidf_validate(req, &pidf_doc) == FALSE) {
22916       res = -1;
22917       goto cc_publish_cleanup;
22918    }
22919 
22920    /* It's important to note that the PIDF validation routine has no knowledge
22921     * of what we specifically want in this instance. A valid PIDF document could
22922     * have no tuples, or it could have tuples whose status element has no basic
22923     * element contained within. While not violating the PIDF spec, these are
22924     * insufficient for our needs in this situation
22925     */
22926    presence_node = ast_xml_get_root(pidf_doc);
22927    if (!(presence_children = ast_xml_node_get_children(presence_node))) {
22928       ast_log(LOG_WARNING, "No tuples within presence element.\n");
22929       res = -1;
22930       goto cc_publish_cleanup;
22931    }
22932 
22933    if (!(tuple_node = ast_xml_find_element(presence_children, "tuple", NULL, NULL))) {
22934       ast_log(LOG_NOTICE, "Couldn't find tuple node?\n");
22935       res = -1;
22936       goto cc_publish_cleanup;
22937    }
22938 
22939    /* We already made sure that the tuple has a status node when we validated the PIDF
22940     * document earlier. So there's no need to enclose this operation in an if statement.
22941     */
22942    tuple_children = ast_xml_node_get_children(tuple_node);
22943    status_node = ast_xml_find_element(tuple_children, "status", NULL, NULL);
22944 
22945    if (!(status_children = ast_xml_node_get_children(status_node))) {
22946       ast_log(LOG_WARNING, "No basic elements within status element.\n");
22947       res = -1;
22948       goto cc_publish_cleanup;
22949    }
22950 
22951    if (!(basic_node = ast_xml_find_element(status_children, "basic", NULL, NULL))) {
22952       ast_log(LOG_WARNING, "Couldn't find basic node?\n");
22953       res = -1;
22954       goto cc_publish_cleanup;
22955    }
22956 
22957    basic_status = ast_xml_get_text(basic_node);
22958 
22959    if (ast_strlen_zero(basic_status)) {
22960       ast_log(LOG_NOTICE, "NOthing in basic node?\n");
22961       res = -1;
22962       goto cc_publish_cleanup;
22963    }
22964 
22965    if (!strcmp(basic_status, "open")) {
22966       agent_pvt->is_available = TRUE;
22967       ast_cc_agent_caller_available(agent->core_id, "Received PUBLISH stating SIP caller %s is available",
22968             agent->device_name);
22969    } else if (!strcmp(basic_status, "closed")) {
22970       agent_pvt->is_available = FALSE;
22971       ast_cc_agent_caller_busy(agent->core_id, "Received PUBLISH stating SIP caller %s is busy",
22972             agent->device_name);
22973    } else {
22974       ast_log(LOG_NOTICE, "Invalid content in basic element: %s\n", basic_status);
22975    }
22976 
22977 cc_publish_cleanup:
22978    if (basic_status) {
22979       ast_xml_free_text(basic_status);
22980    }
22981    if (pidf_doc) {
22982       ast_xml_close(pidf_doc);
22983    }
22984    ao2_ref(agent, -1);
22985    if (res) {
22986       transmit_response(pvt, "400 Bad Request", req);
22987    }
22988    return res;
22989 }
22990 
22991 #endif /* HAVE_LIBXML2 */
22992 
22993 static int handle_sip_publish_initial(struct sip_pvt *p, struct sip_request *req, struct event_state_compositor *esc, const int expires)
22994 {
22995    struct sip_esc_entry *esc_entry = create_esc_entry(esc, req, expires);
22996    int res = 0;
22997 
22998    if (!esc_entry) {
22999       transmit_response(p, "503 Internal Server Failure", req);
23000       return -1;
23001    }
23002 
23003    if (esc->callbacks->initial_handler) {
23004       res = esc->callbacks->initial_handler(p, req, esc, esc_entry);
23005    }
23006 
23007    if (!res) {
23008       transmit_response_with_sip_etag(p, "200 OK", req, esc_entry, 0);
23009    }
23010 
23011    ao2_ref(esc_entry, -1);
23012    return res;
23013 }
23014 
23015 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)
23016 {
23017    struct sip_esc_entry *esc_entry = get_esc_entry(etag, esc);
23018    int expires_ms = expires * 1000;
23019    int res = 0;
23020 
23021    if (!esc_entry) {
23022       transmit_response(p, "412 Conditional Request Failed", req);
23023       return -1;
23024    }
23025 
23026    AST_SCHED_REPLACE_UNREF(esc_entry->sched_id, sched, expires_ms, publish_expire, esc_entry,
23027          ao2_ref(_data, -1),
23028          ao2_ref(esc_entry, -1),
23029          ao2_ref(esc_entry, +1));
23030 
23031    if (esc->callbacks->refresh_handler) {
23032       res = esc->callbacks->refresh_handler(p, req, esc, esc_entry);
23033    }
23034 
23035    if (!res) {
23036       transmit_response_with_sip_etag(p, "200 OK", req, esc_entry, 1);
23037    }
23038 
23039    ao2_ref(esc_entry, -1);
23040    return res;
23041 }
23042 
23043 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)
23044 {
23045    struct sip_esc_entry *esc_entry = get_esc_entry(etag, esc);
23046    int expires_ms = expires * 1000;
23047    int res = 0;
23048 
23049    if (!esc_entry) {
23050       transmit_response(p, "412 Conditional Request Failed", req);
23051       return -1;
23052    }
23053 
23054    AST_SCHED_REPLACE_UNREF(esc_entry->sched_id, sched, expires_ms, publish_expire, esc_entry,
23055          ao2_ref(_data, -1),
23056          ao2_ref(esc_entry, -1),
23057          ao2_ref(esc_entry, +1));
23058 
23059    if (esc->callbacks->modify_handler) {
23060       res = esc->callbacks->modify_handler(p, req, esc, esc_entry);
23061    }
23062 
23063    if (!res) {
23064       transmit_response_with_sip_etag(p, "200 OK", req, esc_entry, 1);
23065    }
23066 
23067    ao2_ref(esc_entry, -1);
23068    return res;
23069 }
23070 
23071 static int handle_sip_publish_remove(struct sip_pvt *p, struct sip_request *req, struct event_state_compositor *esc, const char * const etag)
23072 {
23073    struct sip_esc_entry *esc_entry = get_esc_entry(etag, esc);
23074    int res = 0;
23075 
23076    if (!esc_entry) {
23077       transmit_response(p, "412 Conditional Request Failed", req);
23078       return -1;
23079    }
23080 
23081    AST_SCHED_DEL(sched, esc_entry->sched_id);
23082    /* Scheduler's ref of the esc_entry */
23083    ao2_ref(esc_entry, -1);
23084 
23085    if (esc->callbacks->remove_handler) {
23086       res = esc->callbacks->remove_handler(p, req, esc, esc_entry);
23087    }
23088 
23089    if (!res) {
23090       transmit_response_with_sip_etag(p, "200 OK", req, esc_entry, 1);
23091    }
23092 
23093    /* Ref from finding the esc_entry earlier in function */
23094    ao2_unlink(esc->compositor, esc_entry);
23095    ao2_ref(esc_entry, -1);
23096    return res;
23097 }
23098 
23099 static int handle_request_publish(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, const int seqno, const char *uri)
23100 {
23101    const char *etag = get_header(req, "SIP-If-Match");
23102    const char *event = get_header(req, "Event");
23103    struct event_state_compositor *esc;
23104    enum sip_publish_type publish_type;
23105    const char *expires_str = get_header(req, "Expires");
23106    int expires_int;
23107    int auth_result;
23108    int handler_result = -1;
23109 
23110    if (ast_strlen_zero(event)) {
23111       transmit_response(p, "489 Bad Event", req);
23112       return -1;
23113    }
23114 
23115    if (!(esc = get_esc(event))) {
23116       transmit_response(p, "489 Bad Event", req);
23117       return -1;
23118    }
23119 
23120    auth_result = check_user(p, req, SIP_PUBLISH, uri, XMIT_RELIABLE, addr);
23121    if (auth_result == AUTH_CHALLENGE_SENT) {
23122       p->lastinvite = seqno;
23123       return 0;
23124    } else if (auth_result < 0) {
23125       if (auth_result == AUTH_FAKE_AUTH) {
23126          ast_log(LOG_NOTICE, "Sending fake auth rejection for device %s\n", get_header(req, "From"));
23127          transmit_fake_auth_response(p, SIP_INVITE, req, XMIT_RELIABLE);
23128       } else {
23129          ast_log(LOG_NOTICE, "Failed to authenticate device %s\n", get_header(req, "From"));
23130          transmit_response_reliable(p, "403 Forbidden", req);
23131       }
23132       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
23133       ast_string_field_set(p, theirtag, NULL);
23134       return 0;
23135    } else if (auth_result == AUTH_SUCCESSFUL && p->lastinvite) {
23136       /* We need to stop retransmitting the 401 */
23137       __sip_ack(p, p->lastinvite, 1, 0);
23138    }
23139 
23140    publish_type = determine_sip_publish_type(req, event, etag, expires_str, &expires_int);
23141 
23142    /* It is the responsibility of these handlers to formulate any response
23143     * sent for a PUBLISH
23144     */
23145    switch (publish_type) {
23146    case SIP_PUBLISH_UNKNOWN:
23147       transmit_response(p, "400 Bad Request", req);
23148       break;
23149    case SIP_PUBLISH_INITIAL:
23150       handler_result = handle_sip_publish_initial(p, req, esc, expires_int);
23151       break;
23152    case SIP_PUBLISH_REFRESH:
23153       handler_result = handle_sip_publish_refresh(p, req, esc, etag, expires_int);
23154       break;
23155    case SIP_PUBLISH_MODIFY:
23156       handler_result = handle_sip_publish_modify(p, req, esc, etag, expires_int);
23157       break;
23158    case SIP_PUBLISH_REMOVE:
23159       handler_result = handle_sip_publish_remove(p, req, esc, etag);
23160       break;
23161    default:
23162       transmit_response(p, "400 Impossible Condition", req);
23163       break;
23164    }
23165 
23166    return handler_result;
23167 }
23168 
23169 static void add_peer_mwi_subs(struct sip_peer *peer)
23170 {
23171    struct sip_mailbox *mailbox;
23172 
23173    AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
23174       mailbox->event_sub = ast_event_subscribe(AST_EVENT_MWI, mwi_event_cb, "SIP mbox event", peer,
23175          AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, mailbox->mailbox,
23176          AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, S_OR(mailbox->context, "default"),
23177          AST_EVENT_IE_END);
23178    }
23179 }
23180 
23181 static int handle_cc_subscribe(struct sip_pvt *p, struct sip_request *req)
23182 {
23183    const char *uri = REQ_OFFSET_TO_STR(req, rlPart2);
23184    char *param_separator;
23185    struct ast_cc_agent *agent;
23186    struct sip_cc_agent_pvt *agent_pvt;
23187    const char *expires_str = get_header(req, "Expires");
23188    int expires = -1; /* Just need it to be non-zero */
23189 
23190    if (!ast_strlen_zero(expires_str)) {
23191       sscanf(expires_str, "%d", &expires);
23192    }
23193 
23194    if ((param_separator = strchr(uri, ';'))) {
23195       *param_separator = '\0';
23196    }
23197 
23198    if (!(agent = find_sip_cc_agent_by_subscribe_uri(uri))) {
23199       if (!expires) {
23200          /* Typically, if a 0 Expires reaches us and we can't find
23201           * the corresponding agent, it means that the CC transaction
23202           * has completed and so the calling side is just trying to
23203           * clean up its subscription. We'll just respond with a
23204           * 200 OK and be done with it
23205           */
23206          transmit_response(p, "200 OK", req);
23207          return 0;
23208       }
23209       ast_log(LOG_WARNING, "Invalid URI '%s' in CC subscribe\n", uri);
23210       transmit_response(p, "404 Not Found", req);
23211       return -1;
23212    }
23213 
23214    agent_pvt = agent->private_data;
23215 
23216    if (!expires) {
23217       /* We got sent a SUBSCRIBE and found an agent. This means that CC
23218        * is being canceled.
23219        */
23220       ast_cc_failed(agent->core_id, "CC is being canceled by %s", agent->device_name);
23221       transmit_response(p, "200 OK", req);
23222       ao2_ref(agent, -1);
23223       return 0;
23224    }
23225 
23226    agent_pvt->subscribe_pvt = dialog_ref(p, "SIP CC agent gains reference to subscription dialog");
23227    ast_cc_agent_accept_request(agent->core_id, "SIP caller %s has requested CC via SUBSCRIBE",
23228          agent->device_name);
23229    p->subscribed = CALL_COMPLETION;
23230 
23231    /* We don't send a response here. That is done in the agent's ack callback or in the
23232     * agent destructor, should a failure occur before we have responded
23233     */
23234    ao2_ref(agent, -1);
23235    return 0;
23236 }
23237 
23238 /*! \brief  Handle incoming SUBSCRIBE request */
23239 static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, int seqno, const char *e)
23240 {
23241    int gotdest = 0;
23242    int res = 0;
23243    int firststate = AST_EXTENSION_REMOVED;
23244    struct sip_peer *authpeer = NULL;
23245    const char *eventheader = get_header(req, "Event");   /* Get Event package name */
23246    int resubscribe = (p->subscribed != NONE) && !req->ignore;
23247    char *temp, *event;
23248 
23249    if (p->initreq.headers) {  
23250       /* We already have a dialog */
23251       if (p->initreq.method != SIP_SUBSCRIBE) {
23252          /* This is a SUBSCRIBE within another SIP dialog, which we do not support */
23253          /* For transfers, this could happen, but since we haven't seen it happening, let us just refuse this */
23254          transmit_response(p, "403 Forbidden (within dialog)", req);
23255          /* Do not destroy session, since we will break the call if we do */
23256          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);
23257          return 0;
23258       } else if (req->debug) {
23259          if (resubscribe)
23260             ast_debug(1, "Got a re-subscribe on existing subscription %s\n", p->callid);
23261          else
23262             ast_debug(1, "Got a new subscription %s (possibly with auth) or retransmission\n", p->callid);
23263       }
23264    }
23265 
23266    /* Check if we have a global disallow setting on subscriptions.
23267       if so, we don't have to check peer settings after auth, which saves a lot of processing
23268    */
23269    if (!sip_cfg.allowsubscribe) {
23270       transmit_response(p, "403 Forbidden (policy)", req);
23271       pvt_set_needdestroy(p, "forbidden");
23272       return 0;
23273    }
23274 
23275    if (!req->ignore && !resubscribe) { /* Set up dialog, new subscription */
23276       const char *to = get_header(req, "To");
23277       char totag[128];
23278       set_pvt_allowed_methods(p, req);
23279 
23280       /* Check to see if a tag was provided, if so this is actually a resubscription of a dialog we no longer know about */
23281       if (!ast_strlen_zero(to) && gettag(req, "To", totag, sizeof(totag))) {
23282          if (req->debug)
23283             ast_verbose("Received resubscription for a dialog we no longer know about. Telling remote side to subscribe again.\n");
23284          transmit_response(p, "481 Subscription does not exist", req);
23285          pvt_set_needdestroy(p, "subscription does not exist");
23286          return 0;
23287       }
23288 
23289       /* Use this as the basis */
23290       if (req->debug)
23291          ast_verbose("Creating new subscription\n");
23292 
23293       copy_request(&p->initreq, req);
23294       if (sipdebug)
23295          ast_debug(4, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
23296       check_via(p, req);
23297       build_route(p, req, 0);
23298    } else if (req->debug && req->ignore)
23299       ast_verbose("Ignoring this SUBSCRIBE request\n");
23300 
23301    /* Find parameters to Event: header value and remove them for now */
23302    if (ast_strlen_zero(eventheader)) {
23303       transmit_response(p, "489 Bad Event", req);
23304       ast_debug(2, "Received SIP subscribe for unknown event package: <none>\n");
23305       pvt_set_needdestroy(p, "unknown event package in subscribe");
23306       return 0;
23307    }
23308 
23309    if ( (strchr(eventheader, ';'))) {
23310       event = ast_strdupa(eventheader);   /* Since eventheader is a const, we can't change it */
23311       temp = strchr(event, ';');       
23312       *temp = '\0';           /* Remove any options for now */
23313                      /* We might need to use them later :-) */
23314    } else
23315       event = (char *) eventheader;    /* XXX is this legal ? */
23316 
23317    /* Handle authentication if we're new and not a retransmission. We can't just
23318     * use if !req->ignore, because then we'll end up sending
23319     * a 200 OK if someone retransmits without sending auth */
23320    if (p->subscribed == NONE || resubscribe) {
23321       res = check_user_full(p, req, SIP_SUBSCRIBE, e, 0, addr, &authpeer);
23322 
23323       /* if an authentication response was sent, we are done here */
23324       if (res == AUTH_CHALLENGE_SENT)  /* authpeer = NULL here */
23325          return 0;
23326       if (res < 0) {
23327          if (res == AUTH_FAKE_AUTH) {
23328             ast_log(LOG_NOTICE, "Sending fake auth rejection for device %s\n", get_header(req, "From"));
23329             transmit_fake_auth_response(p, SIP_SUBSCRIBE, req, XMIT_UNRELIABLE);
23330          } else {
23331             ast_log(LOG_NOTICE, "Failed to authenticate device %s for SUBSCRIBE\n", get_header(req, "From"));
23332             transmit_response_reliable(p, "403 Forbidden", req);
23333          }
23334 
23335          pvt_set_needdestroy(p, "authentication failed");
23336          return 0;
23337       }
23338    }
23339 
23340    /* At this point, authpeer cannot be NULL. Remember we hold a reference,
23341     * so we must release it when done.
23342     * XXX must remove all the checks for authpeer == NULL.
23343     */
23344 
23345    /* Check if this device  is allowed to subscribe at all */
23346    if (!ast_test_flag(&p->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)) {
23347       transmit_response(p, "403 Forbidden (policy)", req);
23348       pvt_set_needdestroy(p, "subscription not allowed");
23349       if (authpeer)
23350          unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 1)");
23351       return 0;
23352    }
23353 
23354    if (strcmp(event, "message-summary") && strcmp(event, "call-completion")) {
23355       /* Get destination right away */
23356       gotdest = get_destination(p, NULL, NULL);
23357    }
23358 
23359    /* Get full contact header - this needs to be used as a request URI in NOTIFY's */
23360    parse_ok_contact(p, req);
23361 
23362    build_contact(p);
23363    if (gotdest != SIP_GET_DEST_EXTEN_FOUND) {
23364       if (gotdest == SIP_GET_DEST_INVALID_URI) {
23365          transmit_response(p, "416 Unsupported URI scheme", req);
23366       } else {
23367          transmit_response(p, "404 Not Found", req);
23368       }
23369       pvt_set_needdestroy(p, "subscription target not found");
23370       if (authpeer)
23371          unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 2)");
23372       return 0;
23373    }
23374 
23375    /* Initialize tag for new subscriptions */   
23376    if (ast_strlen_zero(p->tag))
23377       make_our_tag(p->tag, sizeof(p->tag));
23378 
23379    if (!strcmp(event, "presence") || !strcmp(event, "dialog")) { /* Presence, RFC 3842 */
23380       unsigned int pidf_xml;
23381       const char *accept;
23382       int start = 0;
23383       enum subscriptiontype subscribed = NONE;
23384       const char *unknown_acceptheader = NULL;
23385 
23386       if (authpeer)  /* We do not need the authpeer any more */
23387          unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 2)");
23388 
23389       /* Header from Xten Eye-beam Accept: multipart/related, application/rlmi+xml, application/pidf+xml, application/xpidf+xml */
23390       accept = __get_header(req, "Accept", &start);
23391       while ((subscribed == NONE) && !ast_strlen_zero(accept)) {
23392          pidf_xml = strstr(accept, "application/pidf+xml") ? 1 : 0;
23393 
23394          /* Older versions of Polycom firmware will claim pidf+xml, but really
23395           * they only support xpidf+xml. */
23396          if (pidf_xml && strstr(p->useragent, "Polycom")) {
23397             subscribed = XPIDF_XML;
23398          } else if (pidf_xml) {
23399             subscribed = PIDF_XML;         /* RFC 3863 format */
23400          } else if (strstr(accept, "application/dialog-info+xml")) {
23401             subscribed = DIALOG_INFO_XML;
23402             /* IETF draft: draft-ietf-sipping-dialog-package-05.txt */
23403          } else if (strstr(accept, "application/cpim-pidf+xml")) {
23404             subscribed = CPIM_PIDF_XML;    /* RFC 3863 format */
23405          } else if (strstr(accept, "application/xpidf+xml")) {
23406             subscribed = XPIDF_XML;        /* Early pre-RFC 3863 format with MSN additions (Microsoft Messenger) */
23407          } else {
23408             unknown_acceptheader = accept;
23409          }
23410          /* check to see if there is another Accept header present */
23411          accept = __get_header(req, "Accept", &start);
23412       }
23413 
23414       if (!start) {
23415          if (p->subscribed == NONE) { /* if the subscribed field is not already set, and there is no accept header... */
23416             transmit_response(p, "489 Bad Event", req);
23417             ast_log(LOG_WARNING,"SUBSCRIBE failure: no Accept header: pvt: "
23418                "stateid: %d, laststate: %d, dialogver: %d, subscribecont: "
23419                "'%s', subscribeuri: '%s'\n",
23420                p->stateid,
23421                p->laststate,
23422                p->dialogver,
23423                p->subscribecontext,
23424                p->subscribeuri);
23425             pvt_set_needdestroy(p, "no Accept header");
23426             return 0;
23427          }
23428          /* if p->subscribed is non-zero, then accept is not obligatory; according to rfc 3265 section 3.1.3, at least.
23429             so, we'll just let it ride, keeping the value from a previous subscription, and not abort the subscription */
23430       } else if (subscribed == NONE) {
23431          /* Can't find a format for events that we know about */
23432          char mybuf[200];
23433          if (!ast_strlen_zero(unknown_acceptheader)) {
23434             snprintf(mybuf, sizeof(mybuf), "489 Bad Event (format %s)", unknown_acceptheader);
23435          } else {
23436             snprintf(mybuf, sizeof(mybuf), "489 Bad Event");
23437          }
23438          transmit_response(p, mybuf, req);
23439          ast_log(LOG_WARNING,"SUBSCRIBE failure: unrecognized format:"
23440             "'%s' pvt: subscribed: %d, stateid: %d, laststate: %d,"
23441             "dialogver: %d, subscribecont: '%s', subscribeuri: '%s'\n",
23442             unknown_acceptheader,
23443             (int)p->subscribed,
23444             p->stateid,
23445             p->laststate,
23446             p->dialogver,
23447             p->subscribecontext,
23448             p->subscribeuri);
23449          pvt_set_needdestroy(p, "unrecognized format");
23450          return 0;
23451       } else {
23452          p->subscribed = subscribed;
23453       }
23454    } else if (!strcmp(event, "message-summary")) {
23455       int start = 0;
23456       int found_supported = 0;
23457       const char *acceptheader;
23458 
23459       acceptheader = __get_header(req, "Accept", &start);
23460       while (!found_supported && !ast_strlen_zero(acceptheader)) {
23461          found_supported = strcmp(acceptheader, "application/simple-message-summary") ? 0 : 1;
23462          if (!found_supported && (option_debug > 2)) {
23463             ast_log(LOG_DEBUG, "Received SIP mailbox subscription for unknown format: %s\n", acceptheader);
23464          }
23465          acceptheader = __get_header(req, "Accept", &start);
23466       }
23467       if (start && !found_supported) {
23468          /* Format requested that we do not support */
23469          transmit_response(p, "406 Not Acceptable", req);
23470          ast_debug(2, "Received SIP mailbox subscription for unknown format: %s\n", acceptheader);
23471          pvt_set_needdestroy(p, "unknown format");
23472          if (authpeer)
23473             unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 3)");
23474          return 0;
23475       }
23476       /* Looks like they actually want a mailbox status
23477         This version of Asterisk supports mailbox subscriptions
23478         The subscribed URI needs to exist in the dial plan
23479         In most devices, this is configurable to the voicemailmain extension you use
23480       */
23481       if (!authpeer || AST_LIST_EMPTY(&authpeer->mailboxes)) {
23482          transmit_response(p, "404 Not found (no mailbox)", req);
23483          pvt_set_needdestroy(p, "received 404 response");
23484          ast_log(LOG_NOTICE, "Received SIP subscribe for peer without mailbox: %s\n", authpeer->name);
23485          if (authpeer)
23486             unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 4)");
23487          return 0;
23488       }
23489 
23490       p->subscribed = MWI_NOTIFICATION;
23491       if (ast_test_flag(&authpeer->flags[1], SIP_PAGE2_SUBSCRIBEMWIONLY)) {
23492          add_peer_mwi_subs(authpeer);
23493       }
23494       if (authpeer->mwipvt && authpeer->mwipvt != p) {   /* Destroy old PVT if this is a new one */
23495          /* We only allow one subscription per peer */
23496          dialog_unlink_all(authpeer->mwipvt, TRUE, TRUE);
23497          authpeer->mwipvt = dialog_unref(authpeer->mwipvt, "unref dialog authpeer->mwipvt");
23498          /* sip_destroy(authpeer->mwipvt); */
23499       }
23500       if (authpeer->mwipvt)
23501          dialog_unref(authpeer->mwipvt, "Unref previously stored mwipvt dialog pointer");
23502       authpeer->mwipvt = dialog_ref(p, "setting peers' mwipvt to p");      /* Link from peer to pvt UH- should this be dialog_ref()? */
23503       if (p->relatedpeer)
23504          unref_peer(p->relatedpeer, "Unref previously stored relatedpeer ptr");
23505       p->relatedpeer = ref_peer(authpeer, "setting dialog's relatedpeer pointer");  /* already refcounted...Link from pvt to peer UH- should this be dialog_ref()? */
23506       /* Do not release authpeer here */
23507    } else if (!strcmp(event, "call-completion")) {
23508       handle_cc_subscribe(p, req);
23509    } else { /* At this point, Asterisk does not understand the specified event */
23510       transmit_response(p, "489 Bad Event", req);
23511       ast_debug(2, "Received SIP subscribe for unknown event package: %s\n", event);
23512       pvt_set_needdestroy(p, "unknown event package");
23513       if (authpeer)
23514          unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 5)");
23515       return 0;
23516    }
23517 
23518    /* Add subscription for extension state from the PBX core */
23519    if (p->subscribed != MWI_NOTIFICATION  && p->subscribed != CALL_COMPLETION && !resubscribe) {
23520       if (p->stateid > -1) {
23521          ast_extension_state_del(p->stateid, cb_extensionstate);
23522          /* we need to dec the refcount, now that the extensionstate is removed */
23523          dialog_unref(p, "the extensionstate containing this dialog ptr was deleted");
23524       }
23525       p->stateid = ast_extension_state_add(p->context, p->exten, cb_extensionstate, dialog_ref(p,"copying dialog ptr into extension state struct"));
23526    }
23527 
23528    if (!req->ignore && p)
23529       p->lastinvite = seqno;
23530    if (p && !p->needdestroy) {
23531       p->expiry = atoi(get_header(req, "Expires"));
23532 
23533       /* check if the requested expiry-time is within the approved limits from sip.conf */
23534       if (p->expiry > max_expiry) {
23535          p->expiry = max_expiry;
23536       } else if (p->expiry < min_expiry && p->expiry > 0) {
23537          transmit_response_with_minexpires(p, "423 Interval too small", req);
23538          ast_log(LOG_WARNING, "Received subscription for extension \"%s\" context \"%s\" "
23539             "with Expire header less that 'minexpire' limit. Received \"Expire: %d\" min is %d\n",
23540             p->exten, p->context, p->expiry, min_expiry);
23541          p->expiry = min_expiry;
23542          pvt_set_needdestroy(p, "Expires is less that the min expires allowed. ");
23543          return 0;
23544       }
23545 
23546       if (sipdebug) {
23547          if (p->subscribed == MWI_NOTIFICATION && p->relatedpeer) {
23548             ast_debug(2, "Adding subscription for mailbox notification - peer %s\n", p->relatedpeer->name);
23549          } else if (p->subscribed == CALL_COMPLETION) {
23550             ast_debug(2, "Adding CC subscription for peer %s\n", p->username);
23551          } else {
23552             ast_debug(2, "Adding subscription for extension %s context %s for peer %s\n", p->exten, p->context, p->username);
23553          }
23554       }
23555       if (p->autokillid > -1 && sip_cancel_destroy(p))   /* Remove subscription expiry for renewals */
23556          ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
23557       if (p->expiry > 0)
23558          sip_scheddestroy(p, (p->expiry + 10) * 1000);   /* Set timer for destruction of call at expiration */
23559 
23560       if (p->subscribed == MWI_NOTIFICATION) {
23561          ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
23562          transmit_response(p, "200 OK", req);
23563          if (p->relatedpeer) {   /* Send first notification */
23564             ao2_lock(p->relatedpeer); /* was WRLOCK */
23565             sip_send_mwi_to_peer(p->relatedpeer, NULL, 0);
23566             ao2_unlock(p->relatedpeer);
23567          }
23568       } else if (p->subscribed != CALL_COMPLETION) {
23569          if ((firststate = ast_extension_state(NULL, p->context, p->exten)) < 0) {
23570 
23571             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));
23572             transmit_response(p, "404 Not found", req);
23573             pvt_set_needdestroy(p, "no extension for SUBSCRIBE");
23574             return 0;
23575          }
23576          ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
23577          transmit_response(p, "200 OK", req);
23578          transmit_state_notify(p, firststate, 1, FALSE); /* Send first notification */
23579          append_history(p, "Subscribestatus", "%s", ast_extension_state2str(firststate));
23580          /* hide the 'complete' exten/context in the refer_to field for later display */
23581          ast_string_field_build(p, subscribeuri, "%s@%s", p->exten, p->context);
23582          /* Deleted the slow iteration of all sip dialogs to find old subscribes from this peer for exten@context */
23583 
23584       }
23585       if (!p->expiry) {
23586          pvt_set_needdestroy(p, "forcing expiration");
23587       }
23588    }
23589    return 1;
23590 }
23591 
23592 /*! \brief Handle incoming REGISTER request */
23593 static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, const char *e)
23594 {
23595    enum check_auth_result res;
23596 
23597    /* If this is not the intial request, and the initial request isn't
23598     * a register, something screwy happened, so bail */
23599    if (p->initreq.headers && p->initreq.method != SIP_REGISTER) {
23600       ast_log(LOG_WARNING, "Ignoring spurious REGISTER with Call-ID: %s\n", p->callid);
23601       return -1;
23602    }
23603 
23604    /* Use this as the basis */
23605    copy_request(&p->initreq, req);
23606    if (sipdebug)
23607       ast_debug(4, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
23608    check_via(p, req);
23609    if ((res = register_verify(p, addr, req, e)) < 0) {
23610       const char *reason;
23611 
23612       switch (res) {
23613       case AUTH_SECRET_FAILED:
23614          reason = "Wrong password";
23615          break;
23616       case AUTH_USERNAME_MISMATCH:
23617          reason = "Username/auth name mismatch";
23618          break;
23619       case AUTH_NOT_FOUND:
23620          reason = "No matching peer found";
23621          break;
23622       case AUTH_UNKNOWN_DOMAIN:
23623          reason = "Not a local domain";
23624          break;
23625       case AUTH_PEER_NOT_DYNAMIC:
23626          reason = "Peer is not supposed to register";
23627          break;
23628       case AUTH_ACL_FAILED:
23629          reason = "Device does not match ACL";
23630          break;
23631       case AUTH_BAD_TRANSPORT:
23632          reason = "Device not configured to use this transport type";
23633          break;
23634       default:
23635          reason = "Unknown failure";
23636          break;
23637       }
23638       ast_log(LOG_NOTICE, "Registration from '%s' failed for '%s' - %s\n",
23639          get_header(req, "To"), ast_sockaddr_stringify(addr),
23640          reason);
23641       append_history(p, "RegRequest", "Failed : Account %s : %s", get_header(req, "To"), reason);
23642    } else {
23643       req->authenticated = 1;
23644       append_history(p, "RegRequest", "Succeeded : Account %s", get_header(req, "To"));
23645    }
23646 
23647    if (res < 1) {
23648       /* Destroy the session, but keep us around for just a bit in case they don't
23649          get our 200 OK */
23650       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
23651    }
23652    return res;
23653 }
23654 
23655 /*!
23656  * \brief Handle incoming SIP requests (methods)
23657  * \note
23658  * This is where all incoming requests go first.
23659  * \note
23660  * called with p and p->owner locked
23661  */
23662 static int handle_incoming(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, int *recount, int *nounlock)
23663 {
23664    /* Called with p->lock held, as well as p->owner->lock if appropriate, keeping things
23665       relatively static */
23666    const char *cmd;
23667    const char *cseq;
23668    const char *useragent;
23669    const char *via;
23670    const char *callid;
23671    int via_pos = 0;
23672    int seqno;
23673    int len;
23674    int respid;
23675    int res = 0;
23676    int debug = sip_debug_test_pvt(p);
23677    const char *e;
23678    int error = 0;
23679    int oldmethod = p->method;
23680    int acked = 0;
23681 
23682    /* RFC 3261 - 8.1.1 A valid SIP request must contain To, From, CSeq, Call-ID and Via.
23683     * 8.2.6.2 Response must have To, From, Call-ID CSeq, and Via related to the request,
23684     * so we can check to make sure these fields exist for all requests and responses */
23685    cseq = get_header(req, "Cseq");
23686    cmd = REQ_OFFSET_TO_STR(req, header[0]);
23687    /* Save the via_pos so we can check later that responses only have 1 Via header */
23688    via = __get_header(req, "Via", &via_pos);
23689    /* This must exist already because we've called find_call by now */
23690    callid = get_header(req, "Call-ID");
23691 
23692    /* Must have Cseq */
23693    if (ast_strlen_zero(cmd) || ast_strlen_zero(cseq) || ast_strlen_zero(via)) {
23694       ast_log(LOG_ERROR, "Dropping this SIP message with Call-ID '%s', it's incomplete.\n", callid);
23695       error = 1;
23696    }
23697    if (!error && sscanf(cseq, "%30d%n", &seqno, &len) != 1) {
23698       ast_log(LOG_ERROR, "No seqno in '%s'. Dropping incomplete message.\n", cmd);
23699       error = 1;
23700    }
23701    if (error) {
23702       if (!p->initreq.headers) { /* New call */
23703          pvt_set_needdestroy(p, "no headers");
23704       }
23705       return -1;
23706    }
23707    /* Get the command XXX */
23708 
23709    cmd = REQ_OFFSET_TO_STR(req, rlPart1);
23710    e = ast_skip_blanks(REQ_OFFSET_TO_STR(req, rlPart2));
23711 
23712    /* Save useragent of the client */
23713    useragent = get_header(req, "User-Agent");
23714    if (!ast_strlen_zero(useragent))
23715       ast_string_field_set(p, useragent, useragent);
23716 
23717    /* Find out SIP method for incoming request */
23718    if (req->method == SIP_RESPONSE) {  /* Response to our request */
23719       /* ignore means "don't do anything with it" but still have to
23720        * respond appropriately.
23721        * But in this case this is a response already, so we really
23722        * have nothing to do with this message, and even setting the
23723        * ignore flag is pointless.
23724        */
23725       if (ast_strlen_zero(e)) {
23726          return 0;
23727       }
23728       if (sscanf(e, "%30d %n", &respid, &len) != 1) {
23729          ast_log(LOG_WARNING, "Invalid response: '%s'\n", e);
23730          return 0;
23731       }
23732       if (respid <= 0) {
23733          ast_log(LOG_WARNING, "Invalid SIP response code: '%d'\n", respid);
23734          return 0;
23735       }
23736       /* RFC 3261 - 8.1.3.3 If more than one Via header field value is present in a reponse
23737        * the UAC SHOULD discard the message. This is not perfect, as it will not catch multiple
23738        * headers joined with a comma. Fixing that would pretty much involve writing a new parser */
23739       if (!ast_strlen_zero(__get_header(req, "via", &via_pos))) {
23740          ast_log(LOG_WARNING, "Misrouted SIP response '%s' with Call-ID '%s', too many vias\n", e, callid);
23741          return 0;
23742       }
23743       if (p->ocseq && (p->ocseq < seqno)) {
23744          ast_debug(1, "Ignoring out of order response %d (expecting %d)\n", seqno, p->ocseq);
23745          return -1;
23746       } else {
23747          char causevar[256], causeval[256];
23748 
23749          if ((respid == 200) || ((respid >= 300) && (respid <= 399))) {
23750             extract_uri(p, req);
23751          }
23752 
23753          handle_response(p, respid, e + len, req, seqno);
23754 
23755          if (p->owner) {
23756             struct ast_channel *owner = p->owner;
23757 
23758             snprintf(causevar, sizeof(causevar), "MASTER_CHANNEL(HASH(SIP_CAUSE,%s))", owner->name);
23759             snprintf(causeval, sizeof(causeval), "SIP %s", REQ_OFFSET_TO_STR(req, rlPart2));
23760 
23761             ast_channel_ref(owner);
23762             sip_pvt_unlock(p);
23763             ast_channel_unlock(owner);
23764             *nounlock = 1;
23765             pbx_builtin_setvar_helper(owner, causevar, causeval);
23766             ast_channel_unref(owner);
23767             sip_pvt_lock(p);
23768          }
23769       }
23770       return 0;
23771    }
23772 
23773    /* New SIP request coming in
23774       (could be new request in existing SIP dialog as well...)
23775     */         
23776    
23777    p->method = req->method;   /* Find out which SIP method they are using */
23778    ast_debug(4, "**** Received %s (%d) - Command in SIP %s\n", sip_methods[p->method].text, sip_methods[p->method].id, cmd);
23779 
23780    if (p->icseq && (p->icseq > seqno) ) {
23781       if (p->pendinginvite && seqno == p->pendinginvite && (req->method == SIP_ACK || req->method == SIP_CANCEL)) {
23782          ast_debug(2, "Got CANCEL or ACK on INVITE with transactions in between.\n");
23783       } else {
23784          ast_debug(1, "Ignoring too old SIP packet packet %d (expecting >= %d)\n", seqno, p->icseq);
23785          if (req->method == SIP_INVITE) {
23786             unsigned int ran = (ast_random() % 10) + 1;
23787             char seconds[4];
23788             snprintf(seconds, sizeof(seconds), "%u", ran);
23789             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 */
23790          } else if (req->method != SIP_ACK) {
23791             transmit_response(p, "500 Server error", req);  /* We must respond according to RFC 3261 sec 12.2 */
23792          }
23793          return -1;
23794       }
23795    } else if (p->icseq &&
23796          p->icseq == seqno &&
23797          req->method != SIP_ACK &&
23798          (p->method != SIP_CANCEL || p->alreadygone)) {
23799       /* ignore means "don't do anything with it" but still have to
23800          respond appropriately.  We do this if we receive a repeat of
23801          the last sequence number  */
23802       req->ignore = 1;
23803       ast_debug(3, "Ignoring SIP message because of retransmit (%s Seqno %d, ours %d)\n", sip_methods[p->method].text, p->icseq, seqno);
23804    }
23805 
23806    /* RFC 3261 section 9. "CANCEL has no effect on a request to which a UAS has
23807     * already given a final response." */
23808    if (!p->pendinginvite && (req->method == SIP_CANCEL)) {
23809       transmit_response(p, "481 Call/Transaction Does Not Exist", req);
23810       return res;
23811    }
23812 
23813    if (seqno >= p->icseq)
23814       /* Next should follow monotonically (but not necessarily
23815          incrementally -- thanks again to the genius authors of SIP --
23816          increasing */
23817       p->icseq = seqno;
23818 
23819    /* Find their tag if we haven't got it */
23820    if (ast_strlen_zero(p->theirtag)) {
23821       char tag[128];
23822 
23823       gettag(req, "From", tag, sizeof(tag));
23824       ast_string_field_set(p, theirtag, tag);
23825    }
23826    snprintf(p->lastmsg, sizeof(p->lastmsg), "Rx: %s", cmd);
23827 
23828    if (sip_cfg.pedanticsipchecking) {
23829       /* If this is a request packet without a from tag, it's not
23830          correct according to RFC 3261  */
23831       /* Check if this a new request in a new dialog with a totag already attached to it,
23832          RFC 3261 - section 12.2 - and we don't want to mess with recovery  */
23833       if (!p->initreq.headers && req->has_to_tag) {
23834          /* If this is a first request and it got a to-tag, it is not for us */
23835          if (!req->ignore && req->method == SIP_INVITE) {
23836             transmit_response_reliable(p, "481 Call/Transaction Does Not Exist", req);
23837             /* Will cease to exist after ACK */
23838          } else if (req->method != SIP_ACK) {
23839             transmit_response(p, "481 Call/Transaction Does Not Exist", req);
23840             sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
23841          } else {
23842             ast_debug(1, "Got ACK for unknown dialog... strange.\n");
23843          }
23844          return res;
23845       }
23846    }
23847 
23848    if (!e && (p->method == SIP_INVITE || p->method == SIP_SUBSCRIBE || p->method == SIP_REGISTER || p->method == SIP_NOTIFY || p->method == SIP_PUBLISH)) {
23849       transmit_response(p, "400 Bad request", req);
23850       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
23851       return -1;
23852    }
23853 
23854    /* Handle various incoming SIP methods in requests */
23855    switch (p->method) {
23856    case SIP_OPTIONS:
23857       res = handle_request_options(p, req, addr, e);
23858       break;
23859    case SIP_INVITE:
23860       res = handle_request_invite(p, req, debug, seqno, addr, recount, e, nounlock);
23861       break;
23862    case SIP_REFER:
23863       res = handle_request_refer(p, req, debug, seqno, nounlock);
23864       break;
23865    case SIP_CANCEL:
23866       res = handle_request_cancel(p, req);
23867       break;
23868    case SIP_BYE:
23869       res = handle_request_bye(p, req);
23870       break;
23871    case SIP_MESSAGE:
23872       res = handle_request_message(p, req);
23873       break;
23874    case SIP_PUBLISH:
23875       res = handle_request_publish(p, req, addr, seqno, e);
23876       break;
23877    case SIP_SUBSCRIBE:
23878       res = handle_request_subscribe(p, req, addr, seqno, e);
23879       break;
23880    case SIP_REGISTER:
23881       res = handle_request_register(p, req, addr, e);
23882       break;
23883    case SIP_INFO:
23884       if (req->debug)
23885          ast_verbose("Receiving INFO!\n");
23886       if (!req->ignore)
23887          handle_request_info(p, req);
23888       else  /* if ignoring, transmit response */
23889          transmit_response(p, "200 OK", req);
23890       break;
23891    case SIP_NOTIFY:
23892       res = handle_request_notify(p, req, addr, seqno, e);
23893       break;
23894    case SIP_UPDATE:
23895       res = handle_request_update(p, req);
23896       break;
23897    case SIP_ACK:
23898       /* Make sure we don't ignore this */
23899       if (seqno == p->pendinginvite) {
23900          p->invitestate = INV_TERMINATED;
23901          p->pendinginvite = 0;
23902          acked = __sip_ack(p, seqno, 1 /* response */, 0);
23903          if (find_sdp(req)) {
23904             if (process_sdp(p, req, SDP_T38_NONE))
23905                return -1;
23906          }
23907          check_pendings(p);
23908       } else if (p->glareinvite == seqno) {
23909          /* handle ack for the 491 pending sent for glareinvite */
23910          p->glareinvite = 0;
23911          acked = __sip_ack(p, seqno, 1, 0);
23912       }
23913       if (!acked) {
23914          /* Got an ACK that did not match anything. Ignore
23915           * silently and restore previous method */
23916          p->method = oldmethod;
23917       }
23918       if (!p->lastinvite && ast_strlen_zero(p->randdata)) {
23919          pvt_set_needdestroy(p, "unmatched ACK");
23920       }
23921       break;
23922    default:
23923       transmit_response_with_allow(p, "501 Method Not Implemented", req, 0);
23924       ast_log(LOG_NOTICE, "Unknown SIP command '%s' from '%s'\n",
23925          cmd, ast_sockaddr_stringify(&p->sa));
23926       /* If this is some new method, and we don't have a call, destroy it now */
23927       if (!p->initreq.headers) {
23928          pvt_set_needdestroy(p, "unimplemented method");
23929       }
23930       break;
23931    }
23932    return res;
23933 }
23934 
23935 static void process_request_queue(struct sip_pvt *p, int *recount, int *nounlock)
23936 {
23937    struct sip_request *req;
23938 
23939    while ((req = AST_LIST_REMOVE_HEAD(&p->request_queue, next))) {
23940       if (handle_incoming(p, req, &p->recv, recount, nounlock) == -1) {
23941          /* Request failed */
23942          ast_debug(1, "SIP message could not be handled, bad request: %-70.70s\n", p->callid[0] ? p->callid : "<no callid>");
23943       }
23944       ast_free(req);
23945    }
23946 }
23947 
23948 static int scheduler_process_request_queue(const void *data)
23949 {
23950    struct sip_pvt *p = (struct sip_pvt *) data;
23951    int recount = 0;
23952    int nounlock = 0;
23953    int lockretry;
23954 
23955    for (lockretry = 10; lockretry > 0; lockretry--) {
23956       sip_pvt_lock(p);
23957 
23958       /* lock the owner if it has one -- we may need it */
23959       /* because this is deadlock-prone, we need to try and unlock if failed */
23960       if (!p->owner || !ast_channel_trylock(p->owner)) {
23961          break;   /* locking succeeded */
23962       }
23963 
23964       if (lockretry != 1) {
23965          sip_pvt_unlock(p);
23966          /* Sleep for a very short amount of time */
23967          usleep(1);
23968       }
23969    }
23970 
23971    if (!lockretry) {
23972       int retry = !AST_LIST_EMPTY(&p->request_queue);
23973 
23974       /* we couldn't get the owner lock, which is needed to process
23975          the queued requests, so return a non-zero value, which will
23976          cause the scheduler to run this request again later if there
23977          still requests to be processed
23978       */
23979       sip_pvt_unlock(p);
23980       if (!retry) {
23981          dialog_unref(p, "The ref to a dialog passed to this sched callback is going out of scope; unref it.");
23982       }
23983       return retry;
23984    };
23985 
23986    process_request_queue(p, &recount, &nounlock);
23987    p->request_queue_sched_id = -1;
23988 
23989    if (p->owner && !nounlock) {
23990       ast_channel_unlock(p->owner);
23991    }
23992    sip_pvt_unlock(p);
23993 
23994    if (recount) {
23995       ast_update_use_count();
23996    }
23997 
23998    dialog_unref(p, "The ref to a dialog passed to this sched callback is going out of scope; unref it.");
23999 
24000    return 0;
24001 }
24002 
24003 static int queue_request(struct sip_pvt *p, const struct sip_request *req)
24004 {
24005    struct sip_request *newreq;
24006 
24007    if (!(newreq = ast_calloc(1, sizeof(*newreq)))) {
24008       return -1;
24009    }
24010 
24011    copy_request(newreq, req);
24012    AST_LIST_INSERT_TAIL(&p->request_queue, newreq, next);
24013    if (p->request_queue_sched_id == -1) {
24014       if ((p->request_queue_sched_id = ast_sched_add(sched, 10, scheduler_process_request_queue, dialog_ref(p, "Increment refcount to pass dialog pointer to sched callback"))) == -1) {
24015          dialog_unref(p, "Decrement refcount due to sched_add failure");
24016       }
24017    }
24018 
24019    return 0;
24020 }
24021 
24022 /*! \brief Read data from SIP UDP socket
24023 \note sipsock_read locks the owner channel while we are processing the SIP message
24024 \return 1 on error, 0 on success
24025 \note Successful messages is connected to SIP call and forwarded to handle_incoming()
24026 */
24027 static int sipsock_read(int *id, int fd, short events, void *ignore)
24028 {
24029    struct sip_request req;
24030    struct ast_sockaddr addr;
24031    int res;
24032    static char readbuf[65535];
24033 
24034    memset(&req, 0, sizeof(req));
24035    res = ast_recvfrom(fd, readbuf, sizeof(readbuf) - 1, 0, &addr);
24036    if (res < 0) {
24037 #if !defined(__FreeBSD__)
24038       if (errno == EAGAIN)
24039          ast_log(LOG_NOTICE, "SIP: Received packet with bad UDP checksum\n");
24040       else
24041 #endif
24042       if (errno != ECONNREFUSED)
24043          ast_log(LOG_WARNING, "Recv error: %s\n", strerror(errno));
24044       return 1;
24045    }
24046 
24047    readbuf[res] = '\0';
24048 
24049    if (!(req.data = ast_str_create(SIP_MIN_PACKET))) {
24050       return 1;
24051    }
24052 
24053    if (ast_str_set(&req.data, 0, "%s", readbuf) == AST_DYNSTR_BUILD_FAILED) {
24054       return -1;
24055    }
24056 
24057    req.len = res;
24058    req.socket.fd = sipsock;
24059    set_socket_transport(&req.socket, SIP_TRANSPORT_UDP);
24060    req.socket.tcptls_session  = NULL;
24061    req.socket.port = htons(ast_sockaddr_port(&bindaddr));
24062 
24063    handle_request_do(&req, &addr);
24064    deinit_req(&req);
24065 
24066    return 1;
24067 }
24068 
24069 /*! \brief Handle incoming SIP message - request or response
24070 
24071    This is used for all transports (udp, tcp and tcp/tls)
24072 */
24073 static int handle_request_do(struct sip_request *req, struct ast_sockaddr *addr)
24074 {
24075    struct sip_pvt *p;
24076    int recount = 0;
24077    int nounlock = 0;
24078    int lockretry;
24079 
24080    if (sip_debug_test_addr(addr))   /* Set the debug flag early on packet level */
24081       req->debug = 1;
24082    if (sip_cfg.pedanticsipchecking)
24083       req->len = lws2sws(req->data->str, req->len);   /* Fix multiline headers */
24084    if (req->debug) {
24085       ast_verbose("\n<--- SIP read from %s:%s --->\n%s\n<------------->\n",
24086          get_transport(req->socket.type), ast_sockaddr_stringify(addr), req->data->str);
24087    }
24088 
24089    if (parse_request(req) == -1) { /* Bad packet, can't parse */
24090       ast_str_reset(req->data); /* nulling this out is NOT a good idea here. */
24091       return 1;
24092    }
24093    req->method = find_sip_method(REQ_OFFSET_TO_STR(req, rlPart1));
24094 
24095    if (req->debug)
24096       ast_verbose("--- (%d headers %d lines)%s ---\n", req->headers, req->lines, (req->headers + req->lines == 0) ? " Nat keepalive" : "");
24097 
24098    if (req->headers < 2) { /* Must have at least two headers */
24099       ast_str_reset(req->data); /* nulling this out is NOT a good idea here. */
24100       return 1;
24101    }
24102 
24103    /* Process request, with netlock held, and with usual deadlock avoidance */
24104    for (lockretry = 10; lockretry > 0; lockretry--) {
24105       ast_mutex_lock(&netlock);
24106 
24107       /* Find the active SIP dialog or create a new one */
24108       p = find_call(req, addr, req->method); /* returns p locked */
24109       if (p == NULL) {
24110          ast_debug(1, "Invalid SIP message - rejected , no callid, len %d\n", req->len);
24111          ast_mutex_unlock(&netlock);
24112          return 1;
24113       }
24114 
24115       copy_socket_data(&p->socket, &req->socket);
24116 
24117       /* Go ahead and lock the owner if it has one -- we may need it */
24118       /* becaues this is deadlock-prone, we need to try and unlock if failed */
24119       if (!p->owner || !ast_channel_trylock(p->owner))
24120          break;   /* locking succeeded */
24121 
24122       if (lockretry != 1) {
24123          sip_pvt_unlock(p);
24124          ao2_t_ref(p, -1, "release p (from find_call) inside lockretry loop"); /* we'll look for it again, but p is dead now */
24125          ast_mutex_unlock(&netlock);
24126          /* Sleep for a very short amount of time */
24127          usleep(1);
24128       }
24129    }
24130    ast_sockaddr_copy(&p->recv, addr);
24131 
24132    /* if we have an owner, then this request has been authenticated */
24133    if (p->owner) {
24134       req->authenticated = 1;
24135    }
24136 
24137    if (p->do_history) /* This is a request or response, note what it was for */
24138       append_history(p, "Rx", "%s / %s / %s", req->data->str, get_header(req, "CSeq"), REQ_OFFSET_TO_STR(req, rlPart2));
24139 
24140    if (!lockretry) {
24141       if (!queue_request(p, req)) {
24142          /* the request has been queued for later handling */
24143          sip_pvt_unlock(p);
24144          ao2_t_ref(p, -1, "release p (from find_call) after queueing request");
24145          ast_mutex_unlock(&netlock);
24146          return 1;
24147       }
24148 
24149       if (p->owner)
24150          ast_log(LOG_ERROR, "Channel lock for %s could not be obtained, and request was unable to be queued.\n", S_OR(p->owner->name, "- no channel name ??? - "));
24151       ast_log(LOG_ERROR, "SIP transaction failed: %s \n", p->callid);
24152       if (req->method != SIP_ACK)
24153          transmit_response(p, "503 Server error", req);  /* We must respond according to RFC 3261 sec 12.2 */
24154       /* XXX We could add retry-after to make sure they come back */
24155       append_history(p, "LockFail", "Owner lock failed, transaction failed.");
24156       sip_pvt_unlock(p);
24157       ao2_t_ref(p, -1, "release p (from find_call) at end of lockretry"); /* p is gone after the return */
24158       ast_mutex_unlock(&netlock);
24159       return 1;
24160    }
24161 
24162    /* if there are queued requests on this sip_pvt, process them first, so that everything is
24163       handled in order
24164    */
24165    if (!AST_LIST_EMPTY(&p->request_queue)) {
24166       AST_SCHED_DEL_UNREF(sched, p->request_queue_sched_id, dialog_unref(p, "when you delete the request_queue_sched_id sched, you should dec the refcount for the stored dialog ptr"));
24167       process_request_queue(p, &recount, &nounlock);
24168    }
24169 
24170    if (handle_incoming(p, req, addr, &recount, &nounlock) == -1) {
24171       /* Request failed */
24172       ast_debug(1, "SIP message could not be handled, bad request: %-70.70s\n", p->callid[0] ? p->callid : "<no callid>");
24173    }
24174       
24175    if (recount)
24176       ast_update_use_count();
24177 
24178    if (p->owner && !nounlock)
24179       ast_channel_unlock(p->owner);
24180    sip_pvt_unlock(p);
24181    ao2_t_ref(p, -1, "throw away dialog ptr from find_call at end of routine"); /* p is gone after the return */
24182    ast_mutex_unlock(&netlock);
24183    return 1;
24184 }
24185 
24186 /*! \brief Returns the port to use for this socket
24187  *
24188  * \param type The type of transport used
24189  * \param port Port we are checking to see if it's the standard port.
24190  * \note port is expected in host byte order
24191  */
24192 static int sip_standard_port(enum sip_transport type, int port)
24193 {
24194    if (type & SIP_TRANSPORT_TLS)
24195       return port == STANDARD_TLS_PORT;
24196    else
24197       return port == STANDARD_SIP_PORT;
24198 }
24199 
24200 static int threadinfo_locate_cb(void *obj, void *arg, int flags)
24201 {
24202    struct sip_threadinfo *th = obj;
24203    struct ast_sockaddr *s = arg;
24204 
24205    if (!ast_sockaddr_cmp(s, &th->tcptls_session->remote_address)) {
24206       return CMP_MATCH | CMP_STOP;
24207    }
24208 
24209    return 0;
24210 }
24211 
24212 /*!
24213  * \brief Find thread for TCP/TLS session (based on IP/Port
24214  *
24215  * \note This function returns an astobj2 reference
24216  */
24217 static struct ast_tcptls_session_instance *sip_tcp_locate(struct ast_sockaddr *s)
24218 {
24219    struct sip_threadinfo *th;
24220    struct ast_tcptls_session_instance *tcptls_instance = NULL;
24221 
24222    if ((th = ao2_callback(threadt, 0, threadinfo_locate_cb, s))) {
24223       tcptls_instance = (ao2_ref(th->tcptls_session, +1), th->tcptls_session);
24224       ao2_t_ref(th, -1, "decrement ref from callback");
24225    }
24226 
24227    return tcptls_instance;
24228 }
24229 
24230 /*!
24231  * \brief Helper for dns resolution to filter by address family.
24232  *
24233  * \note return 0 if addr is [::] else it returns addr's family.
24234  */
24235 int get_address_family_filter(const struct ast_sockaddr *addr)
24236 {
24237    if (ast_sockaddr_is_ipv6(addr) && ast_sockaddr_is_any(addr)) {
24238       return 0;
24239    }
24240 
24241    return addr->ss.ss_family;
24242 }
24243 
24244 /*! \todo Get socket for dialog, prepare if needed, and return file handle  */
24245 static int sip_prepare_socket(struct sip_pvt *p)
24246 {
24247    struct sip_socket *s = &p->socket;
24248    static const char name[] = "SIP socket";
24249    struct sip_threadinfo *th = NULL;
24250    struct ast_tcptls_session_instance *tcptls_session;
24251    struct ast_tcptls_session_args *ca;
24252    struct ast_sockaddr sa_tmp;
24253 
24254    /* check to see if a socket is already active */
24255    if ((s->fd != -1) && (s->type == SIP_TRANSPORT_UDP)) {
24256       return s->fd;
24257    }
24258    if ((s->type & (SIP_TRANSPORT_TCP | SIP_TRANSPORT_TLS)) &&
24259          (s->tcptls_session) &&
24260          (s->tcptls_session->fd != -1)) {
24261       return s->tcptls_session->fd;
24262    }
24263 
24264    /*! \todo Check this... This might be wrong, depending on the proxy configuration
24265       If proxy is in "force" mode its correct.
24266     */
24267    if (p->outboundproxy && p->outboundproxy->transport) {
24268       s->type = p->outboundproxy->transport;
24269    }
24270 
24271    if (s->type == SIP_TRANSPORT_UDP) {
24272       s->fd = sipsock;
24273       return s->fd;
24274    }
24275 
24276    /* At this point we are dealing with a TCP/TLS connection
24277     * 1. We need to check to see if a connectin thread exists
24278     *    for this address, if so use that.
24279     * 2. If a thread does not exist for this address, but the tcptls_session
24280     *    exists on the socket, the connection was closed.
24281     * 3. If no tcptls_session thread exists for the address, and no tcptls_session
24282     *    already exists on the socket, create a new one and launch a new thread.
24283     */
24284 
24285    /* 1.  check for existing threads */
24286    ast_sockaddr_copy(&sa_tmp, sip_real_dst(p));
24287    if ((tcptls_session = sip_tcp_locate(&sa_tmp))) {
24288       s->fd = tcptls_session->fd;
24289       if (s->tcptls_session) {
24290          ao2_ref(s->tcptls_session, -1);
24291          s->tcptls_session = NULL;
24292       }
24293       s->tcptls_session = tcptls_session;
24294       return s->fd;
24295    /* 2.  Thread not found, if tcptls_session already exists, it once had a thread and is now terminated */
24296    } else if (s->tcptls_session) {
24297       return s->fd; /* XXX whether reconnection is ever necessary here needs to be investigated further */
24298    }
24299 
24300    /* 3.  Create a new TCP/TLS client connection */
24301    /* create new session arguments for the client connection */
24302    if (!(ca = ao2_alloc(sizeof(*ca), sip_tcptls_client_args_destructor)) ||
24303       !(ca->name = ast_strdup(name))) {
24304       goto create_tcptls_session_fail;
24305    }
24306    ca->accept_fd = -1;
24307    ast_sockaddr_copy(&ca->remote_address,sip_real_dst(p));
24308    /* if type is TLS, we need to create a tls cfg for this session arg */
24309    if (s->type == SIP_TRANSPORT_TLS) {
24310       if (!(ca->tls_cfg = ast_calloc(1, sizeof(*ca->tls_cfg)))) {
24311          goto create_tcptls_session_fail;
24312       }
24313       memcpy(ca->tls_cfg, &default_tls_cfg, sizeof(*ca->tls_cfg));
24314 
24315       if (!(ca->tls_cfg->certfile = ast_strdup(default_tls_cfg.certfile)) ||
24316          !(ca->tls_cfg->pvtfile = ast_strdup(default_tls_cfg.pvtfile)) ||
24317          !(ca->tls_cfg->cipher = ast_strdup(default_tls_cfg.cipher)) ||
24318          !(ca->tls_cfg->cafile = ast_strdup(default_tls_cfg.cafile)) ||
24319          !(ca->tls_cfg->capath = ast_strdup(default_tls_cfg.capath))) {
24320 
24321          goto create_tcptls_session_fail;
24322       }
24323 
24324       /* this host is used as the common name in ssl/tls */
24325       if (!ast_strlen_zero(p->tohost)) {
24326          ast_copy_string(ca->hostname, p->tohost, sizeof(ca->hostname));
24327       }
24328    }
24329 
24330    /* Create a client connection for address, this does not start the connection, just sets it up. */
24331    if (!(s->tcptls_session = ast_tcptls_client_create(ca))) {
24332       goto create_tcptls_session_fail;
24333    }
24334 
24335    s->fd = s->tcptls_session->fd;
24336 
24337    /* client connections need to have the sip_threadinfo object created before
24338     * the thread is detached.  This ensures the alert_pipe is up before it will
24339     * be used.  Note that this function links the new threadinfo object into the
24340     * threadt container. */
24341    if (!(th = sip_threadinfo_create(s->tcptls_session, s->type))) {
24342       goto create_tcptls_session_fail;
24343    }
24344 
24345    /* Give the new thread a reference to the tcptls_session */
24346    ao2_ref(s->tcptls_session, +1);
24347 
24348    if (ast_pthread_create_background(&ca->master, NULL, sip_tcp_worker_fn, s->tcptls_session)) {
24349       ast_debug(1, "Unable to launch '%s'.", ca->name);
24350       ao2_ref(s->tcptls_session, -1); /* take away the thread ref we just gave it */
24351       goto create_tcptls_session_fail;
24352    }
24353 
24354    return s->fd;
24355 
24356 create_tcptls_session_fail:
24357    if (ca) {
24358       ao2_t_ref(ca, -1, "failed to create client, getting rid of client tcptls_session arguments");
24359    }
24360    if (s->tcptls_session) {
24361       close(tcptls_session->fd);
24362       s->fd = tcptls_session->fd = -1;
24363       ao2_ref(s->tcptls_session, -1);
24364       s->tcptls_session = NULL;
24365    }
24366    if (th) {
24367       ao2_t_unlink(threadt, th, "Removing tcptls thread info object, thread failed to open");
24368    }
24369 
24370    return -1;
24371 }
24372 
24373 /*!
24374  * \brief Get cached MWI info
24375  * \retval 0 At least one message is waiting
24376  * \retval 1 no messages waiting
24377  */
24378 static int get_cached_mwi(struct sip_peer *peer, int *new, int *old)
24379 {
24380    struct sip_mailbox *mailbox;
24381 
24382    AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
24383       struct ast_event *event;
24384       event = ast_event_get_cached(AST_EVENT_MWI,
24385          AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, mailbox->mailbox,
24386          AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, S_OR(mailbox->context, "default"),
24387          AST_EVENT_IE_END);
24388       if (!event)
24389          continue;
24390       *new += ast_event_get_ie_uint(event, AST_EVENT_IE_NEWMSGS);
24391       *old += ast_event_get_ie_uint(event, AST_EVENT_IE_OLDMSGS);
24392       ast_event_destroy(event);
24393    }
24394 
24395    return (*new || *old) ? 0 : 1;
24396 }
24397 
24398 /*! \brief Send message waiting indication to alert peer that they've got voicemail */
24399 static int sip_send_mwi_to_peer(struct sip_peer *peer, const struct ast_event *event, int cache_only)
24400 {
24401    /* Called with peerl lock, but releases it */
24402    struct sip_pvt *p;
24403    int newmsgs = 0, oldmsgs = 0;
24404 
24405    if (ast_test_flag((&peer->flags[1]), SIP_PAGE2_SUBSCRIBEMWIONLY) && !peer->mwipvt)
24406       return 0;
24407 
24408    /* Do we have an IP address? If not, skip this peer */
24409    if (ast_sockaddr_isnull(&peer->addr) && ast_sockaddr_isnull(&peer->defaddr))
24410       return 0;
24411 
24412    if (event) {
24413       newmsgs = ast_event_get_ie_uint(event, AST_EVENT_IE_NEWMSGS);
24414       oldmsgs = ast_event_get_ie_uint(event, AST_EVENT_IE_OLDMSGS);
24415    } else if (!cache_only) { /* Fall back to manually checking the mailbox */
24416       struct ast_str *mailbox_str = ast_str_alloca(512);
24417       peer_mailboxes_to_str(&mailbox_str, peer);
24418       ast_app_inboxcount(mailbox_str->str, &newmsgs, &oldmsgs);
24419    } else {
24420       get_cached_mwi(peer, &newmsgs, &oldmsgs);
24421    }
24422    
24423    if (peer->mwipvt) {
24424       /* Base message on subscription */
24425       p = dialog_ref(peer->mwipvt, "sip_send_mwi_to_peer: Setting dialog ptr p from peer->mwipvt-- should this be done?");
24426    } else {
24427       /* Build temporary dialog for this message */
24428       if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY, NULL)))
24429          return -1;
24430       /* If we don't set the socket type to 0, then create_addr_from_peer will fail immediately if the peer
24431        * uses any transport other than UDP. We set the type to 0 here and then let create_addr_from_peer copy
24432        * the peer's socket information to the sip_pvt we just allocated
24433        */
24434       set_socket_transport(&p->socket, 0);
24435       if (create_addr_from_peer(p, peer)) {
24436          /* Maybe they're not registered, etc. */
24437          dialog_unlink_all(p, TRUE, TRUE);
24438          dialog_unref(p, "unref dialog p just created via sip_alloc");
24439          /* sip_destroy(p); */
24440          return 0;
24441       }
24442       /* Recalculate our side, and recalculate Call ID */
24443       ast_sip_ouraddrfor(&p->sa, &p->ourip, p);
24444       build_via(p);
24445       ao2_t_unlink(dialogs, p, "About to change the callid -- remove the old name");
24446       build_callid_pvt(p);
24447       if (!ast_strlen_zero(peer->mwi_from)) {
24448          ast_string_field_set(p, mwi_from, peer->mwi_from);
24449       } else if (!ast_strlen_zero(default_mwi_from)) {
24450          ast_string_field_set(p, mwi_from, default_mwi_from);
24451       }
24452       ao2_t_link(dialogs, p, "Linking in under new name");
24453       /* Destroy this session after 32 secs */
24454       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
24455    }
24456 
24457    /* Send MWI */
24458    ast_set_flag(&p->flags[0], SIP_OUTGOING);
24459    /* the following will decrement the refcount on p as it finishes */
24460    transmit_notify_with_mwi(p, newmsgs, oldmsgs, peer->vmexten);
24461    dialog_unref(p, "unref dialog ptr p just before it goes out of scope at the end of sip_send_mwi_to_peer.");
24462    return 0;
24463 }
24464 
24465 /*! \brief helper function for the monitoring thread -- seems to be called with the assumption that the dialog is locked */
24466 static void check_rtp_timeout(struct sip_pvt *dialog, time_t t)
24467 {
24468    /* If we have no RTP or no active owner, no need to check timers */
24469    if (!dialog->rtp || !dialog->owner)
24470       return;
24471    /* If the call is not in UP state or redirected outside Asterisk, no need to check timers */
24472 
24473    if (dialog->owner->_state != AST_STATE_UP || !ast_sockaddr_isnull(&dialog->redirip))
24474       return;
24475 
24476    /* If the call is involved in a T38 fax session do not check RTP timeout */
24477    if (dialog->t38.state == T38_ENABLED)
24478       return;
24479 
24480    /* If we have no timers set, return now */
24481    if (!ast_rtp_instance_get_timeout(dialog->rtp) && !ast_rtp_instance_get_hold_timeout(dialog->rtp)) {
24482       return;
24483    }
24484 
24485    /*! \todo Check video RTP keepalives
24486 
24487       Do we need to move the lastrtptx to the RTP structure to have one for audio and one
24488       for video? It really does belong to the RTP structure.
24489    */
24490 
24491    /* Check AUDIO RTP timers */
24492    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))) {
24493       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)))) {
24494          /* Needs a hangup */
24495          if (ast_rtp_instance_get_timeout(dialog->rtp)) {
24496             while (dialog->owner && ast_channel_trylock(dialog->owner)) {
24497                sip_pvt_unlock(dialog);
24498                usleep(1);
24499                sip_pvt_lock(dialog);
24500             }
24501             if (!dialog->owner) {
24502                return; /* channel hangup can occur during deadlock avoidance. */
24503             }
24504             ast_log(LOG_NOTICE, "Disconnecting call '%s' for lack of RTP activity in %ld seconds\n",
24505                dialog->owner->name, (long) (t - dialog->lastrtprx));
24506             /* Issue a softhangup */
24507             ast_softhangup_nolock(dialog->owner, AST_SOFTHANGUP_DEV);
24508             ast_channel_unlock(dialog->owner);
24509             /* forget the timeouts for this call, since a hangup
24510                has already been requested and we don't want to
24511                repeatedly request hangups
24512             */
24513             ast_rtp_instance_set_timeout(dialog->rtp, 0);
24514             ast_rtp_instance_set_hold_timeout(dialog->rtp, 0);
24515             if (dialog->vrtp) {
24516                ast_rtp_instance_set_timeout(dialog->vrtp, 0);
24517                ast_rtp_instance_set_hold_timeout(dialog->vrtp, 0);
24518             }
24519          }
24520       }
24521    }
24522 }
24523 
24524 /*! \brief The SIP monitoring thread
24525 \note This thread monitors all the SIP sessions and peers that needs notification of mwi
24526    (and thus do not have a separate thread) indefinitely
24527 */
24528 static void *do_monitor(void *data)
24529 {
24530    int res;
24531    time_t t;
24532    int reloading;
24533 
24534    /* Add an I/O event to our SIP UDP socket */
24535    if (sipsock > -1)
24536       sipsock_read_id = ast_io_add(io, sipsock, sipsock_read, AST_IO_IN, NULL);
24537 
24538    /* From here on out, we die whenever asked */
24539    for(;;) {
24540       /* Check for a reload request */
24541       ast_mutex_lock(&sip_reload_lock);
24542       reloading = sip_reloading;
24543       sip_reloading = FALSE;
24544       ast_mutex_unlock(&sip_reload_lock);
24545       if (reloading) {
24546          ast_verb(1, "Reloading SIP\n");
24547          sip_do_reload(sip_reloadreason);
24548 
24549          /* Change the I/O fd of our UDP socket */
24550          if (sipsock > -1) {
24551             if (sipsock_read_id)
24552                sipsock_read_id = ast_io_change(io, sipsock_read_id, sipsock, NULL, 0, NULL);
24553             else
24554                sipsock_read_id = ast_io_add(io, sipsock, sipsock_read, AST_IO_IN, NULL);
24555          } else if (sipsock_read_id) {
24556             ast_io_remove(io, sipsock_read_id);
24557             sipsock_read_id = NULL;
24558          }
24559       }
24560 
24561       /* Check for dialogs needing to be killed */
24562       t = time(NULL);
24563       /* don't scan the dialogs list if it hasn't been a reasonable period
24564          of time since the last time we did it (when MWI is being sent, we can
24565          get back to this point every millisecond or less)
24566       */
24567       ao2_t_callback(dialogs, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, dialog_needdestroy, &t,
24568             "callback to remove dialogs w/needdestroy");
24569 
24570       /* the old methodology would be to restart the search for dialogs to delete with every
24571          dialog that was found and destroyed, probably because the list contents would change,
24572          so we'd need to restart. This isn't the best thing to do with callbacks. */
24573 
24574       /* XXX TODO The scheduler usage in this module does not have sufficient
24575        * synchronization being done between running the scheduler and places
24576        * scheduling tasks.  As it is written, any scheduled item may not run
24577        * any sooner than about  1 second, regardless of whether a sooner time
24578        * was asked for. */
24579 
24580       pthread_testcancel();
24581       /* Wait for sched or io */
24582       res = ast_sched_wait(sched);
24583       if ((res < 0) || (res > 1000))
24584          res = 1000;
24585       res = ast_io_wait(io, res);
24586       if (res > 20)
24587          ast_debug(1, "chan_sip: ast_io_wait ran %d all at once\n", res);
24588       ast_mutex_lock(&monlock);
24589       res = ast_sched_runq(sched);
24590       if (res >= 20)
24591          ast_debug(1, "chan_sip: ast_sched_runq ran %d all at once\n", res);
24592       ast_mutex_unlock(&monlock);
24593    }
24594 
24595    /* Never reached */
24596    return NULL;
24597 }
24598 
24599 /*! \brief Start the channel monitor thread */
24600 static int restart_monitor(void)
24601 {
24602    /* If we're supposed to be stopped -- stay stopped */
24603    if (monitor_thread == AST_PTHREADT_STOP)
24604       return 0;
24605    ast_mutex_lock(&monlock);
24606    if (monitor_thread == pthread_self()) {
24607       ast_mutex_unlock(&monlock);
24608       ast_log(LOG_WARNING, "Cannot kill myself\n");
24609       return -1;
24610    }
24611    if (monitor_thread != AST_PTHREADT_NULL) {
24612       /* Wake up the thread */
24613       pthread_kill(monitor_thread, SIGURG);
24614    } else {
24615       /* Start a new monitor */
24616       if (ast_pthread_create_background(&monitor_thread, NULL, do_monitor, NULL) < 0) {
24617          ast_mutex_unlock(&monlock);
24618          ast_log(LOG_ERROR, "Unable to start monitor thread.\n");
24619          return -1;
24620       }
24621    }
24622    ast_mutex_unlock(&monlock);
24623    return 0;
24624 }
24625 
24626 
24627 /*! \brief Session-Timers: Restart session timer */
24628 static void restart_session_timer(struct sip_pvt *p)
24629 {
24630    if (!p->stimer) {
24631       ast_log(LOG_WARNING, "Null stimer in restart_session_timer - %s\n", p->callid);
24632       return;
24633    }
24634 
24635    if (p->stimer->st_active == TRUE) {
24636       AST_SCHED_DEL_UNREF(sched, p->stimer->st_schedid,
24637             dialog_unref(p, "Removing session timer ref"));
24638       ast_debug(2, "Session timer stopped: %d - %s\n", p->stimer->st_schedid, p->callid);
24639       start_session_timer(p);
24640    }
24641 }
24642 
24643 
24644 /*! \brief Session-Timers: Stop session timer */
24645 static void stop_session_timer(struct sip_pvt *p)
24646 {
24647    if (!p->stimer) {
24648       ast_log(LOG_WARNING, "Null stimer in stop_session_timer - %s\n", p->callid);
24649       return;
24650    }
24651 
24652    if (p->stimer->st_active == TRUE) {
24653       p->stimer->st_active = FALSE;
24654       AST_SCHED_DEL_UNREF(sched, p->stimer->st_schedid,
24655             dialog_unref(p, "removing session timer ref"));
24656       ast_debug(2, "Session timer stopped: %d - %s\n", p->stimer->st_schedid, p->callid);
24657    }
24658 }
24659 
24660 
24661 /*! \brief Session-Timers: Start session timer */
24662 static void start_session_timer(struct sip_pvt *p)
24663 {
24664    if (!p->stimer) {
24665       ast_log(LOG_WARNING, "Null stimer in start_session_timer - %s\n", p->callid);
24666       return;
24667    }
24668 
24669    p->stimer->st_schedid  = ast_sched_add(sched, p->stimer->st_interval * 1000 / 2, proc_session_timer,
24670          dialog_ref(p, "adding session timer ref"));
24671    if (p->stimer->st_schedid < 0) {
24672       dialog_unref(p, "removing session timer ref");
24673       ast_log(LOG_ERROR, "ast_sched_add failed.\n");
24674    }
24675    ast_debug(2, "Session timer started: %d - %s\n", p->stimer->st_schedid, p->callid);
24676 }
24677 
24678 
24679 /*! \brief Session-Timers: Process session refresh timeout event */
24680 static int proc_session_timer(const void *vp)
24681 {
24682    struct sip_pvt *p = (struct sip_pvt *) vp;
24683    int sendreinv = FALSE;
24684    int res = 0;
24685 
24686    if (!p->stimer) {
24687       ast_log(LOG_WARNING, "Null stimer in proc_session_timer - %s\n", p->callid);
24688       goto return_unref;
24689    }
24690 
24691    ast_debug(2, "Session timer expired: %d - %s\n", p->stimer->st_schedid, p->callid);
24692 
24693    if (!p->owner) {
24694       goto return_unref;
24695    }
24696 
24697    if ((p->stimer->st_active != TRUE) || (p->owner->_state != AST_STATE_UP)) {
24698       goto return_unref;
24699    }
24700 
24701    switch (p->stimer->st_ref) {
24702    case SESSION_TIMER_REFRESHER_UAC:
24703       if (p->outgoing_call == TRUE) {
24704          sendreinv = TRUE;
24705       }
24706       break;
24707    case SESSION_TIMER_REFRESHER_UAS:
24708       if (p->outgoing_call != TRUE) {
24709          sendreinv = TRUE;
24710       }
24711       break;
24712    default:
24713       ast_log(LOG_ERROR, "Unknown session refresher %d\n", p->stimer->st_ref);
24714       goto return_unref;
24715    }
24716 
24717    if (sendreinv == TRUE) {
24718       res = 1;
24719       transmit_reinvite_with_sdp(p, FALSE, TRUE);
24720    } else {
24721       p->stimer->st_expirys++;
24722       if (p->stimer->st_expirys >= 2) {
24723          if (p->stimer->quit_flag) {
24724             goto return_unref;
24725          }
24726          ast_log(LOG_WARNING, "Session-Timer expired - %s\n", p->callid);
24727          sip_pvt_lock(p);
24728          while (p->owner && ast_channel_trylock(p->owner)) {
24729             sip_pvt_unlock(p);
24730             usleep(1);
24731             if (p->stimer && p->stimer->quit_flag) {
24732                goto return_unref;
24733             }
24734             sip_pvt_lock(p);
24735          }
24736 
24737          ast_softhangup_nolock(p->owner, AST_SOFTHANGUP_DEV);
24738          ast_channel_unlock(p->owner);
24739          sip_pvt_unlock(p);
24740       }
24741    }
24742 
24743 return_unref:
24744    if (!res) {
24745       /* An error occurred.  Stop session timer processing */
24746       if (p->stimer) {
24747          p->stimer->st_schedid = -1;
24748          stop_session_timer(p);
24749       }
24750 
24751       /* If we are not asking to be rescheduled, then we need to release our
24752        * reference to the dialog. */
24753       dialog_unref(p, "removing session timer ref");
24754    }
24755 
24756    return res;
24757 }
24758 
24759 
24760 /*! \brief Session-Timers: Function for parsing Min-SE header */
24761 int parse_minse (const char *p_hdrval, int *const p_interval)
24762 {
24763    if (ast_strlen_zero(p_hdrval)) {
24764       ast_log(LOG_WARNING, "Null Min-SE header\n");
24765       return -1;
24766    }
24767 
24768    *p_interval = 0;
24769    p_hdrval = ast_skip_blanks(p_hdrval);
24770    if (!sscanf(p_hdrval, "%30d", p_interval)) {
24771       ast_log(LOG_WARNING, "Parsing of Min-SE header failed %s\n", p_hdrval);
24772       return -1;
24773    }
24774 
24775    ast_debug(2, "Received Min-SE: %d\n", *p_interval);
24776    return 0;
24777 }
24778 
24779 
24780 /*! \brief Session-Timers: Function for parsing Session-Expires header */
24781 int parse_session_expires(const char *p_hdrval, int *const p_interval, enum st_refresher *const p_ref)
24782 {
24783    char *p_token;
24784    int  ref_idx;
24785    char *p_se_hdr;
24786 
24787    if (ast_strlen_zero(p_hdrval)) {
24788       ast_log(LOG_WARNING, "Null Session-Expires header\n");
24789       return -1;
24790    }
24791 
24792    *p_ref = SESSION_TIMER_REFRESHER_AUTO;
24793    *p_interval = 0;
24794 
24795    p_se_hdr = ast_strdupa(p_hdrval);
24796    p_se_hdr = ast_skip_blanks(p_se_hdr);
24797 
24798    while ((p_token = strsep(&p_se_hdr, ";"))) {
24799       p_token = ast_skip_blanks(p_token);
24800       if (!sscanf(p_token, "%30d", p_interval)) {
24801          ast_log(LOG_WARNING, "Parsing of Session-Expires failed\n");
24802          return -1;
24803       }
24804 
24805       ast_debug(2, "Session-Expires: %d\n", *p_interval);
24806 
24807       if (!p_se_hdr)
24808          continue;
24809 
24810       p_se_hdr = ast_skip_blanks(p_se_hdr);
24811       ref_idx = strlen("refresher=");
24812       if (!strncasecmp(p_se_hdr, "refresher=", ref_idx)) {
24813          p_se_hdr += ref_idx;
24814          p_se_hdr = ast_skip_blanks(p_se_hdr);
24815 
24816          if (!strncasecmp(p_se_hdr, "uac", strlen("uac"))) {
24817             *p_ref = SESSION_TIMER_REFRESHER_UAC;
24818             ast_debug(2, "Refresher: UAC\n");
24819          } else if (!strncasecmp(p_se_hdr, "uas", strlen("uas"))) {
24820             *p_ref = SESSION_TIMER_REFRESHER_UAS;
24821             ast_debug(2, "Refresher: UAS\n");
24822          } else {
24823             ast_log(LOG_WARNING, "Invalid refresher value %s\n", p_se_hdr);
24824             return -1;
24825          }
24826          break;
24827       }
24828    }
24829    return 0;
24830 }
24831 
24832 
24833 /*! \brief Handle 422 response to INVITE with session-timer requested
24834 
24835    Session-Timers:   An INVITE originated by Asterisk that asks for session-timers support
24836    from the UAS can result into a 422 response. This is how a UAS or an intermediary proxy
24837    server tells Asterisk that the session refresh interval offered by Asterisk is too low
24838    for them.  The proc_422_rsp() function handles a 422 response.  It extracts the Min-SE
24839    header that comes back in 422 and sends a new INVITE accordingly. */
24840 static void proc_422_rsp(struct sip_pvt *p, struct sip_request *rsp)
24841 {
24842    int rtn;
24843    const char *p_hdrval;
24844    int minse;
24845 
24846    p_hdrval = get_header(rsp, "Min-SE");
24847    if (ast_strlen_zero(p_hdrval)) {
24848       ast_log(LOG_WARNING, "422 response without a Min-SE header %s\n", p_hdrval);
24849       return;
24850    }
24851    rtn = parse_minse(p_hdrval, &minse);
24852    if (rtn != 0) {
24853       ast_log(LOG_WARNING, "Parsing of Min-SE header failed %s\n", p_hdrval);
24854       return;
24855    }
24856    p->stimer->st_interval = minse;
24857    transmit_invite(p, SIP_INVITE, 1, 2, NULL);
24858 }
24859 
24860 
24861 /*! \brief Get Max or Min SE (session timer expiry)
24862  * \param p pointer to the SIP dialog
24863  * \param max if true, get max se, otherwise min se
24864 */
24865 int st_get_se(struct sip_pvt *p, int max)
24866 {
24867    if (max == TRUE) {
24868       if (p->stimer->st_cached_max_se) {
24869          return  p->stimer->st_cached_max_se;
24870       }
24871       if (p->relatedpeer) {
24872          p->stimer->st_cached_max_se = p->relatedpeer->stimer.st_max_se;
24873          return (p->stimer->st_cached_max_se);
24874       }
24875       p->stimer->st_cached_max_se = global_max_se;
24876       return (p->stimer->st_cached_max_se);
24877    } 
24878    /* Find Min SE timer */
24879    if (p->stimer->st_cached_min_se) {
24880       return p->stimer->st_cached_min_se;
24881    } 
24882    if (p->relatedpeer) {
24883       p->stimer->st_cached_min_se = p->relatedpeer->stimer.st_min_se;
24884       return (p->stimer->st_cached_min_se);
24885    }
24886    p->stimer->st_cached_min_se = global_min_se;
24887    return (p->stimer->st_cached_min_se);
24888 }
24889 
24890 
24891 /*! \brief Get the entity (UAC or UAS) that's acting as the session-timer refresher
24892  * \param p pointer to the SIP dialog
24893 */
24894 enum st_refresher st_get_refresher(struct sip_pvt *p)
24895 {
24896    if (p->stimer->st_cached_ref != SESSION_TIMER_REFRESHER_AUTO)
24897       return p->stimer->st_cached_ref;
24898 
24899    if (p->relatedpeer) {
24900       p->stimer->st_cached_ref = p->relatedpeer->stimer.st_ref;
24901       return p->stimer->st_cached_ref;
24902    }
24903    
24904    p->stimer->st_cached_ref = global_st_refresher;
24905    return global_st_refresher;
24906 }
24907 
24908 
24909 /*! \brief Get the session-timer mode
24910  * \param p pointer to the SIP dialog
24911 */
24912 enum st_mode st_get_mode(struct sip_pvt *p)
24913 {
24914    if (!p->stimer)
24915       sip_st_alloc(p);
24916 
24917    if (p->stimer->st_cached_mode != SESSION_TIMER_MODE_INVALID)
24918       return p->stimer->st_cached_mode;
24919 
24920    if (p->relatedpeer) {
24921       p->stimer->st_cached_mode = p->relatedpeer->stimer.st_mode_oper;
24922       return p->stimer->st_cached_mode;
24923    }
24924 
24925    p->stimer->st_cached_mode = global_st_mode;
24926    return global_st_mode;
24927 }
24928 
24929 
24930 /*! \brief React to lack of answer to Qualify poke */
24931 static int sip_poke_noanswer(const void *data)
24932 {
24933    struct sip_peer *peer = (struct sip_peer *)data;
24934 
24935    peer->pokeexpire = -1;
24936 
24937    if (peer->lastms > -1) {
24938       ast_log(LOG_NOTICE, "Peer '%s' is now UNREACHABLE!  Last qualify: %d\n", peer->name, peer->lastms);
24939       if (sip_cfg.peer_rtupdate) {
24940          ast_update_realtime(ast_check_realtime("sipregs") ? "sipregs" : "sippeers", "name", peer->name, "lastms", "-1", SENTINEL);
24941       }
24942       manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: Unreachable\r\nTime: %d\r\n", peer->name, -1);
24943       if (sip_cfg.regextenonqualify) {
24944          register_peer_exten(peer, FALSE);
24945       }
24946    }
24947 
24948    if (peer->call) {
24949       dialog_unlink_all(peer->call, TRUE, TRUE);
24950       peer->call = dialog_unref(peer->call, "unref dialog peer->call");
24951       /* peer->call = sip_destroy(peer->call);*/
24952    }
24953 
24954    /* Don't send a devstate change if nothing changed. */
24955    if (peer->lastms > -1) {
24956       peer->lastms = -1;
24957       ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", peer->name);
24958    }
24959 
24960    /* Try again quickly */
24961    AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched,
24962          DEFAULT_FREQ_NOTOK, sip_poke_peer_s, peer,
24963          unref_peer(_data, "removing poke peer ref"),
24964          unref_peer(peer, "removing poke peer ref"),
24965          ref_peer(peer, "adding poke peer ref"));
24966 
24967    /* Release the ref held by the running scheduler entry */
24968    unref_peer(peer, "release peer poke noanswer ref");
24969 
24970    return 0;
24971 }
24972 
24973 /*! \brief Check availability of peer, also keep NAT open
24974 \note This is done with 60 seconds between each ping,
24975    unless forced by cli or manager. If peer is unreachable,
24976    we check every 10th second by default.
24977 */
24978 static int sip_poke_peer(struct sip_peer *peer, int force)
24979 {
24980    struct sip_pvt *p;
24981    int xmitres = 0;
24982    
24983    if ((!peer->maxms && !force) || ast_sockaddr_isnull(&peer->addr)) {
24984       /* IF we have no IP, or this isn't to be monitored, return
24985         immediately after clearing things out */
24986       AST_SCHED_DEL_UNREF(sched, peer->pokeexpire,
24987             unref_peer(peer, "removing poke peer ref"));
24988       
24989       peer->lastms = 0;
24990       if (peer->call) {
24991          peer->call = dialog_unref(peer->call, "unref dialog peer->call");
24992       }
24993       return 0;
24994    }
24995    if (peer->call) {
24996       if (sipdebug) {
24997          ast_log(LOG_NOTICE, "Still have a QUALIFY dialog active, deleting\n");
24998       }
24999       dialog_unlink_all(peer->call, TRUE, TRUE);
25000       peer->call = dialog_unref(peer->call, "unref dialog peer->call");
25001       /* peer->call = sip_destroy(peer->call); */
25002    }
25003    if (!(p = sip_alloc(NULL, NULL, 0, SIP_OPTIONS, NULL))) {
25004       return -1;
25005    }
25006    peer->call = dialog_ref(p, "copy sip alloc from p to peer->call");
25007    
25008    p->sa = peer->addr;
25009    p->recv = peer->addr;
25010    copy_socket_data(&p->socket, &peer->socket);
25011    ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
25012    ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
25013    ast_copy_flags(&p->flags[2], &peer->flags[2], SIP_PAGE3_FLAGS_TO_COPY);
25014 
25015    /* Send OPTIONs to peer's fullcontact */
25016    if (!ast_strlen_zero(peer->fullcontact))
25017       ast_string_field_set(p, fullcontact, peer->fullcontact);
25018 
25019    if (!ast_strlen_zero(peer->tohost))
25020       ast_string_field_set(p, tohost, peer->tohost);
25021    else
25022       ast_string_field_set(p, tohost, ast_sockaddr_stringify_host(&peer->addr));
25023 
25024    /* Recalculate our side, and recalculate Call ID */
25025    ast_sip_ouraddrfor(&p->sa, &p->ourip, p);
25026    build_via(p);
25027    ao2_t_unlink(dialogs, p, "About to change the callid -- remove the old name");
25028    build_callid_pvt(p);
25029    ao2_t_link(dialogs, p, "Linking in under new name");
25030 
25031    AST_SCHED_DEL_UNREF(sched, peer->pokeexpire,
25032          unref_peer(peer, "removing poke peer ref"));
25033    
25034    if (p->relatedpeer)
25035       p->relatedpeer = unref_peer(p->relatedpeer,"unsetting the relatedpeer field in the dialog, before it is set to something else.");
25036    p->relatedpeer = ref_peer(peer, "setting the relatedpeer field in the dialog");
25037    ast_set_flag(&p->flags[0], SIP_OUTGOING);
25038 #ifdef VOCAL_DATA_HACK
25039    ast_copy_string(p->username, "__VOCAL_DATA_SHOULD_READ_THE_SIP_SPEC__", sizeof(p->username));
25040    xmitres = transmit_invite(p, SIP_INVITE, 0, 2, NULL); /* sinks the p refcount */
25041 #else
25042    xmitres = transmit_invite(p, SIP_OPTIONS, 0, 2, NULL); /* sinks the p refcount */
25043 #endif
25044    peer->ps = ast_tvnow();
25045    if (xmitres == XMIT_ERROR) {
25046       sip_poke_noanswer(peer);   /* Immediately unreachable, network problems */
25047    } else if (!force) {
25048       AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched, peer->maxms * 2, sip_poke_noanswer, peer,
25049             unref_peer(_data, "removing poke peer ref"),
25050             unref_peer(peer, "removing poke peer ref"),
25051             ref_peer(peer, "adding poke peer ref"));
25052    }
25053    dialog_unref(p, "unref dialog at end of sip_poke_peer, obtained from sip_alloc, just before it goes out of scope");
25054    return 0;
25055 }
25056 
25057 /*! \brief Part of PBX channel interface
25058 \note
25059 \par  Return values:---
25060 
25061    If we have qualify on and the device is not reachable, regardless of registration
25062    state we return AST_DEVICE_UNAVAILABLE
25063 
25064    For peers with call limit:
25065       - not registered        AST_DEVICE_UNAVAILABLE
25066       - registered, no call         AST_DEVICE_NOT_INUSE
25067       - registered, active calls    AST_DEVICE_INUSE
25068       - registered, call limit reached AST_DEVICE_BUSY
25069       - registered, onhold       AST_DEVICE_ONHOLD
25070       - registered, ringing         AST_DEVICE_RINGING
25071 
25072    For peers without call limit:
25073       - not registered        AST_DEVICE_UNAVAILABLE
25074       - registered            AST_DEVICE_NOT_INUSE
25075       - fixed IP (!dynamic)         AST_DEVICE_NOT_INUSE
25076    
25077    Peers that does not have a known call and can't be reached by OPTIONS
25078       - unreachable           AST_DEVICE_UNAVAILABLE
25079 
25080    If we return AST_DEVICE_UNKNOWN, the device state engine will try to find
25081    out a state by walking the channel list.
25082 
25083    The queue system (\ref app_queue.c) treats a member as "active"
25084    if devicestate is != AST_DEVICE_UNAVAILBALE && != AST_DEVICE_INVALID
25085 
25086    When placing a call to the queue member, queue system sets a member to busy if
25087    != AST_DEVICE_NOT_INUSE and != AST_DEVICE_UNKNOWN
25088 
25089 */
25090 static int sip_devicestate(void *data)
25091 {
25092    char *host;
25093    char *tmp;
25094    struct sip_peer *p;
25095 
25096    int res = AST_DEVICE_INVALID;
25097 
25098    /* make sure data is not null. Maybe unnecessary, but better be safe */
25099    host = ast_strdupa(data ? data : "");
25100    if ((tmp = strchr(host, '@')))
25101       host = tmp + 1;
25102 
25103    ast_debug(3, "Checking device state for peer %s\n", host);
25104 
25105    /* If find_peer asks for a realtime peer, then this breaks rtautoclear.  This
25106     * is because when a peer tries to autoexpire, the last thing it does is to
25107     * queue up an event telling the system that the devicestate has changed
25108     * (presumably to unavailable).  If we ask for a realtime peer here, this would
25109     * load it BACK into memory, thus defeating the point of trying to clear dead
25110     * hosts out of memory.
25111     */
25112    if ((p = find_peer(host, NULL, FALSE, FINDALLDEVICES, TRUE, 0))) {
25113       if (!(ast_sockaddr_isnull(&p->addr) && ast_sockaddr_isnull(&p->defaddr))) {
25114          /* we have an address for the peer */
25115       
25116          /* Check status in this order
25117             - Hold
25118             - Ringing
25119             - Busy (enforced only by call limit)
25120             - Inuse (we have a call)
25121             - Unreachable (qualify)
25122             If we don't find any of these state, report AST_DEVICE_NOT_INUSE
25123             for registered devices */
25124 
25125          if (p->onHold)
25126             /* First check for hold or ring states */
25127             res = AST_DEVICE_ONHOLD;
25128          else if (p->inRinging) {
25129             if (p->inRinging == p->inUse)
25130                res = AST_DEVICE_RINGING;
25131             else
25132                res = AST_DEVICE_RINGINUSE;
25133          } else if (p->call_limit && (p->inUse == p->call_limit))
25134             /* check call limit */
25135             res = AST_DEVICE_BUSY;
25136          else if (p->call_limit && p->busy_level && p->inUse >= p->busy_level)
25137             /* We're forcing busy before we've reached the call limit */
25138             res = AST_DEVICE_BUSY;
25139          else if (p->call_limit && p->inUse)
25140             /* Not busy, but we do have a call */
25141             res = AST_DEVICE_INUSE;
25142          else if (p->maxms && ((p->lastms > p->maxms) || (p->lastms < 0)))
25143             /* We don't have a call. Are we reachable at all? Requires qualify= */
25144             res = AST_DEVICE_UNAVAILABLE;
25145          else  /* Default reply if we're registered and have no other data */
25146             res = AST_DEVICE_NOT_INUSE;
25147       } else {
25148          /* there is no address, it's unavailable */
25149          res = AST_DEVICE_UNAVAILABLE;
25150       }
25151       unref_peer(p, "unref_peer, from sip_devicestate, release ref from find_peer");
25152    } else {
25153       res = AST_DEVICE_UNKNOWN;
25154    }
25155 
25156    return res;
25157 }
25158 
25159 /*! \brief PBX interface function -build SIP pvt structure
25160  * SIP calls initiated by the PBX arrive here.
25161  *
25162  * \verbatim   
25163  *    SIP Dial string syntax
25164  *    SIP/exten@host!dnid
25165  * or SIP/host/exten!dnid
25166  * or SIP/host!dnid
25167  * \endverbatim
25168 */
25169 static struct ast_channel *sip_request_call(const char *type, format_t format, const struct ast_channel *requestor, void *data, int *cause)
25170 {
25171    struct sip_pvt *p;
25172    struct ast_channel *tmpc = NULL;
25173    char *ext = NULL, *host;
25174    char tmp[256];
25175    char *dest = data;
25176    char *dnid;
25177    char *secret = NULL;
25178    char *md5secret = NULL;
25179    char *authname = NULL;
25180    char *trans = NULL;
25181    char dialstring[256];
25182    char *remote_address;
25183    enum sip_transport transport = 0;
25184    struct ast_sockaddr remote_address_sa = { {0,} };
25185    format_t oldformat = format;
25186    AST_DECLARE_APP_ARGS(args,
25187       AST_APP_ARG(peerorhost);
25188       AST_APP_ARG(exten);
25189       AST_APP_ARG(remote_address);
25190    );
25191 
25192    /* mask request with some set of allowed formats.
25193     * XXX this needs to be fixed.
25194     * The original code uses AST_FORMAT_AUDIO_MASK, but it is
25195     * unclear what to use here. We have global_capabilities, which is
25196     * configured from sip.conf, and sip_tech.capabilities, which is
25197     * hardwired to all audio formats.
25198     */
25199    format &= AST_FORMAT_AUDIO_MASK;
25200    if (!format) {
25201       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));
25202       *cause = AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;   /* Can't find codec to connect to host */
25203       return NULL;
25204    }
25205    ast_debug(1, "Asked to create a SIP channel with formats: %s\n", ast_getformatname_multiple(tmp, sizeof(tmp), oldformat));
25206 
25207    if (!(p = sip_alloc(NULL, NULL, 0, SIP_INVITE, NULL))) {
25208       ast_log(LOG_ERROR, "Unable to build sip pvt data for '%s' (Out of memory or socket error)\n", dest);
25209       *cause = AST_CAUSE_SWITCH_CONGESTION;
25210       return NULL;
25211    }
25212 
25213    p->outgoing_call = TRUE;
25214 
25215    snprintf(dialstring, sizeof(dialstring), "%s/%s", type, dest);
25216    ast_string_field_set(p, dialstring, dialstring);
25217 
25218    if (!(p->options = ast_calloc(1, sizeof(*p->options)))) {
25219       dialog_unlink_all(p, TRUE, TRUE);
25220       dialog_unref(p, "unref dialog p from mem fail");
25221       /* sip_destroy(p); */
25222       ast_log(LOG_ERROR, "Unable to build option SIP data structure - Out of memory\n");
25223       *cause = AST_CAUSE_SWITCH_CONGESTION;
25224       return NULL;
25225    }
25226 
25227    /* Save the destination, the SIP dial string */
25228    ast_copy_string(tmp, dest, sizeof(tmp));
25229 
25230    /* Find DNID and take it away */
25231    dnid = strchr(tmp, '!');
25232    if (dnid != NULL) {
25233       *dnid++ = '\0';
25234       ast_string_field_set(p, todnid, dnid);
25235    }
25236 
25237    /* Divvy up the items separated by slashes */
25238    AST_NONSTANDARD_APP_ARGS(args, tmp, '/');
25239 
25240    /* Find at sign - @ */
25241    host = strchr(args.peerorhost, '@');
25242    if (host) {
25243       *host++ = '\0';
25244       ext = args.peerorhost;
25245       secret = strchr(ext, ':');
25246    }
25247    if (secret) {
25248       *secret++ = '\0';
25249       md5secret = strchr(secret, ':');
25250    }
25251    if (md5secret) {
25252       *md5secret++ = '\0';
25253       authname = strchr(md5secret, ':');
25254    }
25255    if (authname) {
25256       *authname++ = '\0';
25257       trans = strchr(authname, ':');
25258    }
25259    if (trans) {
25260       *trans++ = '\0';
25261       if (!strcasecmp(trans, "tcp"))
25262          transport = SIP_TRANSPORT_TCP;
25263       else if (!strcasecmp(trans, "tls"))
25264          transport = SIP_TRANSPORT_TLS;
25265       else {
25266          if (strcasecmp(trans, "udp"))
25267             ast_log(LOG_WARNING, "'%s' is not a valid transport option to Dial() for SIP calls, using udp by default.\n", trans);
25268          transport = SIP_TRANSPORT_UDP;
25269       }
25270    } else { /* use default */
25271       transport = SIP_TRANSPORT_UDP;
25272    }
25273 
25274    if (!host) {
25275       ext = args.exten;
25276       host = args.peerorhost;
25277       remote_address = args.remote_address;
25278    } else {
25279       remote_address = args.remote_address;
25280       if (!ast_strlen_zero(args.exten)) {
25281          ast_log(LOG_NOTICE, "Conflicting extension values given. Using '%s' and not '%s'\n", ext, args.exten);
25282       }
25283    }
25284 
25285    if (!ast_strlen_zero(remote_address)) {
25286       if (ast_sockaddr_resolve_first(&remote_address_sa, remote_address, 0)) {
25287          ast_log(LOG_WARNING, "Unable to find IP address for host %s. We will not use this remote IP address\n", remote_address);
25288       } else {
25289          if (!ast_sockaddr_port(&remote_address_sa)) {
25290             ast_sockaddr_set_port(&remote_address_sa,
25291                         transport & SIP_TRANSPORT_TLS ?
25292                         STANDARD_TLS_PORT :
25293                         STANDARD_SIP_PORT);
25294          }
25295       }
25296    }
25297 
25298    set_socket_transport(&p->socket, transport);
25299 
25300    /* We now have
25301       host = peer name, DNS host name or DNS domain (for SRV)
25302       ext = extension (user part of URI)
25303       dnid = destination of the call (applies to the To: header)
25304    */
25305    if (create_addr(p, host, NULL, 1, &remote_address_sa)) {
25306       *cause = AST_CAUSE_UNREGISTERED;
25307       ast_debug(3, "Cant create SIP call - target device not registered\n");
25308       dialog_unlink_all(p, TRUE, TRUE);
25309       dialog_unref(p, "unref dialog p UNREGISTERED");
25310       /* sip_destroy(p); */
25311       return NULL;
25312    }
25313    if (ast_strlen_zero(p->peername) && ext)
25314       ast_string_field_set(p, peername, ext);
25315    /* Recalculate our side, and recalculate Call ID */
25316    ast_sip_ouraddrfor(&p->sa, &p->ourip, p);
25317    build_via(p);
25318    ao2_t_unlink(dialogs, p, "About to change the callid -- remove the old name");
25319    build_callid_pvt(p);
25320    ao2_t_link(dialogs, p, "Linking in under new name");
25321    
25322    /* We have an extension to call, don't use the full contact here */
25323    /* This to enable dialing registered peers with extension dialling,
25324       like SIP/peername/extension   
25325       SIP/peername will still use the full contact
25326     */
25327    if (ext) {
25328       ast_string_field_set(p, username, ext);
25329       ast_string_field_set(p, fullcontact, NULL);
25330    }
25331    if (secret && !ast_strlen_zero(secret))
25332       ast_string_field_set(p, peersecret, secret);
25333 
25334    if (md5secret && !ast_strlen_zero(md5secret))
25335       ast_string_field_set(p, peermd5secret, md5secret);
25336 
25337    if (authname && !ast_strlen_zero(authname))
25338       ast_string_field_set(p, authname, authname);
25339 #if 0
25340    printf("Setting up to call extension '%s' at '%s'\n", ext ? ext : "<none>", host);
25341 #endif
25342    p->prefcodec = oldformat;           /* Format for this call */
25343    p->jointcapability = oldformat & p->capability;
25344    sip_pvt_lock(p);
25345    tmpc = sip_new(p, AST_STATE_DOWN, host, requestor ? requestor->linkedid : NULL); /* Place the call */
25346    if (sip_cfg.callevents)
25347       manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
25348          "Channel: %s\r\nChanneltype: %s\r\nSIPcallid: %s\r\nSIPfullcontact: %s\r\nPeername: %s\r\n",
25349          p->owner? p->owner->name : "", "SIP", p->callid, p->fullcontact, p->peername);
25350    sip_pvt_unlock(p);
25351    if (!tmpc) {
25352       dialog_unlink_all(p, TRUE, TRUE);
25353       /* sip_destroy(p); */
25354    }
25355    dialog_unref(p, "toss pvt ptr at end of sip_request_call");
25356    ast_update_use_count();
25357    restart_monitor();
25358    return tmpc;
25359 }
25360 
25361 /*! \brief Parse insecure= setting in sip.conf and set flags according to setting */
25362 static void set_insecure_flags (struct ast_flags *flags, const char *value, int lineno)
25363 {
25364    if (ast_strlen_zero(value))
25365       return;
25366 
25367    if (!ast_false(value)) {
25368       char buf[64];
25369       char *word, *next;
25370 
25371       ast_copy_string(buf, value, sizeof(buf));
25372       next = buf;
25373       while ((word = strsep(&next, ","))) {
25374          if (!strcasecmp(word, "port"))
25375             ast_set_flag(&flags[0], SIP_INSECURE_PORT);
25376          else if (!strcasecmp(word, "invite"))
25377             ast_set_flag(&flags[0], SIP_INSECURE_INVITE);
25378          else
25379             ast_log(LOG_WARNING, "Unknown insecure mode '%s' on line %d\n", value, lineno);
25380       }
25381    }
25382 }
25383 
25384 /*!
25385   \brief Handle T.38 configuration options common to users and peers
25386   \returns non-zero if any config options were handled, zero otherwise
25387 */
25388 static int handle_t38_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v,
25389                int *maxdatagram)
25390 {
25391    int res = 1;
25392 
25393    if (!strcasecmp(v->name, "t38pt_udptl")) {
25394       char *buf = ast_strdupa(v->value);
25395       char *word, *next = buf;
25396 
25397       ast_set_flag(&mask[1], SIP_PAGE2_T38SUPPORT);
25398 
25399       while ((word = strsep(&next, ","))) {
25400          if (ast_true(word) || !strcasecmp(word, "fec")) {
25401             ast_clear_flag(&flags[1], SIP_PAGE2_T38SUPPORT);
25402             ast_set_flag(&flags[1], SIP_PAGE2_T38SUPPORT_UDPTL_FEC);
25403          } else if (!strcasecmp(word, "redundancy")) {
25404             ast_clear_flag(&flags[1], SIP_PAGE2_T38SUPPORT);
25405             ast_set_flag(&flags[1], SIP_PAGE2_T38SUPPORT_UDPTL_REDUNDANCY);
25406          } else if (!strcasecmp(word, "none")) {
25407             ast_clear_flag(&flags[1], SIP_PAGE2_T38SUPPORT);
25408             ast_set_flag(&flags[1], SIP_PAGE2_T38SUPPORT_UDPTL);
25409          } else if (!strncasecmp(word, "maxdatagram=", 12)) {
25410             if (sscanf(&word[12], "%30u", maxdatagram) != 1) {
25411                ast_log(LOG_WARNING, "Invalid maxdatagram '%s' at line %d of %s\n", v->value, v->lineno, config);
25412                *maxdatagram = global_t38_maxdatagram;
25413             }
25414          }
25415       }
25416    } else if (!strcasecmp(v->name, "t38pt_usertpsource")) {
25417       ast_set_flag(&mask[1], SIP_PAGE2_UDPTL_DESTINATION);
25418       ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_UDPTL_DESTINATION);
25419    } else {
25420       res = 0;
25421    }
25422 
25423    return res;
25424 }
25425 
25426 /*!
25427   \brief Handle flag-type options common to configuration of devices - peers
25428   \param flags array of two struct ast_flags
25429   \param mask array of two struct ast_flags
25430   \param v linked list of config variables to process
25431   \returns non-zero if any config options were handled, zero otherwise
25432 */
25433 static int handle_common_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v)
25434 {
25435    int res = 1;
25436 
25437    if (!strcasecmp(v->name, "trustrpid")) {
25438       ast_set_flag(&mask[0], SIP_TRUSTRPID);
25439       ast_set2_flag(&flags[0], ast_true(v->value), SIP_TRUSTRPID);
25440    } else if (!strcasecmp(v->name, "sendrpid")) {
25441       ast_set_flag(&mask[0], SIP_SENDRPID);
25442       if (!strcasecmp(v->value, "pai")) {
25443          ast_set_flag(&flags[0], SIP_SENDRPID_PAI);
25444       } else if (!strcasecmp(v->value, "rpid")) {
25445          ast_set_flag(&flags[0], SIP_SENDRPID_RPID);
25446       } else if (ast_true(v->value)) {
25447          ast_set_flag(&flags[0], SIP_SENDRPID_RPID);
25448       }
25449    } else if (!strcasecmp(v->name, "rpid_update")) {
25450       ast_set_flag(&mask[1], SIP_PAGE2_RPID_UPDATE);
25451       ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_RPID_UPDATE);
25452    } else if (!strcasecmp(v->name, "rpid_immediate")) {
25453       ast_set_flag(&mask[1], SIP_PAGE2_RPID_IMMEDIATE);
25454       ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_RPID_IMMEDIATE);
25455    } else if (!strcasecmp(v->name, "g726nonstandard")) {
25456       ast_set_flag(&mask[0], SIP_G726_NONSTANDARD);
25457       ast_set2_flag(&flags[0], ast_true(v->value), SIP_G726_NONSTANDARD);
25458    } else if (!strcasecmp(v->name, "useclientcode")) {
25459       ast_set_flag(&mask[0], SIP_USECLIENTCODE);
25460       ast_set2_flag(&flags[0], ast_true(v->value), SIP_USECLIENTCODE);
25461    } else if (!strcasecmp(v->name, "dtmfmode")) {
25462       ast_set_flag(&mask[0], SIP_DTMF);
25463       ast_clear_flag(&flags[0], SIP_DTMF);
25464       if (!strcasecmp(v->value, "inband"))
25465          ast_set_flag(&flags[0], SIP_DTMF_INBAND);
25466       else if (!strcasecmp(v->value, "rfc2833"))
25467          ast_set_flag(&flags[0], SIP_DTMF_RFC2833);
25468       else if (!strcasecmp(v->value, "info"))
25469          ast_set_flag(&flags[0], SIP_DTMF_INFO);
25470       else if (!strcasecmp(v->value, "shortinfo"))
25471          ast_set_flag(&flags[0], SIP_DTMF_SHORTINFO);
25472       else if (!strcasecmp(v->value, "auto"))
25473          ast_set_flag(&flags[0], SIP_DTMF_AUTO);
25474       else {
25475          ast_log(LOG_WARNING, "Unknown dtmf mode '%s' on line %d, using rfc2833\n", v->value, v->lineno);
25476          ast_set_flag(&flags[0], SIP_DTMF_RFC2833);
25477       }
25478    } else if (!strcasecmp(v->name, "nat")) {
25479       ast_set_flag(&mask[0], SIP_NAT_FORCE_RPORT);
25480       if (!strcasecmp(v->value, "no")) {
25481          ast_clear_flag(&flags[0], SIP_NAT_FORCE_RPORT);
25482       } else if (!strcasecmp(v->value, "force_rport")) {
25483          ast_set_flag(&flags[0], SIP_NAT_FORCE_RPORT);
25484       } else if (!strcasecmp(v->value, "yes")) {
25485          ast_set_flag(&flags[0], SIP_NAT_FORCE_RPORT);
25486          ast_set_flag(&mask[1], SIP_PAGE2_SYMMETRICRTP);
25487          ast_set_flag(&flags[1], SIP_PAGE2_SYMMETRICRTP);
25488       } else if (!strcasecmp(v->value, "comedia")) {
25489          ast_clear_flag(&flags[0], SIP_NAT_FORCE_RPORT);
25490          ast_set_flag(&mask[1], SIP_PAGE2_SYMMETRICRTP);
25491          ast_set_flag(&flags[1], SIP_PAGE2_SYMMETRICRTP);
25492       }
25493    } else if (!strcasecmp(v->name, "directmedia") || !strcasecmp(v->name, "canreinvite")) {
25494       ast_set_flag(&mask[0], SIP_REINVITE);
25495       ast_clear_flag(&flags[0], SIP_REINVITE);
25496       if (ast_true(v->value)) {
25497          ast_set_flag(&flags[0], SIP_DIRECT_MEDIA | SIP_DIRECT_MEDIA_NAT);
25498       } else if (!ast_false(v->value)) {
25499          char buf[64];
25500          char *word, *next = buf;
25501 
25502          ast_copy_string(buf, v->value, sizeof(buf));
25503          while ((word = strsep(&next, ","))) {
25504             if (!strcasecmp(word, "update")) {
25505                ast_set_flag(&flags[0], SIP_REINVITE_UPDATE | SIP_DIRECT_MEDIA);
25506             } else if (!strcasecmp(word, "nonat")) {
25507                ast_set_flag(&flags[0], SIP_DIRECT_MEDIA);
25508                ast_clear_flag(&flags[0], SIP_DIRECT_MEDIA_NAT);
25509             } else {
25510                ast_log(LOG_WARNING, "Unknown directmedia mode '%s' on line %d\n", v->value, v->lineno);
25511             }
25512          }
25513       }
25514    } else if (!strcasecmp(v->name, "insecure")) {
25515       ast_set_flag(&mask[0], SIP_INSECURE);
25516       ast_clear_flag(&flags[0], SIP_INSECURE);
25517       set_insecure_flags(&flags[0], v->value, v->lineno);   
25518    } else if (!strcasecmp(v->name, "progressinband")) {
25519       ast_set_flag(&mask[0], SIP_PROG_INBAND);
25520       ast_clear_flag(&flags[0], SIP_PROG_INBAND);
25521       if (ast_true(v->value))
25522          ast_set_flag(&flags[0], SIP_PROG_INBAND_YES);
25523       else if (strcasecmp(v->value, "never"))
25524          ast_set_flag(&flags[0], SIP_PROG_INBAND_NO);
25525    } else if (!strcasecmp(v->name, "promiscredir")) {
25526       ast_set_flag(&mask[0], SIP_PROMISCREDIR);
25527       ast_set2_flag(&flags[0], ast_true(v->value), SIP_PROMISCREDIR);
25528    } else if (!strcasecmp(v->name, "videosupport")) {
25529       if (!strcasecmp(v->value, "always")) {
25530          ast_set_flag(&mask[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS);
25531          ast_set_flag(&flags[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS);
25532       } else {
25533          ast_set_flag(&mask[1], SIP_PAGE2_VIDEOSUPPORT);
25534          ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_VIDEOSUPPORT);
25535       }
25536    } else if (!strcasecmp(v->name, "textsupport")) {
25537       ast_set_flag(&mask[1], SIP_PAGE2_TEXTSUPPORT);
25538       ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_TEXTSUPPORT);
25539       res = 1;
25540    } else if (!strcasecmp(v->name, "allowoverlap")) {
25541       ast_set_flag(&mask[1], SIP_PAGE2_ALLOWOVERLAP);
25542       ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_ALLOWOVERLAP);
25543    } else if (!strcasecmp(v->name, "allowsubscribe")) {
25544       ast_set_flag(&mask[1], SIP_PAGE2_ALLOWSUBSCRIBE);
25545       ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_ALLOWSUBSCRIBE);
25546    } else if (!strcasecmp(v->name, "ignoresdpversion")) {
25547       ast_set_flag(&mask[1], SIP_PAGE2_IGNORESDPVERSION);
25548       ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_IGNORESDPVERSION);
25549    } else if (!strcasecmp(v->name, "faxdetect")) {
25550       ast_set_flag(&mask[1], SIP_PAGE2_FAX_DETECT);
25551       if (ast_true(v->value)) {
25552          ast_set_flag(&flags[1], SIP_PAGE2_FAX_DETECT_BOTH);
25553       } else if (ast_false(v->value)) {
25554          ast_clear_flag(&flags[1], SIP_PAGE2_FAX_DETECT_BOTH);
25555       } else {
25556          char *buf = ast_strdupa(v->value);
25557          char *word, *next = buf;
25558 
25559          while ((word = strsep(&next, ","))) {
25560             if (!strcasecmp(word, "cng")) {
25561                ast_set_flag(&flags[1], SIP_PAGE2_FAX_DETECT_CNG);
25562             } else if (!strcasecmp(word, "t38")) {
25563                ast_set_flag(&flags[1], SIP_PAGE2_FAX_DETECT_T38);
25564             } else {
25565                ast_log(LOG_WARNING, "Unknown faxdetect mode '%s' on line %d.\n", word, v->lineno);
25566             }
25567          }
25568       }
25569    } else if (!strcasecmp(v->name, "rfc2833compensate")) {
25570       ast_set_flag(&mask[1], SIP_PAGE2_RFC2833_COMPENSATE);
25571       ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_RFC2833_COMPENSATE);
25572    } else if (!strcasecmp(v->name, "buggymwi")) {
25573       ast_set_flag(&mask[1], SIP_PAGE2_BUGGY_MWI);
25574       ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_BUGGY_MWI);
25575    } else
25576       res = 0;
25577 
25578    return res;
25579 }
25580 
25581 /*! \brief Add SIP domain to list of domains we are responsible for */
25582 static int add_sip_domain(const char *domain, const enum domain_mode mode, const char *context)
25583 {
25584    struct domain *d;
25585 
25586    if (ast_strlen_zero(domain)) {
25587       ast_log(LOG_WARNING, "Zero length domain.\n");
25588       return 1;
25589    }
25590 
25591    if (!(d = ast_calloc(1, sizeof(*d))))
25592       return 0;
25593 
25594    ast_copy_string(d->domain, domain, sizeof(d->domain));
25595 
25596    if (!ast_strlen_zero(context))
25597       ast_copy_string(d->context, context, sizeof(d->context));
25598 
25599    d->mode = mode;
25600 
25601    AST_LIST_LOCK(&domain_list);
25602    AST_LIST_INSERT_TAIL(&domain_list, d, list);
25603    AST_LIST_UNLOCK(&domain_list);
25604 
25605    if (sipdebug)  
25606       ast_debug(1, "Added local SIP domain '%s'\n", domain);
25607 
25608    return 1;
25609 }
25610 
25611 /*! \brief  check_sip_domain: Check if domain part of uri is local to our server */
25612 static int check_sip_domain(const char *domain, char *context, size_t len)
25613 {
25614    struct domain *d;
25615    int result = 0;
25616 
25617    AST_LIST_LOCK(&domain_list);
25618    AST_LIST_TRAVERSE(&domain_list, d, list) {
25619       if (strcasecmp(d->domain, domain))
25620          continue;
25621 
25622       if (len && !ast_strlen_zero(d->context))
25623          ast_copy_string(context, d->context, len);
25624       
25625       result = 1;
25626       break;
25627    }
25628    AST_LIST_UNLOCK(&domain_list);
25629 
25630    return result;
25631 }
25632 
25633 /*! \brief Clear our domain list (at reload) */
25634 static void clear_sip_domains(void)
25635 {
25636    struct domain *d;
25637 
25638    AST_LIST_LOCK(&domain_list);
25639    while ((d = AST_LIST_REMOVE_HEAD(&domain_list, list)))
25640       ast_free(d);
25641    AST_LIST_UNLOCK(&domain_list);
25642 }
25643 
25644 
25645 /*! \brief Add realm authentication in list */
25646 static struct sip_auth *add_realm_authentication(struct sip_auth *authlist, const char *configuration, int lineno)
25647 {
25648    char authcopy[256];
25649    char *username=NULL, *realm=NULL, *secret=NULL, *md5secret=NULL;
25650    struct sip_auth *a, *b, *auth;
25651 
25652    if (ast_strlen_zero(configuration))
25653       return authlist;
25654 
25655    ast_debug(1, "Auth config ::  %s\n", configuration);
25656 
25657    ast_copy_string(authcopy, configuration, sizeof(authcopy));
25658    username = authcopy;
25659 
25660    /* split user[:secret] and relm */
25661    realm = strrchr(username, '@');
25662    if (realm)
25663       *realm++ = '\0';
25664    if (ast_strlen_zero(username) || ast_strlen_zero(realm)) {
25665       ast_log(LOG_WARNING, "Format for authentication entry is user[:secret]@realm at line %d\n", lineno);
25666       return authlist;
25667    }
25668 
25669    /* parse username at ':' for secret, or '#" for md5secret */
25670    if ((secret = strchr(username, ':'))) {
25671       *secret++ = '\0';
25672    } else if ((md5secret = strchr(username, '#'))) {
25673       *md5secret++ = '\0';
25674    }
25675 
25676    if (!(auth = ast_calloc(1, sizeof(*auth))))
25677       return authlist;
25678 
25679    ast_copy_string(auth->realm, realm, sizeof(auth->realm));
25680    ast_copy_string(auth->username, username, sizeof(auth->username));
25681    if (secret)
25682       ast_copy_string(auth->secret, secret, sizeof(auth->secret));
25683    if (md5secret)
25684       ast_copy_string(auth->md5secret, md5secret, sizeof(auth->md5secret));
25685 
25686    /* find the end of the list */
25687    for (b = NULL, a = authlist; a ; b = a, a = a->next)
25688       ;
25689    if (b)
25690       b->next = auth;   /* Add structure add end of list */
25691    else
25692       authlist = auth;
25693 
25694    ast_verb(3, "Added authentication for realm %s\n", realm);
25695 
25696    return authlist;
25697 
25698 }
25699 
25700 /*! \brief Clear realm authentication list (at reload) */
25701 static int clear_realm_authentication(struct sip_auth *authlist)
25702 {
25703    struct sip_auth *a = authlist;
25704    struct sip_auth *b;
25705 
25706    while (a) {
25707       b = a;
25708       a = a->next;
25709       ast_free(b);
25710    }
25711 
25712    return 1;
25713 }
25714 
25715 /*! \brief Find authentication for a specific realm */
25716 static struct sip_auth *find_realm_authentication(struct sip_auth *authlist, const char *realm)
25717 {
25718    struct sip_auth *a;
25719 
25720    for (a = authlist; a; a = a->next) {
25721       if (!strcasecmp(a->realm, realm))
25722          break;
25723    }
25724 
25725    return a;
25726 }
25727 
25728 /*! \brief
25729  * implement the setvar config line
25730  */
25731 static struct ast_variable *add_var(const char *buf, struct ast_variable *list)
25732 {
25733    struct ast_variable *tmpvar = NULL;
25734    char *varname = ast_strdupa(buf), *varval = NULL;
25735    
25736    if ((varval = strchr(varname, '='))) {
25737       *varval++ = '\0';
25738       if ((tmpvar = ast_variable_new(varname, varval, ""))) {
25739          tmpvar->next = list;
25740          list = tmpvar;
25741       }
25742    }
25743    return list;
25744 }
25745 
25746 /*! \brief Set peer defaults before configuring specific configurations */
25747 static void set_peer_defaults(struct sip_peer *peer)
25748 {
25749    if (peer->expire == 0) {
25750       /* Don't reset expire or port time during reload
25751          if we have an active registration
25752       */
25753       peer->expire = -1;
25754       peer->pokeexpire = -1;
25755       set_socket_transport(&peer->socket, SIP_TRANSPORT_UDP);
25756    }
25757    peer->type = SIP_TYPE_PEER;
25758    ast_copy_flags(&peer->flags[0], &global_flags[0], SIP_FLAGS_TO_COPY);
25759    ast_copy_flags(&peer->flags[1], &global_flags[1], SIP_PAGE2_FLAGS_TO_COPY);
25760    ast_copy_flags(&peer->flags[2], &global_flags[2], SIP_PAGE3_FLAGS_TO_COPY);
25761    ast_string_field_set(peer, context, sip_cfg.default_context);
25762    ast_string_field_set(peer, subscribecontext, sip_cfg.default_subscribecontext);
25763    ast_string_field_set(peer, language, default_language);
25764    ast_string_field_set(peer, mohinterpret, default_mohinterpret);
25765    ast_string_field_set(peer, mohsuggest, default_mohsuggest);
25766    ast_string_field_set(peer, engine, default_engine);
25767    ast_sockaddr_setnull(&peer->addr);
25768    ast_sockaddr_setnull(&peer->defaddr);
25769    peer->capability = sip_cfg.capability;
25770    peer->maxcallbitrate = default_maxcallbitrate;
25771    peer->rtptimeout = global_rtptimeout;
25772    peer->rtpholdtimeout = global_rtpholdtimeout;
25773    peer->rtpkeepalive = global_rtpkeepalive;
25774    peer->allowtransfer = sip_cfg.allowtransfer;
25775    peer->autoframing = global_autoframing;
25776    peer->t38_maxdatagram = global_t38_maxdatagram;
25777    peer->qualifyfreq = global_qualifyfreq;
25778    if (global_callcounter)
25779       peer->call_limit=INT_MAX;
25780    ast_string_field_set(peer, vmexten, default_vmexten);
25781    ast_string_field_set(peer, secret, "");
25782    ast_string_field_set(peer, remotesecret, "");
25783    ast_string_field_set(peer, md5secret, "");
25784    ast_string_field_set(peer, cid_num, "");
25785    ast_string_field_set(peer, cid_name, "");
25786    ast_string_field_set(peer, cid_tag, "");
25787    ast_string_field_set(peer, fromdomain, "");
25788    ast_string_field_set(peer, fromuser, "");
25789    ast_string_field_set(peer, regexten, "");
25790    peer->callgroup = 0;
25791    peer->pickupgroup = 0;
25792    peer->maxms = default_qualify;
25793    peer->prefs = default_prefs;
25794    peer->stimer.st_mode_oper = global_st_mode;  /* Session-Timers */
25795    peer->stimer.st_ref = global_st_refresher;
25796    peer->stimer.st_min_se = global_min_se;
25797    peer->stimer.st_max_se = global_max_se;
25798    peer->timer_t1 = global_t1;
25799    peer->timer_b = global_timer_b;
25800    clear_peer_mailboxes(peer);
25801    peer->disallowed_methods = sip_cfg.disallowed_methods;
25802    peer->transports = default_transports;
25803    peer->default_outbound_transport = default_primary_transport;
25804 }
25805 
25806 /*! \brief Create temporary peer (used in autocreatepeer mode) */
25807 static struct sip_peer *temp_peer(const char *name)
25808 {
25809    struct sip_peer *peer;
25810 
25811    if (!(peer = ao2_t_alloc(sizeof(*peer), sip_destroy_peer_fn, "allocate a peer struct")))
25812       return NULL;
25813 
25814    if (ast_string_field_init(peer, 512)) {
25815       ao2_t_ref(peer, -1, "failed to string_field_init, drop peer");
25816       return NULL;
25817    }
25818    
25819    if (!(peer->cc_params = ast_cc_config_params_init())) {
25820       ao2_t_ref(peer, -1, "failed to allocate cc_params for peer");
25821       return NULL;
25822    }
25823 
25824    ast_atomic_fetchadd_int(&apeerobjs, 1);
25825    set_peer_defaults(peer);
25826 
25827    ast_copy_string(peer->name, name, sizeof(peer->name));
25828 
25829    peer->selfdestruct = TRUE;
25830    peer->host_dynamic = TRUE;
25831    peer->prefs = default_prefs;
25832    reg_source_db(peer);
25833 
25834    return peer;
25835 }
25836 
25837 /*! \todo document this function */
25838 static void add_peer_mailboxes(struct sip_peer *peer, const char *value)
25839 {
25840    char *next, *mbox, *context;
25841 
25842    next = ast_strdupa(value);
25843 
25844    while ((mbox = context = strsep(&next, ","))) {
25845       struct sip_mailbox *mailbox;
25846       int duplicate = 0;
25847 
25848       strsep(&context, "@");
25849 
25850       if (ast_strlen_zero(mbox)) {
25851          continue;
25852       }
25853 
25854       /* Check whether the mailbox is already in the list */
25855       AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
25856          if (!strcmp(mailbox->mailbox, mbox) && !strcmp(S_OR(mailbox->context, ""), S_OR(context, ""))) {
25857             duplicate = 1;
25858             mailbox->delme = 0;
25859             break;
25860          }
25861       }
25862       if (duplicate) {
25863          continue;
25864       }
25865 
25866       if (!(mailbox = ast_calloc(1, sizeof(*mailbox) + strlen(mbox) + strlen(S_OR(context, ""))))) {
25867          continue;
25868       }
25869 
25870       if (!ast_strlen_zero(context)) {
25871          mailbox->context = mailbox->mailbox + strlen(mbox) + 1;
25872          strcpy(mailbox->context, context); /* SAFE */
25873       }
25874       strcpy(mailbox->mailbox, mbox); /* SAFE */
25875 
25876       AST_LIST_INSERT_TAIL(&peer->mailboxes, mailbox, entry);
25877    }
25878 }
25879 
25880 /*! \brief Build peer from configuration (file or realtime static/dynamic) */
25881 static struct sip_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime, int devstate_only)
25882 {
25883    struct sip_peer *peer = NULL;
25884    struct ast_ha *oldha = NULL;
25885    struct ast_ha *olddirectmediaha = NULL;
25886    int found = 0;
25887    int firstpass = 1;
25888    uint16_t port = 0;
25889    int format = 0;      /* Ama flags */
25890    int timerb_set = 0, timert1_set = 0;
25891    time_t regseconds = 0;
25892    struct ast_flags peerflags[3] = {{(0)}};
25893    struct ast_flags mask[3] = {{(0)}};
25894    char callback[256] = "";
25895    struct sip_peer tmp_peer;
25896    const char *srvlookup = NULL;
25897    static int deprecation_warning = 1;
25898    int alt_fullcontact = alt ? 1 : 0, headercount = 0;
25899    struct ast_str *fullcontact = ast_str_alloca(512);
25900 
25901    if (!realtime || ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
25902       /* Note we do NOT use find_peer here, to avoid realtime recursion */
25903       /* We also use a case-sensitive comparison (unlike find_peer) so
25904          that case changes made to the peer name will be properly handled
25905          during reload
25906       */
25907       ast_copy_string(tmp_peer.name, name, sizeof(tmp_peer.name));
25908       peer = ao2_t_find(peers, &tmp_peer, OBJ_POINTER | OBJ_UNLINK, "find and unlink peer from peers table");
25909    }
25910 
25911    if (peer) {
25912       /* Already in the list, remove it and it will be added back (or FREE'd)  */
25913       found++;
25914       if (!(peer->the_mark))
25915          firstpass = 0;
25916    } else {
25917       if (!(peer = ao2_t_alloc(sizeof(*peer), sip_destroy_peer_fn, "allocate a peer struct")))
25918          return NULL;
25919 
25920       if (ast_string_field_init(peer, 512)) {
25921          ao2_t_ref(peer, -1, "failed to string_field_init, drop peer");
25922          return NULL;
25923       }
25924 
25925       if (!(peer->cc_params = ast_cc_config_params_init())) {
25926          ao2_t_ref(peer, -1, "failed to allocate cc_params for peer");
25927          return NULL;
25928       }
25929 
25930       if (realtime && !ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
25931          ast_atomic_fetchadd_int(&rpeerobjs, 1);
25932          ast_debug(3, "-REALTIME- peer built. Name: %s. Peer objects: %d\n", name, rpeerobjs);
25933       } else
25934          ast_atomic_fetchadd_int(&speerobjs, 1);
25935    }
25936 
25937    /* Note that our peer HAS had its reference count increased */
25938    if (firstpass) {
25939       peer->lastmsgssent = -1;
25940       oldha = peer->ha;
25941       peer->ha = NULL;
25942       olddirectmediaha = peer->directmediaha;
25943       peer->directmediaha = NULL;
25944       set_peer_defaults(peer);   /* Set peer defaults */
25945       peer->type = 0;
25946    }
25947    if (!found && name)
25948       ast_copy_string(peer->name, name, sizeof(peer->name));
25949 
25950    /* If we have channel variables, remove them (reload) */
25951    if (peer->chanvars) {
25952       ast_variables_destroy(peer->chanvars);
25953       peer->chanvars = NULL;
25954       /* XXX should unregister ? */
25955    }
25956 
25957    if (found)
25958       peer->portinuri = 0;
25959 
25960    /* If we have realm authentication information, remove them (reload) */
25961    clear_realm_authentication(peer->auth);
25962    peer->auth = NULL;
25963    /* clear the transport information.  We will detect if a default value is required after parsing the config */
25964    peer->default_outbound_transport = 0;
25965    peer->transports = 0;
25966 
25967    if (!devstate_only) {
25968       struct sip_mailbox *mailbox;
25969       AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
25970          mailbox->delme = 1;
25971       }
25972    }
25973 
25974    for (; v || ((v = alt) && !(alt=NULL)); v = v->next) {
25975       if (!devstate_only) {
25976          if (handle_common_options(&peerflags[0], &mask[0], v)) {
25977             continue;
25978          }
25979          if (handle_t38_options(&peerflags[0], &mask[0], v, &peer->t38_maxdatagram)) {
25980             continue;
25981          }
25982          if (!strcasecmp(v->name, "transport") && !ast_strlen_zero(v->value)) {
25983             char *val = ast_strdupa(v->value);
25984             char *trans;
25985 
25986             while ((trans = strsep(&val, ","))) {
25987                trans = ast_skip_blanks(trans);
25988 
25989                if (!strncasecmp(trans, "udp", 3)) {
25990                   peer->transports |= SIP_TRANSPORT_UDP;
25991                } else if (!strncasecmp(trans, "tcp", 3)) {
25992                   peer->transports |= SIP_TRANSPORT_TCP;
25993                } else if (!strncasecmp(trans, "tls", 3)) {
25994                   peer->transports |= SIP_TRANSPORT_TLS;
25995                } else {
25996                   ast_log(LOG_NOTICE, "'%s' is not a valid transport type. if no other is specified, udp will be used.\n", trans);
25997                }
25998 
25999                if (!peer->default_outbound_transport) { /*!< The first transport listed should be default outbound */
26000                   peer->default_outbound_transport = peer->transports;
26001                }
26002             }
26003          } else if (realtime && !strcasecmp(v->name, "regseconds")) {
26004             ast_get_time_t(v->value, &regseconds, 0, NULL);
26005          } else if (realtime && !strcasecmp(v->name, "name")) {
26006             ast_copy_string(peer->name, v->value, sizeof(peer->name));
26007          } else if (realtime && !strcasecmp(v->name, "useragent")) {
26008             ast_string_field_set(peer, useragent, v->value);
26009          } else if (!strcasecmp(v->name, "type")) {
26010             if (!strcasecmp(v->value, "peer")) {
26011                peer->type |= SIP_TYPE_PEER;
26012             } else if (!strcasecmp(v->value, "user")) {
26013                peer->type |= SIP_TYPE_USER;
26014             } else if (!strcasecmp(v->value, "friend")) {
26015                peer->type = SIP_TYPE_USER | SIP_TYPE_PEER;
26016             }
26017          } else if (!strcasecmp(v->name, "remotesecret")) {
26018             ast_string_field_set(peer, remotesecret, v->value);
26019          } else if (!strcasecmp(v->name, "secret")) {
26020             ast_string_field_set(peer, secret, v->value);
26021          } else if (!strcasecmp(v->name, "md5secret")) {
26022             ast_string_field_set(peer, md5secret, v->value);
26023          } else if (!strcasecmp(v->name, "auth")) {
26024             peer->auth = add_realm_authentication(peer->auth, v->value, v->lineno);
26025          } else if (!strcasecmp(v->name, "callerid")) {
26026             char cid_name[80] = { '\0' }, cid_num[80] = { '\0' };
26027 
26028             ast_callerid_split(v->value, cid_name, sizeof(cid_name), cid_num, sizeof(cid_num));
26029             ast_string_field_set(peer, cid_name, cid_name);
26030             ast_string_field_set(peer, cid_num, cid_num);
26031          } else if (!strcasecmp(v->name, "mwi_from")) {
26032             ast_string_field_set(peer, mwi_from, v->value);
26033          } else if (!strcasecmp(v->name, "fullname")) {
26034             ast_string_field_set(peer, cid_name, v->value);
26035          } else if (!strcasecmp(v->name, "trunkname")) {
26036             /* This is actually for a trunk, so we don't want to override callerid */
26037             ast_string_field_set(peer, cid_name, "");
26038          } else if (!strcasecmp(v->name, "cid_number")) {
26039             ast_string_field_set(peer, cid_num, v->value);
26040          } else if (!strcasecmp(v->name, "cid_tag")) {
26041             ast_string_field_set(peer, cid_tag, v->value);
26042          } else if (!strcasecmp(v->name, "context")) {
26043             ast_string_field_set(peer, context, v->value);
26044             ast_set_flag(&peer->flags[1], SIP_PAGE2_HAVEPEERCONTEXT);
26045          } else if (!strcasecmp(v->name, "subscribecontext")) {
26046             ast_string_field_set(peer, subscribecontext, v->value);
26047          } else if (!strcasecmp(v->name, "fromdomain")) {
26048             char *fromdomainport;
26049             ast_string_field_set(peer, fromdomain, v->value);
26050             if ((fromdomainport = strchr(peer->fromdomain, ':'))) {
26051                *fromdomainport++ = '\0';
26052                if (!(peer->fromdomainport = port_str2int(fromdomainport, 0))) {
26053                   ast_log(LOG_NOTICE, "'%s' is not a valid port number for fromdomain.\n",fromdomainport);
26054                }
26055             } else {
26056                peer->fromdomainport = STANDARD_SIP_PORT;
26057             }
26058          } else if (!strcasecmp(v->name, "usereqphone")) {
26059             ast_set2_flag(&peer->flags[0], ast_true(v->value), SIP_USEREQPHONE);
26060          } else if (!strcasecmp(v->name, "fromuser")) {
26061             ast_string_field_set(peer, fromuser, v->value);
26062          } else if (!strcasecmp(v->name, "outboundproxy")) {
26063             char *tok, *proxyname;
26064 
26065             if (ast_strlen_zero(v->value)) {
26066                ast_log(LOG_WARNING, "no value given for outbound proxy on line %d of sip.conf.", v->lineno);
26067                continue;
26068             }
26069 
26070             peer->outboundproxy =
26071                 ao2_alloc(sizeof(*peer->outboundproxy), NULL);
26072 
26073             tok = ast_skip_blanks(strtok(ast_strdupa(v->value), ","));
26074 
26075             sip_parse_host(tok, v->lineno, &proxyname,
26076                       &peer->outboundproxy->port,
26077                       &peer->outboundproxy->transport);
26078 
26079             tok = ast_skip_blanks(strtok(ast_strdupa(v->value), ","));
26080 
26081             if ((tok = strtok(NULL, ","))) {
26082                peer->outboundproxy->force = !strncasecmp(ast_skip_blanks(tok), "force", 5);
26083             } else {
26084                peer->outboundproxy->force = FALSE;
26085             }
26086 
26087             if (ast_strlen_zero(proxyname)) {
26088                ast_log(LOG_WARNING, "you must specify a name for the outboundproxy on line %d of sip.conf.", v->lineno);
26089                sip_cfg.outboundproxy.name[0] = '\0';
26090                continue;
26091             }
26092 
26093             ast_copy_string(peer->outboundproxy->name, proxyname, sizeof(peer->outboundproxy->name));
26094 
26095             proxy_update(peer->outboundproxy);
26096          } else if (!strcasecmp(v->name, "host")) {
26097             if (!strcasecmp(v->value, "dynamic")) {
26098                /* They'll register with us */
26099                if (!found || !peer->host_dynamic) {
26100                   /* Initialize stuff if this is a new peer, or if it used to
26101                    * not be dynamic before the reload. */
26102                   ast_sockaddr_setnull(&peer->addr);
26103                }
26104                peer->host_dynamic = TRUE;
26105             } else {
26106                /* Non-dynamic.  Make sure we become that way if we're not */
26107                AST_SCHED_DEL_UNREF(sched, peer->expire,
26108                      unref_peer(peer, "removing register expire ref"));
26109                peer->host_dynamic = FALSE;
26110                srvlookup = v->value;
26111             }
26112          } else if (!strcasecmp(v->name, "defaultip")) {
26113             if (!ast_strlen_zero(v->value) && ast_get_ip(&peer->defaddr, v->value)) {
26114                unref_peer(peer, "unref_peer: from build_peer defaultip");
26115                return NULL;
26116             }
26117          } else if (!strcasecmp(v->name, "permit") || !strcasecmp(v->name, "deny")) {
26118             int ha_error = 0;
26119             if (!ast_strlen_zero(v->value)) {
26120                peer->ha = ast_append_ha(v->name, v->value, peer->ha, &ha_error);
26121             }
26122             if (ha_error) {
26123                ast_log(LOG_ERROR, "Bad ACL entry in configuration line %d : %s\n", v->lineno, v->value);
26124             }
26125          } else if (!strcasecmp(v->name, "contactpermit") || !strcasecmp(v->name, "contactdeny")) {
26126             int ha_error = 0;
26127             if (!ast_strlen_zero(v->value)) {
26128                peer->contactha = ast_append_ha(v->name + 7, v->value, peer->contactha, &ha_error);
26129             }
26130             if (ha_error) {
26131                ast_log(LOG_ERROR, "Bad ACL entry in configuration line %d : %s\n", v->lineno, v->value);
26132             }
26133          } else if (!strcasecmp(v->name, "directmediapermit") || !strcasecmp(v->name, "directmediadeny")) {
26134             int ha_error = 0;
26135             peer->directmediaha = ast_append_ha(v->name + 11, v->value, peer->directmediaha, &ha_error);
26136             if (ha_error) {
26137                ast_log(LOG_ERROR, "Bad directmedia ACL entry in configuration line %d : %s\n", v->lineno, v->value);
26138             }
26139          } else if (!strcasecmp(v->name, "port")) {
26140             peer->portinuri = 1;
26141             if (!(port = port_str2int(v->value, 0))) {
26142                if (realtime) {
26143                   /* If stored as integer, could be 0 for some DBs (notably MySQL) */
26144                   peer->portinuri = 0;
26145                } else {
26146                   ast_log(LOG_WARNING, "Invalid peer port configuration at line %d : %s\n", v->lineno, v->value);
26147                }
26148             }
26149          } else if (!strcasecmp(v->name, "callingpres")) {
26150             peer->callingpres = ast_parse_caller_presentation(v->value);
26151             if (peer->callingpres == -1) {
26152                peer->callingpres = atoi(v->value);
26153             }
26154          } else if (!strcasecmp(v->name, "username") || !strcmp(v->name, "defaultuser")) {   /* "username" is deprecated */
26155             ast_string_field_set(peer, username, v->value);
26156             if (!strcasecmp(v->name, "username")) {
26157                if (deprecation_warning) {
26158                   ast_log(LOG_NOTICE, "The 'username' field for sip peers has been deprecated in favor of the term 'defaultuser'\n");
26159                   deprecation_warning = 0;
26160                }
26161                peer->deprecated_username = 1;
26162             }
26163          } else if (!strcasecmp(v->name, "language")) {
26164             ast_string_field_set(peer, language, v->value);
26165          } else if (!strcasecmp(v->name, "regexten")) {
26166             ast_string_field_set(peer, regexten, v->value);
26167          } else if (!strcasecmp(v->name, "callbackextension")) {
26168             ast_copy_string(callback, v->value, sizeof(callback));
26169          } else if (!strcasecmp(v->name, "amaflags")) {
26170             format = ast_cdr_amaflags2int(v->value);
26171             if (format < 0) {
26172                ast_log(LOG_WARNING, "Invalid AMA Flags for peer: %s at line %d\n", v->value, v->lineno);
26173             } else {
26174                peer->amaflags = format;
26175             }
26176          } else if (!strcasecmp(v->name, "maxforwards")) {
26177             if ((sscanf(v->value, "%30d", &peer->maxforwards) != 1) || (peer->maxforwards < 1)) {
26178                ast_log(LOG_WARNING, "'%s' is not a valid maxforwards value at line %d.  Using default.\n", v->value, v->lineno);
26179                peer->maxforwards = sip_cfg.default_max_forwards;
26180             }
26181          } else if (!strcasecmp(v->name, "accountcode")) {
26182             ast_string_field_set(peer, accountcode, v->value);
26183          } else if (!strcasecmp(v->name, "mohinterpret")) {
26184             ast_string_field_set(peer, mohinterpret, v->value);
26185          } else if (!strcasecmp(v->name, "mohsuggest")) {
26186             ast_string_field_set(peer, mohsuggest, v->value);
26187          } else if (!strcasecmp(v->name, "parkinglot")) {
26188             ast_string_field_set(peer, parkinglot, v->value);
26189          } else if (!strcasecmp(v->name, "rtp_engine")) {
26190             ast_string_field_set(peer, engine, v->value);
26191          } else if (!strcasecmp(v->name, "mailbox")) {
26192             add_peer_mailboxes(peer, v->value);
26193          } else if (!strcasecmp(v->name, "hasvoicemail")) {
26194             /* People expect that if 'hasvoicemail' is set, that the mailbox will
26195              * be also set, even if not explicitly specified. */
26196             if (ast_true(v->value) && AST_LIST_EMPTY(&peer->mailboxes)) {
26197                add_peer_mailboxes(peer, name);
26198             }
26199          } else if (!strcasecmp(v->name, "subscribemwi")) {
26200             ast_set2_flag(&peer->flags[1], ast_true(v->value), SIP_PAGE2_SUBSCRIBEMWIONLY);
26201          } else if (!strcasecmp(v->name, "vmexten")) {
26202             ast_string_field_set(peer, vmexten, v->value);
26203          } else if (!strcasecmp(v->name, "callgroup")) {
26204             peer->callgroup = ast_get_group(v->value);
26205          } else if (!strcasecmp(v->name, "allowtransfer")) {
26206             peer->allowtransfer = ast_true(v->value) ? TRANSFER_OPENFORALL : TRANSFER_CLOSED;
26207          } else if (!strcasecmp(v->name, "pickupgroup")) {
26208             peer->pickupgroup = ast_get_group(v->value);
26209          } else if (!strcasecmp(v->name, "allow")) {
26210             int error =  ast_parse_allow_disallow(&peer->prefs, &peer->capability, v->value, TRUE);
26211             if (error) {
26212                ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
26213             }
26214          } else if (!strcasecmp(v->name, "disallow")) {
26215             int error =  ast_parse_allow_disallow(&peer->prefs, &peer->capability, v->value, FALSE);
26216             if (error) {
26217                ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
26218             }
26219          } else if (!strcasecmp(v->name, "preferred_codec_only")) {
26220             ast_set2_flag(&peer->flags[1], ast_true(v->value), SIP_PAGE2_PREFERRED_CODEC);
26221          } else if (!strcasecmp(v->name, "registertrying")) {
26222             ast_set2_flag(&peer->flags[1], ast_true(v->value), SIP_PAGE2_REGISTERTRYING);
26223          } else if (!strcasecmp(v->name, "autoframing")) {
26224             peer->autoframing = ast_true(v->value);
26225          } else if (!strcasecmp(v->name, "rtptimeout")) {
26226             if ((sscanf(v->value, "%30d", &peer->rtptimeout) != 1) || (peer->rtptimeout < 0)) {
26227                ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d.  Using default.\n", v->value, v->lineno);
26228                peer->rtptimeout = global_rtptimeout;
26229             }
26230          } else if (!strcasecmp(v->name, "rtpholdtimeout")) {
26231             if ((sscanf(v->value, "%30d", &peer->rtpholdtimeout) != 1) || (peer->rtpholdtimeout < 0)) {
26232                ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d.  Using default.\n", v->value, v->lineno);
26233                peer->rtpholdtimeout = global_rtpholdtimeout;
26234             }
26235          } else if (!strcasecmp(v->name, "rtpkeepalive")) {
26236             if ((sscanf(v->value, "%30d", &peer->rtpkeepalive) != 1) || (peer->rtpkeepalive < 0)) {
26237                ast_log(LOG_WARNING, "'%s' is not a valid RTP keepalive time at line %d.  Using default.\n", v->value, v->lineno);
26238                peer->rtpkeepalive = global_rtpkeepalive;
26239             }
26240          } else if (!strcasecmp(v->name, "timert1")) {
26241             if ((sscanf(v->value, "%30d", &peer->timer_t1) != 1) || (peer->timer_t1 < 200) || (peer->timer_t1 < global_t1min)) {
26242                ast_log(LOG_WARNING, "'%s' is not a valid T1 time at line %d.  Using default.\n", v->value, v->lineno);
26243                peer->timer_t1 = global_t1min;
26244             }
26245             timert1_set = 1;
26246          } else if (!strcasecmp(v->name, "timerb")) {
26247             if ((sscanf(v->value, "%30d", &peer->timer_b) != 1) || (peer->timer_b < 200)) {
26248                ast_log(LOG_WARNING, "'%s' is not a valid Timer B time at line %d.  Using default.\n", v->value, v->lineno);
26249                peer->timer_b = global_timer_b;
26250             }
26251             timerb_set = 1;
26252          } else if (!strcasecmp(v->name, "setvar")) {
26253             peer->chanvars = add_var(v->value, peer->chanvars);
26254          } else if (!strcasecmp(v->name, "header")) {
26255             char tmp[4096];
26256             snprintf(tmp, sizeof(tmp), "__SIPADDHEADERpre%2d=%s", ++headercount, v->value);
26257             peer->chanvars = add_var(tmp, peer->chanvars);
26258          } else if (!strcasecmp(v->name, "qualifyfreq")) {
26259             int i;
26260             if (sscanf(v->value, "%30d", &i) == 1) {
26261                peer->qualifyfreq = i * 1000;
26262             } else {
26263                ast_log(LOG_WARNING, "Invalid qualifyfreq number '%s' at line %d of %s\n", v->value, v->lineno, config);
26264                peer->qualifyfreq = global_qualifyfreq;
26265             }
26266          } else if (!strcasecmp(v->name, "maxcallbitrate")) {
26267             peer->maxcallbitrate = atoi(v->value);
26268             if (peer->maxcallbitrate < 0) {
26269                peer->maxcallbitrate = default_maxcallbitrate;
26270             }
26271          } else if (!strcasecmp(v->name, "session-timers")) {
26272             int i = (int) str2stmode(v->value);
26273             if (i < 0) {
26274                ast_log(LOG_WARNING, "Invalid session-timers '%s' at line %d of %s\n", v->value, v->lineno, config);
26275                peer->stimer.st_mode_oper = global_st_mode;
26276             } else {
26277                peer->stimer.st_mode_oper = i;
26278             }
26279          } else if (!strcasecmp(v->name, "session-expires")) {
26280             if (sscanf(v->value, "%30d", &peer->stimer.st_max_se) != 1) {
26281                ast_log(LOG_WARNING, "Invalid session-expires '%s' at line %d of %s\n", v->value, v->lineno, config);
26282                peer->stimer.st_max_se = global_max_se;
26283             }
26284          } else if (!strcasecmp(v->name, "session-minse")) {
26285             if (sscanf(v->value, "%30d", &peer->stimer.st_min_se) != 1) {
26286                ast_log(LOG_WARNING, "Invalid session-minse '%s' at line %d of %s\n", v->value, v->lineno, config);
26287                peer->stimer.st_min_se = global_min_se;
26288             }
26289             if (peer->stimer.st_min_se < 90) {
26290                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);
26291                peer->stimer.st_min_se = global_min_se;
26292             }
26293          } else if (!strcasecmp(v->name, "session-refresher")) {
26294             int i = (int) str2strefresher(v->value);
26295             if (i < 0) {
26296                ast_log(LOG_WARNING, "Invalid session-refresher '%s' at line %d of %s\n", v->value, v->lineno, config);
26297                peer->stimer.st_ref = global_st_refresher;
26298             } else {
26299                peer->stimer.st_ref = i;
26300             }
26301          } else if (!strcasecmp(v->name, "disallowed_methods")) {
26302             char *disallow = ast_strdupa(v->value);
26303             mark_parsed_methods(&peer->disallowed_methods, disallow);
26304          } else if (!strcasecmp(v->name, "unsolicited_mailbox")) {
26305             ast_string_field_set(peer, unsolicited_mailbox, v->value);
26306          } else if (!strcasecmp(v->name, "use_q850_reason")) {
26307             ast_set2_flag(&peer->flags[1], ast_true(v->value), SIP_PAGE2_Q850_REASON);
26308          } else if (!strcasecmp(v->name, "encryption")) {
26309             ast_set2_flag(&peer->flags[1], ast_true(v->value), SIP_PAGE2_USE_SRTP);
26310          } else if (!strcasecmp(v->name, "snom_aoc_enabled")) {
26311             ast_set2_flag(&peer->flags[2], ast_true(v->value), SIP_PAGE3_SNOM_AOC);
26312          }
26313       }
26314 
26315       /* These apply to devstate lookups */
26316       if (realtime && !strcasecmp(v->name, "lastms")) {
26317          sscanf(v->value, "%30d", &peer->lastms);
26318       } else if (realtime && !strcasecmp(v->name, "ipaddr") && !ast_strlen_zero(v->value) ) {
26319          ast_sockaddr_parse(&peer->addr, v->value, PARSE_PORT_FORBID);
26320       } else if (realtime && !strcasecmp(v->name, "fullcontact")) {
26321          if (alt_fullcontact && !alt) {
26322             /* Reset, because the alternate also has a fullcontact and we
26323              * do NOT want the field value to be doubled. It might be
26324              * tempting to skip this, but the first table might not have
26325              * fullcontact and since we're here, we know that the alternate
26326              * absolutely does. */
26327             alt_fullcontact = 0;
26328             ast_str_reset(fullcontact);
26329          }
26330          /* Reconstruct field, because realtime separates our value at the ';' */
26331          if (fullcontact->used > 0) {
26332             ast_str_append(&fullcontact, 0, ";%s", v->value);
26333          } else {
26334             ast_str_set(&fullcontact, 0, "%s", v->value);
26335          }
26336       } else if (!strcasecmp(v->name, "qualify")) {
26337          if (!strcasecmp(v->value, "no")) {
26338             peer->maxms = 0;
26339          } else if (!strcasecmp(v->value, "yes")) {
26340             peer->maxms = default_qualify ? default_qualify : DEFAULT_MAXMS;
26341          } else if (sscanf(v->value, "%30d", &peer->maxms) != 1) {
26342             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);
26343             peer->maxms = 0;
26344          }
26345          if (realtime && !ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) && peer->maxms > 0) {
26346             /* This would otherwise cause a network storm, where the
26347              * qualify response refreshes the peer from the database,
26348              * which in turn causes another qualify to be sent, ad
26349              * infinitum. */
26350             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);
26351             peer->maxms = 0;
26352          }
26353       } else if (!strcasecmp(v->name, "callcounter")) {
26354          peer->call_limit = ast_true(v->value) ? INT_MAX : 0;
26355       } else if (!strcasecmp(v->name, "call-limit")) {
26356          peer->call_limit = atoi(v->value);
26357          if (peer->call_limit < 0) {
26358             peer->call_limit = 0;
26359          }
26360       } else if (!strcasecmp(v->name, "busylevel")) {
26361          peer->busy_level = atoi(v->value);
26362          if (peer->busy_level < 0) {
26363             peer->busy_level = 0;
26364          }
26365       } else if (ast_cc_is_config_param(v->name)) {
26366          ast_cc_set_param(peer->cc_params, v->name, v->value);
26367       }
26368    }
26369 
26370    if (!devstate_only) {
26371       struct sip_mailbox *mailbox;
26372       AST_LIST_TRAVERSE_SAFE_BEGIN(&peer->mailboxes, mailbox, entry) {
26373          if (mailbox->delme) {
26374             AST_LIST_REMOVE_CURRENT(entry);
26375             destroy_mailbox(mailbox);
26376          }
26377       }
26378       AST_LIST_TRAVERSE_SAFE_END;
26379    }
26380 
26381    if (!can_parse_xml && (ast_get_cc_agent_policy(peer->cc_params) == AST_CC_AGENT_NATIVE)) {
26382       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);
26383       ast_set_cc_agent_policy(peer->cc_params, AST_CC_AGENT_NEVER);
26384    }
26385 
26386    /* Note that Timer B is dependent upon T1 and MUST NOT be lower
26387     * than T1 * 64, according to RFC 3261, Section 17.1.1.2 */
26388    if (peer->timer_b < peer->timer_t1 * 64) {
26389       if (timerb_set && timert1_set) {
26390          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);
26391       } else if (timerb_set) {
26392          if ((peer->timer_t1 = peer->timer_b / 64) < global_t1min) {
26393             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);
26394             peer->timer_t1 = global_t1min;
26395             peer->timer_b = peer->timer_t1 * 64;
26396          }
26397          peer->timer_t1 = peer->timer_b / 64;
26398       } else {
26399          peer->timer_b = peer->timer_t1 * 64;
26400       }
26401    }
26402 
26403    if (!peer->default_outbound_transport) {
26404       /* Set default set of transports */
26405       peer->transports = default_transports;
26406       /* Set default primary transport */
26407       peer->default_outbound_transport = default_primary_transport;
26408    }
26409 
26410    /* The default transport type set during build_peer should only replace the socket.type when...
26411     * 1. Registration is not present and the socket.type and default transport types are different.
26412     * 2. The socket.type is not an acceptable transport type after rebuilding peer.
26413     * 3. The socket.type is not set yet. */
26414    if (((peer->socket.type != peer->default_outbound_transport) && (peer->expire == -1)) ||
26415       !(peer->socket.type & peer->transports) || !(peer->socket.type)) {
26416 
26417       set_socket_transport(&peer->socket, peer->default_outbound_transport);
26418    }
26419 
26420    if (ast_str_strlen(fullcontact)) {
26421       ast_string_field_set(peer, fullcontact, ast_str_buffer(fullcontact));
26422       peer->rt_fromcontact = TRUE;
26423       /* We have a hostname in the fullcontact, but if we don't have an
26424        * address listed on the entry (or if it's 'dynamic'), then we need to
26425        * parse the entry to obtain the IP address, so a dynamic host can be
26426        * contacted immediately after reload (as opposed to waiting for it to
26427        * register once again). But if we have an address for this peer and NAT was
26428        * specified, use that address instead. */
26429       /* XXX May need to revisit the final argument; does the realtime DB store whether
26430        * the original contact was over TLS or not? XXX */
26431       if (!ast_test_flag(&peer->flags[0], SIP_NAT_RPORT_PRESENT) || ast_sockaddr_isnull(&peer->addr)) {
26432          __set_address_from_contact(fullcontact->str, &peer->addr, 0);
26433       }
26434    }
26435 
26436    if (srvlookup && peer->dnsmgr == NULL) {
26437       char transport[MAXHOSTNAMELEN];
26438       char _srvlookup[MAXHOSTNAMELEN];
26439       char *params;
26440 
26441       ast_copy_string(_srvlookup, srvlookup, sizeof(_srvlookup));
26442       if ((params = strchr(_srvlookup, ';'))) {
26443          *params++ = '\0';
26444       }
26445 
26446       snprintf(transport, sizeof(transport), "_%s._%s", get_srv_service(peer->socket.type), get_srv_protocol(peer->socket.type));
26447 
26448       peer->addr.ss.ss_family = get_address_family_filter(&bindaddr); /* Filter address family */
26449       if (ast_dnsmgr_lookup(_srvlookup, &peer->addr, &peer->dnsmgr, sip_cfg.srvlookup && !peer->portinuri ? transport : NULL)) {
26450          ast_log(LOG_ERROR, "srvlookup failed for host: %s, on peer %s, removing peer\n", _srvlookup, peer->name);
26451          unref_peer(peer, "getting rid of a peer pointer");
26452          return NULL;
26453       }
26454 
26455       ast_string_field_set(peer, tohost, srvlookup);
26456 
26457       if (global_dynamic_exclude_static) {
26458          int err = 0;
26459          sip_cfg.contact_ha = ast_append_ha("deny", ast_sockaddr_stringify_addr(&peer->addr), 
26460                      sip_cfg.contact_ha, &err);
26461          if (err) {
26462             ast_log(LOG_ERROR, "Bad ACL entry in configuration line %d : %s\n", v->lineno, v->value);
26463          }
26464       }
26465    } else if (peer->dnsmgr && !peer->host_dynamic) {
26466       /* force a refresh here on reload if dnsmgr already exists and host is set. */
26467       ast_dnsmgr_refresh(peer->dnsmgr);
26468    }
26469 
26470    if (port && !realtime && peer->host_dynamic) {
26471       ast_sockaddr_set_port(&peer->defaddr, port);
26472    } else if (port) {
26473       ast_sockaddr_set_port(&peer->addr, port);
26474    }
26475 
26476    if (ast_sockaddr_port(&peer->addr) == 0) {
26477       ast_sockaddr_set_port(&peer->addr,
26478                   (peer->socket.type & SIP_TRANSPORT_TLS) ?
26479                   STANDARD_TLS_PORT : STANDARD_SIP_PORT);
26480    }
26481    if (ast_sockaddr_port(&peer->defaddr) == 0) {
26482       ast_sockaddr_set_port(&peer->defaddr,
26483                   (peer->socket.type & SIP_TRANSPORT_TLS) ?
26484                   STANDARD_TLS_PORT : STANDARD_SIP_PORT);
26485    }
26486    if (!peer->socket.port) {
26487       peer->socket.port = htons(((peer->socket.type & SIP_TRANSPORT_TLS) ? STANDARD_TLS_PORT : STANDARD_SIP_PORT));
26488    }
26489 
26490    if (!sip_cfg.ignore_regexpire && peer->host_dynamic && realtime) {
26491       time_t nowtime = time(NULL);
26492 
26493       if ((nowtime - regseconds) > 0) {
26494          destroy_association(peer);
26495          memset(&peer->addr, 0, sizeof(peer->addr));
26496          peer->lastms = -1;
26497          ast_debug(1, "Bah, we're expired (%d/%d/%d)!\n", (int)(nowtime - regseconds), (int)regseconds, (int)nowtime);
26498       }
26499    }
26500 
26501    /* Startup regular pokes */
26502    if (!devstate_only && realtime && peer->lastms > 0) {
26503       ref_peer(peer, "schedule qualify");
26504       sip_poke_peer(peer, 0);
26505    }
26506 
26507    ast_copy_flags(&peer->flags[0], &peerflags[0], mask[0].flags);
26508    ast_copy_flags(&peer->flags[1], &peerflags[1], mask[1].flags);
26509    ast_copy_flags(&peer->flags[2], &peerflags[2], mask[2].flags);
26510    if (ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)) {
26511       sip_cfg.allowsubscribe = TRUE;   /* No global ban any more */
26512    }
26513    if (peer->host_dynamic && !peer->is_realtime) {
26514       reg_source_db(peer);
26515    }
26516 
26517    /* If they didn't request that MWI is sent *only* on subscribe, go ahead and
26518     * subscribe to it now. */
26519    if (!devstate_only && !ast_test_flag(&peer->flags[1], SIP_PAGE2_SUBSCRIBEMWIONLY) &&
26520       !AST_LIST_EMPTY(&peer->mailboxes)) {
26521       add_peer_mwi_subs(peer);
26522       /* Send MWI from the event cache only.  This is so we can send initial
26523        * MWI if app_voicemail got loaded before chan_sip.  If it is the other
26524        * way, then we will get events when app_voicemail gets loaded. */
26525       sip_send_mwi_to_peer(peer, NULL, 1);
26526    }
26527 
26528    peer->the_mark = 0;
26529 
26530    ast_free_ha(oldha);
26531    ast_free_ha(olddirectmediaha);
26532    if (!ast_strlen_zero(callback)) { /* build string from peer info */
26533       char *reg_string;
26534       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) {
26535          ast_log(LOG_WARNING, "asprintf() failed: %s\n", strerror(errno));
26536       } else if (reg_string) {
26537          sip_register(reg_string, 0); /* XXX TODO: count in registry_count */
26538          ast_free(reg_string);
26539       }
26540    }
26541    return peer;
26542 }
26543 
26544 static int peer_markall_func(void *device, void *arg, int flags)
26545 {
26546    struct sip_peer *peer = device;
26547    peer->the_mark = 1;
26548    return 0;
26549 }
26550 
26551 /*! \brief Re-read SIP.conf config file
26552 \note This function reloads all config data, except for
26553    active peers (with registrations). They will only
26554    change configuration data at restart, not at reload.
26555    SIP debug and recordhistory state will not change
26556  */
26557 static int reload_config(enum channelreloadreason reason)
26558 {
26559    struct ast_config *cfg, *ucfg;
26560    struct ast_variable *v;
26561    struct sip_peer *peer;
26562    char *cat, *stringp, *context, *oldregcontext;
26563    char newcontexts[AST_MAX_CONTEXT], oldcontexts[AST_MAX_CONTEXT];
26564    struct ast_flags dummy[2];
26565    struct ast_flags config_flags = { reason == CHANNEL_MODULE_LOAD ? 0 : ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) ? 0 : CONFIG_FLAG_FILEUNCHANGED };
26566    int auto_sip_domains = FALSE;
26567    struct ast_sockaddr old_bindaddr = bindaddr;
26568    int registry_count = 0, peer_count = 0, timerb_set = 0, timert1_set = 0;
26569    int subscribe_network_change = 1;
26570    time_t run_start, run_end;
26571    int bindport = 0;
26572 
26573    run_start = time(0);
26574    ast_unload_realtime("sipregs");
26575    ast_unload_realtime("sippeers");
26576    cfg = ast_config_load(config, config_flags);
26577 
26578    /* We *must* have a config file otherwise stop immediately */
26579    if (!cfg) {
26580       ast_log(LOG_NOTICE, "Unable to load config %s\n", config);
26581       return -1;
26582    } else if (cfg == CONFIG_STATUS_FILEUNCHANGED) {
26583       ucfg = ast_config_load("users.conf", config_flags);
26584       if (ucfg == CONFIG_STATUS_FILEUNCHANGED) {
26585          return 1;
26586       } else if (ucfg == CONFIG_STATUS_FILEINVALID) {
26587          ast_log(LOG_ERROR, "Contents of users.conf are invalid and cannot be parsed\n");
26588          return 1;
26589       }
26590       /* Must reread both files, because one changed */
26591       ast_clear_flag(&config_flags, CONFIG_FLAG_FILEUNCHANGED);
26592       if ((cfg = ast_config_load(config, config_flags)) == CONFIG_STATUS_FILEINVALID) {
26593          ast_log(LOG_ERROR, "Contents of %s are invalid and cannot be parsed\n", config);
26594          ast_config_destroy(ucfg);
26595          return 1;
26596       }
26597    } else if (cfg == CONFIG_STATUS_FILEINVALID) {
26598       ast_log(LOG_ERROR, "Contents of %s are invalid and cannot be parsed\n", config);
26599       return 1;
26600    } else {
26601       ast_clear_flag(&config_flags, CONFIG_FLAG_FILEUNCHANGED);
26602       if ((ucfg = ast_config_load("users.conf", config_flags)) == CONFIG_STATUS_FILEINVALID) {
26603          ast_log(LOG_ERROR, "Contents of users.conf are invalid and cannot be parsed\n");
26604          ast_config_destroy(cfg);
26605          return 1;
26606       }
26607    }
26608 
26609    ast_free_ha(sip_cfg.contact_ha);
26610    sip_cfg.contact_ha = NULL;
26611 
26612    default_tls_cfg.enabled = FALSE;    /* Default: Disable TLS */
26613 
26614    if (reason != CHANNEL_MODULE_LOAD) {
26615       ast_debug(4, "--------------- SIP reload started\n");
26616 
26617       clear_realm_authentication(authl);
26618       clear_sip_domains();
26619       authl = NULL;
26620 
26621       /* First, destroy all outstanding registry calls */
26622       /* This is needed, since otherwise active registry entries will not be destroyed */
26623       ASTOBJ_CONTAINER_TRAVERSE(&regl, 1, do {  /* regl is locked */
26624 
26625             ASTOBJ_RDLOCK(iterator); /* now regl is locked, and the object is also locked */
26626             if (iterator->call) {
26627                ast_debug(3, "Destroying active SIP dialog for registry %s@%s\n", iterator->username, iterator->hostname);
26628                /* This will also remove references to the registry */
26629                dialog_unlink_all(iterator->call, TRUE, TRUE);
26630                iterator->call = dialog_unref(iterator->call, "remove iterator->call from registry traversal");
26631             }
26632             if (iterator->expire > -1) {
26633                AST_SCHED_DEL_UNREF(sched, iterator->expire, registry_unref(iterator, "reg ptr unref from reload config"));
26634             }
26635             if (iterator->timeout > -1) {
26636                AST_SCHED_DEL_UNREF(sched, iterator->timeout, registry_unref(iterator, "reg ptr unref from reload config"));
26637             }
26638             ASTOBJ_UNLOCK(iterator);
26639       } while(0));
26640 
26641       /* Then, actually destroy users and registry */
26642       ASTOBJ_CONTAINER_DESTROYALL(&regl, sip_registry_destroy);
26643       ast_debug(4, "--------------- Done destroying registry list\n");
26644       ao2_t_callback(peers, OBJ_NODATA, peer_markall_func, NULL, "callback to mark all peers");
26645    }
26646 
26647    /* Reset certificate handling for TLS sessions */
26648    if (reason != CHANNEL_MODULE_LOAD) {
26649       ast_free(default_tls_cfg.certfile);
26650       ast_free(default_tls_cfg.pvtfile);
26651       ast_free(default_tls_cfg.cipher);
26652       ast_free(default_tls_cfg.cafile);
26653       ast_free(default_tls_cfg.capath);
26654    }
26655    default_tls_cfg.certfile = ast_strdup(AST_CERTFILE); /*XXX Not sure if this is useful */
26656    default_tls_cfg.pvtfile = ast_strdup("");
26657    default_tls_cfg.cipher = ast_strdup("");
26658    default_tls_cfg.cafile = ast_strdup("");
26659    default_tls_cfg.capath = ast_strdup("");
26660 
26661    /* Initialize copy of current sip_cfg.regcontext for later use in removing stale contexts */
26662    ast_copy_string(oldcontexts, sip_cfg.regcontext, sizeof(oldcontexts));
26663    oldregcontext = oldcontexts;
26664 
26665    /* Clear all flags before setting default values */
26666    /* Preserve debugging settings for console */
26667    sipdebug &= sip_debug_console;
26668    ast_clear_flag(&global_flags[0], AST_FLAGS_ALL);
26669    ast_clear_flag(&global_flags[1], AST_FLAGS_ALL);
26670 
26671    /* Reset IP addresses  */
26672    ast_sockaddr_parse(&bindaddr, "0.0.0.0:0", 0);
26673    memset(&internip, 0, sizeof(internip));
26674 
26675    /* Free memory for local network address mask */
26676    ast_free_ha(localaddr);
26677    memset(&localaddr, 0, sizeof(localaddr));
26678    memset(&externaddr, 0, sizeof(externaddr));
26679    memset(&media_address, 0, sizeof(media_address));
26680    memset(&default_prefs, 0 , sizeof(default_prefs));
26681    memset(&sip_cfg.outboundproxy, 0, sizeof(struct sip_proxy));
26682    sip_cfg.outboundproxy.force = FALSE;      /*!< Don't force proxy usage, use route: headers */
26683    default_transports = 0;          /*!< Reset default transport to zero here, default value later on */
26684    default_primary_transport = 0;         /*!< Reset default primary transport to zero here, default value later on */
26685    ourport_tcp = STANDARD_SIP_PORT;
26686    ourport_tls = STANDARD_TLS_PORT;
26687    externtcpport = STANDARD_SIP_PORT;
26688    externtlsport = STANDARD_TLS_PORT;
26689    sip_cfg.srvlookup = DEFAULT_SRVLOOKUP;
26690    global_tos_sip = DEFAULT_TOS_SIP;
26691    global_tos_audio = DEFAULT_TOS_AUDIO;
26692    global_tos_video = DEFAULT_TOS_VIDEO;
26693    global_tos_text = DEFAULT_TOS_TEXT;
26694    global_cos_sip = DEFAULT_COS_SIP;
26695    global_cos_audio = DEFAULT_COS_AUDIO;
26696    global_cos_video = DEFAULT_COS_VIDEO;
26697    global_cos_text = DEFAULT_COS_TEXT;
26698 
26699    externhost[0] = '\0';         /* External host name (for behind NAT DynDNS support) */
26700    externexpire = 0;       /* Expiration for DNS re-issuing */
26701    externrefresh = 10;
26702 
26703    /* Reset channel settings to default before re-configuring */
26704    sip_cfg.allow_external_domains = DEFAULT_ALLOW_EXT_DOM;           /* Allow external invites */
26705    sip_cfg.regcontext[0] = '\0';
26706    sip_cfg.capability = DEFAULT_CAPABILITY;
26707    sip_cfg.regextenonqualify = DEFAULT_REGEXTENONQUALIFY;
26708    sip_cfg.notifyringing = DEFAULT_NOTIFYRINGING;
26709    sip_cfg.notifycid = DEFAULT_NOTIFYCID;
26710    sip_cfg.notifyhold = FALSE;      /*!< Keep track of hold status for a peer */
26711    sip_cfg.directrtpsetup = FALSE;     /* Experimental feature, disabled by default */
26712    sip_cfg.alwaysauthreject = DEFAULT_ALWAYSAUTHREJECT;
26713    sip_cfg.auth_options_requests = DEFAULT_AUTH_OPTIONS;
26714    sip_cfg.allowsubscribe = FALSE;
26715    sip_cfg.disallowed_methods = SIP_UNKNOWN;
26716    sip_cfg.contact_ha = NULL;    /* Reset the contact ACL */
26717    snprintf(global_useragent, sizeof(global_useragent), "%s %s", DEFAULT_USERAGENT, ast_get_version());
26718    snprintf(global_sdpsession, sizeof(global_sdpsession), "%s %s", DEFAULT_SDPSESSION, ast_get_version());
26719    snprintf(global_sdpowner, sizeof(global_sdpowner), "%s", DEFAULT_SDPOWNER);
26720    global_prematuremediafilter = TRUE;
26721    ast_copy_string(default_notifymime, DEFAULT_NOTIFYMIME, sizeof(default_notifymime));
26722    ast_copy_string(sip_cfg.realm, S_OR(ast_config_AST_SYSTEM_NAME, DEFAULT_REALM), sizeof(sip_cfg.realm));
26723    sip_cfg.domainsasrealm = DEFAULT_DOMAINSASREALM;
26724    ast_copy_string(default_callerid, DEFAULT_CALLERID, sizeof(default_callerid));
26725    ast_copy_string(default_mwi_from, DEFAULT_MWI_FROM, sizeof(default_mwi_from));
26726    sip_cfg.compactheaders = DEFAULT_COMPACTHEADERS;
26727    global_reg_timeout = DEFAULT_REGISTRATION_TIMEOUT;
26728    global_regattempts_max = 0;
26729    sip_cfg.pedanticsipchecking = DEFAULT_PEDANTIC;
26730    sip_cfg.autocreatepeer = DEFAULT_AUTOCREATEPEER;
26731    global_autoframing = 0;
26732    sip_cfg.allowguest = DEFAULT_ALLOWGUEST;
26733    global_callcounter = DEFAULT_CALLCOUNTER;
26734    global_match_auth_username = FALSE;    /*!< Match auth username if available instead of From: Default off. */
26735    global_rtptimeout = 0;
26736    global_rtpholdtimeout = 0;
26737    global_rtpkeepalive = DEFAULT_RTPKEEPALIVE;
26738    sip_cfg.allowtransfer = TRANSFER_OPENFORALL; /* Merrily accept all transfers by default */
26739    sip_cfg.rtautoclear = 120;
26740    ast_set_flag(&global_flags[1], SIP_PAGE2_ALLOWSUBSCRIBE);   /* Default for all devices: TRUE */
26741    ast_set_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP);     /* Default for all devices: TRUE */
26742    sip_cfg.peer_rtupdate = TRUE;
26743    global_dynamic_exclude_static = 0;  /* Exclude static peers */
26744    sip_cfg.tcp_enabled = FALSE;
26745 
26746    /* Session-Timers */
26747    global_st_mode = SESSION_TIMER_MODE_ACCEPT;
26748    global_st_refresher = SESSION_TIMER_REFRESHER_UAS;
26749    global_min_se  = DEFAULT_MIN_SE;
26750    global_max_se  = DEFAULT_MAX_SE;
26751 
26752    /* Peer poking settings */
26753    global_qualify_gap = DEFAULT_QUALIFY_GAP;
26754    global_qualify_peers = DEFAULT_QUALIFY_PEERS;
26755 
26756    /* Initialize some reasonable defaults at SIP reload (used both for channel and as default for devices */
26757    ast_copy_string(sip_cfg.default_context, DEFAULT_CONTEXT, sizeof(sip_cfg.default_context));
26758    sip_cfg.default_subscribecontext[0] = '\0';
26759    sip_cfg.default_max_forwards = DEFAULT_MAX_FORWARDS;
26760    default_language[0] = '\0';
26761    default_fromdomain[0] = '\0';
26762    default_fromdomainport = 0;
26763    default_qualify = DEFAULT_QUALIFY;
26764    default_maxcallbitrate = DEFAULT_MAX_CALL_BITRATE;
26765    ast_copy_string(default_mohinterpret, DEFAULT_MOHINTERPRET, sizeof(default_mohinterpret));
26766    ast_copy_string(default_mohsuggest, DEFAULT_MOHSUGGEST, sizeof(default_mohsuggest));
26767    ast_copy_string(default_vmexten, DEFAULT_VMEXTEN, sizeof(default_vmexten));
26768    ast_set_flag(&global_flags[0], SIP_DTMF_RFC2833);        /*!< Default DTMF setting: RFC2833 */
26769    ast_set_flag(&global_flags[0], SIP_DIRECT_MEDIA);        /*!< Allow re-invites */
26770    ast_copy_string(default_engine, DEFAULT_ENGINE, sizeof(default_engine));
26771    ast_copy_string(default_parkinglot, DEFAULT_PARKINGLOT, sizeof(default_parkinglot));
26772 
26773    /* Debugging settings, always default to off */
26774    dumphistory = FALSE;
26775    recordhistory = FALSE;
26776    sipdebug &= ~sip_debug_config;
26777 
26778    /* Misc settings for the channel */
26779    global_relaxdtmf = FALSE;
26780    sip_cfg.callevents = DEFAULT_CALLEVENTS;
26781    global_authfailureevents = FALSE;
26782    global_t1 = DEFAULT_TIMER_T1;
26783    global_timer_b = 64 * DEFAULT_TIMER_T1;
26784    global_t1min = DEFAULT_T1MIN;
26785    global_qualifyfreq = DEFAULT_QUALIFYFREQ;
26786    global_t38_maxdatagram = -1;
26787    global_shrinkcallerid = 1;
26788    authlimit = DEFAULT_AUTHLIMIT;
26789    authtimeout = DEFAULT_AUTHTIMEOUT;
26790 
26791    sip_cfg.matchexternaddrlocally = DEFAULT_MATCHEXTERNADDRLOCALLY;
26792 
26793    /* Copy the default jb config over global_jbconf */
26794    memcpy(&global_jbconf, &default_jbconf, sizeof(struct ast_jb_conf));
26795 
26796    ast_clear_flag(&global_flags[1], SIP_PAGE2_FAX_DETECT);
26797    ast_clear_flag(&global_flags[1], SIP_PAGE2_VIDEOSUPPORT | SIP_PAGE2_VIDEOSUPPORT_ALWAYS);
26798    ast_clear_flag(&global_flags[1], SIP_PAGE2_TEXTSUPPORT);
26799    ast_clear_flag(&global_flags[1], SIP_PAGE2_IGNORESDPVERSION);
26800 
26801 
26802    /* Read the [general] config section of sip.conf (or from realtime config) */
26803    for (v = ast_variable_browse(cfg, "general"); v; v = v->next) {
26804       if (handle_common_options(&global_flags[0], &dummy[0], v)) {
26805          continue;
26806       }
26807       if (handle_t38_options(&global_flags[0], &dummy[0], v, &global_t38_maxdatagram)) {
26808          continue;
26809       }
26810       /* handle jb conf */
26811       if (!ast_jb_read_conf(&global_jbconf, v->name, v->value))
26812          continue;
26813 
26814       /* handle tls conf */
26815       if (!ast_tls_read_conf(&default_tls_cfg, &sip_tls_desc, v->name, v->value)) {
26816          continue;
26817       }
26818 
26819       if (!strcasecmp(v->name, "context")) {
26820          ast_copy_string(sip_cfg.default_context, v->value, sizeof(sip_cfg.default_context));
26821       } else if (!strcasecmp(v->name, "subscribecontext")) {
26822          ast_copy_string(sip_cfg.default_subscribecontext, v->value, sizeof(sip_cfg.default_subscribecontext));
26823       } else if (!strcasecmp(v->name, "callcounter")) {
26824          global_callcounter = ast_true(v->value) ? 1 : 0;
26825       } else if (!strcasecmp(v->name, "allowguest")) {
26826          sip_cfg.allowguest = ast_true(v->value) ? 1 : 0;
26827       } else if (!strcasecmp(v->name, "realm")) {
26828          ast_copy_string(sip_cfg.realm, v->value, sizeof(sip_cfg.realm));
26829       } else if (!strcasecmp(v->name, "domainsasrealm")) {
26830          sip_cfg.domainsasrealm = ast_true(v->value);
26831       } else if (!strcasecmp(v->name, "useragent")) {
26832          ast_copy_string(global_useragent, v->value, sizeof(global_useragent));
26833          ast_debug(1, "Setting SIP channel User-Agent Name to %s\n", global_useragent);
26834       } else if (!strcasecmp(v->name, "sdpsession")) {
26835          ast_copy_string(global_sdpsession, v->value, sizeof(global_sdpsession));
26836       } else if (!strcasecmp(v->name, "sdpowner")) {
26837          /* Field cannot contain spaces */
26838          if (!strstr(v->value, " ")) {
26839             ast_copy_string(global_sdpowner, v->value, sizeof(global_sdpowner));
26840          } else {
26841             ast_log(LOG_WARNING, "'%s' must not contain spaces at line %d.  Using default.\n", v->value, v->lineno);
26842          }
26843       } else if (!strcasecmp(v->name, "allowtransfer")) {
26844          sip_cfg.allowtransfer = ast_true(v->value) ? TRANSFER_OPENFORALL : TRANSFER_CLOSED;
26845       } else if (!strcasecmp(v->name, "rtcachefriends")) {
26846          ast_set2_flag(&global_flags[1], ast_true(v->value), SIP_PAGE2_RTCACHEFRIENDS);
26847       } else if (!strcasecmp(v->name, "rtsavesysname")) {
26848          sip_cfg.rtsave_sysname = ast_true(v->value);
26849       } else if (!strcasecmp(v->name, "rtupdate")) {
26850          sip_cfg.peer_rtupdate = ast_true(v->value);
26851       } else if (!strcasecmp(v->name, "ignoreregexpire")) {
26852          sip_cfg.ignore_regexpire = ast_true(v->value);
26853       } else if (!strcasecmp(v->name, "timert1")) {
26854          /* Defaults to 500ms, but RFC 3261 states that it is recommended
26855           * for the value to be set higher, though a lower value is only
26856           * allowed on private networks unconnected to the Internet. */
26857          global_t1 = atoi(v->value);
26858       } else if (!strcasecmp(v->name, "timerb")) {
26859          int tmp = atoi(v->value);
26860          if (tmp < 500) {
26861             global_timer_b = global_t1 * 64;
26862             ast_log(LOG_WARNING, "Invalid value for timerb ('%s').  Setting to default ('%d').\n", v->value, global_timer_b);
26863          }
26864          timerb_set = 1;
26865       } else if (!strcasecmp(v->name, "t1min")) {
26866          global_t1min = atoi(v->value);
26867       } else if (!strcasecmp(v->name, "transport") && !ast_strlen_zero(v->value)) {
26868          char *val = ast_strdupa(v->value);
26869          char *trans;
26870 
26871          while ((trans = strsep(&val, ","))) {
26872             trans = ast_skip_blanks(trans);
26873 
26874             if (!strncasecmp(trans, "udp", 3)) {
26875                default_transports |= SIP_TRANSPORT_UDP;
26876             } else if (!strncasecmp(trans, "tcp", 3)) {
26877                default_transports |= SIP_TRANSPORT_TCP;
26878             } else if (!strncasecmp(trans, "tls", 3)) {
26879                default_transports |= SIP_TRANSPORT_TLS;
26880             } else {
26881                ast_log(LOG_NOTICE, "'%s' is not a valid transport type. if no other is specified, udp will be used.\n", trans);
26882             }
26883             if (default_primary_transport == 0) {
26884                default_primary_transport = default_transports;
26885             }
26886          }
26887       } else if (!strcasecmp(v->name, "tcpenable")) {
26888          if (!ast_false(v->value)) {
26889             ast_debug(2, "Enabling TCP socket for listening\n");
26890             sip_cfg.tcp_enabled = TRUE;
26891          }
26892       } else if (!strcasecmp(v->name, "tcpbindaddr")) {
26893          if (ast_parse_arg(v->value, PARSE_ADDR,
26894                  &sip_tcp_desc.local_address)) {
26895             ast_log(LOG_WARNING, "Invalid %s '%s' at line %d of %s\n",
26896                v->name, v->value, v->lineno, config);
26897          }
26898          ast_debug(2, "Setting TCP socket address to %s\n",
26899               ast_sockaddr_stringify(&sip_tcp_desc.local_address));
26900       } else if (!strcasecmp(v->name, "dynamic_exclude_static") || !strcasecmp(v->name, "dynamic_excludes_static")) {
26901          global_dynamic_exclude_static = ast_true(v->value);
26902       } else if (!strcasecmp(v->name, "contactpermit") || !strcasecmp(v->name, "contactdeny")) {
26903          int ha_error = 0;
26904          sip_cfg.contact_ha = ast_append_ha(v->name + 7, v->value, sip_cfg.contact_ha, &ha_error);
26905          if (ha_error) {
26906             ast_log(LOG_ERROR, "Bad ACL entry in configuration line %d : %s\n", v->lineno, v->value);
26907          }
26908       } else if (!strcasecmp(v->name, "rtautoclear")) {
26909          int i = atoi(v->value);
26910          if (i > 0) {
26911             sip_cfg.rtautoclear = i;
26912          } else {
26913             i = 0;
26914          }
26915          ast_set2_flag(&global_flags[1], i || ast_true(v->value), SIP_PAGE2_RTAUTOCLEAR);
26916       } else if (!strcasecmp(v->name, "usereqphone")) {
26917          ast_set2_flag(&global_flags[0], ast_true(v->value), SIP_USEREQPHONE);
26918       } else if (!strcasecmp(v->name, "prematuremedia")) {
26919          global_prematuremediafilter = ast_true(v->value);
26920       } else if (!strcasecmp(v->name, "relaxdtmf")) {
26921          global_relaxdtmf = ast_true(v->value);
26922       } else if (!strcasecmp(v->name, "vmexten")) {
26923          ast_copy_string(default_vmexten, v->value, sizeof(default_vmexten));
26924       } else if (!strcasecmp(v->name, "rtptimeout")) {
26925          if ((sscanf(v->value, "%30d", &global_rtptimeout) != 1) || (global_rtptimeout < 0)) {
26926             ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d.  Using default.\n", v->value, v->lineno);
26927             global_rtptimeout = 0;
26928          }
26929       } else if (!strcasecmp(v->name, "rtpholdtimeout")) {
26930          if ((sscanf(v->value, "%30d", &global_rtpholdtimeout) != 1) || (global_rtpholdtimeout < 0)) {
26931             ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d.  Using default.\n", v->value, v->lineno);
26932             global_rtpholdtimeout = 0;
26933          }
26934       } else if (!strcasecmp(v->name, "rtpkeepalive")) {
26935          if ((sscanf(v->value, "%30d", &global_rtpkeepalive) != 1) || (global_rtpkeepalive < 0)) {
26936             ast_log(LOG_WARNING, "'%s' is not a valid RTP keepalive time at line %d.  Using default.\n", v->value, v->lineno);
26937             global_rtpkeepalive = DEFAULT_RTPKEEPALIVE;
26938          }
26939       } else if (!strcasecmp(v->name, "compactheaders")) {
26940          sip_cfg.compactheaders = ast_true(v->value);
26941       } else if (!strcasecmp(v->name, "notifymimetype")) {
26942          ast_copy_string(default_notifymime, v->value, sizeof(default_notifymime));
26943       } else if (!strcasecmp(v->name, "directrtpsetup")) {
26944          sip_cfg.directrtpsetup = ast_true(v->value);
26945       } else if (!strcasecmp(v->name, "notifyringing")) {
26946          sip_cfg.notifyringing = ast_true(v->value);
26947       } else if (!strcasecmp(v->name, "notifyhold")) {
26948          sip_cfg.notifyhold = ast_true(v->value);
26949       } else if (!strcasecmp(v->name, "notifycid")) {
26950          if (!strcasecmp(v->value, "ignore-context")) {
26951             sip_cfg.notifycid = IGNORE_CONTEXT;
26952          } else {
26953             sip_cfg.notifycid = ast_true(v->value);
26954          }
26955       } else if (!strcasecmp(v->name, "alwaysauthreject")) {
26956          sip_cfg.alwaysauthreject = ast_true(v->value);
26957       } else if (!strcasecmp(v->name, "auth_options_requests")) {
26958          if (ast_true(v->value)) {
26959             sip_cfg.auth_options_requests = 1;
26960          }
26961       } else if (!strcasecmp(v->name, "mohinterpret")) {
26962          ast_copy_string(default_mohinterpret, v->value, sizeof(default_mohinterpret));
26963       } else if (!strcasecmp(v->name, "mohsuggest")) {
26964          ast_copy_string(default_mohsuggest, v->value, sizeof(default_mohsuggest));
26965       } else if (!strcasecmp(v->name, "language")) {
26966          ast_copy_string(default_language, v->value, sizeof(default_language));
26967       } else if (!strcasecmp(v->name, "regcontext")) {
26968          ast_copy_string(newcontexts, v->value, sizeof(newcontexts));
26969          stringp = newcontexts;
26970          /* Let's remove any contexts that are no longer defined in regcontext */
26971          cleanup_stale_contexts(stringp, oldregcontext);
26972          /* Create contexts if they don't exist already */
26973          while ((context = strsep(&stringp, "&"))) {
26974             ast_copy_string(used_context, context, sizeof(used_context));
26975             ast_context_find_or_create(NULL, NULL, context, "SIP");
26976          }
26977          ast_copy_string(sip_cfg.regcontext, v->value, sizeof(sip_cfg.regcontext));
26978       } else if (!strcasecmp(v->name, "regextenonqualify")) {
26979          sip_cfg.regextenonqualify = ast_true(v->value);
26980       } else if (!strcasecmp(v->name, "callerid")) {
26981          ast_copy_string(default_callerid, v->value, sizeof(default_callerid));
26982       } else if (!strcasecmp(v->name, "mwi_from")) {
26983          ast_copy_string(default_mwi_from, v->value, sizeof(default_mwi_from));
26984       } else if (!strcasecmp(v->name, "fromdomain")) {
26985          char *fromdomainport;
26986          ast_copy_string(default_fromdomain, v->value, sizeof(default_fromdomain));
26987          if ((fromdomainport = strchr(default_fromdomain, ':'))) {
26988             *fromdomainport++ = '\0';
26989             if (!(default_fromdomainport = port_str2int(fromdomainport, 0))) {
26990                ast_log(LOG_NOTICE, "'%s' is not a valid port number for fromdomain.\n",fromdomainport);
26991             }
26992          } else {
26993             default_fromdomainport = STANDARD_SIP_PORT;
26994          }
26995       } else if (!strcasecmp(v->name, "outboundproxy")) {
26996          char *tok, *proxyname;
26997 
26998          if (ast_strlen_zero(v->value)) {
26999             ast_log(LOG_WARNING, "no value given for outbound proxy on line %d of sip.conf.", v->lineno);
27000             continue;
27001          }
27002 
27003          tok = ast_skip_blanks(strtok(ast_strdupa(v->value), ","));
27004 
27005          sip_parse_host(tok, v->lineno, &proxyname,
27006                    &sip_cfg.outboundproxy.port,
27007                    &sip_cfg.outboundproxy.transport);
27008 
27009          if ((tok = strtok(NULL, ","))) {
27010             sip_cfg.outboundproxy.force = !strncasecmp(ast_skip_blanks(tok), "force", 5);
27011          } else {
27012             sip_cfg.outboundproxy.force = FALSE;
27013          }
27014 
27015          if (ast_strlen_zero(proxyname)) {
27016             ast_log(LOG_WARNING, "you must specify a name for the outboundproxy on line %d of sip.conf.", v->lineno);
27017             sip_cfg.outboundproxy.name[0] = '\0';
27018             continue;
27019          }
27020 
27021          ast_copy_string(sip_cfg.outboundproxy.name, proxyname, sizeof(sip_cfg.outboundproxy.name));
27022 
27023          proxy_update(&sip_cfg.outboundproxy);
27024       } else if (!strcasecmp(v->name, "autocreatepeer")) {
27025          sip_cfg.autocreatepeer = ast_true(v->value);
27026       } else if (!strcasecmp(v->name, "match_auth_username")) {
27027          global_match_auth_username = ast_true(v->value);
27028       } else if (!strcasecmp(v->name, "srvlookup")) {
27029          sip_cfg.srvlookup = ast_true(v->value);
27030       } else if (!strcasecmp(v->name, "pedantic")) {
27031          sip_cfg.pedanticsipchecking = ast_true(v->value);
27032       } else if (!strcasecmp(v->name, "maxexpirey") || !strcasecmp(v->name, "maxexpiry")) {
27033          max_expiry = atoi(v->value);
27034          if (max_expiry < 1) {
27035             max_expiry = DEFAULT_MAX_EXPIRY;
27036          }
27037       } else if (!strcasecmp(v->name, "minexpirey") || !strcasecmp(v->name, "minexpiry")) {
27038          min_expiry = atoi(v->value);
27039          if (min_expiry < 1) {
27040             min_expiry = DEFAULT_MIN_EXPIRY;
27041          }
27042       } else if (!strcasecmp(v->name, "defaultexpiry") || !strcasecmp(v->name, "defaultexpirey")) {
27043          default_expiry = atoi(v->value);
27044          if (default_expiry < 1) {
27045             default_expiry = DEFAULT_DEFAULT_EXPIRY;
27046          }
27047       } else if (!strcasecmp(v->name, "mwiexpiry") || !strcasecmp(v->name, "mwiexpirey")) {
27048          mwi_expiry = atoi(v->value);
27049          if (mwi_expiry < 1) {
27050             mwi_expiry = DEFAULT_MWI_EXPIRY;
27051          }
27052       } else if (!strcasecmp(v->name, "tcpauthtimeout")) {
27053          if (ast_parse_arg(v->value, PARSE_INT32|PARSE_DEFAULT|PARSE_IN_RANGE,
27054                  &authtimeout, DEFAULT_AUTHTIMEOUT, 1, INT_MAX)) {
27055             ast_log(LOG_WARNING, "Invalid %s '%s' at line %d of %s\n",
27056                v->name, v->value, v->lineno, config);
27057          }
27058       } else if (!strcasecmp(v->name, "tcpauthlimit")) {
27059          if (ast_parse_arg(v->value, PARSE_INT32|PARSE_DEFAULT|PARSE_IN_RANGE,
27060                  &authlimit, DEFAULT_AUTHLIMIT, 1, INT_MAX)) {
27061             ast_log(LOG_WARNING, "Invalid %s '%s' at line %d of %s\n",
27062                v->name, v->value, v->lineno, config);
27063          }
27064       } else if (!strcasecmp(v->name, "sipdebug")) {
27065          if (ast_true(v->value))
27066             sipdebug |= sip_debug_config;
27067       } else if (!strcasecmp(v->name, "dumphistory")) {
27068          dumphistory = ast_true(v->value);
27069       } else if (!strcasecmp(v->name, "recordhistory")) {
27070          recordhistory = ast_true(v->value);
27071       } else if (!strcasecmp(v->name, "registertimeout")) {
27072          global_reg_timeout = atoi(v->value);
27073          if (global_reg_timeout < 1) {
27074             global_reg_timeout = DEFAULT_REGISTRATION_TIMEOUT;
27075          }
27076       } else if (!strcasecmp(v->name, "registerattempts")) {
27077          global_regattempts_max = atoi(v->value);
27078       } else if (!strcasecmp(v->name, "bindaddr") || !strcasecmp(v->name, "udpbindaddr")) {
27079          if (ast_parse_arg(v->value, PARSE_ADDR, &bindaddr)) {
27080             ast_log(LOG_WARNING, "Invalid address: %s\n", v->value);
27081          }
27082       } else if (!strcasecmp(v->name, "localnet")) {
27083          struct ast_ha *na;
27084          int ha_error = 0;
27085 
27086          if (!(na = ast_append_ha("d", v->value, localaddr, &ha_error))) {
27087             ast_log(LOG_WARNING, "Invalid localnet value: %s\n", v->value);
27088          } else {
27089             localaddr = na;
27090          }
27091          if (ha_error) {
27092             ast_log(LOG_ERROR, "Bad localnet configuration value line %d : %s\n", v->lineno, v->value);
27093          }
27094       } else if (!strcasecmp(v->name, "media_address")) {
27095          if (ast_parse_arg(v->value, PARSE_ADDR, &media_address))
27096             ast_log(LOG_WARNING, "Invalid address for media_address keyword: %s\n", v->value);
27097       } else if (!strcasecmp(v->name, "externaddr") || !strcasecmp(v->name, "externip")) {
27098          if (ast_parse_arg(v->value, PARSE_ADDR, &externaddr)) {
27099             ast_log(LOG_WARNING,
27100                "Invalid address for externaddr keyword: %s\n",
27101                v->value);
27102          }
27103          externexpire = 0;
27104       } else if (!strcasecmp(v->name, "externhost")) {
27105          ast_copy_string(externhost, v->value, sizeof(externhost));
27106          if (ast_sockaddr_resolve_first(&externaddr, externhost, 0)) {
27107             ast_log(LOG_WARNING, "Invalid address for externhost keyword: %s\n", externhost);
27108          }
27109          externexpire = time(NULL);
27110       } else if (!strcasecmp(v->name, "externrefresh")) {
27111          if (sscanf(v->value, "%30d", &externrefresh) != 1) {
27112             ast_log(LOG_WARNING, "Invalid externrefresh value '%s', must be an integer >0 at line %d\n", v->value, v->lineno);
27113             externrefresh = 10;
27114          }
27115       } else if (!strcasecmp(v->name, "externtcpport")) {
27116          if (!(externtcpport = port_str2int(v->value, 0))) {
27117             ast_log(LOG_WARNING, "Invalid externtcpport value, must be a positive integer between 1 and 65535 at line %d\n", v->lineno);
27118             externtcpport = 0;
27119          }
27120       } else if (!strcasecmp(v->name, "externtlsport")) {
27121          if (!(externtlsport = port_str2int(v->value, STANDARD_TLS_PORT))) {
27122             ast_log(LOG_WARNING, "Invalid externtlsport value, must be a positive integer between 1 and 65535 at line %d\n", v->lineno);
27123          }
27124       } else if (!strcasecmp(v->name, "allow")) {
27125          int error =  ast_parse_allow_disallow(&default_prefs, &sip_cfg.capability, v->value, TRUE);
27126          if (error) {
27127             ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
27128          }
27129       } else if (!strcasecmp(v->name, "disallow")) {
27130          int error =  ast_parse_allow_disallow(&default_prefs, &sip_cfg.capability, v->value, FALSE);
27131          if (error) {
27132             ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
27133          }
27134       } else if (!strcasecmp(v->name, "preferred_codec_only")) {
27135          ast_set2_flag(&global_flags[1], ast_true(v->value), SIP_PAGE2_PREFERRED_CODEC);
27136       } else if (!strcasecmp(v->name, "autoframing")) {
27137          global_autoframing = ast_true(v->value);
27138       } else if (!strcasecmp(v->name, "allowexternaldomains")) {
27139          sip_cfg.allow_external_domains = ast_true(v->value);
27140       } else if (!strcasecmp(v->name, "autodomain")) {
27141          auto_sip_domains = ast_true(v->value);
27142       } else if (!strcasecmp(v->name, "domain")) {
27143          char *domain = ast_strdupa(v->value);
27144          char *cntx = strchr(domain, ',');
27145 
27146          if (cntx) {
27147             *cntx++ = '\0';
27148          }
27149 
27150          if (ast_strlen_zero(cntx)) {
27151             ast_debug(1, "No context specified at line %d for domain '%s'\n", v->lineno, domain);
27152          }
27153          if (ast_strlen_zero(domain)) {
27154             ast_log(LOG_WARNING, "Empty domain specified at line %d\n", v->lineno);
27155          } else {
27156             add_sip_domain(ast_strip(domain), SIP_DOMAIN_CONFIG, cntx ? ast_strip(cntx) : "");
27157          }
27158       } else if (!strcasecmp(v->name, "register")) {
27159          if (sip_register(v->value, v->lineno) == 0) {
27160             registry_count++;
27161          }
27162       } else if (!strcasecmp(v->name, "mwi")) {
27163          sip_subscribe_mwi(v->value, v->lineno);
27164       } else if (!strcasecmp(v->name, "tos_sip")) {
27165          if (ast_str2tos(v->value, &global_tos_sip)) {
27166             ast_log(LOG_WARNING, "Invalid tos_sip value at line %d, refer to QoS documentation\n", v->lineno);
27167          }
27168       } else if (!strcasecmp(v->name, "tos_audio")) {
27169          if (ast_str2tos(v->value, &global_tos_audio)) {
27170             ast_log(LOG_WARNING, "Invalid tos_audio value at line %d, refer to QoS documentation\n", v->lineno);
27171          }
27172       } else if (!strcasecmp(v->name, "tos_video")) {
27173          if (ast_str2tos(v->value, &global_tos_video)) {
27174             ast_log(LOG_WARNING, "Invalid tos_video value at line %d, refer to QoS documentation\n", v->lineno);
27175          }
27176       } else if (!strcasecmp(v->name, "tos_text")) {
27177          if (ast_str2tos(v->value, &global_tos_text)) {
27178             ast_log(LOG_WARNING, "Invalid tos_text value at line %d, refer to QoS documentation\n", v->lineno);
27179          }
27180       } else if (!strcasecmp(v->name, "cos_sip")) {
27181          if (ast_str2cos(v->value, &global_cos_sip)) {
27182             ast_log(LOG_WARNING, "Invalid cos_sip value at line %d, refer to QoS documentation\n", v->lineno);
27183          }
27184       } else if (!strcasecmp(v->name, "cos_audio")) {
27185          if (ast_str2cos(v->value, &global_cos_audio)) {
27186             ast_log(LOG_WARNING, "Invalid cos_audio value at line %d, refer to QoS documentation\n", v->lineno);
27187          }
27188       } else if (!strcasecmp(v->name, "cos_video")) {
27189          if (ast_str2cos(v->value, &global_cos_video)) {
27190             ast_log(LOG_WARNING, "Invalid cos_video value at line %d, refer to QoS documentation\n", v->lineno);
27191          }
27192       } else if (!strcasecmp(v->name, "cos_text")) {
27193          if (ast_str2cos(v->value, &global_cos_text)) {
27194             ast_log(LOG_WARNING, "Invalid cos_text value at line %d, refer to QoS documentation\n", v->lineno);
27195          }
27196       } else if (!strcasecmp(v->name, "bindport")) {
27197          if (sscanf(v->value, "%5d", &bindport) != 1) {
27198             ast_log(LOG_WARNING, "Invalid port number '%s' at line %d of %s\n", v->value, v->lineno, config);
27199          }
27200       } else if (!strcasecmp(v->name, "qualify")) {
27201          if (!strcasecmp(v->value, "no")) {
27202             default_qualify = 0;
27203          } else if (!strcasecmp(v->value, "yes")) {
27204             default_qualify = DEFAULT_MAXMS;
27205          } else if (sscanf(v->value, "%30d", &default_qualify) != 1) {
27206             ast_log(LOG_WARNING, "Qualification default should be 'yes', 'no', or a number of milliseconds at line %d of sip.conf\n", v->lineno);
27207             default_qualify = 0;
27208          }
27209       } else if (!strcasecmp(v->name, "qualifyfreq")) {
27210          int i;
27211          if (sscanf(v->value, "%30d", &i) == 1) {
27212             global_qualifyfreq = i * 1000;
27213          } else {
27214             ast_log(LOG_WARNING, "Invalid qualifyfreq number '%s' at line %d of %s\n", v->value, v->lineno, config);
27215             global_qualifyfreq = DEFAULT_QUALIFYFREQ;
27216          }
27217       } else if (!strcasecmp(v->name, "callevents")) {
27218          sip_cfg.callevents = ast_true(v->value);
27219       } else if (!strcasecmp(v->name, "authfailureevents")) {
27220          global_authfailureevents = ast_true(v->value);
27221       } else if (!strcasecmp(v->name, "maxcallbitrate")) {
27222          default_maxcallbitrate = atoi(v->value);
27223          if (default_maxcallbitrate < 0)
27224             default_maxcallbitrate = DEFAULT_MAX_CALL_BITRATE;
27225       } else if (!strcasecmp(v->name, "matchexternaddrlocally") || !strcasecmp(v->name, "matchexterniplocally")) {
27226          sip_cfg.matchexternaddrlocally = ast_true(v->value);
27227       } else if (!strcasecmp(v->name, "session-timers")) {
27228          int i = (int) str2stmode(v->value);
27229          if (i < 0) {
27230             ast_log(LOG_WARNING, "Invalid session-timers '%s' at line %d of %s\n", v->value, v->lineno, config);
27231             global_st_mode = SESSION_TIMER_MODE_ACCEPT;
27232          } else {
27233             global_st_mode = i;
27234          }
27235       } else if (!strcasecmp(v->name, "session-expires")) {
27236          if (sscanf(v->value, "%30d", &global_max_se) != 1) {
27237             ast_log(LOG_WARNING, "Invalid session-expires '%s' at line %d of %s\n", v->value, v->lineno, config);
27238             global_max_se = DEFAULT_MAX_SE;
27239          }
27240       } else if (!strcasecmp(v->name, "session-minse")) {
27241          if (sscanf(v->value, "%30d", &global_min_se) != 1) {
27242             ast_log(LOG_WARNING, "Invalid session-minse '%s' at line %d of %s\n", v->value, v->lineno, config);
27243             global_min_se = DEFAULT_MIN_SE;
27244          }
27245          if (global_min_se < 90) {
27246             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);
27247             global_min_se = DEFAULT_MIN_SE;
27248          }
27249       } else if (!strcasecmp(v->name, "session-refresher")) {
27250          int i = (int) str2strefresher(v->value);
27251          if (i < 0) {
27252             ast_log(LOG_WARNING, "Invalid session-refresher '%s' at line %d of %s\n", v->value, v->lineno, config);
27253             global_st_refresher = SESSION_TIMER_REFRESHER_UAS;
27254          } else {
27255             global_st_refresher = i;
27256          }
27257       } else if (!strcasecmp(v->name, "qualifygap")) {
27258          if (sscanf(v->value, "%30d", &global_qualify_gap) != 1) {
27259             ast_log(LOG_WARNING, "Invalid qualifygap '%s' at line %d of %s\n", v->value, v->lineno, config);
27260             global_qualify_gap = DEFAULT_QUALIFY_GAP;
27261          }
27262       } else if (!strcasecmp(v->name, "qualifypeers")) {
27263          if (sscanf(v->value, "%30d", &global_qualify_peers) != 1) {
27264             ast_log(LOG_WARNING, "Invalid pokepeers '%s' at line %d of %s\n", v->value, v->lineno, config);
27265             global_qualify_peers = DEFAULT_QUALIFY_PEERS;
27266          }
27267       } else if (!strcasecmp(v->name, "disallowed_methods")) {
27268          char *disallow = ast_strdupa(v->value);
27269          mark_parsed_methods(&sip_cfg.disallowed_methods, disallow);
27270       } else if (!strcasecmp(v->name, "shrinkcallerid")) {
27271          if (ast_true(v->value)) {
27272             global_shrinkcallerid = 1;
27273          } else if (ast_false(v->value)) {
27274             global_shrinkcallerid = 0;
27275          } else {
27276             ast_log(LOG_WARNING, "shrinkcallerid value %s is not valid at line %d.\n", v->value, v->lineno);
27277          }
27278       } else if (!strcasecmp(v->name, "use_q850_reason")) {
27279          ast_set2_flag(&global_flags[1], ast_true(v->value), SIP_PAGE2_Q850_REASON);
27280       } else if (!strcasecmp(v->name, "maxforwards")) {
27281          if ((sscanf(v->value, "%30d", &sip_cfg.default_max_forwards) != 1) || (sip_cfg.default_max_forwards < 1)) {
27282             ast_log(LOG_WARNING, "'%s' is not a valid maxforwards value at line %d.  Using default.\n", v->value, v->lineno);
27283             sip_cfg.default_max_forwards = DEFAULT_MAX_FORWARDS;
27284          }
27285       } else if (!strcasecmp(v->name, "subscribe_network_change_event")) {
27286          if (ast_true(v->value)) {
27287             subscribe_network_change = 1;
27288          } else if (ast_false(v->value)) {
27289             subscribe_network_change = 0;
27290          } else {
27291             ast_log(LOG_WARNING, "subscribe_network_change_event value %s is not valid at line %d.\n", v->value, v->lineno);
27292          }
27293       } else if (!strcasecmp(v->name, "snom_aoc_enabled")) {
27294          ast_set2_flag(&global_flags[2], ast_true(v->value), SIP_PAGE3_SNOM_AOC);
27295       } else if (!strcasecmp(v->name, "parkinglot")) {
27296          ast_copy_string(default_parkinglot, v->value, sizeof(default_parkinglot));
27297       }
27298    }
27299 
27300    if (subscribe_network_change) {
27301       network_change_event_subscribe();
27302    } else {
27303       network_change_event_unsubscribe();
27304    }
27305 
27306    if (global_t1 < global_t1min) {
27307       ast_log(LOG_WARNING, "'t1min' (%d) cannot be greater than 't1timer' (%d).  Resetting 't1timer' to the value of 't1min'\n", global_t1min, global_t1);
27308       global_t1 = global_t1min;
27309    }
27310 
27311    if (global_timer_b < global_t1 * 64) {
27312       if (timerb_set && timert1_set) {
27313          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);
27314       } else if (timerb_set) {
27315          if ((global_t1 = global_timer_b / 64) < global_t1min) {
27316             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);
27317             global_t1 = global_t1min;
27318             global_timer_b = global_t1 * 64;
27319          }
27320       } else {
27321          global_timer_b = global_t1 * 64;
27322       }
27323    }
27324    if (!sip_cfg.allow_external_domains && AST_LIST_EMPTY(&domain_list)) {
27325       ast_log(LOG_WARNING, "To disallow external domains, you need to configure local SIP domains.\n");
27326       sip_cfg.allow_external_domains = 1;
27327    }
27328    /* If not configured, set default transports */
27329    if (default_transports == 0) {
27330       default_transports = default_primary_transport = SIP_TRANSPORT_UDP;
27331    }
27332 
27333    /* Build list of authentication to various SIP realms, i.e. service providers */
27334    for (v = ast_variable_browse(cfg, "authentication"); v ; v = v->next) {
27335       /* Format for authentication is auth = username:password@realm */
27336       if (!strcasecmp(v->name, "auth")) {
27337          authl = add_realm_authentication(authl, v->value, v->lineno);
27338       }
27339    }
27340 
27341    if (bindport) {
27342       if (ast_sockaddr_port(&bindaddr)) {
27343          ast_log(LOG_WARNING, "bindport is also specified in bindaddr. "
27344             "Using %d.\n", bindport);
27345       }
27346       ast_sockaddr_set_port(&bindaddr, bindport);
27347    }
27348 
27349    if (!ast_sockaddr_port(&bindaddr)) {
27350       ast_sockaddr_set_port(&bindaddr, STANDARD_SIP_PORT);
27351    }
27352 
27353    /* Set UDP address and open socket */
27354    ast_sockaddr_copy(&internip, &bindaddr);
27355    if (ast_find_ourip(&internip, &bindaddr, 0)) {
27356       ast_log(LOG_WARNING, "Unable to get own IP address, SIP disabled\n");
27357       ast_config_destroy(cfg);
27358       return 0;
27359    }
27360 
27361    ast_mutex_lock(&netlock);
27362    if ((sipsock > -1) && (ast_sockaddr_cmp(&old_bindaddr, &bindaddr))) {
27363       close(sipsock);
27364       sipsock = -1;
27365    }
27366    if (sipsock < 0) {
27367       sipsock = socket(ast_sockaddr_is_ipv6(&bindaddr) ?
27368              AF_INET6 : AF_INET, SOCK_DGRAM, 0);
27369       if (sipsock < 0) {
27370          ast_log(LOG_WARNING, "Unable to create SIP socket: %s\n", strerror(errno));
27371          ast_config_destroy(cfg);
27372          ast_mutex_unlock(&netlock);
27373          return -1;
27374       } else {
27375          /* Allow SIP clients on the same host to access us: */
27376          const int reuseFlag = 1;
27377 
27378          setsockopt(sipsock, SOL_SOCKET, SO_REUSEADDR,
27379                (const char*)&reuseFlag,
27380                sizeof reuseFlag);
27381 
27382          ast_enable_packet_fragmentation(sipsock);
27383 
27384          if (ast_bind(sipsock, &bindaddr) < 0) {
27385             ast_log(LOG_WARNING, "Failed to bind to %s: %s\n",
27386                ast_sockaddr_stringify(&bindaddr), strerror(errno));
27387             close(sipsock);
27388             sipsock = -1;
27389          } else {
27390             ast_verb(2, "SIP Listening on %s\n", ast_sockaddr_stringify(&bindaddr));
27391             ast_set_qos(sipsock, global_tos_sip, global_cos_sip, "SIP");
27392          }
27393       }
27394    } else {
27395       ast_set_qos(sipsock, global_tos_sip, global_cos_sip, "SIP");
27396    }
27397    ast_mutex_unlock(&netlock);
27398 
27399    /* Start TCP server */
27400    if (sip_cfg.tcp_enabled) {
27401       if (ast_sockaddr_isnull(&sip_tcp_desc.local_address)) {
27402          ast_sockaddr_copy(&sip_tcp_desc.local_address, &bindaddr);
27403       }
27404       if (!ast_sockaddr_port(&sip_tcp_desc.local_address)) {
27405          ast_sockaddr_set_port(&sip_tcp_desc.local_address, STANDARD_SIP_PORT);
27406       }
27407    } else {
27408       ast_sockaddr_setnull(&sip_tcp_desc.local_address);
27409    }
27410    ast_tcptls_server_start(&sip_tcp_desc);
27411    if (sip_cfg.tcp_enabled && sip_tcp_desc.accept_fd == -1) {
27412       /* TCP server start failed. Tell the admin */
27413       ast_log(LOG_ERROR, "SIP TCP Server start failed. Not listening on TCP socket.\n");
27414    } else {
27415       ast_debug(2, "SIP TCP server started\n");
27416    }
27417 
27418    /* Start TLS server if needed */
27419    memcpy(sip_tls_desc.tls_cfg, &default_tls_cfg, sizeof(default_tls_cfg));
27420 
27421    if (ast_ssl_setup(sip_tls_desc.tls_cfg)) {
27422       if (ast_sockaddr_isnull(&sip_tls_desc.local_address)) {
27423          ast_sockaddr_copy(&sip_tls_desc.local_address, &bindaddr);
27424          ast_sockaddr_set_port(&sip_tls_desc.local_address,
27425                      STANDARD_TLS_PORT);
27426       }
27427       if (!ast_sockaddr_port(&sip_tls_desc.local_address)) {
27428          ast_sockaddr_set_port(&sip_tls_desc.local_address,
27429                      STANDARD_TLS_PORT);
27430       }
27431       ast_tcptls_server_start(&sip_tls_desc);
27432       if (default_tls_cfg.enabled && sip_tls_desc.accept_fd == -1) {
27433          ast_log(LOG_ERROR, "TLS Server start failed. Not listening on TLS socket.\n");
27434          sip_tls_desc.tls_cfg = NULL;
27435       }
27436    } else if (sip_tls_desc.tls_cfg->enabled) {
27437       sip_tls_desc.tls_cfg = NULL;
27438       ast_log(LOG_WARNING, "SIP TLS server did not load because of errors.\n");
27439    }
27440 
27441    if (ucfg) {
27442       struct ast_variable *gen;
27443       int genhassip, genregistersip;
27444       const char *hassip, *registersip;
27445       
27446       genhassip = ast_true(ast_variable_retrieve(ucfg, "general", "hassip"));
27447       genregistersip = ast_true(ast_variable_retrieve(ucfg, "general", "registersip"));
27448       gen = ast_variable_browse(ucfg, "general");
27449       cat = ast_category_browse(ucfg, NULL);
27450       while (cat) {
27451          if (strcasecmp(cat, "general")) {
27452             hassip = ast_variable_retrieve(ucfg, cat, "hassip");
27453             registersip = ast_variable_retrieve(ucfg, cat, "registersip");
27454             if (ast_true(hassip) || (!hassip && genhassip)) {
27455                peer = build_peer(cat, gen, ast_variable_browse(ucfg, cat), 0, 0);
27456                if (peer) {
27457                   /* user.conf entries are always of type friend */
27458                   peer->type = SIP_TYPE_USER | SIP_TYPE_PEER;
27459                   ao2_t_link(peers, peer, "link peer into peer table");
27460                   if ((peer->type & SIP_TYPE_PEER) && !ast_sockaddr_isnull(&peer->addr)) {
27461                      ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
27462                   }
27463                   
27464                   unref_peer(peer, "unref_peer: from reload_config");
27465                   peer_count++;
27466                }
27467             }
27468             if (ast_true(registersip) || (!registersip && genregistersip)) {
27469                char tmp[256];
27470                const char *host = ast_variable_retrieve(ucfg, cat, "host");
27471                const char *username = ast_variable_retrieve(ucfg, cat, "username");
27472                const char *secret = ast_variable_retrieve(ucfg, cat, "secret");
27473                const char *contact = ast_variable_retrieve(ucfg, cat, "contact");
27474                const char *authuser = ast_variable_retrieve(ucfg, cat, "authuser");
27475                if (!host) {
27476                   host = ast_variable_retrieve(ucfg, "general", "host");
27477                }
27478                if (!username) {
27479                   username = ast_variable_retrieve(ucfg, "general", "username");
27480                }
27481                if (!secret) {
27482                   secret = ast_variable_retrieve(ucfg, "general", "secret");
27483                }
27484                if (!contact) {
27485                   contact = "s";
27486                }
27487                if (!ast_strlen_zero(username) && !ast_strlen_zero(host)) {
27488                   if (!ast_strlen_zero(secret)) {
27489                      if (!ast_strlen_zero(authuser)) {
27490                         snprintf(tmp, sizeof(tmp), "%s?%s:%s:%s@%s/%s", cat, username, secret, authuser, host, contact);
27491                      } else {
27492                         snprintf(tmp, sizeof(tmp), "%s?%s:%s@%s/%s", cat, username, secret, host, contact);
27493                      }
27494                   } else if (!ast_strlen_zero(authuser)) {
27495                      snprintf(tmp, sizeof(tmp), "%s?%s::%s@%s/%s", cat, username, authuser, host, contact);
27496                   } else {
27497                      snprintf(tmp, sizeof(tmp), "%s?%s@%s/%s", cat, username, host, contact);
27498                   }
27499                   if (sip_register(tmp, 0) == 0) {
27500                      registry_count++;
27501                   }
27502                }
27503             }
27504          }
27505          cat = ast_category_browse(ucfg, cat);
27506       }
27507       ast_config_destroy(ucfg);
27508    }
27509 
27510    /* Load peers, users and friends */
27511    cat = NULL;
27512    while ( (cat = ast_category_browse(cfg, cat)) ) {
27513       const char *utype;
27514       if (!strcasecmp(cat, "general") || !strcasecmp(cat, "authentication"))
27515          continue;
27516       utype = ast_variable_retrieve(cfg, cat, "type");
27517       if (!utype) {
27518          ast_log(LOG_WARNING, "Section '%s' lacks type\n", cat);
27519          continue;
27520       } else {
27521          if (!strcasecmp(utype, "user")) {
27522             ;
27523          } else if (!strcasecmp(utype, "friend")) {
27524             ;
27525          } else if (!strcasecmp(utype, "peer")) {
27526             ;
27527          } else {
27528             ast_log(LOG_WARNING, "Unknown type '%s' for '%s' in %s\n", utype, cat, "sip.conf");
27529             continue;
27530          }
27531          peer = build_peer(cat, ast_variable_browse(cfg, cat), NULL, 0, 0);
27532          if (peer) {
27533             ao2_t_link(peers, peer, "link peer into peers table");
27534             if ((peer->type & SIP_TYPE_PEER) && !ast_sockaddr_isnull(&peer->addr)) {
27535                ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
27536             }
27537             unref_peer(peer, "unref the result of the build_peer call. Now, the links from the tables are the only ones left.");
27538             peer_count++;
27539          }
27540       }
27541    }
27542 
27543    /* Add default domains - host name, IP address and IP:port
27544     * Only do this if user added any sip domain with "localdomains"
27545     * In order to *not* break backwards compatibility
27546     *    Some phones address us at IP only, some with additional port number
27547     */
27548    if (auto_sip_domains) {
27549       char temp[MAXHOSTNAMELEN];
27550 
27551       /* First our default IP address */
27552       if (!ast_sockaddr_isnull(&bindaddr) && !ast_sockaddr_is_any(&bindaddr)) {
27553          add_sip_domain(ast_sockaddr_stringify_addr(&bindaddr),
27554                    SIP_DOMAIN_AUTO, NULL);
27555       } else if (!ast_sockaddr_isnull(&internip) && !ast_sockaddr_is_any(&internip)) {
27556       /* Our internal IP address, if configured */
27557          add_sip_domain(ast_sockaddr_stringify_addr(&internip),
27558                    SIP_DOMAIN_AUTO, NULL);
27559       } else {
27560          ast_log(LOG_NOTICE, "Can't add wildcard IP address to domain list, please add IP address to domain manually.\n");
27561       }
27562 
27563       /* If TCP is running on a different IP than UDP, then add it too */
27564       if (!ast_sockaddr_isnull(&sip_tcp_desc.local_address) &&
27565           !ast_sockaddr_cmp(&bindaddr, &sip_tcp_desc.local_address)) {
27566          add_sip_domain(ast_sockaddr_stringify_addr(&sip_tcp_desc.local_address),
27567                    SIP_DOMAIN_AUTO, NULL);
27568       }
27569 
27570       /* If TLS is running on a different IP than UDP and TCP, then add that too */
27571       if (!ast_sockaddr_isnull(&sip_tls_desc.local_address) &&
27572           !ast_sockaddr_cmp(&bindaddr, &sip_tls_desc.local_address) &&
27573           !ast_sockaddr_cmp(&sip_tcp_desc.local_address,
27574                   &sip_tls_desc.local_address)) {
27575          add_sip_domain(ast_sockaddr_stringify_addr(&sip_tcp_desc.local_address),
27576                    SIP_DOMAIN_AUTO, NULL);
27577       }
27578 
27579       /* Our extern IP address, if configured */
27580       if (!ast_sockaddr_isnull(&externaddr)) {
27581          add_sip_domain(ast_sockaddr_stringify_addr(&externaddr),
27582                    SIP_DOMAIN_AUTO, NULL);
27583       }
27584 
27585       /* Extern host name (NAT traversal support) */
27586       if (!ast_strlen_zero(externhost)) {
27587          add_sip_domain(externhost, SIP_DOMAIN_AUTO, NULL);
27588       }
27589       
27590       /* Our host name */
27591       if (!gethostname(temp, sizeof(temp))) {
27592          add_sip_domain(temp, SIP_DOMAIN_AUTO, NULL);
27593       }
27594    }
27595 
27596    /* Release configuration from memory */
27597    ast_config_destroy(cfg);
27598 
27599    /* Load the list of manual NOTIFY types to support */
27600    if (notify_types)
27601       ast_config_destroy(notify_types);
27602    if ((notify_types = ast_config_load(notify_config, config_flags)) == CONFIG_STATUS_FILEINVALID) {
27603       ast_log(LOG_ERROR, "Contents of %s are invalid and cannot be parsed.\n", notify_config);
27604       notify_types = NULL;
27605    }
27606 
27607    /* Done, tell the manager */
27608    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);
27609    run_end = time(0);
27610    ast_debug(4, "SIP reload_config done...Runtime= %d sec\n", (int)(run_end-run_start));
27611 
27612    return 0;
27613 }
27614 
27615 static int apply_directmedia_ha(struct sip_pvt *p, const char *op)
27616 {
27617    struct ast_sockaddr us = { { 0, }, }, them = { { 0, }, };
27618    int res = AST_SENSE_ALLOW;
27619 
27620    ast_rtp_instance_get_remote_address(p->rtp, &them);
27621    ast_rtp_instance_get_local_address(p->rtp, &us);
27622 
27623    if ((res = ast_apply_ha(p->directmediaha, &them)) == AST_SENSE_DENY) {
27624       const char *us_addr = ast_strdupa(ast_sockaddr_stringify(&us));
27625       const char *them_addr = ast_strdupa(ast_sockaddr_stringify(&them));
27626 
27627       ast_debug(3, "Reinvite %s to %s denied by directmedia ACL on %s\n",
27628          op, them_addr, us_addr);
27629    }
27630 
27631    return res;
27632 }
27633 
27634 static struct ast_udptl *sip_get_udptl_peer(struct ast_channel *chan)
27635 {
27636    struct sip_pvt *p;
27637    struct ast_udptl *udptl = NULL;
27638    
27639    p = chan->tech_pvt;
27640    if (!p) {
27641       return NULL;
27642    }
27643    
27644    sip_pvt_lock(p);
27645    if (p->udptl && ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA)) {
27646       if (apply_directmedia_ha(p, "UDPTL T.38 data")) {
27647          udptl = p->udptl;
27648       }
27649    }
27650    sip_pvt_unlock(p);
27651    return udptl;
27652 }
27653 
27654 static int sip_set_udptl_peer(struct ast_channel *chan, struct ast_udptl *udptl)
27655 {
27656    struct sip_pvt *p;
27657    
27658    p = chan->tech_pvt;
27659    if (!p) {
27660       return -1;
27661    }
27662    sip_pvt_lock(p);
27663    if (udptl) {
27664       ast_udptl_get_peer(udptl, &p->udptlredirip);
27665    } else {
27666       memset(&p->udptlredirip, 0, sizeof(p->udptlredirip));
27667    }
27668    if (!ast_test_flag(&p->flags[0], SIP_GOTREFER)) {
27669       if (!p->pendinginvite) {
27670          ast_debug(3, "Sending reinvite on SIP '%s' - It's UDPTL soon redirected to IP %s\n",
27671                p->callid, ast_sockaddr_stringify(udptl ? &p->udptlredirip : &p->ourip));
27672          transmit_reinvite_with_sdp(p, TRUE, FALSE);
27673       } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
27674          ast_debug(3, "Deferring reinvite on SIP '%s' - It's UDPTL will be redirected to IP %s\n",
27675                p->callid, ast_sockaddr_stringify(udptl ? &p->udptlredirip : &p->ourip));
27676          ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
27677       }
27678    }
27679    /* Reset lastrtprx timer */
27680    p->lastrtprx = p->lastrtptx = time(NULL);
27681    sip_pvt_unlock(p);
27682    return 0;
27683 }
27684 
27685 static enum ast_rtp_glue_result sip_get_rtp_peer(struct ast_channel *chan, struct ast_rtp_instance **instance)
27686 {
27687    struct sip_pvt *p = NULL;
27688    enum ast_rtp_glue_result res = AST_RTP_GLUE_RESULT_LOCAL;
27689 
27690    if (!(p = chan->tech_pvt)) {
27691       return AST_RTP_GLUE_RESULT_FORBID;
27692    }
27693 
27694    sip_pvt_lock(p);
27695    if (!(p->rtp)) {
27696       sip_pvt_unlock(p);
27697       return AST_RTP_GLUE_RESULT_FORBID;
27698    }
27699 
27700    ao2_ref(p->rtp, +1);
27701    *instance = p->rtp;
27702 
27703    if (ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA)) {
27704       res = AST_RTP_GLUE_RESULT_REMOTE;
27705       if (!apply_directmedia_ha(p, "audio")) {
27706          res = AST_RTP_GLUE_RESULT_FORBID;
27707       }
27708    } else if (ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA_NAT)) {
27709       res = AST_RTP_GLUE_RESULT_REMOTE;
27710    } else if (ast_test_flag(&global_jbconf, AST_JB_FORCED)) {
27711       res = AST_RTP_GLUE_RESULT_FORBID;
27712    }
27713 
27714    if (p->srtp) {
27715       res = AST_RTP_GLUE_RESULT_FORBID;
27716    }
27717 
27718    sip_pvt_unlock(p);
27719 
27720    return res;
27721 }
27722 
27723 static enum ast_rtp_glue_result sip_get_vrtp_peer(struct ast_channel *chan, struct ast_rtp_instance **instance)
27724 {
27725    struct sip_pvt *p = NULL;
27726    enum ast_rtp_glue_result res = AST_RTP_GLUE_RESULT_FORBID;
27727 
27728    if (!(p = chan->tech_pvt)) {
27729       return AST_RTP_GLUE_RESULT_FORBID;
27730    }
27731 
27732    sip_pvt_lock(p);
27733    if (!(p->vrtp)) {
27734       sip_pvt_unlock(p);
27735       return AST_RTP_GLUE_RESULT_FORBID;
27736    }
27737 
27738    ao2_ref(p->vrtp, +1);
27739    *instance = p->vrtp;
27740 
27741    if (ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA)) {
27742       res = AST_RTP_GLUE_RESULT_REMOTE;
27743       if (!apply_directmedia_ha(p, "video")) {
27744          res = AST_RTP_GLUE_RESULT_FORBID;
27745       }
27746    }
27747 
27748    sip_pvt_unlock(p);
27749 
27750    return res;
27751 }
27752 
27753 static enum ast_rtp_glue_result sip_get_trtp_peer(struct ast_channel *chan, struct ast_rtp_instance **instance)
27754 {
27755    struct sip_pvt *p = NULL;
27756    enum ast_rtp_glue_result res = AST_RTP_GLUE_RESULT_FORBID;
27757 
27758    if (!(p = chan->tech_pvt)) {
27759       return AST_RTP_GLUE_RESULT_FORBID;
27760    }
27761 
27762    sip_pvt_lock(p);
27763    if (!(p->trtp)) {
27764       sip_pvt_unlock(p);
27765       return AST_RTP_GLUE_RESULT_FORBID;
27766    }
27767 
27768    ao2_ref(p->trtp, +1);
27769    *instance = p->trtp;
27770 
27771    if (ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA)) {
27772       res = AST_RTP_GLUE_RESULT_REMOTE;
27773       if (!apply_directmedia_ha(p, "text")) {
27774          res = AST_RTP_GLUE_RESULT_FORBID;
27775       }
27776    }
27777 
27778    sip_pvt_unlock(p);
27779 
27780    return res;
27781 }
27782 
27783 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)
27784 {
27785    struct sip_pvt *p;
27786    int changed = 0;
27787 
27788    p = chan->tech_pvt;
27789    if (!p) {
27790       return -1;
27791    }
27792 
27793    /* Disable early RTP bridge  */
27794    if (!ast_bridged_channel(chan) && !sip_cfg.directrtpsetup)  /* We are in early state */
27795       return 0;
27796 
27797    sip_pvt_lock(p);
27798    if (p->alreadygone) {
27799       /* If we're destroyed, don't bother */
27800       sip_pvt_unlock(p);
27801       return 0;
27802    }
27803 
27804    /* if this peer cannot handle reinvites of the media stream to devices
27805       that are known to be behind a NAT, then stop the process now
27806    */
27807    if (nat_active && !ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA_NAT)) {
27808       sip_pvt_unlock(p);
27809       return 0;
27810    }
27811 
27812    if (instance) {
27813       changed |= ast_rtp_instance_get_and_cmp_remote_address(instance, &p->redirip);
27814    } else if (!ast_sockaddr_isnull(&p->redirip)) {
27815       memset(&p->redirip, 0, sizeof(p->redirip));
27816       changed = 1;
27817    }
27818    if (vinstance) {
27819       changed |= ast_rtp_instance_get_and_cmp_remote_address(vinstance, &p->vredirip);
27820    } else if (!ast_sockaddr_isnull(&p->vredirip)) {
27821       memset(&p->vredirip, 0, sizeof(p->vredirip));
27822       changed = 1;
27823    }
27824    if (tinstance) {
27825       changed |= ast_rtp_instance_get_and_cmp_remote_address(tinstance, &p->tredirip);
27826    } else if (!ast_sockaddr_isnull(&p->tredirip)) {
27827       memset(&p->tredirip, 0, sizeof(p->tredirip));
27828       changed = 1;
27829    }
27830    if (codecs && (p->redircodecs != codecs)) {
27831       p->redircodecs = codecs;
27832       changed = 1;
27833    }
27834    if (changed && !ast_test_flag(&p->flags[0], SIP_GOTREFER) && !ast_test_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER)) {
27835       if (chan->_state != AST_STATE_UP) {     /* We are in early state */
27836          if (p->do_history)
27837             append_history(p, "ExtInv", "Initial invite sent with remote bridge proposal.");
27838          ast_debug(1, "Early remote bridge setting SIP '%s' - Sending media to %s\n", p->callid, ast_sockaddr_stringify(instance ? &p->redirip : &p->ourip));
27839       } else if (!p->pendinginvite) {   /* We are up, and have no outstanding invite */
27840          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));
27841          transmit_reinvite_with_sdp(p, FALSE, FALSE);
27842       } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
27843          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));
27844          /* We have a pending Invite. Send re-invite when we're done with the invite */
27845          ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
27846       }
27847    }
27848    /* Reset lastrtprx timer */
27849    p->lastrtprx = p->lastrtptx = time(NULL);
27850    sip_pvt_unlock(p);
27851    return 0;
27852 }
27853 
27854 static format_t sip_get_codec(struct ast_channel *chan)
27855 {
27856    struct sip_pvt *p = chan->tech_pvt;
27857    return p->peercapability ? p->peercapability : p->capability;
27858 }
27859 
27860 static struct ast_rtp_glue sip_rtp_glue = {
27861    .type = "SIP",
27862    .get_rtp_info = sip_get_rtp_peer,
27863    .get_vrtp_info = sip_get_vrtp_peer,
27864    .get_trtp_info = sip_get_trtp_peer,
27865    .update_peer = sip_set_rtp_peer,
27866    .get_codec = sip_get_codec,
27867 };
27868 
27869 static char *app_dtmfmode = "SIPDtmfMode";
27870 static char *app_sipaddheader = "SIPAddHeader";
27871 static char *app_sipremoveheader = "SIPRemoveHeader";
27872 
27873 /*! \brief Set the DTMFmode for an outbound SIP call (application) */
27874 static int sip_dtmfmode(struct ast_channel *chan, const char *data)
27875 {
27876    struct sip_pvt *p;
27877    const char *mode = data;
27878 
27879    if (!data) {
27880       ast_log(LOG_WARNING, "This application requires the argument: info, inband, rfc2833\n");
27881       return 0;
27882    }
27883    ast_channel_lock(chan);
27884    if (!IS_SIP_TECH(chan->tech)) {
27885       ast_log(LOG_WARNING, "Call this application only on SIP incoming calls\n");
27886       ast_channel_unlock(chan);
27887       return 0;
27888    }
27889    p = chan->tech_pvt;
27890    if (!p) {
27891       ast_channel_unlock(chan);
27892       return 0;
27893    }
27894    sip_pvt_lock(p);
27895    if (!strcasecmp(mode, "info")) {
27896       ast_clear_flag(&p->flags[0], SIP_DTMF);
27897       ast_set_flag(&p->flags[0], SIP_DTMF_INFO);
27898       p->jointnoncodeccapability &= ~AST_RTP_DTMF;
27899    } else if (!strcasecmp(mode, "shortinfo")) {
27900       ast_clear_flag(&p->flags[0], SIP_DTMF);
27901       ast_set_flag(&p->flags[0], SIP_DTMF_SHORTINFO);
27902       p->jointnoncodeccapability &= ~AST_RTP_DTMF;
27903    } else if (!strcasecmp(mode, "rfc2833")) {
27904       ast_clear_flag(&p->flags[0], SIP_DTMF);
27905       ast_set_flag(&p->flags[0], SIP_DTMF_RFC2833);
27906       p->jointnoncodeccapability |= AST_RTP_DTMF;
27907    } else if (!strcasecmp(mode, "inband")) {
27908       ast_clear_flag(&p->flags[0], SIP_DTMF);
27909       ast_set_flag(&p->flags[0], SIP_DTMF_INBAND);
27910       p->jointnoncodeccapability &= ~AST_RTP_DTMF;
27911    } else {
27912       ast_log(LOG_WARNING, "I don't know about this dtmf mode: %s\n", mode);
27913    }
27914    if (p->rtp)
27915       ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_DTMF, ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
27916    if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) ||
27917        (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO)) {
27918       enable_dsp_detect(p);
27919    } else {
27920       disable_dsp_detect(p);
27921    }
27922    sip_pvt_unlock(p);
27923    ast_channel_unlock(chan);
27924    return 0;
27925 }
27926 
27927 /*! \brief Add a SIP header to an outbound INVITE */
27928 static int sip_addheader(struct ast_channel *chan, const char *data)
27929 {
27930    int no = 0;
27931    int ok = FALSE;
27932    char varbuf[30];
27933    const char *inbuf = data;
27934    char *subbuf;
27935    
27936    if (ast_strlen_zero(inbuf)) {
27937       ast_log(LOG_WARNING, "This application requires the argument: Header\n");
27938       return 0;
27939    }
27940    ast_channel_lock(chan);
27941 
27942    /* Check for headers */
27943    while (!ok && no <= 50) {
27944       no++;
27945       snprintf(varbuf, sizeof(varbuf), "__SIPADDHEADER%.2d", no);
27946 
27947       /* Compare without the leading underscores */
27948       if ((pbx_builtin_getvar_helper(chan, (const char *) varbuf + 2) == (const char *) NULL)) {
27949          ok = TRUE;
27950       }
27951    }
27952    if (ok) {
27953       size_t len = strlen(inbuf);
27954       subbuf = alloca(len + 1);
27955       ast_get_encoded_str(inbuf, subbuf, len + 1);
27956       pbx_builtin_setvar_helper(chan, varbuf, subbuf);
27957       if (sipdebug) {
27958          ast_debug(1, "SIP Header added \"%s\" as %s\n", inbuf, varbuf);
27959       }
27960    } else {
27961       ast_log(LOG_WARNING, "Too many SIP headers added, max 50\n");
27962    }
27963    ast_channel_unlock(chan);
27964    return 0;
27965 }
27966 
27967 /*! \brief Remove SIP headers added previously with SipAddHeader application */
27968 static int sip_removeheader(struct ast_channel *chan, const char *data)
27969 {
27970    struct ast_var_t *newvariable;
27971    struct varshead *headp;
27972    int removeall = 0;
27973    char *inbuf = (char *) data;
27974 
27975    if (ast_strlen_zero(inbuf)) {
27976       removeall = 1;
27977    }
27978    ast_channel_lock(chan);
27979 
27980    headp=&chan->varshead;
27981    AST_LIST_TRAVERSE_SAFE_BEGIN (headp, newvariable, entries) {
27982       if (strncasecmp(ast_var_name(newvariable), "SIPADDHEADER", strlen("SIPADDHEADER")) == 0) {
27983          if (removeall || (!strncasecmp(ast_var_value(newvariable),inbuf,strlen(inbuf)))) {
27984             if (sipdebug)
27985                ast_debug(1,"removing SIP Header \"%s\" as %s\n",
27986                   ast_var_value(newvariable),
27987                   ast_var_name(newvariable));
27988             AST_LIST_REMOVE_CURRENT(entries);
27989             ast_var_delete(newvariable);
27990          }
27991       }
27992    }
27993    AST_LIST_TRAVERSE_SAFE_END;
27994 
27995    ast_channel_unlock(chan);
27996    return 0;
27997 }
27998 
27999 /*! \brief Transfer call before connect with a 302 redirect
28000 \note Called by the transfer() dialplan application through the sip_transfer()
28001    pbx interface function if the call is in ringing state
28002 \todo Fix this function so that we wait for reply to the REFER and
28003    react to errors, denials or other issues the other end might have.
28004  */
28005 static int sip_sipredirect(struct sip_pvt *p, const char *dest)
28006 {
28007    char *cdest;
28008    char *extension, *domain;
28009 
28010    cdest = ast_strdupa(dest);
28011    
28012    extension = strsep(&cdest, "@");
28013    domain = strsep(&cdest, ":");
28014    if (ast_strlen_zero(extension)) {
28015       ast_log(LOG_ERROR, "Missing mandatory argument: extension\n");
28016       return 0;
28017    }
28018 
28019    /* we'll issue the redirect message here */
28020    if (!domain) {
28021       char *local_to_header;
28022       char to_header[256];
28023 
28024       ast_copy_string(to_header, get_header(&p->initreq, "To"), sizeof(to_header));
28025       if (ast_strlen_zero(to_header)) {
28026          ast_log(LOG_ERROR, "Cannot retrieve the 'To' header from the original SIP request!\n");
28027          return 0;
28028       }
28029       if (((local_to_header = strcasestr(to_header, "sip:")) || (local_to_header = strcasestr(to_header, "sips:")))
28030          && (local_to_header = strchr(local_to_header, '@'))) {
28031          char ldomain[256];
28032 
28033          memset(ldomain, 0, sizeof(ldomain));
28034          local_to_header++;
28035          /* This is okey because lhost and lport are as big as tmp */
28036          sscanf(local_to_header, "%256[^<>; ]", ldomain);
28037          if (ast_strlen_zero(ldomain)) {
28038             ast_log(LOG_ERROR, "Can't find the host address\n");
28039             return 0;
28040          }
28041          domain = ast_strdupa(ldomain);
28042       }
28043    }
28044 
28045    ast_string_field_build(p, our_contact, "Transfer <sip:%s@%s>", extension, domain);
28046    transmit_response_reliable(p, "302 Moved Temporarily", &p->initreq);
28047 
28048    sip_scheddestroy(p, SIP_TRANS_TIMEOUT);   /* Make sure we stop send this reply. */
28049    sip_alreadygone(p);
28050 
28051    if (p->owner) {
28052       enum ast_control_transfer message = AST_TRANSFER_SUCCESS;
28053       ast_queue_control_data(p->owner, AST_CONTROL_TRANSFER, &message, sizeof(message));
28054    }
28055    /* hangup here */
28056    return 0;
28057 }
28058 
28059 static int sip_is_xml_parsable(void)
28060 {
28061 #ifdef HAVE_LIBXML2
28062    return TRUE;
28063 #else
28064    return FALSE;
28065 #endif
28066 }
28067 
28068 /*! \brief Send a poke to all known peers */
28069 static void sip_poke_all_peers(void)
28070 {
28071    int ms = 0, num = 0;
28072    struct ao2_iterator i;
28073    struct sip_peer *peer;
28074 
28075    if (!speerobjs) { /* No peers, just give up */
28076       return;
28077    }
28078 
28079    i = ao2_iterator_init(peers, 0);
28080    while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
28081       ao2_lock(peer);
28082       if (num == global_qualify_peers) {
28083          ms += global_qualify_gap;
28084          num = 0;
28085       } else {
28086          num++;
28087       }
28088       AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched, ms, sip_poke_peer_s, peer,
28089             unref_peer(_data, "removing poke peer ref"),
28090             unref_peer(peer, "removing poke peer ref"),
28091             ref_peer(peer, "adding poke peer ref"));
28092       ao2_unlock(peer);
28093       unref_peer(peer, "toss iterator peer ptr");
28094    }
28095    ao2_iterator_destroy(&i);
28096 }
28097 
28098 /*! \brief Send all known registrations */
28099 static void sip_send_all_registers(void)
28100 {
28101    int ms;
28102    int regspacing;
28103    if (!regobjs)
28104       return;
28105    regspacing = default_expiry * 1000/regobjs;
28106    if (regspacing > 100) {
28107       regspacing = 100;
28108    }
28109    ms = regspacing;
28110    ASTOBJ_CONTAINER_TRAVERSE(&regl, 1, do {
28111       ASTOBJ_WRLOCK(iterator);
28112       ms += regspacing;
28113       AST_SCHED_REPLACE_UNREF(iterator->expire, sched, ms, sip_reregister, iterator,
28114                         registry_unref(_data, "REPLACE sched del decs the refcount"),
28115                         registry_unref(iterator, "REPLACE sched add failure decs the refcount"),
28116                         registry_addref(iterator, "REPLACE sched add incs the refcount"));
28117       ASTOBJ_UNLOCK(iterator);
28118    } while (0)
28119    );
28120 }
28121 
28122 /*! \brief Send all MWI subscriptions */
28123 static void sip_send_all_mwi_subscriptions(void)
28124 {
28125    ASTOBJ_CONTAINER_TRAVERSE(&submwil, 1, do {
28126       ASTOBJ_WRLOCK(iterator);
28127       AST_SCHED_DEL(sched, iterator->resub);
28128       if ((iterator->resub = ast_sched_add(sched, 1, sip_subscribe_mwi_do, ASTOBJ_REF(iterator))) < 0) {
28129          ASTOBJ_UNREF(iterator, sip_subscribe_mwi_destroy);
28130       }
28131       ASTOBJ_UNLOCK(iterator);
28132    } while (0));
28133 }
28134 
28135 /* SRTP */
28136 static int setup_srtp(struct sip_srtp **srtp)
28137 {
28138    if (!ast_rtp_engine_srtp_is_registered()) {
28139       ast_log(LOG_ERROR, "No SRTP module loaded, can't setup SRTP session.\n");
28140       return -1;
28141    }
28142 
28143    if (!(*srtp = sip_srtp_alloc())) { /* Allocate SRTP data structure */
28144       return -1;
28145    }
28146 
28147    return 0;
28148 }
28149 
28150 static int process_crypto(struct sip_pvt *p, struct ast_rtp_instance *rtp, struct sip_srtp **srtp, const char *a)
28151 {
28152    if (strncasecmp(a, "crypto:", 7)) {
28153       return FALSE;
28154    }
28155    if (!*srtp) {
28156       if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
28157          ast_log(LOG_WARNING, "Ignoring unexpected crypto attribute in SDP answer\n");
28158          return FALSE;
28159       }
28160 
28161       if (setup_srtp(srtp) < 0) {
28162          return FALSE;
28163       }
28164    }
28165 
28166    /* For now, when we receive an INVITE just take the first successful crypto line */
28167    if ((*srtp)->crypto && !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
28168       ast_debug(3, "We've already processed a crypto attribute, skipping '%s'\n", a);
28169       return FALSE;
28170    }
28171 
28172    if (!(*srtp)->crypto && !((*srtp)->crypto = sdp_crypto_setup())) {
28173       return FALSE;
28174    }
28175 
28176    if (sdp_crypto_process((*srtp)->crypto, a, rtp) < 0) {
28177       return FALSE;
28178    }
28179 
28180    ast_set_flag(*srtp, SRTP_CRYPTO_OFFER_OK);
28181 
28182    return TRUE;
28183 }
28184 
28185 /*! \brief Reload module */
28186 static int sip_do_reload(enum channelreloadreason reason)
28187 {
28188    time_t start_poke, end_poke;
28189    
28190    reload_config(reason);
28191    ast_sched_dump(sched);
28192 
28193    start_poke = time(0);
28194    /* Prune peers who still are supposed to be deleted */
28195    unlink_marked_peers_from_tables();
28196 
28197    ast_debug(4, "--------------- Done destroying pruned peers\n");
28198 
28199    /* Send qualify (OPTIONS) to all peers */
28200    sip_poke_all_peers();
28201 
28202    /* Register with all services */
28203    sip_send_all_registers();
28204 
28205    sip_send_all_mwi_subscriptions();
28206 
28207    end_poke = time(0);
28208    
28209    ast_debug(4, "do_reload finished. peer poke/prune reg contact time = %d sec.\n", (int)(end_poke-start_poke));
28210 
28211    ast_debug(4, "--------------- SIP reload done\n");
28212 
28213    return 0;
28214 }
28215 
28216 /*! \brief Force reload of module from cli */
28217 static char *sip_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
28218 {
28219    
28220    switch (cmd) {
28221    case CLI_INIT:
28222       e->command = "sip reload";
28223       e->usage =
28224          "Usage: sip reload\n"
28225          "       Reloads SIP configuration from sip.conf\n";
28226       return NULL;
28227    case CLI_GENERATE:
28228       return NULL;
28229    }
28230 
28231    ast_mutex_lock(&sip_reload_lock);
28232    if (sip_reloading) {
28233       ast_verbose("Previous SIP reload not yet done\n");
28234    } else {
28235       sip_reloading = TRUE;
28236       sip_reloadreason = (a && a->fd) ? CHANNEL_CLI_RELOAD : CHANNEL_MODULE_RELOAD;
28237    }
28238    ast_mutex_unlock(&sip_reload_lock);
28239    restart_monitor();
28240 
28241    return CLI_SUCCESS;
28242 }
28243 
28244 /*! \brief  Part of Asterisk module interface */
28245 static int reload(void)
28246 {
28247    if (sip_reload(0, 0, NULL))
28248       return 0;
28249    return 1;
28250 }
28251 
28252 /*! \brief  Return the first entry from ast_sockaddr_resolve filtered by address family
28253  *
28254  * \warn Using this function probably means you have a faulty design.
28255  */
28256 static int ast_sockaddr_resolve_first_af(struct ast_sockaddr *addr,
28257                   const char* name, int flag, int family)
28258 {
28259    struct ast_sockaddr *addrs;
28260    int addrs_cnt;
28261 
28262    addrs_cnt = ast_sockaddr_resolve(&addrs, name, flag, family);
28263    if (addrs_cnt <= 0) {
28264       return 1;
28265    }
28266    if (addrs_cnt > 1) {
28267       ast_debug(1, "Multiple addresses, using the first one only\n");
28268    }
28269 
28270    ast_sockaddr_copy(addr, &addrs[0]);
28271 
28272    ast_free(addrs);
28273    return 0;
28274 }
28275 
28276 /*! \brief  Return the first entry from ast_sockaddr_resolve filtered by family of binddaddr
28277  *
28278  * \warn Using this function probably means you have a faulty design.
28279  */
28280 static int ast_sockaddr_resolve_first(struct ast_sockaddr *addr,
28281                   const char* name, int flag)
28282 {
28283    return ast_sockaddr_resolve_first_af(addr, name, flag, get_address_family_filter(&bindaddr));
28284 }
28285 
28286 /*! \brief
28287  * \note The only member of the peer used here is the name field
28288  */
28289 static int peer_hash_cb(const void *obj, const int flags)
28290 {
28291    const struct sip_peer *peer = obj;
28292 
28293    return ast_str_case_hash(peer->name);
28294 }
28295 
28296 /*!
28297  * \note The only member of the peer used here is the name field
28298  */
28299 static int peer_cmp_cb(void *obj, void *arg, int flags)
28300 {
28301    struct sip_peer *peer = obj, *peer2 = arg;
28302 
28303    return !strcasecmp(peer->name, peer2->name) ? CMP_MATCH | CMP_STOP : 0;
28304 }
28305 
28306 /*!
28307  * Hash function based on the the peer's ip address.  For IPv6, we use the end
28308  * of the address.
28309  * \todo Find a better hashing function
28310  */
28311 static int peer_iphash_cb(const void *obj, const int flags)
28312 {
28313    const struct sip_peer *peer = obj;
28314    int ret = 0;
28315 
28316    if (ast_sockaddr_isnull(&peer->addr)) {
28317       ast_log(LOG_ERROR, "Empty address\n");
28318    }
28319 
28320    ret = ast_sockaddr_hash(&peer->addr);
28321 
28322    if (ret < 0) {
28323       ret = -ret;
28324    }
28325 
28326    return ret;
28327 }
28328 
28329 /*!
28330  * Match Peers by IP and Port number.
28331  *
28332  * This function has two modes.
28333  *  - If the peer arg does not have INSECURE_PORT set, then we will only return
28334  *    a match for a peer that matches both the IP and port.
28335  *  - If the peer arg does have the INSECURE_PORT flag set, then we will only
28336  *    return a match for a peer that matches the IP and has insecure=port
28337  *    in its configuration.
28338  *
28339  * This callback will be used twice when doing peer matching.  There is a first
28340  * pass for full IP+port matching, and a second pass in case there is a match
28341  * that meets the insecure=port criteria.
28342  *
28343  * \note Connections coming in over TCP or TLS should never be matched by port.
28344  *
28345  * \note the peer's addr struct provides to fields combined to make a key: the sin_addr.s_addr and sin_port fields.
28346  */
28347 static int peer_ipcmp_cb(void *obj, void *arg, int flags)
28348 {
28349    struct sip_peer *peer = obj, *peer2 = arg;
28350 
28351    if (ast_sockaddr_cmp_addr(&peer->addr, &peer2->addr)) {
28352       /* IP doesn't match */
28353       return 0;
28354    }
28355 
28356    /* We matched the IP, check to see if we need to match by port as well. */
28357    if ((peer->transports & peer2->transports) & (SIP_TRANSPORT_TLS | SIP_TRANSPORT_TCP)) {
28358       /* peer matching on port is not possible with TCP/TLS */
28359       return CMP_MATCH | CMP_STOP;
28360    } else if (ast_test_flag(&peer2->flags[0], SIP_INSECURE_PORT)) {
28361       /* We are allowing match without port for peers configured that
28362        * way in this pass through the peers. */
28363       return ast_test_flag(&peer->flags[0], SIP_INSECURE_PORT) ?
28364             (CMP_MATCH | CMP_STOP) : 0;
28365    }
28366 
28367    /* Now only return a match if the port matches, as well. */
28368    return ast_sockaddr_port(&peer->addr) == ast_sockaddr_port(&peer2->addr) ?
28369          (CMP_MATCH | CMP_STOP) : 0;
28370 }
28371 
28372 
28373 static int threadt_hash_cb(const void *obj, const int flags)
28374 {
28375    const struct sip_threadinfo *th = obj;
28376 
28377    return ast_sockaddr_hash(&th->tcptls_session->remote_address);
28378 }
28379 
28380 static int threadt_cmp_cb(void *obj, void *arg, int flags)
28381 {
28382    struct sip_threadinfo *th = obj, *th2 = arg;
28383 
28384    return (th->tcptls_session == th2->tcptls_session) ? CMP_MATCH | CMP_STOP : 0;
28385 }
28386 
28387 /*!
28388  * \note The only member of the dialog used here callid string
28389  */
28390 static int dialog_hash_cb(const void *obj, const int flags)
28391 {
28392    const struct sip_pvt *pvt = obj;
28393 
28394    return ast_str_case_hash(pvt->callid);
28395 }
28396 
28397 /*!
28398  * \note Same as dialog_cmp_cb, except without the CMP_STOP on match
28399  */
28400 static int dialog_find_multiple(void *obj, void *arg, int flags)
28401 {
28402    struct sip_pvt *pvt = obj, *pvt2 = arg;
28403 
28404    return !strcasecmp(pvt->callid, pvt2->callid) ? CMP_MATCH : 0;
28405 }
28406 
28407 /*!
28408  * \note The only member of the dialog used here callid string
28409  */
28410 static int dialog_cmp_cb(void *obj, void *arg, int flags)
28411 {
28412    struct sip_pvt *pvt = obj, *pvt2 = arg;
28413 
28414    return !strcasecmp(pvt->callid, pvt2->callid) ? CMP_MATCH | CMP_STOP : 0;
28415 }
28416 
28417 /*! \brief SIP Cli commands definition */
28418 static struct ast_cli_entry cli_sip[] = {
28419    AST_CLI_DEFINE(sip_show_channels, "List active SIP channels or subscriptions"),
28420    AST_CLI_DEFINE(sip_show_channelstats, "List statistics for active SIP channels"),
28421    AST_CLI_DEFINE(sip_show_domains, "List our local SIP domains"),
28422    AST_CLI_DEFINE(sip_show_inuse, "List all inuse/limits"),
28423    AST_CLI_DEFINE(sip_show_objects, "List all SIP object allocations"),
28424    AST_CLI_DEFINE(sip_show_peers, "List defined SIP peers"),
28425    AST_CLI_DEFINE(sip_show_registry, "List SIP registration status"),
28426    AST_CLI_DEFINE(sip_unregister, "Unregister (force expiration) a SIP peer from the registry"),
28427    AST_CLI_DEFINE(sip_show_settings, "Show SIP global settings"),
28428    AST_CLI_DEFINE(sip_show_mwi, "Show MWI subscriptions"),
28429    AST_CLI_DEFINE(sip_cli_notify, "Send a notify packet to a SIP peer"),
28430    AST_CLI_DEFINE(sip_show_channel, "Show detailed SIP channel info"),
28431    AST_CLI_DEFINE(sip_show_history, "Show SIP dialog history"),
28432    AST_CLI_DEFINE(sip_show_peer, "Show details on specific SIP peer"),
28433    AST_CLI_DEFINE(sip_show_users, "List defined SIP users"),
28434    AST_CLI_DEFINE(sip_show_user, "Show details on specific SIP user"),
28435    AST_CLI_DEFINE(sip_qualify_peer, "Send an OPTIONS packet to a peer"),
28436    AST_CLI_DEFINE(sip_show_sched, "Present a report on the status of the scheduler queue"),
28437    AST_CLI_DEFINE(sip_prune_realtime, "Prune cached Realtime users/peers"),
28438    AST_CLI_DEFINE(sip_do_debug, "Enable/Disable SIP debugging"),
28439    AST_CLI_DEFINE(sip_set_history, "Enable/Disable SIP history"),
28440    AST_CLI_DEFINE(sip_reload, "Reload SIP configuration"),
28441    AST_CLI_DEFINE(sip_show_tcp, "List TCP Connections")
28442 };
28443 
28444 /*! \brief SIP test registration */
28445 static void sip_register_tests(void)
28446 {
28447    sip_config_parser_register_tests();
28448    sip_request_parser_register_tests();
28449    sip_dialplan_function_register_tests();
28450 }
28451 
28452 /*! \brief SIP test registration */
28453 static void sip_unregister_tests(void)
28454 {
28455    sip_config_parser_unregister_tests();
28456    sip_request_parser_unregister_tests();
28457    sip_dialplan_function_unregister_tests();
28458 }
28459 
28460 #ifdef TEST_FRAMEWORK
28461 AST_TEST_DEFINE(test_sip_mwi_subscribe_parse)
28462 {
28463    int found = 0;
28464    enum ast_test_result_state res = AST_TEST_PASS;
28465    const char *mwi1 = "1234@mysipprovider.com/1234";
28466    const char *mwi2 = "1234:password@mysipprovider.com/1234";
28467    const char *mwi3 = "1234:password@mysipprovider.com:5061/1234";
28468    const char *mwi4 = "1234:password:authuser@mysipprovider.com/1234";
28469    const char *mwi5 = "1234:password:authuser@mysipprovider.com:5061/1234";
28470    const char *mwi6 = "1234:password";
28471 
28472    switch (cmd) {
28473    case TEST_INIT:
28474       info->name = "sip_mwi_subscribe_parse_test";
28475       info->category = "/channels/chan_sip/";
28476       info->summary = "SIP MWI subscribe line parse unit test";
28477       info->description =
28478          "Tests the parsing of mwi subscription lines (e.g., mwi => from sip.conf)";
28479       return AST_TEST_NOT_RUN;
28480    case TEST_EXECUTE:
28481       break;
28482    }
28483 
28484    if (sip_subscribe_mwi(mwi1, 1)) {
28485       res = AST_TEST_FAIL;
28486    } else {
28487       found = 0;
28488       res = AST_TEST_FAIL;
28489       ASTOBJ_CONTAINER_TRAVERSE(&submwil, 1, do {
28490          ASTOBJ_WRLOCK(iterator);
28491          if (
28492             !strcmp(iterator->hostname, "mysipprovider.com") &&
28493             !strcmp(iterator->username, "1234") &&
28494             !strcmp(iterator->secret, "") &&
28495             !strcmp(iterator->authuser, "") &&
28496             !strcmp(iterator->mailbox, "1234") &&
28497             iterator->portno == 0) {
28498             found = 1;
28499             res = AST_TEST_PASS;
28500          }
28501          ASTOBJ_UNLOCK(iterator);
28502       } while(0));
28503       if (!found) {
28504          ast_test_status_update(test, "sip_subscribe_mwi test 1 failed\n");
28505       }
28506    }
28507 
28508    if (sip_subscribe_mwi(mwi2, 1)) {
28509       res = AST_TEST_FAIL;
28510    } else {
28511       found = 0;
28512       res = AST_TEST_FAIL;
28513       ASTOBJ_CONTAINER_TRAVERSE(&submwil, 1, do {
28514          ASTOBJ_WRLOCK(iterator);
28515          if (
28516             !strcmp(iterator->hostname, "mysipprovider.com") &&
28517             !strcmp(iterator->username, "1234") &&
28518             !strcmp(iterator->secret, "password") &&
28519             !strcmp(iterator->authuser, "") &&
28520             !strcmp(iterator->mailbox, "1234") &&
28521             iterator->portno == 0) {
28522             found = 1;
28523             res = AST_TEST_PASS;
28524          }
28525          ASTOBJ_UNLOCK(iterator);
28526       } while(0));
28527       if (!found) {
28528          ast_test_status_update(test, "sip_subscribe_mwi test 2 failed\n");
28529       }
28530    }
28531 
28532    if (sip_subscribe_mwi(mwi3, 1)) {
28533       res = AST_TEST_FAIL;
28534    } else {
28535       found = 0;
28536       res = AST_TEST_FAIL;
28537       ASTOBJ_CONTAINER_TRAVERSE(&submwil, 1, do {
28538          ASTOBJ_WRLOCK(iterator);
28539          if (
28540             !strcmp(iterator->hostname, "mysipprovider.com") &&
28541             !strcmp(iterator->username, "1234") &&
28542             !strcmp(iterator->secret, "password") &&
28543             !strcmp(iterator->authuser, "") &&
28544             !strcmp(iterator->mailbox, "1234") &&
28545             iterator->portno == 5061) {
28546             found = 1;
28547             res = AST_TEST_PASS;
28548          }
28549          ASTOBJ_UNLOCK(iterator);
28550       } while(0));
28551       if (!found) {
28552          ast_test_status_update(test, "sip_subscribe_mwi test 3 failed\n");
28553       }
28554    }
28555 
28556    if (sip_subscribe_mwi(mwi4, 1)) {
28557       res = AST_TEST_FAIL;
28558    } else {
28559       found = 0;
28560       res = AST_TEST_FAIL;
28561       ASTOBJ_CONTAINER_TRAVERSE(&submwil, 1, do {
28562          ASTOBJ_WRLOCK(iterator);
28563          if (
28564             !strcmp(iterator->hostname, "mysipprovider.com") &&
28565             !strcmp(iterator->username, "1234") &&
28566             !strcmp(iterator->secret, "password") &&
28567             !strcmp(iterator->authuser, "authuser") &&
28568             !strcmp(iterator->mailbox, "1234") &&
28569             iterator->portno == 0) {
28570             found = 1;
28571             res = AST_TEST_PASS;
28572          }
28573          ASTOBJ_UNLOCK(iterator);
28574       } while(0));
28575       if (!found) {
28576          ast_test_status_update(test, "sip_subscribe_mwi test 4 failed\n");
28577       }
28578    }
28579 
28580    if (sip_subscribe_mwi(mwi5, 1)) {
28581       res = AST_TEST_FAIL;
28582    } else {
28583       found = 0;
28584       res = AST_TEST_FAIL;
28585       ASTOBJ_CONTAINER_TRAVERSE(&submwil, 1, do {
28586          ASTOBJ_WRLOCK(iterator);
28587          if (
28588             !strcmp(iterator->hostname, "mysipprovider.com") &&
28589             !strcmp(iterator->username, "1234") &&
28590             !strcmp(iterator->secret, "password") &&
28591             !strcmp(iterator->authuser, "authuser") &&
28592             !strcmp(iterator->mailbox, "1234") &&
28593             iterator->portno == 5061) {
28594             found = 1;
28595             res = AST_TEST_PASS;
28596          }
28597          ASTOBJ_UNLOCK(iterator);
28598       } while(0));
28599       if (!found) {
28600          ast_test_status_update(test, "sip_subscribe_mwi test 5 failed\n");
28601       }
28602    }
28603    
28604    if (sip_subscribe_mwi(mwi6, 1)) {
28605       res = AST_TEST_PASS;
28606    } else {
28607       res = AST_TEST_FAIL;
28608    }
28609    return res;
28610 }
28611 
28612 AST_TEST_DEFINE(test_sip_peers_get)
28613 {
28614    struct sip_peer *peer;
28615    struct ast_data *node;
28616    struct ast_data_query query = {
28617       .path = "/asterisk/channel/sip/peers",
28618       .search = "peers/peer/name=test_peer_data_provider"
28619    };
28620 
28621    switch (cmd) {
28622       case TEST_INIT:
28623          info->name = "sip_peers_get_data_test";
28624          info->category = "/main/data/sip/peers/";
28625          info->summary = "SIP peers data providers unit test";
28626          info->description =
28627             "Tests whether the SIP peers data provider implementation works as expected.";
28628          return AST_TEST_NOT_RUN;
28629       case TEST_EXECUTE:
28630          break;
28631    }
28632 
28633    /* Create the peer that we will retrieve. */
28634    peer = build_peer("test_peer_data_provider", NULL, NULL, 0, 0);
28635    if (!peer) {
28636       return AST_TEST_FAIL;
28637    }
28638    peer->type = SIP_TYPE_USER;
28639    peer->call_limit = 10;
28640    ao2_link(peers, peer);
28641 
28642    /* retrieve the chan_sip/peers tree and check the created peer. */
28643    node = ast_data_get(&query);
28644    if (!node) {
28645       ao2_unlink(peers, peer);
28646       ao2_ref(peer, -1);
28647       return AST_TEST_FAIL;
28648    }
28649 
28650    /* compare item. */
28651    if (strcmp(ast_data_retrieve_string(node, "peer/name"), "test_peer_data_provider")) {
28652       ao2_unlink(peers, peer);
28653       ao2_ref(peer, -1);
28654       ast_data_free(node);
28655       return AST_TEST_FAIL;
28656    }
28657 
28658    if (strcmp(ast_data_retrieve_string(node, "peer/type"), "user")) {
28659       ao2_unlink(peers, peer);
28660       ao2_ref(peer, -1);
28661       ast_data_free(node);
28662       return AST_TEST_FAIL;
28663    }
28664 
28665    if (ast_data_retrieve_int(node, "peer/call_limit") != 10) {
28666       ao2_unlink(peers, peer);
28667       ao2_ref(peer, -1);
28668       ast_data_free(node);
28669       return AST_TEST_FAIL;
28670    }
28671 
28672    /* release resources */
28673    ast_data_free(node);
28674 
28675    ao2_unlink(peers, peer);
28676    ao2_ref(peer, -1);
28677 
28678    return AST_TEST_PASS;
28679 }
28680 
28681 #endif
28682 
28683 #define DATA_EXPORT_SIP_PEER(MEMBER)            \
28684    MEMBER(sip_peer, name, AST_DATA_STRING)         \
28685    MEMBER(sip_peer, secret, AST_DATA_PASSWORD)     \
28686    MEMBER(sip_peer, md5secret, AST_DATA_PASSWORD)     \
28687    MEMBER(sip_peer, remotesecret, AST_DATA_PASSWORD)  \
28688    MEMBER(sip_peer, context, AST_DATA_STRING)      \
28689    MEMBER(sip_peer, subscribecontext, AST_DATA_STRING)   \
28690    MEMBER(sip_peer, username, AST_DATA_STRING)     \
28691    MEMBER(sip_peer, accountcode, AST_DATA_STRING)     \
28692    MEMBER(sip_peer, tohost, AST_DATA_STRING)    \
28693    MEMBER(sip_peer, regexten, AST_DATA_STRING)     \
28694    MEMBER(sip_peer, fromuser, AST_DATA_STRING)     \
28695    MEMBER(sip_peer, fromdomain, AST_DATA_STRING)      \
28696    MEMBER(sip_peer, fullcontact, AST_DATA_STRING)     \
28697    MEMBER(sip_peer, cid_num, AST_DATA_STRING)      \
28698    MEMBER(sip_peer, cid_name, AST_DATA_STRING)     \
28699    MEMBER(sip_peer, vmexten, AST_DATA_STRING)      \
28700    MEMBER(sip_peer, language, AST_DATA_STRING)     \
28701    MEMBER(sip_peer, mohinterpret, AST_DATA_STRING)    \
28702    MEMBER(sip_peer, mohsuggest, AST_DATA_STRING)      \
28703    MEMBER(sip_peer, parkinglot, AST_DATA_STRING)      \
28704    MEMBER(sip_peer, useragent, AST_DATA_STRING)    \
28705    MEMBER(sip_peer, mwi_from, AST_DATA_STRING)     \
28706    MEMBER(sip_peer, engine, AST_DATA_STRING)    \
28707    MEMBER(sip_peer, unsolicited_mailbox, AST_DATA_STRING)   \
28708    MEMBER(sip_peer, is_realtime, AST_DATA_BOOLEAN)    \
28709    MEMBER(sip_peer, host_dynamic, AST_DATA_BOOLEAN)   \
28710    MEMBER(sip_peer, autoframing, AST_DATA_BOOLEAN)    \
28711    MEMBER(sip_peer, inUse, AST_DATA_INTEGER)    \
28712    MEMBER(sip_peer, inRinging, AST_DATA_INTEGER)      \
28713    MEMBER(sip_peer, onHold, AST_DATA_INTEGER)      \
28714    MEMBER(sip_peer, call_limit, AST_DATA_INTEGER)     \
28715    MEMBER(sip_peer, t38_maxdatagram, AST_DATA_INTEGER)   \
28716    MEMBER(sip_peer, maxcallbitrate, AST_DATA_INTEGER) \
28717    MEMBER(sip_peer, rtptimeout, AST_DATA_SECONDS)     \
28718    MEMBER(sip_peer, rtpholdtimeout, AST_DATA_SECONDS) \
28719    MEMBER(sip_peer, rtpkeepalive, AST_DATA_SECONDS)   \
28720    MEMBER(sip_peer, lastms, AST_DATA_MILLISECONDS)    \
28721    MEMBER(sip_peer, maxms, AST_DATA_MILLISECONDS)     \
28722    MEMBER(sip_peer, qualifyfreq, AST_DATA_MILLISECONDS)  \
28723    MEMBER(sip_peer, timer_t1, AST_DATA_MILLISECONDS)  \
28724    MEMBER(sip_peer, timer_b, AST_DATA_MILLISECONDS)
28725 
28726 AST_DATA_STRUCTURE(sip_peer, DATA_EXPORT_SIP_PEER);
28727 
28728 static int peers_data_provider_get(const struct ast_data_search *search,
28729    struct ast_data *data_root)
28730 {
28731    struct sip_peer *peer;
28732    struct ao2_iterator i;
28733    struct ast_data *data_peer, *data_peer_mailboxes = NULL, *data_peer_mailbox, *enum_node;
28734    struct ast_data *data_sip_options;
28735    int total_mailboxes, x;
28736    struct sip_mailbox *mailbox;
28737 
28738    i = ao2_iterator_init(peers, 0);
28739    while ((peer = ao2_iterator_next(&i))) {
28740       ao2_lock(peer);
28741 
28742       data_peer = ast_data_add_node(data_root, "peer");
28743       if (!data_peer) {
28744          ao2_unlock(peer);
28745          ao2_ref(peer, -1);
28746          continue;
28747       }
28748 
28749       ast_data_add_structure(sip_peer, data_peer, peer);
28750 
28751       /* transfer mode */
28752       enum_node = ast_data_add_node(data_peer, "allowtransfer");
28753       if (!enum_node) {
28754          continue;
28755       }
28756       ast_data_add_str(enum_node, "text", transfermode2str(peer->allowtransfer));
28757       ast_data_add_int(enum_node, "value", peer->allowtransfer);
28758 
28759       /* transports */
28760       ast_data_add_str(data_peer, "transports", get_transport_list(peer->transports));
28761 
28762       /* peer type */
28763       if ((peer->type & SIP_TYPE_USER) && (peer->type & SIP_TYPE_PEER)) {
28764          ast_data_add_str(data_peer, "type", "friend");
28765       } else if (peer->type & SIP_TYPE_PEER) {
28766          ast_data_add_str(data_peer, "type", "peer");
28767       } else if (peer->type & SIP_TYPE_USER) {
28768          ast_data_add_str(data_peer, "type", "user");
28769       }
28770 
28771       /* mailboxes */
28772       total_mailboxes = 0;
28773       AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
28774          if (!total_mailboxes) {
28775             data_peer_mailboxes = ast_data_add_node(data_peer, "mailboxes");
28776             if (!data_peer_mailboxes) {
28777                break;
28778             }
28779             total_mailboxes++;
28780          }
28781 
28782          data_peer_mailbox = ast_data_add_node(data_peer_mailboxes, "mailbox");
28783          if (!data_peer_mailbox) {
28784             continue;
28785          }
28786          ast_data_add_str(data_peer_mailbox, "mailbox", mailbox->mailbox);
28787          ast_data_add_str(data_peer_mailbox, "context", mailbox->context);
28788       }
28789 
28790       /* amaflags */
28791       enum_node = ast_data_add_node(data_peer, "amaflags");
28792       if (!enum_node) {
28793          continue;
28794       }
28795       ast_data_add_int(enum_node, "value", peer->amaflags);
28796       ast_data_add_str(enum_node, "text", ast_cdr_flags2str(peer->amaflags));
28797 
28798       /* sip options */
28799       data_sip_options = ast_data_add_node(data_peer, "sipoptions");
28800       if (!data_sip_options) {
28801          continue;
28802       }
28803       for (x = 0 ; x < ARRAY_LEN(sip_options); x++) {
28804          ast_data_add_bool(data_sip_options, sip_options[x].text, peer->sipoptions & sip_options[x].id);
28805       }
28806 
28807       /* callingpres */
28808       enum_node = ast_data_add_node(data_peer, "callingpres");
28809       if (!enum_node) {
28810          continue;
28811       }
28812       ast_data_add_int(enum_node, "value", peer->callingpres);
28813       ast_data_add_str(enum_node, "text", ast_describe_caller_presentation(peer->callingpres));
28814 
28815       /* codecs */
28816       ast_data_add_codecs(data_peer, "codecs", peer->capability);
28817 
28818       if (!ast_data_search_match(search, data_peer)) {
28819          ast_data_remove_node(data_root, data_peer);
28820       }
28821 
28822       ao2_unlock(peer);
28823       ao2_ref(peer, -1);
28824    }
28825    ao2_iterator_destroy(&i);
28826 
28827    return 0;
28828 }
28829 
28830 static const struct ast_data_handler peers_data_provider = {
28831    .version = AST_DATA_HANDLER_VERSION,
28832    .get = peers_data_provider_get
28833 };
28834 
28835 static const struct ast_data_entry sip_data_providers[] = {
28836    AST_DATA_ENTRY("asterisk/channel/sip/peers", &peers_data_provider),
28837 };
28838 
28839 /*! \brief PBX load module - initialization */
28840 static int load_module(void)
28841 {
28842    ast_verbose("SIP channel loading...\n");
28843    /* the fact that ao2_containers can't resize automatically is a major worry! */
28844    /* if the number of objects gets above MAX_XXX_BUCKETS, things will slow down */
28845    peers = ao2_t_container_alloc(HASH_PEER_SIZE, peer_hash_cb, peer_cmp_cb, "allocate peers");
28846    peers_by_ip = ao2_t_container_alloc(HASH_PEER_SIZE, peer_iphash_cb, peer_ipcmp_cb, "allocate peers_by_ip");
28847    dialogs = ao2_t_container_alloc(HASH_DIALOG_SIZE, dialog_hash_cb, dialog_cmp_cb, "allocate dialogs");
28848    threadt = ao2_t_container_alloc(HASH_DIALOG_SIZE, threadt_hash_cb, threadt_cmp_cb, "allocate threadt table");
28849    
28850    ASTOBJ_CONTAINER_INIT(&regl); /* Registry object list -- not searched for anything */
28851    ASTOBJ_CONTAINER_INIT(&submwil); /* MWI subscription object list */
28852 
28853    if (!(sched = sched_context_create())) {
28854       ast_log(LOG_ERROR, "Unable to create scheduler context\n");
28855       return AST_MODULE_LOAD_FAILURE;
28856    }
28857 
28858    if (!(io = io_context_create())) {
28859       ast_log(LOG_ERROR, "Unable to create I/O context\n");
28860       sched_context_destroy(sched);
28861       return AST_MODULE_LOAD_FAILURE;
28862    }
28863 
28864    sip_reloadreason = CHANNEL_MODULE_LOAD;
28865 
28866    can_parse_xml = sip_is_xml_parsable();
28867    if(reload_config(sip_reloadreason)) {  /* Load the configuration from sip.conf */
28868       return AST_MODULE_LOAD_DECLINE;
28869    }
28870 
28871    /* Prepare the version that does not require DTMF BEGIN frames.
28872     * We need to use tricks such as memcpy and casts because the variable
28873     * has const fields.
28874     */
28875    memcpy(&sip_tech_info, &sip_tech, sizeof(sip_tech));
28876    memset((void *) &sip_tech_info.send_digit_begin, 0, sizeof(sip_tech_info.send_digit_begin));
28877 
28878    /* Make sure we can register our sip channel type */
28879    if (ast_channel_register(&sip_tech)) {
28880       ast_log(LOG_ERROR, "Unable to register channel type 'SIP'\n");
28881       io_context_destroy(io);
28882       sched_context_destroy(sched);
28883       return AST_MODULE_LOAD_FAILURE;
28884    }
28885 
28886 #ifdef TEST_FRAMEWORK
28887    AST_TEST_REGISTER(test_sip_peers_get);
28888    AST_TEST_REGISTER(test_sip_mwi_subscribe_parse);
28889 #endif
28890 
28891    /* Register AstData providers */
28892    ast_data_register_multiple(sip_data_providers, ARRAY_LEN(sip_data_providers));
28893 
28894    /* Register all CLI functions for SIP */
28895    ast_cli_register_multiple(cli_sip, ARRAY_LEN(cli_sip));
28896 
28897    /* Tell the UDPTL subdriver that we're here */
28898    ast_udptl_proto_register(&sip_udptl);
28899 
28900    /* Tell the RTP engine about our RTP glue */
28901    ast_rtp_glue_register(&sip_rtp_glue);
28902 
28903    /* Register dialplan applications */
28904    ast_register_application_xml(app_dtmfmode, sip_dtmfmode);
28905    ast_register_application_xml(app_sipaddheader, sip_addheader);
28906    ast_register_application_xml(app_sipremoveheader, sip_removeheader);
28907 
28908    /* Register dialplan functions */
28909    ast_custom_function_register(&sip_header_function);
28910    ast_custom_function_register(&sippeer_function);
28911    ast_custom_function_register(&sipchaninfo_function);
28912    ast_custom_function_register(&checksipdomain_function);
28913 
28914    /* Register manager commands */
28915    ast_manager_register_xml("SIPpeers", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_sip_show_peers);
28916    ast_manager_register_xml("SIPshowpeer", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_sip_show_peer);
28917    ast_manager_register_xml("SIPqualifypeer", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_sip_qualify_peer);
28918    ast_manager_register_xml("SIPshowregistry", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_show_registry);
28919    ast_manager_register_xml("SIPnotify", EVENT_FLAG_SYSTEM, manager_sipnotify);
28920    sip_poke_all_peers();   
28921    sip_send_all_registers();
28922    sip_send_all_mwi_subscriptions();
28923    initialize_escs();
28924 
28925    if (sip_epa_register(&cc_epa_static_data)) {
28926       return AST_MODULE_LOAD_DECLINE;
28927    }
28928 
28929    if (sip_reqresp_parser_init() == -1) {
28930       ast_log(LOG_ERROR, "Unable to initialize the SIP request and response parser\n");
28931       return AST_MODULE_LOAD_DECLINE;
28932    }
28933 
28934    if (can_parse_xml) {
28935       /* SIP CC agents require the ability to parse XML PIDF bodies
28936        * in incoming PUBLISH requests
28937        */
28938       if (ast_cc_agent_register(&sip_cc_agent_callbacks)) {
28939          return AST_MODULE_LOAD_DECLINE;
28940       }
28941    }
28942    if (ast_cc_monitor_register(&sip_cc_monitor_callbacks)) {
28943       return AST_MODULE_LOAD_DECLINE;
28944    }
28945    if (!(sip_monitor_instances = ao2_container_alloc(37, sip_monitor_instance_hash_fn, sip_monitor_instance_cmp_fn))) {
28946       return AST_MODULE_LOAD_DECLINE;
28947    }
28948 
28949    /* And start the monitor for the first time */
28950    restart_monitor();
28951 
28952    ast_realtime_require_field(ast_check_realtime("sipregs") ? "sipregs" : "sippeers",
28953       "name", RQ_CHAR, 10,
28954       "ipaddr", RQ_CHAR, INET6_ADDRSTRLEN - 1,
28955       "port", RQ_UINTEGER2, 5,
28956       "regseconds", RQ_INTEGER4, 11,
28957       "defaultuser", RQ_CHAR, 10,
28958       "fullcontact", RQ_CHAR, 35,
28959       "regserver", RQ_CHAR, 20,
28960       "useragent", RQ_CHAR, 20,
28961       "lastms", RQ_INTEGER4, 11,
28962       SENTINEL);
28963 
28964 
28965    sip_register_tests();
28966    network_change_event_subscribe();
28967 
28968    return AST_MODULE_LOAD_SUCCESS;
28969 }
28970 
28971 /*! \brief PBX unload module API */
28972 static int unload_module(void)
28973 {
28974    struct sip_pvt *p;
28975    struct sip_threadinfo *th;
28976    struct ast_context *con;
28977    struct ao2_iterator i;
28978 
28979    network_change_event_unsubscribe();
28980 
28981    ast_sched_dump(sched);
28982    
28983    /* First, take us out of the channel type list */
28984    ast_channel_unregister(&sip_tech);
28985 
28986    /* Unregister dial plan functions */
28987    ast_custom_function_unregister(&sipchaninfo_function);
28988    ast_custom_function_unregister(&sippeer_function);
28989    ast_custom_function_unregister(&sip_header_function);
28990    ast_custom_function_unregister(&checksipdomain_function);
28991 
28992    /* Unregister dial plan applications */
28993    ast_unregister_application(app_dtmfmode);
28994    ast_unregister_application(app_sipaddheader);
28995    ast_unregister_application(app_sipremoveheader);
28996 
28997 #ifdef TEST_FRAMEWORK
28998    AST_TEST_UNREGISTER(test_sip_peers_get);
28999    AST_TEST_UNREGISTER(test_sip_mwi_subscribe_parse);
29000 #endif
29001    /* Unregister all the AstData providers */
29002    ast_data_unregister(NULL);
29003 
29004    /* Unregister CLI commands */
29005    ast_cli_unregister_multiple(cli_sip, ARRAY_LEN(cli_sip));
29006 
29007    /* Disconnect from UDPTL */
29008    ast_udptl_proto_unregister(&sip_udptl);
29009 
29010    /* Disconnect from RTP engine */
29011    ast_rtp_glue_unregister(&sip_rtp_glue);
29012 
29013    /* Unregister AMI actions */
29014    ast_manager_unregister("SIPpeers");
29015    ast_manager_unregister("SIPshowpeer");
29016    ast_manager_unregister("SIPqualifypeer");
29017    ast_manager_unregister("SIPshowregistry");
29018    ast_manager_unregister("SIPnotify");
29019    
29020    /* Kill TCP/TLS server threads */
29021    if (sip_tcp_desc.master) {
29022       ast_tcptls_server_stop(&sip_tcp_desc);
29023    }
29024    if (sip_tls_desc.master) {
29025       ast_tcptls_server_stop(&sip_tls_desc);
29026    }
29027 
29028    /* Kill all existing TCP/TLS threads */
29029    i = ao2_iterator_init(threadt, 0);
29030    while ((th = ao2_t_iterator_next(&i, "iterate through tcp threads for 'sip show tcp'"))) {
29031       pthread_t thread = th->threadid;
29032       th->stop = 1;
29033       pthread_kill(thread, SIGURG);
29034       pthread_join(thread, NULL);
29035       ao2_t_ref(th, -1, "decrement ref from iterator");
29036    }
29037    ao2_iterator_destroy(&i);
29038 
29039    /* Hangup all dialogs if they have an owner */
29040    i = ao2_iterator_init(dialogs, 0);
29041    while ((p = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
29042       if (p->owner)
29043          ast_softhangup(p->owner, AST_SOFTHANGUP_APPUNLOAD);
29044       ao2_t_ref(p, -1, "toss dialog ptr from iterator_next");
29045    }
29046    ao2_iterator_destroy(&i);
29047 
29048    ast_mutex_lock(&monlock);
29049    if (monitor_thread && (monitor_thread != AST_PTHREADT_STOP) && (monitor_thread != AST_PTHREADT_NULL)) {
29050       pthread_cancel(monitor_thread);
29051       pthread_kill(monitor_thread, SIGURG);
29052       pthread_join(monitor_thread, NULL);
29053    }
29054    monitor_thread = AST_PTHREADT_STOP;
29055    ast_mutex_unlock(&monlock);
29056 
29057    /* Destroy all the dialogs and free their memory */
29058    i = ao2_iterator_init(dialogs, 0);
29059    while ((p = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
29060       dialog_unlink_all(p, TRUE, TRUE);
29061       ao2_t_ref(p, -1, "throw away iterator result");
29062    }
29063    ao2_iterator_destroy(&i);
29064 
29065    /* Free memory for local network address mask */
29066    ast_free_ha(localaddr);
29067 
29068    clear_realm_authentication(authl);
29069 
29070    destroy_escs();
29071 
29072    if (default_tls_cfg.certfile) {
29073       ast_free(default_tls_cfg.certfile);
29074    }
29075    if (default_tls_cfg.pvtfile) {
29076       ast_free(default_tls_cfg.pvtfile);
29077    }
29078    if (default_tls_cfg.cipher) {
29079       ast_free(default_tls_cfg.cipher);
29080    }
29081    if (default_tls_cfg.cafile) {
29082       ast_free(default_tls_cfg.cafile);
29083    }
29084    if (default_tls_cfg.capath) {
29085       ast_free(default_tls_cfg.capath);
29086    }
29087 
29088    ASTOBJ_CONTAINER_DESTROYALL(&regl, sip_registry_destroy);
29089    ASTOBJ_CONTAINER_DESTROY(&regl);
29090    ASTOBJ_CONTAINER_DESTROYALL(&submwil, sip_subscribe_mwi_destroy);
29091    ASTOBJ_CONTAINER_DESTROY(&submwil);
29092 
29093    ao2_t_ref(peers, -1, "unref the peers table");
29094    ao2_t_ref(peers_by_ip, -1, "unref the peers_by_ip table");
29095    ao2_t_ref(dialogs, -1, "unref the dialogs table");
29096    ao2_t_ref(threadt, -1, "unref the thread table");
29097 
29098    clear_sip_domains();
29099    ast_free_ha(sip_cfg.contact_ha);
29100    close(sipsock);
29101    sched_context_destroy(sched);
29102    con = ast_context_find(used_context);
29103    if (con) {
29104       ast_context_destroy(con, "SIP");
29105    }
29106    ast_unload_realtime("sipregs");
29107    ast_unload_realtime("sippeers");
29108    ast_cc_monitor_unregister(&sip_cc_monitor_callbacks);
29109    ast_cc_agent_unregister(&sip_cc_agent_callbacks);
29110 
29111    sip_reqresp_parser_exit();
29112    sip_unregister_tests();
29113 
29114    return 0;
29115 }
29116 
29117 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "Session Initiation Protocol (SIP)",
29118       .load = load_module,
29119       .unload = unload_module,
29120       .reload = reload,
29121       .load_pri = AST_MODPRI_CHANNEL_DRIVER,
29122       .nonoptreq = "res_crypto,chan_local",
29123           );