Sat Mar 26 11:07:12 2011

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: 291942 $")
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 />
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 />
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 /*! \brief Global jitterbuffer configuration - by default, jb is disabled */
00563 static struct ast_jb_conf default_jbconf =
00564 {
00565    .flags = 0,
00566    .max_size = -1,
00567    .resync_threshold = -1,
00568    .impl = "",
00569    .target_extra = -1,
00570 };
00571 static struct ast_jb_conf global_jbconf;                /*!< Global jitterbuffer configuration */
00572 
00573 static const char config[] = "sip.conf";                /*!< Main configuration file */
00574 static const char notify_config[] = "sip_notify.conf";  /*!< Configuration file for sending Notify with CLI commands to reconfigure or reboot phones */
00575 
00576 /*! \brief Readable descriptions of device states.
00577  *  \note Should be aligned to above table as index */
00578 static const struct invstate2stringtable {
00579    const enum invitestates state;
00580    const char *desc;
00581 } invitestate2string[] = {
00582    {INV_NONE,              "None"  },
00583    {INV_CALLING,           "Calling (Trying)"},
00584    {INV_PROCEEDING,        "Proceeding "},
00585    {INV_EARLY_MEDIA,       "Early media"},
00586    {INV_COMPLETED,         "Completed (done)"},
00587    {INV_CONFIRMED,         "Confirmed (up)"},
00588    {INV_TERMINATED,        "Done"},
00589    {INV_CANCELLED,         "Cancelled"}
00590 };
00591 
00592 /*! \brief Subscription types that we support. We support
00593  * - dialoginfo updates (really device status, not dialog info as was the original intent of the standard)
00594  * - SIMPLE presence used for device status
00595  * - Voicemail notification subscriptions
00596  */
00597 static const struct cfsubscription_types {
00598    enum subscriptiontype type;
00599    const char * const event;
00600    const char * const mediatype;
00601    const char * const text;
00602 } subscription_types[] = {
00603    { NONE,        "-",        "unknown",               "unknown" },
00604    /* RFC 4235: SIP Dialog event package */
00605    { DIALOG_INFO_XML, "dialog",   "application/dialog-info+xml", "dialog-info+xml" },
00606    { CPIM_PIDF_XML,   "presence", "application/cpim-pidf+xml",   "cpim-pidf+xml" },  /* RFC 3863 */
00607    { PIDF_XML,        "presence", "application/pidf+xml",        "pidf+xml" },       /* RFC 3863 */
00608    { XPIDF_XML,       "presence", "application/xpidf+xml",       "xpidf+xml" },       /* Pre-RFC 3863 with MS additions */
00609    { MWI_NOTIFICATION,  "message-summary", "application/simple-message-summary", "mwi" } /* RFC 3842: Mailbox notification */
00610 };
00611 
00612 /*! \brief The core structure to setup dialogs. We parse incoming messages by using
00613  *  structure and then route the messages according to the type.
00614  *
00615  *  \note Note that sip_methods[i].id == i must hold or the code breaks
00616  */
00617 static const struct  cfsip_methods {
00618    enum sipmethod id;
00619    int need_rtp;     /*!< when this is the 'primary' use for a pvt structure, does it need RTP? */
00620    char * const text;
00621    enum can_create_dialog can_create;
00622 } sip_methods[] = {
00623    { SIP_UNKNOWN,   RTP,    "-UNKNOWN-",CAN_CREATE_DIALOG },
00624    { SIP_RESPONSE,  NO_RTP, "SIP/2.0",  CAN_NOT_CREATE_DIALOG },
00625    { SIP_REGISTER,  NO_RTP, "REGISTER", CAN_CREATE_DIALOG },
00626    { SIP_OPTIONS,   NO_RTP, "OPTIONS",  CAN_CREATE_DIALOG },
00627    { SIP_NOTIFY,    NO_RTP, "NOTIFY",   CAN_CREATE_DIALOG },
00628    { SIP_INVITE,    RTP,    "INVITE",   CAN_CREATE_DIALOG },
00629    { SIP_ACK,       NO_RTP, "ACK",      CAN_NOT_CREATE_DIALOG },
00630    { SIP_PRACK,     NO_RTP, "PRACK",    CAN_NOT_CREATE_DIALOG },
00631    { SIP_BYE,       NO_RTP, "BYE",      CAN_NOT_CREATE_DIALOG },
00632    { SIP_REFER,     NO_RTP, "REFER",    CAN_CREATE_DIALOG },
00633    { SIP_SUBSCRIBE, NO_RTP, "SUBSCRIBE",CAN_CREATE_DIALOG },
00634    { SIP_MESSAGE,   NO_RTP, "MESSAGE",  CAN_CREATE_DIALOG },
00635    { SIP_UPDATE,    NO_RTP, "UPDATE",   CAN_NOT_CREATE_DIALOG },
00636    { SIP_INFO,      NO_RTP, "INFO",     CAN_NOT_CREATE_DIALOG },
00637    { SIP_CANCEL,    NO_RTP, "CANCEL",   CAN_NOT_CREATE_DIALOG },
00638    { SIP_PUBLISH,   NO_RTP, "PUBLISH",  CAN_CREATE_DIALOG },
00639    { SIP_PING,      NO_RTP, "PING",     CAN_CREATE_DIALOG_UNSUPPORTED_METHOD }
00640 };
00641 
00642 /*! \brief Diversion header reasons
00643  *
00644  * The core defines a bunch of constants used to define
00645  * redirecting reasons. This provides a translation table
00646  * between those and the strings which may be present in
00647  * a SIP Diversion header
00648  */
00649 static const struct sip_reasons {
00650    enum AST_REDIRECTING_REASON code;
00651    char * const text;
00652 } sip_reason_table[] = {
00653    { AST_REDIRECTING_REASON_UNKNOWN, "unknown" },
00654    { AST_REDIRECTING_REASON_USER_BUSY, "user-busy" },
00655    { AST_REDIRECTING_REASON_NO_ANSWER, "no-answer" },
00656    { AST_REDIRECTING_REASON_UNAVAILABLE, "unavailable" },
00657    { AST_REDIRECTING_REASON_UNCONDITIONAL, "unconditional" },
00658    { AST_REDIRECTING_REASON_TIME_OF_DAY, "time-of-day" },
00659    { AST_REDIRECTING_REASON_DO_NOT_DISTURB, "do-not-disturb" },
00660    { AST_REDIRECTING_REASON_DEFLECTION, "deflection" },
00661    { AST_REDIRECTING_REASON_FOLLOW_ME, "follow-me" },
00662    { AST_REDIRECTING_REASON_OUT_OF_ORDER, "out-of-service" },
00663    { AST_REDIRECTING_REASON_AWAY, "away" },
00664    { AST_REDIRECTING_REASON_CALL_FWD_DTE, "unknown"}
00665 };
00666 
00667 
00668 /*! \name DefaultSettings
00669    Default setttings are used as a channel setting and as a default when
00670    configuring devices
00671 */
00672 /*@{*/
00673 static char default_language[MAX_LANGUAGE];      /*!< Default language setting for new channels */
00674 static char default_callerid[AST_MAX_EXTENSION]; /*!< Default caller ID for sip messages */
00675 static char default_mwi_from[80];                /*!< Default caller ID for MWI updates */
00676 static char default_fromdomain[AST_MAX_EXTENSION]; /*!< Default domain on outound messages */
00677 static int default_fromdomainport;                 /*!< Default domain port on outbound messages */
00678 static char default_notifymime[AST_MAX_EXTENSION]; /*!< Default MIME media type for MWI notify messages */
00679 static char default_vmexten[AST_MAX_EXTENSION];    /*!< Default From Username on MWI updates */
00680 static int default_qualify;                        /*!< Default Qualify= setting */
00681 static char default_mohinterpret[MAX_MUSICCLASS];  /*!< Global setting for moh class to use when put on hold */
00682 static char default_mohsuggest[MAX_MUSICCLASS];    /*!< Global setting for moh class to suggest when putting
00683                                                     *   a bridged channel on hold */
00684 static char default_parkinglot[AST_MAX_CONTEXT];   /*!< Parkinglot */
00685 static char default_engine[256];                   /*!< Default RTP engine */
00686 static int default_maxcallbitrate;                 /*!< Maximum bitrate for call */
00687 static struct ast_codec_pref default_prefs;        /*!< Default codec prefs */
00688 static unsigned int default_transports;            /*!< Default Transports (enum sip_transport) that are acceptable */
00689 static unsigned int default_primary_transport;     /*!< Default primary Transport (enum sip_transport) for outbound connections to devices */
00690 /*@}*/
00691 
00692 static struct sip_settings sip_cfg;    /*!< SIP configuration data.
00693                \note in the future we could have multiple of these (per domain, per device group etc) */
00694 
00695 /*!< use this macro when ast_uri_decode is dependent on pedantic checking to be on. */
00696 #define SIP_PEDANTIC_DECODE(str) \
00697    if (sip_cfg.pedanticsipchecking && !ast_strlen_zero(str)) { \
00698       ast_uri_decode(str); \
00699    }  \
00700 
00701 static unsigned int chan_idx;       /*!< used in naming sip channel */
00702 static int global_match_auth_username;    /*!< Match auth username if available instead of From: Default off. */
00703 
00704 static int global_relaxdtmf;        /*!< Relax DTMF */
00705 static int global_prematuremediafilter;   /*!< Enable/disable premature frames in a call (causing 183 early media) */
00706 static int global_rtptimeout;       /*!< Time out call if no RTP */
00707 static int global_rtpholdtimeout;   /*!< Time out call if no RTP during hold */
00708 static int global_rtpkeepalive;     /*!< Send RTP keepalives */
00709 static int global_reg_timeout;      /*!< Global time between attempts for outbound registrations */
00710 static int global_regattempts_max;  /*!< Registration attempts before giving up */
00711 static int global_shrinkcallerid;   /*!< enable or disable shrinking of caller id  */
00712 static int global_callcounter;      /*!< Enable call counters for all devices. This is currently enabled by setting the peer
00713                                      *   call-limit to INT_MAX. When we remove the call-limit from the code, we can make it
00714                                      *   with just a boolean flag in the device structure */
00715 static unsigned int global_tos_sip;      /*!< IP type of service for SIP packets */
00716 static unsigned int global_tos_audio;    /*!< IP type of service for audio RTP packets */
00717 static unsigned int global_tos_video;    /*!< IP type of service for video RTP packets */
00718 static unsigned int global_tos_text;     /*!< IP type of service for text RTP packets */
00719 static unsigned int global_cos_sip;      /*!< 802.1p class of service for SIP packets */
00720 static unsigned int global_cos_audio;    /*!< 802.1p class of service for audio RTP packets */
00721 static unsigned int global_cos_video;    /*!< 802.1p class of service for video RTP packets */
00722 static unsigned int global_cos_text;     /*!< 802.1p class of service for text RTP packets */
00723 static unsigned int recordhistory;       /*!< Record SIP history. Off by default */
00724 static unsigned int dumphistory;         /*!< Dump history to verbose before destroying SIP dialog */
00725 static char global_useragent[AST_MAX_EXTENSION];    /*!< Useragent for the SIP channel */
00726 static char global_sdpsession[AST_MAX_EXTENSION];   /*!< SDP session name for the SIP channel */
00727 static char global_sdpowner[AST_MAX_EXTENSION];     /*!< SDP owner name for the SIP channel */
00728 static int global_authfailureevents;     /*!< Whether we send authentication failure manager events or not. Default no. */
00729 static int global_t1;           /*!< T1 time */
00730 static int global_t1min;        /*!< T1 roundtrip time minimum */
00731 static int global_timer_b;      /*!< Timer B - RFC 3261 Section 17.1.1.2 */
00732 static unsigned int global_autoframing; /*!< Turn autoframing on or off. */
00733 static int global_qualifyfreq;          /*!< Qualify frequency */
00734 static int global_qualify_gap;          /*!< Time between our group of peer pokes */
00735 static int global_qualify_peers;        /*!< Number of peers to poke at a given time */
00736 
00737 static enum st_mode global_st_mode;           /*!< Mode of operation for Session-Timers           */
00738 static enum st_refresher global_st_refresher; /*!< Session-Timer refresher                        */
00739 static int global_min_se;                     /*!< Lowest threshold for session refresh interval  */
00740 static int global_max_se;                     /*!< Highest threshold for session refresh interval */
00741 
00742 static int global_dynamic_exclude_static = 0; /*!< Exclude static peers from contact registrations */
00743 /*@}*/
00744 
00745 /*!
00746  * We use libxml2 in order to parse XML that may appear in the body of a SIP message. Currently,
00747  * the only usage is for parsing PIDF bodies of incoming PUBLISH requests in the call-completion
00748  * event package. This variable is set at module load time and may be checked at runtime to determine
00749  * if XML parsing support was found.
00750  */
00751 static int can_parse_xml;
00752 
00753 /*! \name Object counters @{
00754  *  \bug These counters are not handled in a thread-safe way ast_atomic_fetchadd_int()
00755  *  should be used to modify these values. */
00756 static int speerobjs = 0;     /*!< Static peers */
00757 static int rpeerobjs = 0;     /*!< Realtime peers */
00758 static int apeerobjs = 0;     /*!< Autocreated peer objects */
00759 static int regobjs = 0;       /*!< Registry objects */
00760 /* }@ */
00761 
00762 static struct ast_flags global_flags[3] = {{0}};  /*!< global SIP_ flags */
00763 static int global_t38_maxdatagram;                /*!< global T.38 FaxMaxDatagram override */
00764 
00765 static struct ast_event_sub *network_change_event_subscription; /*!< subscription id for network change events */
00766 static int network_change_event_sched_id = -1;
00767 
00768 static char used_context[AST_MAX_CONTEXT];        /*!< name of automatically created context for unloading */
00769 
00770 AST_MUTEX_DEFINE_STATIC(netlock);
00771 
00772 /*! \brief Protect the monitoring thread, so only one process can kill or start it, and not
00773    when it's doing something critical. */
00774 AST_MUTEX_DEFINE_STATIC(monlock);
00775 
00776 AST_MUTEX_DEFINE_STATIC(sip_reload_lock);
00777 
00778 /*! \brief This is the thread for the monitor which checks for input on the channels
00779    which are not currently in use.  */
00780 static pthread_t monitor_thread = AST_PTHREADT_NULL;
00781 
00782 static int sip_reloading = FALSE;                       /*!< Flag for avoiding multiple reloads at the same time */
00783 static enum channelreloadreason sip_reloadreason;       /*!< Reason for last reload/load of configuration */
00784 
00785 struct sched_context *sched;     /*!< The scheduling context */
00786 static struct io_context *io;           /*!< The IO context */
00787 static int *sipsock_read_id;            /*!< ID of IO entry for sipsock FD */
00788 struct sip_pkt;
00789 static AST_LIST_HEAD_STATIC(domain_list, domain);    /*!< The SIP domain list */
00790 
00791 AST_LIST_HEAD_NOLOCK(sip_history_head, sip_history); /*!< history list, entry in sip_pvt */
00792 
00793 static enum sip_debug_e sipdebug;
00794 
00795 /*! \brief extra debugging for 'text' related events.
00796  *  At the moment this is set together with sip_debug_console.
00797  *  \note It should either go away or be implemented properly.
00798  */
00799 static int sipdebug_text;
00800 
00801 static const struct _map_x_s referstatusstrings[] = {
00802    { REFER_IDLE,      "<none>" },
00803    { REFER_SENT,      "Request sent" },
00804    { REFER_RECEIVED,  "Request received" },
00805    { REFER_CONFIRMED, "Confirmed" },
00806    { REFER_ACCEPTED,  "Accepted" },
00807    { REFER_RINGING,   "Target ringing" },
00808    { REFER_200OK,     "Done" },
00809    { REFER_FAILED,    "Failed" },
00810    { REFER_NOAUTH,    "Failed - auth failure" },
00811    { -1,               NULL} /* terminator */
00812 };
00813 
00814 /* --- Hash tables of various objects --------*/
00815 #ifdef LOW_MEMORY
00816 static const int HASH_PEER_SIZE = 17;
00817 static const int HASH_DIALOG_SIZE = 17;
00818 #else
00819 static const int HASH_PEER_SIZE = 563; /*!< Size of peer hash table, prime number preferred! */
00820 static const int HASH_DIALOG_SIZE = 563;
00821 #endif
00822 
00823 static const struct {
00824    enum ast_cc_service_type service;
00825    const char *service_string;
00826 } sip_cc_service_map [] = {
00827    [AST_CC_NONE] = { AST_CC_NONE, "" },
00828    [AST_CC_CCBS] = { AST_CC_CCBS, "BS" },
00829    [AST_CC_CCNR] = { AST_CC_CCNR, "NR" },
00830    [AST_CC_CCNL] = { AST_CC_CCNL, "NL" },
00831 };
00832 
00833 static enum ast_cc_service_type service_string_to_service_type(const char * const service_string)
00834 {
00835    enum ast_cc_service_type service;
00836    for (service = AST_CC_CCBS; service <= AST_CC_CCNL; ++service) {
00837       if (!strcasecmp(service_string, sip_cc_service_map[service].service_string)) {
00838          return service;
00839       }
00840    }
00841    return AST_CC_NONE;
00842 }
00843 
00844 static const struct {
00845    enum sip_cc_notify_state state;
00846    const char *state_string;
00847 } sip_cc_notify_state_map [] = {
00848    [CC_QUEUED] = {CC_QUEUED, "cc-state: queued"},
00849    [CC_READY] = {CC_READY, "cc-state: ready"},
00850 };
00851 
00852 AST_LIST_HEAD_STATIC(epa_static_data_list, epa_backend);
00853 
00854 static int sip_epa_register(const struct epa_static_data *static_data)
00855 {
00856    struct epa_backend *backend = ast_calloc(1, sizeof(*backend));
00857 
00858    if (!backend) {
00859       return -1;
00860    }
00861 
00862    backend->static_data = static_data;
00863 
00864    AST_LIST_LOCK(&epa_static_data_list);
00865    AST_LIST_INSERT_TAIL(&epa_static_data_list, backend, next);
00866    AST_LIST_UNLOCK(&epa_static_data_list);
00867    return 0;
00868 }
00869 
00870 static void cc_handle_publish_error(struct sip_pvt *pvt, const int resp, struct sip_request *req, struct sip_epa_entry *epa_entry);
00871 
00872 static void cc_epa_destructor(void *data)
00873 {
00874    struct sip_epa_entry *epa_entry = data;
00875    struct cc_epa_entry *cc_entry = epa_entry->instance_data;
00876    ast_free(cc_entry);
00877 }
00878 
00879 static const struct epa_static_data cc_epa_static_data  = {
00880    .event = CALL_COMPLETION,
00881    .name = "call-completion",
00882    .handle_error = cc_handle_publish_error,
00883    .destructor = cc_epa_destructor,
00884 };
00885 
00886 static const struct epa_static_data *find_static_data(const char * const event_package)
00887 {
00888    const struct epa_backend *backend = NULL;
00889 
00890    AST_LIST_LOCK(&epa_static_data_list);
00891    AST_LIST_TRAVERSE(&epa_static_data_list, backend, next) {
00892       if (!strcmp(backend->static_data->name, event_package)) {
00893          break;
00894       }
00895    }
00896    AST_LIST_UNLOCK(&epa_static_data_list);
00897    return backend ? backend->static_data : NULL;
00898 }
00899 
00900 static struct sip_epa_entry *create_epa_entry (const char * const event_package, const char * const destination)
00901 {
00902    struct sip_epa_entry *epa_entry;
00903    const struct epa_static_data *static_data;
00904 
00905    if (!(static_data = find_static_data(event_package))) {
00906       return NULL;
00907    }
00908 
00909    if (!(epa_entry = ao2_t_alloc(sizeof(*epa_entry), static_data->destructor, "Allocate new EPA entry"))) {
00910       return NULL;
00911    }
00912 
00913    epa_entry->static_data = static_data;
00914    ast_copy_string(epa_entry->destination, destination, sizeof(epa_entry->destination));
00915    return epa_entry;
00916 }
00917 
00918 /*!
00919  * Used to create new entity IDs by ESCs.
00920  */
00921 static int esc_etag_counter;
00922 static const int DEFAULT_PUBLISH_EXPIRES = 3600;
00923 
00924 #ifdef HAVE_LIBXML2
00925 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);
00926 
00927 static const struct sip_esc_publish_callbacks cc_esc_publish_callbacks = {
00928    .initial_handler = cc_esc_publish_handler,
00929    .modify_handler = cc_esc_publish_handler,
00930 };
00931 #endif
00932 
00933 /*!
00934  * \brief The Event State Compositors
00935  *
00936  * An Event State Compositor is an entity which
00937  * accepts PUBLISH requests and acts appropriately
00938  * based on these requests.
00939  *
00940  * The actual event_state_compositor structure is simply
00941  * an ao2_container of sip_esc_entrys. When an incoming
00942  * PUBLISH is received, we can match the appropriate sip_esc_entry
00943  * using the entity ID of the incoming PUBLISH.
00944  */
00945 static struct event_state_compositor {
00946    enum subscriptiontype event;
00947    const char * name;
00948    const struct sip_esc_publish_callbacks *callbacks;
00949    struct ao2_container *compositor;
00950 } event_state_compositors [] = {
00951 #ifdef HAVE_LIBXML2
00952    {CALL_COMPLETION, "call-completion", &cc_esc_publish_callbacks},
00953 #endif
00954 };
00955 
00956 static const int ESC_MAX_BUCKETS = 37;
00957 
00958 static void esc_entry_destructor(void *obj)
00959 {
00960    struct sip_esc_entry *esc_entry = obj;
00961    if (esc_entry->sched_id > -1) {
00962       AST_SCHED_DEL(sched, esc_entry->sched_id);
00963    }
00964 }
00965 
00966 static int esc_hash_fn(const void *obj, const int flags)
00967 {
00968    const struct sip_esc_entry *entry = obj;
00969    return ast_str_hash(entry->entity_tag);
00970 }
00971 
00972 static int esc_cmp_fn(void *obj, void *arg, int flags)
00973 {
00974    struct sip_esc_entry *entry1 = obj;
00975    struct sip_esc_entry *entry2 = arg;
00976 
00977    return (!strcmp(entry1->entity_tag, entry2->entity_tag)) ? (CMP_MATCH | CMP_STOP) : 0;
00978 }
00979 
00980 static struct event_state_compositor *get_esc(const char * const event_package) {
00981    int i;
00982    for (i = 0; i < ARRAY_LEN(event_state_compositors); i++) {
00983       if (!strcasecmp(event_package, event_state_compositors[i].name)) {
00984          return &event_state_compositors[i];
00985       }
00986    }
00987    return NULL;
00988 }
00989 
00990 static struct sip_esc_entry *get_esc_entry(const char * entity_tag, struct event_state_compositor *esc) {
00991    struct sip_esc_entry *entry;
00992    struct sip_esc_entry finder;
00993 
00994    ast_copy_string(finder.entity_tag, entity_tag, sizeof(finder.entity_tag));
00995 
00996    entry = ao2_find(esc->compositor, &finder, OBJ_POINTER);
00997 
00998    return entry;
00999 }
01000 
01001 static int publish_expire(const void *data)
01002 {
01003    struct sip_esc_entry *esc_entry = (struct sip_esc_entry *) data;
01004    struct event_state_compositor *esc = get_esc(esc_entry->event);
01005 
01006    ast_assert(esc != NULL);
01007 
01008    ao2_unlink(esc->compositor, esc_entry);
01009    ao2_ref(esc_entry, -1);
01010    return 0;
01011 }
01012 
01013 static void create_new_sip_etag(struct sip_esc_entry *esc_entry, int is_linked)
01014 {
01015    int new_etag = ast_atomic_fetchadd_int(&esc_etag_counter, +1);
01016    struct event_state_compositor *esc = get_esc(esc_entry->event);
01017 
01018    ast_assert(esc != NULL);
01019    if (is_linked) {
01020       ao2_unlink(esc->compositor, esc_entry);
01021    }
01022    snprintf(esc_entry->entity_tag, sizeof(esc_entry->entity_tag), "%d", new_etag);
01023    ao2_link(esc->compositor, esc_entry);
01024 }
01025 
01026 static struct sip_esc_entry *create_esc_entry(struct event_state_compositor *esc, struct sip_request *req, const int expires)
01027 {
01028    struct sip_esc_entry *esc_entry;
01029    int expires_ms;
01030 
01031    if (!(esc_entry = ao2_alloc(sizeof(*esc_entry), esc_entry_destructor))) {
01032       return NULL;
01033    }
01034 
01035    esc_entry->event = esc->name;
01036 
01037    expires_ms = expires * 1000;
01038    /* Bump refcount for scheduler */
01039    ao2_ref(esc_entry, +1);
01040    esc_entry->sched_id = ast_sched_add(sched, expires_ms, publish_expire, esc_entry);
01041 
01042    /* Note: This links the esc_entry into the ESC properly */
01043    create_new_sip_etag(esc_entry, 0);
01044 
01045    return esc_entry;
01046 }
01047 
01048 static int initialize_escs(void)
01049 {
01050    int i, res = 0;
01051    for (i = 0; i < ARRAY_LEN(event_state_compositors); i++) {
01052       if (!((event_state_compositors[i].compositor) =
01053                ao2_container_alloc(ESC_MAX_BUCKETS, esc_hash_fn, esc_cmp_fn))) {
01054          res = -1;
01055       }
01056    }
01057    return res;
01058 }
01059 
01060 static void destroy_escs(void)
01061 {
01062    int i;
01063    for (i = 0; i < ARRAY_LEN(event_state_compositors); i++) {
01064       ao2_ref(event_state_compositors[i].compositor, -1);
01065    }
01066 }
01067 
01068 /*! \brief
01069  * Here we implement the container for dialogs (sip_pvt), defining
01070  * generic wrapper functions to ease the transition from the current
01071  * implementation (a single linked list) to a different container.
01072  * In addition to a reference to the container, we need functions to lock/unlock
01073  * the container and individual items, and functions to add/remove
01074  * references to the individual items.
01075  */
01076 static struct ao2_container *dialogs;
01077 #define sip_pvt_lock(x) ao2_lock(x)
01078 #define sip_pvt_trylock(x) ao2_trylock(x)
01079 #define sip_pvt_unlock(x) ao2_unlock(x)
01080 
01081 /*! \brief  The table of TCP threads */
01082 static struct ao2_container *threadt;
01083 
01084 /*! \brief  The peer list: Users, Peers and Friends */
01085 static struct ao2_container *peers;
01086 static struct ao2_container *peers_by_ip;
01087 
01088 /*! \brief  The register list: Other SIP proxies we register with and receive calls from */
01089 static struct ast_register_list {
01090    ASTOBJ_CONTAINER_COMPONENTS(struct sip_registry);
01091    int recheck;
01092 } regl;
01093 
01094 /*! \brief  The MWI subscription list */
01095 static struct ast_subscription_mwi_list {
01096    ASTOBJ_CONTAINER_COMPONENTS(struct sip_subscription_mwi);
01097 } submwil;
01098 static int temp_pvt_init(void *);
01099 static void temp_pvt_cleanup(void *);
01100 
01101 /*! \brief A per-thread temporary pvt structure */
01102 AST_THREADSTORAGE_CUSTOM(ts_temp_pvt, temp_pvt_init, temp_pvt_cleanup);
01103 
01104 /*! \brief Authentication list for realm authentication
01105  * \todo Move the sip_auth list to AST_LIST */
01106 static struct sip_auth *authl = NULL;
01107 
01108 /* --- Sockets and networking --------------*/
01109 
01110 /*! \brief Main socket for UDP SIP communication.
01111  *
01112  * sipsock is shared between the SIP manager thread (which handles reload
01113  * requests), the udp io handler (sipsock_read()) and the user routines that
01114  * issue udp writes (using __sip_xmit()).
01115  * The socket is -1 only when opening fails (this is a permanent condition),
01116  * or when we are handling a reload() that changes its address (this is
01117  * a transient situation during which we might have a harmless race, see
01118  * below). Because the conditions for the race to be possible are extremely
01119  * rare, we don't want to pay the cost of locking on every I/O.
01120  * Rather, we remember that when the race may occur, communication is
01121  * bound to fail anyways, so we just live with this event and let
01122  * the protocol handle this above us.
01123  */
01124 static int sipsock  = -1;
01125 
01126 struct ast_sockaddr bindaddr; /*!< UDP: The address we bind to */
01127 
01128 /*! \brief our (internal) default address/port to put in SIP/SDP messages
01129  *  internip is initialized picking a suitable address from one of the
01130  * interfaces, and the same port number we bind to. It is used as the
01131  * default address/port in SIP messages, and as the default address
01132  * (but not port) in SDP messages.
01133  */
01134 static struct ast_sockaddr internip;
01135 
01136 /*! \brief our external IP address/port for SIP sessions.
01137  * externaddr.sin_addr is only set when we know we might be behind
01138  * a NAT, and this is done using a variety of (mutually exclusive)
01139  * ways from the config file:
01140  *
01141  * + with "externaddr = host[:port]" we specify the address/port explicitly.
01142  *   The address is looked up only once when (re)loading the config file;
01143  *
01144  * + with "externhost = host[:port]" we do a similar thing, but the
01145  *   hostname is stored in externhost, and the hostname->IP mapping
01146  *   is refreshed every 'externrefresh' seconds;
01147  *
01148  * Other variables (externhost, externexpire, externrefresh) are used
01149  * to support the above functions.
01150  */
01151 static struct ast_sockaddr externaddr;      /*!< External IP address if we are behind NAT */
01152 static struct ast_sockaddr media_address; /*!< External RTP IP address if we are behind NAT */
01153 
01154 static char externhost[MAXHOSTNAMELEN];   /*!< External host name */
01155 static time_t externexpire;             /*!< Expiration counter for re-resolving external host name in dynamic DNS */
01156 static int externrefresh = 10;          /*!< Refresh timer for DNS-based external address (dyndns) */
01157 static uint16_t externtcpport;          /*!< external tcp port */ 
01158 static uint16_t externtlsport;          /*!< external tls port */
01159 
01160 /*! \brief  List of local networks
01161  * We store "localnet" addresses from the config file into an access list,
01162  * marked as 'DENY', so the call to ast_apply_ha() will return
01163  * AST_SENSE_DENY for 'local' addresses, and AST_SENSE_ALLOW for 'non local'
01164  * (i.e. presumably public) addresses.
01165  */
01166 static struct ast_ha *localaddr;    /*!< List of local networks, on the same side of NAT as this Asterisk */
01167 
01168 static int ourport_tcp;             /*!< The port used for TCP connections */
01169 static int ourport_tls;             /*!< The port used for TCP/TLS connections */
01170 static struct ast_sockaddr debugaddr;
01171 
01172 static struct ast_config *notify_types = NULL;    /*!< The list of manual NOTIFY types we know how to send */
01173 
01174 /*! some list management macros. */
01175 
01176 #define UNLINK(element, head, prev) do {  \
01177    if (prev)            \
01178       (prev)->next = (element)->next;  \
01179    else              \
01180       (head) = (element)->next;  \
01181    } while (0)
01182 
01183 /*---------------------------- Forward declarations of functions in chan_sip.c */
01184 /* Note: This is added to help splitting up chan_sip.c into several files
01185    in coming releases. */
01186 
01187 /*--- PBX interface functions */
01188 static struct ast_channel *sip_request_call(const char *type, format_t format, const struct ast_channel *requestor, void *data, int *cause);
01189 static int sip_devicestate(void *data);
01190 static int sip_sendtext(struct ast_channel *ast, const char *text);
01191 static int sip_call(struct ast_channel *ast, char *dest, int timeout);
01192 static int sip_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen);
01193 static int sip_hangup(struct ast_channel *ast);
01194 static int sip_answer(struct ast_channel *ast);
01195 static struct ast_frame *sip_read(struct ast_channel *ast);
01196 static int sip_write(struct ast_channel *ast, struct ast_frame *frame);
01197 static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen);
01198 static int sip_transfer(struct ast_channel *ast, const char *dest);
01199 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
01200 static int sip_senddigit_begin(struct ast_channel *ast, char digit);
01201 static int sip_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration);
01202 static int sip_setoption(struct ast_channel *chan, int option, void *data, int datalen);
01203 static int sip_queryoption(struct ast_channel *chan, int option, void *data, int *datalen);
01204 static const char *sip_get_callid(struct ast_channel *chan);
01205 
01206 static int handle_request_do(struct sip_request *req, struct ast_sockaddr *addr);
01207 static int sip_standard_port(enum sip_transport type, int port);
01208 static int sip_prepare_socket(struct sip_pvt *p);
01209 static int get_address_family_filter(const struct ast_sockaddr *addr);
01210 
01211 /*--- Transmitting responses and requests */
01212 static int sipsock_read(int *id, int fd, short events, void *ignore);
01213 static int __sip_xmit(struct sip_pvt *p, struct ast_str *data, int len);
01214 static int __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, struct ast_str *data, int len, int fatal, int sipmethod);
01215 static void add_cc_call_info_to_response(struct sip_pvt *p, struct sip_request *resp);
01216 static int __transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
01217 static int retrans_pkt(const void *data);
01218 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);
01219 static int transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req);
01220 static int transmit_response_reliable(struct sip_pvt *p, const char *msg, const struct sip_request *req);
01221 static int transmit_response_with_date(struct sip_pvt *p, const char *msg, const struct sip_request *req);
01222 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);
01223 static int transmit_response_with_unsupported(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *unsupported);
01224 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);
01225 static int transmit_provisional_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, int with_sdp);
01226 static int transmit_response_with_allow(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
01227 static void transmit_fake_auth_response(struct sip_pvt *p, int sipmethod, struct sip_request *req, enum xmittype reliable);
01228 static int transmit_request(struct sip_pvt *p, int sipmethod, int inc, enum xmittype reliable, int newbranch);
01229 static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, int seqno, enum xmittype reliable, int newbranch);
01230 static int transmit_publish(struct sip_epa_entry *epa_entry, enum sip_publish_type publish_type, const char * const explicit_uri);
01231 static int transmit_invite(struct sip_pvt *p, int sipmethod, int sdp, int init, const char * const explicit_uri);
01232 static int transmit_reinvite_with_sdp(struct sip_pvt *p, int t38version, int oldsdp);
01233 static int transmit_info_with_aoc(struct sip_pvt *p, struct ast_aoc_decoded *decoded);
01234 static int transmit_info_with_digit(struct sip_pvt *p, const char digit, unsigned int duration);
01235 static int transmit_info_with_vidupdate(struct sip_pvt *p);
01236 static int transmit_message_with_text(struct sip_pvt *p, const char *text);
01237 static int transmit_refer(struct sip_pvt *p, const char *dest);
01238 static int transmit_notify_with_mwi(struct sip_pvt *p, int newmsgs, int oldmsgs, const char *vmexten);
01239 static int transmit_notify_with_sipfrag(struct sip_pvt *p, int cseq, char *message, int terminate);
01240 static int transmit_cc_notify(struct ast_cc_agent *agent, struct sip_pvt *subscription, enum sip_cc_notify_state state);
01241 static int transmit_register(struct sip_registry *r, int sipmethod, const char *auth, const char *authheader);
01242 static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno);
01243 static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno);
01244 static void copy_request(struct sip_request *dst, const struct sip_request *src);
01245 static void receive_message(struct sip_pvt *p, struct sip_request *req);
01246 static void parse_moved_contact(struct sip_pvt *p, struct sip_request *req, char **name, char **number, int set_call_forward);
01247 static int sip_send_mwi_to_peer(struct sip_peer *peer, const struct ast_event *event, int cache_only);
01248 
01249 /* Misc dialog routines */
01250 static int __sip_autodestruct(const void *data);
01251 static void *registry_unref(struct sip_registry *reg, char *tag);
01252 static int update_call_counter(struct sip_pvt *fup, int event);
01253 static int auto_congest(const void *arg);
01254 static struct sip_pvt *find_call(struct sip_request *req, struct ast_sockaddr *addr, const int intended_method);
01255 static void free_old_route(struct sip_route *route);
01256 static void list_route(struct sip_route *route);
01257 static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards);
01258 static enum check_auth_result register_verify(struct sip_pvt *p, struct ast_sockaddr *addr,
01259                      struct sip_request *req, const char *uri);
01260 static struct sip_pvt *get_sip_pvt_byid_locked(const char *callid, const char *totag, const char *fromtag);
01261 static void check_pendings(struct sip_pvt *p);
01262 static void *sip_park_thread(void *stuff);
01263 static int sip_park(struct ast_channel *chan1, struct ast_channel *chan2, struct sip_request *req, int seqno, char *parkexten);
01264 static int sip_sipredirect(struct sip_pvt *p, const char *dest);
01265 static int is_method_allowed(unsigned int *allowed_methods, enum sipmethod method);
01266 
01267 /*--- Codec handling / SDP */
01268 static void try_suggested_sip_codec(struct sip_pvt *p);
01269 static const char *get_sdp_iterate(int* start, struct sip_request *req, const char *name);
01270 static char get_sdp_line(int *start, int stop, struct sip_request *req, const char **value);
01271 static int find_sdp(struct sip_request *req);
01272 static int process_sdp(struct sip_pvt *p, struct sip_request *req, int t38action);
01273 static int process_sdp_o(const char *o, struct sip_pvt *p);
01274 static int process_sdp_c(const char *c, struct ast_sockaddr *addr);
01275 static int process_sdp_a_sendonly(const char *a, int *sendonly);
01276 static int process_sdp_a_audio(const char *a, struct sip_pvt *p, struct ast_rtp_codecs *newaudiortp, int *last_rtpmap_codec);
01277 static int process_sdp_a_video(const char *a, struct sip_pvt *p, struct ast_rtp_codecs *newvideortp, int *last_rtpmap_codec);
01278 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);
01279 static int process_sdp_a_image(const char *a, struct sip_pvt *p);
01280 static void add_codec_to_sdp(const struct sip_pvt *p, format_t codec,
01281               struct ast_str **m_buf, struct ast_str **a_buf,
01282               int debug, int *min_packet_size);
01283 static void add_noncodec_to_sdp(const struct sip_pvt *p, int format,
01284             struct ast_str **m_buf, struct ast_str **a_buf,
01285             int debug);
01286 static enum sip_result add_sdp(struct sip_request *resp, struct sip_pvt *p, int oldsdp, int add_audio, int add_t38);
01287 static void do_setnat(struct sip_pvt *p);
01288 static void stop_media_flows(struct sip_pvt *p);
01289 
01290 /*--- Authentication stuff */
01291 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod, char *digest, int digest_len);
01292 static int build_reply_digest(struct sip_pvt *p, int method, char *digest, int digest_len);
01293 static enum check_auth_result check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
01294                 const char *secret, const char *md5secret, int sipmethod,
01295                 const char *uri, enum xmittype reliable, int ignore);
01296 static enum check_auth_result check_user_full(struct sip_pvt *p, struct sip_request *req,
01297                      int sipmethod, const char *uri, enum xmittype reliable,
01298                      struct ast_sockaddr *addr, struct sip_peer **authpeer);
01299 static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, const char *uri, enum xmittype reliable, struct ast_sockaddr *addr);
01300 
01301 /*--- Domain handling */
01302 static int check_sip_domain(const char *domain, char *context, size_t len); /* Check if domain is one of our local domains */
01303 static int add_sip_domain(const char *domain, const enum domain_mode mode, const char *context);
01304 static void clear_sip_domains(void);
01305 
01306 /*--- SIP realm authentication */
01307 static struct sip_auth *add_realm_authentication(struct sip_auth *authlist, const char *configuration, int lineno);
01308 static int clear_realm_authentication(struct sip_auth *authlist); /* Clear realm authentication list (at reload) */
01309 static struct sip_auth *find_realm_authentication(struct sip_auth *authlist, const char *realm);
01310 
01311 /*--- Misc functions */
01312 static void check_rtp_timeout(struct sip_pvt *dialog, time_t t);
01313 static int sip_do_reload(enum channelreloadreason reason);
01314 static int reload_config(enum channelreloadreason reason);
01315 static int expire_register(const void *data);
01316 static void *do_monitor(void *data);
01317 static int restart_monitor(void);
01318 static void peer_mailboxes_to_str(struct ast_str **mailbox_str, struct sip_peer *peer);
01319 static struct ast_variable *copy_vars(struct ast_variable *src);
01320 static int dialog_find_multiple(void *obj, void *arg, int flags);
01321 /* static int sip_addrcmp(char *name, struct sockaddr_in *sin);   Support for peer matching */
01322 static int sip_refer_allocate(struct sip_pvt *p);
01323 static int sip_notify_allocate(struct sip_pvt *p);
01324 static void ast_quiet_chan(struct ast_channel *chan);
01325 static int attempt_transfer(struct sip_dual *transferer, struct sip_dual *target);
01326 static int do_magic_pickup(struct ast_channel *channel, const char *extension, const char *context);
01327 
01328 /*--- Device monitoring and Device/extension state/event handling */
01329 static int cb_extensionstate(char *context, char* exten, int state, void *data);
01330 static int sip_devicestate(void *data);
01331 static int sip_poke_noanswer(const void *data);
01332 static int sip_poke_peer(struct sip_peer *peer, int force);
01333 static void sip_poke_all_peers(void);
01334 static void sip_peer_hold(struct sip_pvt *p, int hold);
01335 static void mwi_event_cb(const struct ast_event *, void *);
01336 static void network_change_event_cb(const struct ast_event *, void *);
01337 
01338 /*--- Applications, functions, CLI and manager command helpers */
01339 static const char *sip_nat_mode(const struct sip_pvt *p);
01340 static char *sip_show_inuse(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01341 static char *transfermode2str(enum transfermodes mode) attribute_const;
01342 static int peer_status(struct sip_peer *peer, char *status, int statuslen);
01343 static char *sip_show_sched(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01344 static char * _sip_show_peers(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char *argv[]);
01345 static char *sip_show_peers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01346 static char *sip_show_objects(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01347 static void  print_group(int fd, ast_group_t group, int crlf);
01348 static const char *dtmfmode2str(int mode) attribute_const;
01349 static int str2dtmfmode(const char *str) attribute_unused;
01350 static const char *insecure2str(int mode) attribute_const;
01351 static void cleanup_stale_contexts(char *new, char *old);
01352 static void print_codec_to_cli(int fd, struct ast_codec_pref *pref);
01353 static const char *domain_mode_to_text(const enum domain_mode mode);
01354 static char *sip_show_domains(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01355 static char *_sip_show_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[]);
01356 static char *sip_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01357 static char *_sip_qualify_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[]);
01358 static char *sip_qualify_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01359 static char *sip_show_registry(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01360 static char *sip_unregister(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01361 static char *sip_show_settings(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01362 static char *sip_show_mwi(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01363 static const char *subscription_type2str(enum subscriptiontype subtype) attribute_pure;
01364 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
01365 static char *complete_sip_peer(const char *word, int state, int flags2);
01366 static char *complete_sip_registered_peer(const char *word, int state, int flags2);
01367 static char *complete_sip_show_history(const char *line, const char *word, int pos, int state);
01368 static char *complete_sip_show_peer(const char *line, const char *word, int pos, int state);
01369 static char *complete_sip_unregister(const char *line, const char *word, int pos, int state);
01370 static char *complete_sipnotify(const char *line, const char *word, int pos, int state);
01371 static char *sip_show_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01372 static char *sip_show_channelstats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01373 static char *sip_show_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01374 static char *sip_do_debug_ip(int fd, const char *arg);
01375 static char *sip_do_debug_peer(int fd, const char *arg);
01376 static char *sip_do_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01377 static char *sip_cli_notify(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01378 static char *sip_set_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01379 static int sip_dtmfmode(struct ast_channel *chan, const char *data);
01380 static int sip_addheader(struct ast_channel *chan, const char *data);
01381 static int sip_do_reload(enum channelreloadreason reason);
01382 static char *sip_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01383 static int ast_sockaddr_resolve_first_af(struct ast_sockaddr *addr,
01384                   const char *name, int flag, int family);
01385 static int ast_sockaddr_resolve_first(struct ast_sockaddr *addr,
01386                   const char *name, int flag);
01387 
01388 /*--- Debugging
01389    Functions for enabling debug per IP or fully, or enabling history logging for
01390    a SIP dialog
01391 */
01392 static void sip_dump_history(struct sip_pvt *dialog); /* Dump history to debuglog at end of dialog, before destroying data */
01393 static inline int sip_debug_test_addr(const struct ast_sockaddr *addr);
01394 static inline int sip_debug_test_pvt(struct sip_pvt *p);
01395 static void append_history_full(struct sip_pvt *p, const char *fmt, ...);
01396 static void sip_dump_history(struct sip_pvt *dialog);
01397 
01398 /*--- Device object handling */
01399 static struct sip_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime, int devstate_only);
01400 static int update_call_counter(struct sip_pvt *fup, int event);
01401 static void sip_destroy_peer(struct sip_peer *peer);
01402 static void sip_destroy_peer_fn(void *peer);
01403 static void set_peer_defaults(struct sip_peer *peer);
01404 static struct sip_peer *temp_peer(const char *name);
01405 static void register_peer_exten(struct sip_peer *peer, int onoff);
01406 static struct sip_peer *find_peer(const char *peer, struct ast_sockaddr *addr, int realtime, int forcenamematch, int devstate_only, int transport);
01407 static int sip_poke_peer_s(const void *data);
01408 static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *p, struct sip_request *req);
01409 static void reg_source_db(struct sip_peer *peer);
01410 static void destroy_association(struct sip_peer *peer);
01411 static void set_insecure_flags(struct ast_flags *flags, const char *value, int lineno);
01412 static int handle_common_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v);
01413 static void set_socket_transport(struct sip_socket *socket, int transport);
01414 
01415 /* Realtime device support */
01416 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);
01417 static void update_peer(struct sip_peer *p, int expire);
01418 static struct ast_variable *get_insecure_variable_from_config(struct ast_config *config);
01419 static const char *get_name_from_variable(struct ast_variable *var, const char *newpeername);
01420 static struct sip_peer *realtime_peer(const char *peername, struct ast_sockaddr *sin, int devstate_only);
01421 static char *sip_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01422 
01423 /*--- Internal UA client handling (outbound registrations) */
01424 static void ast_sip_ouraddrfor(const struct ast_sockaddr *them, struct ast_sockaddr *us, struct sip_pvt *p);
01425 static void sip_registry_destroy(struct sip_registry *reg);
01426 static int sip_register(const char *value, int lineno);
01427 static const char *regstate2str(enum sipregistrystate regstate) attribute_const;
01428 static int sip_reregister(const void *data);
01429 static int __sip_do_register(struct sip_registry *r);
01430 static int sip_reg_timeout(const void *data);
01431 static void sip_send_all_registers(void);
01432 static int sip_reinvite_retry(const void *data);
01433 
01434 /*--- Parsing SIP requests and responses */
01435 static void append_date(struct sip_request *req);  /* Append date to SIP packet */
01436 static int determine_firstline_parts(struct sip_request *req);
01437 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
01438 static const char *gettag(const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize);
01439 static int find_sip_method(const char *msg);
01440 static unsigned int parse_allowed_methods(struct sip_request *req);
01441 static unsigned int set_pvt_allowed_methods(struct sip_pvt *pvt, struct sip_request *req);
01442 static int parse_request(struct sip_request *req);
01443 static const char *get_header(const struct sip_request *req, const char *name);
01444 static const char *referstatus2str(enum referstatus rstatus) attribute_pure;
01445 static int method_match(enum sipmethod id, const char *name);
01446 static void parse_copy(struct sip_request *dst, const struct sip_request *src);
01447 static const char *find_alias(const char *name, const char *_default);
01448 static const char *__get_header(const struct sip_request *req, const char *name, int *start);
01449 static int lws2sws(char *msgbuf, int len);
01450 static void extract_uri(struct sip_pvt *p, struct sip_request *req);
01451 static char *remove_uri_parameters(char *uri);
01452 static int get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req);
01453 static int get_also_info(struct sip_pvt *p, struct sip_request *oreq);
01454 static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req);
01455 static int set_address_from_contact(struct sip_pvt *pvt);
01456 static void check_via(struct sip_pvt *p, struct sip_request *req);
01457 static int get_rpid(struct sip_pvt *p, struct sip_request *oreq);
01458 static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq, char **name, char **number, int *reason);
01459 static enum sip_get_dest_result get_destination(struct sip_pvt *p, struct sip_request *oreq, int *cc_recall_core_id);
01460 static int get_msg_text(char *buf, int len, struct sip_request *req, int addnewline);
01461 static int transmit_state_notify(struct sip_pvt *p, int state, int full, int timeout);
01462 static void update_connectedline(struct sip_pvt *p, const void *data, size_t datalen);
01463 static void update_redirecting(struct sip_pvt *p, const void *data, size_t datalen);
01464 static int get_domain(const char *str, char *domain, int len);
01465 static void get_realm(struct sip_pvt *p, const struct sip_request *req);
01466 
01467 /*-- TCP connection handling ---*/
01468 static void *_sip_tcp_helper_thread(struct sip_pvt *pvt, struct ast_tcptls_session_instance *tcptls_session);
01469 static void *sip_tcp_worker_fn(void *);
01470 
01471 /*--- Constructing requests and responses */
01472 static void initialize_initreq(struct sip_pvt *p, struct sip_request *req);
01473 static int init_req(struct sip_request *req, int sipmethod, const char *recip);
01474 static void deinit_req(struct sip_request *req);
01475 static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, int seqno, int newbranch);
01476 static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, const char * const explicit_uri);
01477 static int init_resp(struct sip_request *resp, const char *msg);
01478 static inline int resp_needs_contact(const char *msg, enum sipmethod method);
01479 static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req);
01480 static const struct ast_sockaddr *sip_real_dst(const struct sip_pvt *p);
01481 static void build_via(struct sip_pvt *p);
01482 static int create_addr_from_peer(struct sip_pvt *r, struct sip_peer *peer);
01483 static int create_addr(struct sip_pvt *dialog, const char *opeer, struct ast_sockaddr *addr, int newdialog, struct ast_sockaddr *remote_address);
01484 static char *generate_random_string(char *buf, size_t size);
01485 static void build_callid_pvt(struct sip_pvt *pvt);
01486 static void build_callid_registry(struct sip_registry *reg, const struct ast_sockaddr *ourip, const char *fromdomain);
01487 static void make_our_tag(char *tagbuf, size_t len);
01488 static int add_header(struct sip_request *req, const char *var, const char *value);
01489 static int add_header_max_forwards(struct sip_pvt *dialog, struct sip_request *req);
01490 static int add_content(struct sip_request *req, const char *line);
01491 static int finalize_content(struct sip_request *req);
01492 static int add_text(struct sip_request *req, const char *text);
01493 static int add_digit(struct sip_request *req, char digit, unsigned int duration, int mode);
01494 static int add_rpid(struct sip_request *req, struct sip_pvt *p);
01495 static int add_vidupdate(struct sip_request *req);
01496 static void add_route(struct sip_request *req, struct sip_route *route);
01497 static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field);
01498 static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field);
01499 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field);
01500 static void set_destination(struct sip_pvt *p, char *uri);
01501 static void append_date(struct sip_request *req);
01502 static void build_contact(struct sip_pvt *p);
01503 
01504 /*------Request handling functions */
01505 static int handle_incoming(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, int *recount, int *nounlock);
01506 static int handle_request_update(struct sip_pvt *p, struct sip_request *req);
01507 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);
01508 static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, int *nounlock);
01509 static int handle_request_bye(struct sip_pvt *p, struct sip_request *req);
01510 static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *sin, const char *e);
01511 static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req);
01512 static int handle_request_message(struct sip_pvt *p, struct sip_request *req);
01513 static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, int seqno, const char *e);
01514 static void handle_request_info(struct sip_pvt *p, struct sip_request *req);
01515 static int handle_request_options(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, const char *e);
01516 static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, struct ast_sockaddr *addr, int *nounlock);
01517 static int handle_request_notify(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, int seqno, const char *e);
01518 static int local_attended_transfer(struct sip_pvt *transferer, struct sip_dual *current, struct sip_request *req, int seqno, int *nounlock);
01519 
01520 /*------Response handling functions */
01521 static void handle_response_publish(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno);
01522 static void handle_response_invite(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno);
01523 static void handle_response_notify(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno);
01524 static void handle_response_refer(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno);
01525 static void handle_response_subscribe(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno);
01526 static int handle_response_register(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno);
01527 static void handle_response(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno);
01528 
01529 /*------ SRTP Support -------- */
01530 static int setup_srtp(struct sip_srtp **srtp);
01531 static int process_crypto(struct sip_pvt *p, struct ast_rtp_instance *rtp, struct sip_srtp **srtp, const char *a);
01532 
01533 /*------ T38 Support --------- */
01534 static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans);
01535 static struct ast_udptl *sip_get_udptl_peer(struct ast_channel *chan);
01536 static int sip_set_udptl_peer(struct ast_channel *chan, struct ast_udptl *udptl);
01537 static void change_t38_state(struct sip_pvt *p, int state);
01538 
01539 /*------ Session-Timers functions --------- */
01540 static void proc_422_rsp(struct sip_pvt *p, struct sip_request *rsp);
01541 static int  proc_session_timer(const void *vp);
01542 static void stop_session_timer(struct sip_pvt *p);
01543 static void start_session_timer(struct sip_pvt *p);
01544 static void restart_session_timer(struct sip_pvt *p);
01545 static const char *strefresher2str(enum st_refresher r);
01546 static int parse_session_expires(const char *p_hdrval, int *const p_interval, enum st_refresher *const p_ref);
01547 static int parse_minse(const char *p_hdrval, int *const p_interval);
01548 static int st_get_se(struct sip_pvt *, int max);
01549 static enum st_refresher st_get_refresher(struct sip_pvt *);
01550 static enum st_mode st_get_mode(struct sip_pvt *);
01551 static struct sip_st_dlg* sip_st_alloc(struct sip_pvt *const p);
01552 
01553 /*------- RTP Glue functions -------- */
01554 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);
01555 
01556 /*!--- SIP MWI Subscription support */
01557 static int sip_subscribe_mwi(const char *value, int lineno);
01558 static void sip_subscribe_mwi_destroy(struct sip_subscription_mwi *mwi);
01559 static void sip_send_all_mwi_subscriptions(void);
01560 static int sip_subscribe_mwi_do(const void *data);
01561 static int __sip_subscribe_mwi_do(struct sip_subscription_mwi *mwi);
01562 
01563 /*! \brief Definition of this channel for PBX channel registration */
01564 const struct ast_channel_tech sip_tech = {
01565    .type = "SIP",
01566    .description = "Session Initiation Protocol (SIP)",
01567    .capabilities = AST_FORMAT_AUDIO_MASK, /* all audio formats */
01568    .properties = AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER,
01569    .requester = sip_request_call,         /* called with chan unlocked */
01570    .devicestate = sip_devicestate,        /* called with chan unlocked (not chan-specific) */
01571    .call = sip_call,       /* called with chan locked */
01572    .send_html = sip_sendhtml,
01573    .hangup = sip_hangup,         /* called with chan locked */
01574    .answer = sip_answer,         /* called with chan locked */
01575    .read = sip_read,       /* called with chan locked */
01576    .write = sip_write,        /* called with chan locked */
01577    .write_video = sip_write,     /* called with chan locked */
01578    .write_text = sip_write,
01579    .indicate = sip_indicate,     /* called with chan locked */
01580    .transfer = sip_transfer,     /* called with chan locked */
01581    .fixup = sip_fixup,        /* called with chan locked */
01582    .send_digit_begin = sip_senddigit_begin,  /* called with chan unlocked */
01583    .send_digit_end = sip_senddigit_end,
01584    .bridge = ast_rtp_instance_bridge,        /* XXX chan unlocked ? */
01585    .early_bridge = ast_rtp_instance_early_bridge,
01586    .send_text = sip_sendtext,    /* called with chan locked */
01587    .func_channel_read = sip_acf_channel_read,
01588    .setoption = sip_setoption,
01589    .queryoption = sip_queryoption,
01590    .get_pvt_uniqueid = sip_get_callid,
01591 };
01592 
01593 /*! \brief This version of the sip channel tech has no send_digit_begin
01594  * callback so that the core knows that the channel does not want
01595  * DTMF BEGIN frames.
01596  * The struct is initialized just before registering the channel driver,
01597  * and is for use with channels using SIP INFO DTMF.
01598  */
01599 struct ast_channel_tech sip_tech_info;
01600 
01601 static int sip_cc_agent_init(struct ast_cc_agent *agent, struct ast_channel *chan);
01602 static int sip_cc_agent_start_offer_timer(struct ast_cc_agent *agent);
01603 static int sip_cc_agent_stop_offer_timer(struct ast_cc_agent *agent);
01604 static void sip_cc_agent_ack(struct ast_cc_agent *agent);
01605 static int sip_cc_agent_status_request(struct ast_cc_agent *agent);
01606 static int sip_cc_agent_start_monitoring(struct ast_cc_agent *agent);
01607 static int sip_cc_agent_recall(struct ast_cc_agent *agent);
01608 static void sip_cc_agent_destructor(struct ast_cc_agent *agent);
01609 
01610 static struct ast_cc_agent_callbacks sip_cc_agent_callbacks = {
01611    .type = "SIP",
01612    .init = sip_cc_agent_init,
01613    .start_offer_timer = sip_cc_agent_start_offer_timer,
01614    .stop_offer_timer = sip_cc_agent_stop_offer_timer,
01615    .ack = sip_cc_agent_ack,
01616    .status_request = sip_cc_agent_status_request,
01617    .start_monitoring = sip_cc_agent_start_monitoring,
01618    .callee_available = sip_cc_agent_recall,
01619    .destructor = sip_cc_agent_destructor,
01620 };
01621 
01622 static int find_by_notify_uri_helper(void *obj, void *arg, int flags)
01623 {
01624    struct ast_cc_agent *agent = obj;
01625    struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01626    const char *uri = arg;
01627 
01628    return !strcmp(agent_pvt->notify_uri, uri) ? CMP_MATCH | CMP_STOP : 0;
01629 }
01630 
01631 static struct ast_cc_agent *find_sip_cc_agent_by_notify_uri(const char * const uri)
01632 {
01633    struct ast_cc_agent *agent = ast_cc_agent_callback(0, find_by_notify_uri_helper, (char *)uri, "SIP");
01634    return agent;
01635 }
01636 
01637 static int find_by_subscribe_uri_helper(void *obj, void *arg, int flags)
01638 {
01639    struct ast_cc_agent *agent = obj;
01640    struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01641    const char *uri = arg;
01642 
01643    return !strcmp(agent_pvt->subscribe_uri, uri) ? CMP_MATCH | CMP_STOP : 0;
01644 }
01645 
01646 static struct ast_cc_agent *find_sip_cc_agent_by_subscribe_uri(const char * const uri)
01647 {
01648    struct ast_cc_agent *agent = ast_cc_agent_callback(0, find_by_subscribe_uri_helper, (char *)uri, "SIP");
01649    return agent;
01650 }
01651 
01652 static int find_by_callid_helper(void *obj, void *arg, int flags)
01653 {
01654    struct ast_cc_agent *agent = obj;
01655    struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01656    struct sip_pvt *call_pvt = arg;
01657 
01658    return !strcmp(agent_pvt->original_callid, call_pvt->callid) ? CMP_MATCH | CMP_STOP : 0;
01659 }
01660 
01661 static struct ast_cc_agent *find_sip_cc_agent_by_original_callid(struct sip_pvt *pvt)
01662 {
01663    struct ast_cc_agent *agent = ast_cc_agent_callback(0, find_by_callid_helper, pvt, "SIP");
01664    return agent;
01665 }
01666 
01667 static int sip_cc_agent_init(struct ast_cc_agent *agent, struct ast_channel *chan)
01668 {
01669    struct sip_cc_agent_pvt *agent_pvt = ast_calloc(1, sizeof(*agent_pvt));
01670    struct sip_pvt *call_pvt = chan->tech_pvt;
01671 
01672    if (!agent_pvt) {
01673       return -1;
01674    }
01675 
01676    ast_assert(!strcmp(chan->tech->type, "SIP"));
01677 
01678    ast_copy_string(agent_pvt->original_callid, call_pvt->callid, sizeof(agent_pvt->original_callid));
01679    ast_copy_string(agent_pvt->original_exten, call_pvt->exten, sizeof(agent_pvt->original_exten));
01680    agent_pvt->offer_timer_id = -1;
01681    agent->private_data = agent_pvt;
01682    sip_pvt_lock(call_pvt);
01683    ast_set_flag(&call_pvt->flags[0], SIP_OFFER_CC);
01684    sip_pvt_unlock(call_pvt);
01685    return 0;
01686 }
01687 
01688 static int sip_offer_timer_expire(const void *data)
01689 {
01690    struct ast_cc_agent *agent = (struct ast_cc_agent *) data;
01691    struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01692 
01693    agent_pvt->offer_timer_id = -1;
01694 
01695    return ast_cc_failed(agent->core_id, "SIP agent %s's offer timer expired", agent->device_name);
01696 }
01697 
01698 static int sip_cc_agent_start_offer_timer(struct ast_cc_agent *agent)
01699 {
01700    struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01701    int when;
01702 
01703    when = ast_get_cc_offer_timer(agent->cc_params) * 1000;
01704    agent_pvt->offer_timer_id = ast_sched_add(sched, when, sip_offer_timer_expire, agent);
01705    return 0;
01706 }
01707 
01708 static int sip_cc_agent_stop_offer_timer(struct ast_cc_agent *agent)
01709 {
01710    struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01711 
01712    AST_SCHED_DEL(sched, agent_pvt->offer_timer_id);
01713    return 0;
01714 }
01715 
01716 static void sip_cc_agent_ack(struct ast_cc_agent *agent)
01717 {
01718    struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01719 
01720    sip_pvt_lock(agent_pvt->subscribe_pvt);
01721    ast_set_flag(&agent_pvt->subscribe_pvt->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
01722    transmit_response(agent_pvt->subscribe_pvt, "200 OK", &agent_pvt->subscribe_pvt->initreq);
01723    transmit_cc_notify(agent, agent_pvt->subscribe_pvt, CC_QUEUED);
01724    sip_pvt_unlock(agent_pvt->subscribe_pvt);
01725    agent_pvt->is_available = TRUE;
01726 }
01727 
01728 static int sip_cc_agent_status_request(struct ast_cc_agent *agent)
01729 {
01730    struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01731    enum ast_device_state state = agent_pvt->is_available ? AST_DEVICE_NOT_INUSE : AST_DEVICE_INUSE;
01732    return ast_cc_agent_status_response(agent->core_id, state);
01733 }
01734 
01735 static int sip_cc_agent_start_monitoring(struct ast_cc_agent *agent)
01736 {
01737    /* To start monitoring just means to wait for an incoming PUBLISH
01738     * to tell us that the caller has become available again. No special
01739     * action is needed
01740     */
01741    return 0;
01742 }
01743 
01744 static int sip_cc_agent_recall(struct ast_cc_agent *agent)
01745 {
01746    struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01747    /* If we have received a PUBLISH beforehand stating that the caller in question
01748     * is not available, we can save ourself a bit of effort here and just report
01749     * the caller as busy
01750     */
01751    if (!agent_pvt->is_available) {
01752       return ast_cc_agent_caller_busy(agent->core_id, "Caller %s is busy, reporting to the core",
01753             agent->device_name);
01754    }
01755    /* Otherwise, we transmit a NOTIFY to the caller and await either
01756     * a PUBLISH or an INVITE
01757     */
01758    sip_pvt_lock(agent_pvt->subscribe_pvt);
01759    transmit_cc_notify(agent, agent_pvt->subscribe_pvt, CC_READY);
01760    sip_pvt_unlock(agent_pvt->subscribe_pvt);
01761    return 0;
01762 }
01763 
01764 static void sip_cc_agent_destructor(struct ast_cc_agent *agent)
01765 {
01766    struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01767 
01768    if (!agent_pvt) {
01769       /* The agent constructor probably failed. */
01770       return;
01771    }
01772 
01773    sip_cc_agent_stop_offer_timer(agent);
01774    if (agent_pvt->subscribe_pvt) {
01775       sip_pvt_lock(agent_pvt->subscribe_pvt);
01776       if (!ast_test_flag(&agent_pvt->subscribe_pvt->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED)) {
01777          /* If we haven't sent a 200 OK for the SUBSCRIBE dialog yet, then we need to send a response letting
01778           * the subscriber know something went wrong
01779           */
01780          transmit_response(agent_pvt->subscribe_pvt, "500 Internal Server Error", &agent_pvt->subscribe_pvt->initreq);
01781       }
01782       sip_pvt_unlock(agent_pvt->subscribe_pvt);
01783       agent_pvt->subscribe_pvt = dialog_unref(agent_pvt->subscribe_pvt, "SIP CC agent destructor: Remove ref to subscription");
01784    }
01785    ast_free(agent_pvt);
01786 }
01787 
01788 struct ao2_container *sip_monitor_instances;
01789 
01790 static int sip_monitor_instance_hash_fn(const void *obj, const int flags)
01791 {
01792    const struct sip_monitor_instance *monitor_instance = obj;
01793    return monitor_instance->core_id;
01794 }
01795 
01796 static int sip_monitor_instance_cmp_fn(void *obj, void *arg, int flags)
01797 {
01798    struct sip_monitor_instance *monitor_instance1 = obj;
01799    struct sip_monitor_instance *monitor_instance2 = arg;
01800 
01801    return monitor_instance1->core_id == monitor_instance2->core_id ? CMP_MATCH | CMP_STOP : 0;
01802 }
01803 
01804 static void sip_monitor_instance_destructor(void *data)
01805 {
01806    struct sip_monitor_instance *monitor_instance = data;
01807    if (monitor_instance->subscription_pvt) {
01808       sip_pvt_lock(monitor_instance->subscription_pvt);
01809       monitor_instance->subscription_pvt->expiry = 0;
01810       transmit_invite(monitor_instance->subscription_pvt, SIP_SUBSCRIBE, FALSE, 0, monitor_instance->subscribe_uri);
01811       sip_pvt_unlock(monitor_instance->subscription_pvt);
01812       dialog_unref(monitor_instance->subscription_pvt, "Unref monitor instance ref of subscription pvt");
01813    }
01814    if (monitor_instance->suspension_entry) {
01815       monitor_instance->suspension_entry->body[0] = '\0';
01816       transmit_publish(monitor_instance->suspension_entry, SIP_PUBLISH_REMOVE ,monitor_instance->notify_uri);
01817       ao2_t_ref(monitor_instance->suspension_entry, -1, "Decrementing suspension entry refcount in sip_monitor_instance_destructor");
01818    }
01819    ast_string_field_free_memory(monitor_instance);
01820 }
01821 
01822 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)
01823 {
01824    struct sip_monitor_instance *monitor_instance = ao2_alloc(sizeof(*monitor_instance), sip_monitor_instance_destructor);
01825 
01826    if (!monitor_instance) {
01827       return NULL;
01828    }
01829 
01830    if (ast_string_field_init(monitor_instance, 256)) {
01831       ao2_ref(monitor_instance, -1);
01832       return NULL;
01833    }
01834 
01835    ast_string_field_set(monitor_instance, subscribe_uri, subscribe_uri);
01836    ast_string_field_set(monitor_instance, peername, peername);
01837    ast_string_field_set(monitor_instance, device_name, device_name);
01838    monitor_instance->core_id = core_id;
01839    ao2_link(sip_monitor_instances, monitor_instance);
01840    return monitor_instance;
01841 }
01842 
01843 static int find_sip_monitor_instance_by_subscription_pvt(void *obj, void *arg, int flags)
01844 {
01845    struct sip_monitor_instance *monitor_instance = obj;
01846    return monitor_instance->subscription_pvt == arg ? CMP_MATCH | CMP_STOP : 0;
01847 }
01848 
01849 static int find_sip_monitor_instance_by_suspension_entry(void *obj, void *arg, int flags)
01850 {
01851    struct sip_monitor_instance *monitor_instance = obj;
01852    return monitor_instance->suspension_entry == arg ? CMP_MATCH | CMP_STOP : 0;
01853 }
01854 
01855 static int sip_cc_monitor_request_cc(struct ast_cc_monitor *monitor, int *available_timer_id);
01856 static int sip_cc_monitor_suspend(struct ast_cc_monitor *monitor);
01857 static int sip_cc_monitor_unsuspend(struct ast_cc_monitor *monitor);
01858 static int sip_cc_monitor_cancel_available_timer(struct ast_cc_monitor *monitor, int *sched_id);
01859 static void sip_cc_monitor_destructor(void *private_data);
01860 
01861 static struct ast_cc_monitor_callbacks sip_cc_monitor_callbacks = {
01862    .type = "SIP",
01863    .request_cc = sip_cc_monitor_request_cc,
01864    .suspend = sip_cc_monitor_suspend,
01865    .unsuspend = sip_cc_monitor_unsuspend,
01866    .cancel_available_timer = sip_cc_monitor_cancel_available_timer,
01867    .destructor = sip_cc_monitor_destructor,
01868 };
01869 
01870 static int sip_cc_monitor_request_cc(struct ast_cc_monitor *monitor, int *available_timer_id)
01871 {
01872    struct sip_monitor_instance *monitor_instance = monitor->private_data;
01873    enum ast_cc_service_type service = monitor->service_offered;
01874    int when;
01875 
01876    if (!monitor_instance) {
01877       return -1;
01878    }
01879 
01880    if (!(monitor_instance->subscription_pvt = sip_alloc(NULL, NULL, 0, SIP_SUBSCRIBE, NULL))) {
01881       return -1;
01882    }
01883 
01884    when = service == AST_CC_CCBS ? ast_get_ccbs_available_timer(monitor->interface->config_params) :
01885       ast_get_ccnr_available_timer(monitor->interface->config_params);
01886 
01887    sip_pvt_lock(monitor_instance->subscription_pvt);
01888    create_addr(monitor_instance->subscription_pvt, monitor_instance->peername, 0, 1, NULL);
01889    ast_sip_ouraddrfor(&monitor_instance->subscription_pvt->sa, &monitor_instance->subscription_pvt->ourip, monitor_instance->subscription_pvt);
01890    monitor_instance->subscription_pvt->subscribed = CALL_COMPLETION;
01891    monitor_instance->subscription_pvt->expiry = when;
01892 
01893    transmit_invite(monitor_instance->subscription_pvt, SIP_SUBSCRIBE, FALSE, 2, monitor_instance->subscribe_uri);
01894    sip_pvt_unlock(monitor_instance->subscription_pvt);
01895 
01896    ao2_t_ref(monitor, +1, "Adding a ref to the monitor for the scheduler");
01897    *available_timer_id = ast_sched_add(sched, when * 1000, ast_cc_available_timer_expire, monitor);
01898    return 0;
01899 }
01900 
01901 static int construct_pidf_body(enum sip_cc_publish_state state, char *pidf_body, size_t size, const char *presentity)
01902 {
01903    struct ast_str *body = ast_str_alloca(size);
01904    char tuple_id[32];
01905 
01906    generate_random_string(tuple_id, sizeof(tuple_id));
01907 
01908    /* We'll make this a bare-bones pidf body. In state_notify_build_xml, the PIDF
01909     * body gets a lot more extra junk that isn't necessary, so we'll leave it out here.
01910     */
01911    ast_str_append(&body, 0, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
01912    /* XXX The entity attribute is currently set to the peer name associated with the
01913     * dialog. This is because we currently only call this function for call-completion
01914     * PUBLISH bodies. In such cases, the entity is completely disregarded. For other
01915     * event packages, it may be crucial to have a proper URI as the presentity so this
01916     * should be revisited as support is expanded.
01917     */
01918    ast_str_append(&body, 0, "<presence xmlns=\"urn:ietf:params:xml:ns:pidf\" entity=\"%s\">\n", presentity);
01919    ast_str_append(&body, 0, "<tuple id=\"%s\">\n", tuple_id);
01920    ast_str_append(&body, 0, "<status><basic>%s</basic></status>\n", state == CC_OPEN ? "open" : "closed");
01921    ast_str_append(&body, 0, "</tuple>\n");
01922    ast_str_append(&body, 0, "</presence>\n");
01923    ast_copy_string(pidf_body, ast_str_buffer(body), size);
01924    return 0;
01925 }
01926 
01927 static int sip_cc_monitor_suspend(struct ast_cc_monitor *monitor)
01928 {
01929    struct sip_monitor_instance *monitor_instance = monitor->private_data;
01930    enum sip_publish_type publish_type;
01931    struct cc_epa_entry *cc_entry;
01932 
01933    if (!monitor_instance) {
01934       return -1;
01935    }
01936 
01937    if (!monitor_instance->suspension_entry) {
01938       /* We haven't yet allocated the suspension entry, so let's give it a shot */
01939       if (!(monitor_instance->suspension_entry = create_epa_entry("call-completion", monitor_instance->peername))) {
01940          ast_log(LOG_WARNING, "Unable to allocate sip EPA entry for call-completion\n");
01941          ao2_ref(monitor_instance, -1);
01942          return -1;
01943       }
01944       if (!(cc_entry = ast_calloc(1, sizeof(*cc_entry)))) {
01945          ast_log(LOG_WARNING, "Unable to allocate space for instance data of EPA entry for call-completion\n");
01946          ao2_ref(monitor_instance, -1);
01947          return -1;
01948       }
01949       cc_entry->core_id = monitor->core_id;
01950       monitor_instance->suspension_entry->instance_data = cc_entry;
01951       publish_type = SIP_PUBLISH_INITIAL;
01952    } else {
01953       publish_type = SIP_PUBLISH_MODIFY;
01954       cc_entry = monitor_instance->suspension_entry->instance_data;
01955    }
01956 
01957    cc_entry->current_state = CC_CLOSED;
01958 
01959    if (ast_strlen_zero(monitor_instance->notify_uri)) {
01960       /* If we have no set notify_uri, then what this means is that we have
01961        * not received a NOTIFY from this destination stating that he is
01962        * currently available.
01963        *
01964        * This situation can arise when the core calls the suspend callbacks
01965        * of multiple destinations. If one of the other destinations aside
01966        * from this one notified Asterisk that he is available, then there
01967        * is no reason to take any suspension action on this device. Rather,
01968        * we should return now and if we receive a NOTIFY while monitoring
01969        * is still "suspended" then we can immediately respond with the
01970        * proper PUBLISH to let this endpoint know what is going on.
01971        */
01972       return 0;
01973    }
01974    construct_pidf_body(CC_CLOSED, monitor_instance->suspension_entry->body, sizeof(monitor_instance->suspension_entry->body), monitor_instance->peername);
01975    return transmit_publish(monitor_instance->suspension_entry, publish_type, monitor_instance->notify_uri);
01976 }
01977 
01978 static int sip_cc_monitor_unsuspend(struct ast_cc_monitor *monitor)
01979 {
01980    struct sip_monitor_instance *monitor_instance = monitor->private_data;
01981    struct cc_epa_entry *cc_entry;
01982 
01983    if (!monitor_instance) {
01984       return -1;
01985    }
01986 
01987    ast_assert(monitor_instance->suspension_entry != NULL);
01988 
01989    cc_entry = monitor_instance->suspension_entry->instance_data;
01990    cc_entry->current_state = CC_OPEN;
01991    if (ast_strlen_zero(monitor_instance->notify_uri)) {
01992       /* This means we are being asked to unsuspend a call leg we never
01993        * sent a PUBLISH on. As such, there is no reason to send another
01994        * PUBLISH at this point either. We can just return instead.
01995        */
01996       return 0;
01997    }
01998    construct_pidf_body(CC_OPEN, monitor_instance->suspension_entry->body, sizeof(monitor_instance->suspension_entry->body), monitor_instance->peername);
01999    return transmit_publish(monitor_instance->suspension_entry, SIP_PUBLISH_MODIFY, monitor_instance->notify_uri);
02000 }
02001 
02002 static int sip_cc_monitor_cancel_available_timer(struct ast_cc_monitor *monitor, int *sched_id)
02003 {
02004    if (*sched_id != -1) {
02005       AST_SCHED_DEL(sched, *sched_id);
02006       ao2_t_ref(monitor, -1, "Removing scheduler's reference to the monitor");
02007    }
02008    return 0;
02009 }
02010 
02011 static void sip_cc_monitor_destructor(void *private_data)
02012 {
02013    struct sip_monitor_instance *monitor_instance = private_data;
02014    ao2_unlink(sip_monitor_instances, monitor_instance);
02015    ast_module_unref(ast_module_info->self);
02016 }
02017 
02018 static int sip_get_cc_information(struct sip_request *req, char *subscribe_uri, size_t size, enum ast_cc_service_type *service)
02019 {
02020    char *call_info = ast_strdupa(get_header(req, "Call-Info"));
02021    char *uri;
02022    char *purpose;
02023    char *service_str;
02024    static const char cc_purpose[] = "purpose=call-completion";
02025    static const int cc_purpose_len = sizeof(cc_purpose) - 1;
02026 
02027    if (ast_strlen_zero(call_info)) {
02028       /* No Call-Info present. Definitely no CC offer */
02029       return -1;
02030    }
02031 
02032    uri = strsep(&call_info, ";");
02033 
02034    while ((purpose = strsep(&call_info, ";"))) {
02035       if (!strncmp(purpose, cc_purpose, cc_purpose_len)) {
02036          break;
02037       }
02038    }
02039    if (!purpose) {
02040       /* We didn't find the appropriate purpose= parameter. Oh well */
02041       return -1;
02042    }
02043 
02044    /* Okay, call-completion has been offered. Let's figure out what type of service this is */
02045    while ((service_str = strsep(&call_info, ";"))) {
02046       if (!strncmp(service_str, "m=", 2)) {
02047          break;
02048       }
02049    }
02050    if (!service_str) {
02051       /* So they didn't offer a particular service, We'll just go with CCBS since it really
02052        * doesn't matter anyway
02053        */
02054       service_str = "BS";
02055    } else {
02056       /* We already determined that there is an "m=" so no need to check
02057        * the result of this strsep
02058        */
02059       strsep(&service_str, "=");
02060    }
02061 
02062    if ((*service = service_string_to_service_type(service_str)) == AST_CC_NONE) {
02063       /* Invalid service offered */
02064       return -1;
02065    }
02066 
02067    ast_copy_string(subscribe_uri, get_in_brackets(uri), size);
02068 
02069    return 0;
02070 }
02071 
02072 /*
02073  * \brief Determine what, if any, CC has been offered and queue a CC frame if possible
02074  *
02075  * After taking care of some formalities to be sure that this call is eligible for CC,
02076  * we first try to see if we can make use of native CC. We grab the information from
02077  * the passed-in sip_request (which is always a response to an INVITE). If we can
02078  * use native CC monitoring for the call, then so be it.
02079  *
02080  * If native cc monitoring is not possible or not supported, then we will instead attempt
02081  * to use generic monitoring. Falling back to generic from a failed attempt at using native
02082  * monitoring will only work if the monitor policy of the endpoint is "always"
02083  *
02084  * \param pvt The current dialog. Contains CC parameters for the endpoint
02085  * \param req The response to the INVITE we want to inspect
02086  * \param service The service to use if generic monitoring is to be used. For native
02087  * monitoring, we get the service from the SIP response itself
02088  */
02089 static void sip_handle_cc(struct sip_pvt *pvt, struct sip_request *req, enum ast_cc_service_type service)
02090 {
02091    enum ast_cc_monitor_policies monitor_policy = ast_get_cc_monitor_policy(pvt->cc_params);
02092    int core_id;
02093    char interface_name[AST_CHANNEL_NAME];
02094 
02095    if (monitor_policy == AST_CC_MONITOR_NEVER) {
02096       /* Don't bother, just return */
02097       return;
02098    }
02099 
02100    if ((core_id = ast_cc_get_current_core_id(pvt->owner)) == -1) {
02101       /* For some reason, CC is invalid, so don't try it! */
02102       return;
02103    }
02104 
02105    ast_channel_get_device_name(pvt->owner, interface_name, sizeof(interface_name));
02106 
02107    if (monitor_policy == AST_CC_MONITOR_ALWAYS || monitor_policy == AST_CC_MONITOR_NATIVE) {
02108       char subscribe_uri[SIPBUFSIZE];
02109       char device_name[AST_CHANNEL_NAME];
02110       enum ast_cc_service_type offered_service;
02111       struct sip_monitor_instance *monitor_instance;
02112       if (sip_get_cc_information(req, subscribe_uri, sizeof(subscribe_uri), &offered_service)) {
02113          /* If CC isn't being offered to us, or for some reason the CC offer is
02114           * not formatted correctly, then it may still be possible to use generic
02115           * call completion since the monitor policy may be "always"
02116           */
02117          goto generic;
02118       }
02119       ast_channel_get_device_name(pvt->owner, device_name, sizeof(device_name));
02120       if (!(monitor_instance = sip_monitor_instance_init(core_id, subscribe_uri, pvt->peername, device_name))) {
02121          /* Same deal. We can try using generic still */
02122          goto generic;
02123       }
02124       /* We bump the refcount of chan_sip because once we queue this frame, the CC core
02125        * will have a reference to callbacks in this module. We decrement the module
02126        * refcount once the monitor destructor is called
02127        */
02128       ast_module_ref(ast_module_info->self);
02129       ast_queue_cc_frame(pvt->owner, "SIP", pvt->dialstring, offered_service, monitor_instance);
02130       ao2_ref(monitor_instance, -1);
02131       return;
02132    }
02133 
02134 generic:
02135    if (monitor_policy == AST_CC_MONITOR_GENERIC || monitor_policy == AST_CC_MONITOR_ALWAYS) {
02136       ast_queue_cc_frame(pvt->owner, AST_CC_GENERIC_MONITOR_TYPE, interface_name, service, NULL);
02137    }
02138 }
02139 
02140 /*! \brief Working TLS connection configuration */
02141 static struct ast_tls_config sip_tls_cfg;
02142 
02143 /*! \brief Default TLS connection configuration */
02144 static struct ast_tls_config default_tls_cfg;
02145 
02146 /*! \brief The TCP server definition */
02147 static struct ast_tcptls_session_args sip_tcp_desc = {
02148    .accept_fd = -1,
02149    .master = AST_PTHREADT_NULL,
02150    .tls_cfg = NULL,
02151    .poll_timeout = -1,
02152    .name = "SIP TCP server",
02153    .accept_fn = ast_tcptls_server_root,
02154    .worker_fn = sip_tcp_worker_fn,
02155 };
02156 
02157 /*! \brief The TCP/TLS server definition */
02158 static struct ast_tcptls_session_args sip_tls_desc = {
02159    .accept_fd = -1,
02160    .master = AST_PTHREADT_NULL,
02161    .tls_cfg = &sip_tls_cfg,
02162    .poll_timeout = -1,
02163    .name = "SIP TLS server",
02164    .accept_fn = ast_tcptls_server_root,
02165    .worker_fn = sip_tcp_worker_fn,
02166 };
02167 
02168 /*! \brief Append to SIP dialog history
02169    \return Always returns 0 */
02170 #define append_history(p, event, fmt , args... )   append_history_full(p, "%-15s " fmt, event, ## args)
02171 
02172 struct sip_pvt *dialog_ref_debug(struct sip_pvt *p, char *tag, char *file, int line, const char *func)
02173 {
02174    if (p)
02175 #ifdef REF_DEBUG
02176       __ao2_ref_debug(p, 1, tag, file, line, func);
02177 #else
02178       ao2_ref(p, 1);
02179 #endif
02180    else
02181       ast_log(LOG_ERROR, "Attempt to Ref a null pointer\n");
02182    return p;
02183 }
02184 
02185 struct sip_pvt *dialog_unref_debug(struct sip_pvt *p, char *tag, char *file, int line, const char *func)
02186 {
02187    if (p)
02188 #ifdef REF_DEBUG
02189       __ao2_ref_debug(p, -1, tag, file, line, func);
02190 #else
02191       ao2_ref(p, -1);
02192 #endif
02193    return NULL;
02194 }
02195 
02196 /*! \brief map from an integer value to a string.
02197  * If no match is found, return errorstring
02198  */
02199 static const char *map_x_s(const struct _map_x_s *table, int x, const char *errorstring)
02200 {
02201    const struct _map_x_s *cur;
02202 
02203    for (cur = table; cur->s; cur++)
02204       if (cur->x == x)
02205          return cur->s;
02206    return errorstring;
02207 }
02208 
02209 /*! \brief map from a string to an integer value, case insensitive.
02210  * If no match is found, return errorvalue.
02211  */
02212 static int map_s_x(const struct _map_x_s *table, const char *s, int errorvalue)
02213 {
02214    const struct _map_x_s *cur;
02215 
02216    for (cur = table; cur->s; cur++)
02217       if (!strcasecmp(cur->s, s))
02218          return cur->x;
02219    return errorvalue;
02220 }
02221 
02222 static enum AST_REDIRECTING_REASON sip_reason_str_to_code(const char *text)
02223 {
02224    enum AST_REDIRECTING_REASON ast = AST_REDIRECTING_REASON_UNKNOWN;
02225    int i;
02226 
02227    for (i = 0; i < ARRAY_LEN(sip_reason_table); ++i) {
02228       if (!strcasecmp(text, sip_reason_table[i].text)) {
02229          ast = sip_reason_table[i].code;
02230          break;
02231       }
02232    }
02233 
02234    return ast;
02235 }
02236 
02237 static const char *sip_reason_code_to_str(enum AST_REDIRECTING_REASON code)
02238 {
02239    if (code >= 0 && code < ARRAY_LEN(sip_reason_table)) {
02240       return sip_reason_table[code].text;
02241    }
02242 
02243    return "unknown";
02244 }
02245 
02246 /*!
02247  * \brief generic function for determining if a correct transport is being
02248  * used to contact a peer
02249  *
02250  * this is done as a macro so that the "tmpl" var can be passed either a
02251  * sip_request or a sip_peer
02252  */
02253 #define check_request_transport(peer, tmpl) ({ \
02254    int ret = 0; \
02255    if (peer->socket.type == tmpl->socket.type) \
02256       ; \
02257    else if (!(peer->transports & tmpl->socket.type)) {\
02258       ast_log(LOG_ERROR, \
02259          "'%s' is not a valid transport for '%s'. we only use '%s'! ending call.\n", \
02260          get_transport(tmpl->socket.type), peer->name, get_transport_list(peer->transports) \
02261          ); \
02262       ret = 1; \
02263    } else if (peer->socket.type & SIP_TRANSPORT_TLS) { \
02264       ast_log(LOG_WARNING, \
02265          "peer '%s' HAS NOT USED (OR SWITCHED TO) TLS in favor of '%s' (but this was allowed in sip.conf)!\n", \
02266          peer->name, get_transport(tmpl->socket.type) \
02267       ); \
02268    } else { \
02269       ast_debug(1, \
02270          "peer '%s' has contacted us over %s even though we prefer %s.\n", \
02271          peer->name, get_transport(tmpl->socket.type), get_transport(peer->socket.type) \
02272       ); \
02273    }\
02274    (ret); \
02275 })
02276 
02277 /*! \brief
02278  * duplicate a list of channel variables, \return the copy.
02279  */
02280 static struct ast_variable *copy_vars(struct ast_variable *src)
02281 {
02282    struct ast_variable *res = NULL, *tmp, *v = NULL;
02283 
02284    for (v = src ; v ; v = v->next) {
02285       if ((tmp = ast_variable_new(v->name, v->value, v->file))) {
02286          tmp->next = res;
02287          res = tmp;
02288       }
02289    }
02290    return res;
02291 }
02292 
02293 static void tcptls_packet_destructor(void *obj)
02294 {
02295    struct tcptls_packet *packet = obj;
02296 
02297    ast_free(packet->data);
02298 }
02299 
02300 static void sip_tcptls_client_args_destructor(void *obj)
02301 {
02302    struct ast_tcptls_session_args *args = obj;
02303    if (args->tls_cfg) {
02304       ast_free(args->tls_cfg->certfile);
02305       ast_free(args->tls_cfg->pvtfile);
02306       ast_free(args->tls_cfg->cipher);
02307       ast_free(args->tls_cfg->cafile);
02308       ast_free(args->tls_cfg->capath);
02309    }
02310    ast_free(args->tls_cfg);
02311    ast_free((char *) args->name);
02312 }
02313 
02314 static void sip_threadinfo_destructor(void *obj)
02315 {
02316    struct sip_threadinfo *th = obj;
02317    struct tcptls_packet *packet;
02318    if (th->alert_pipe[1] > -1) {
02319       close(th->alert_pipe[0]);
02320    }
02321    if (th->alert_pipe[1] > -1) {
02322       close(th->alert_pipe[1]);
02323    }
02324    th->alert_pipe[0] = th->alert_pipe[1] = -1;
02325 
02326    while ((packet = AST_LIST_REMOVE_HEAD(&th->packet_q, entry))) {
02327       ao2_t_ref(packet, -1, "thread destruction, removing packet from frame queue");
02328    }
02329 
02330    if (th->tcptls_session) {
02331       ao2_t_ref(th->tcptls_session, -1, "remove tcptls_session for sip_threadinfo object");
02332    }
02333 }
02334 
02335 /*! \brief creates a sip_threadinfo object and links it into the threadt table. */
02336 static struct sip_threadinfo *sip_threadinfo_create(struct ast_tcptls_session_instance *tcptls_session, int transport)
02337 {
02338    struct sip_threadinfo *th;
02339 
02340    if (!tcptls_session || !(th = ao2_alloc(sizeof(*th), sip_threadinfo_destructor))) {
02341       return NULL;
02342    }
02343 
02344    th->alert_pipe[0] = th->alert_pipe[1] = -1;
02345 
02346    if (pipe(th->alert_pipe) == -1) {
02347       ao2_t_ref(th, -1, "Failed to open alert pipe on sip_threadinfo");
02348       ast_log(LOG_ERROR, "Could not create sip alert pipe in tcptls thread, error %s\n", strerror(errno));
02349       return NULL;
02350    }
02351    ao2_t_ref(tcptls_session, +1, "tcptls_session ref for sip_threadinfo object");
02352    th->tcptls_session = tcptls_session;
02353    th->type = transport ? transport : (tcptls_session->ssl ? SIP_TRANSPORT_TLS: SIP_TRANSPORT_TCP);
02354    ao2_t_link(threadt, th, "Adding new tcptls helper thread");
02355    ao2_t_ref(th, -1, "Decrementing threadinfo ref from alloc, only table ref remains");
02356    return th;
02357 }
02358 
02359 /*! \brief used to indicate to a tcptls thread that data is ready to be written */
02360 static int sip_tcptls_write(struct ast_tcptls_session_instance *tcptls_session, const void *buf, size_t len)
02361 {
02362    int res = len;
02363    struct sip_threadinfo *th = NULL;
02364    struct tcptls_packet *packet = NULL;
02365    struct sip_threadinfo tmp = {
02366       .tcptls_session = tcptls_session,
02367    };
02368    enum sip_tcptls_alert alert = TCPTLS_ALERT_DATA;
02369 
02370    if (!tcptls_session) {
02371       return XMIT_ERROR;
02372    }
02373 
02374    ast_mutex_lock(&tcptls_session->lock);
02375 
02376    if ((tcptls_session->fd == -1) ||
02377       !(th = ao2_t_find(threadt, &tmp, OBJ_POINTER, "ao2_find, getting sip_threadinfo in tcp helper thread")) ||
02378       !(packet = ao2_alloc(sizeof(*packet), tcptls_packet_destructor)) ||
02379       !(packet->data = ast_str_create(len))) {
02380       goto tcptls_write_setup_error;
02381    }
02382 
02383    /* goto tcptls_write_error should _NOT_ be used beyond this point */
02384    ast_str_set(&packet->data, 0, "%s", (char *) buf);
02385    packet->len = len;
02386 
02387    /* alert tcptls thread handler that there is a packet to be sent.
02388     * must lock the thread info object to guarantee control of the
02389     * packet queue */
02390    ao2_lock(th);
02391    if (write(th->alert_pipe[1], &alert, sizeof(alert)) == -1) {
02392       ast_log(LOG_ERROR, "write() to alert pipe failed: %s\n", strerror(errno));
02393       ao2_t_ref(packet, -1, "could not write to alert pipe, remove packet");
02394       packet = NULL;
02395       res = XMIT_ERROR;
02396    } else { /* it is safe to queue the frame after issuing the alert when we hold the threadinfo lock */
02397       AST_LIST_INSERT_TAIL(&th->packet_q, packet, entry);
02398    }
02399    ao2_unlock(th);
02400 
02401    ast_mutex_unlock(&tcptls_session->lock);
02402    ao2_t_ref(th, -1, "In sip_tcptls_write, unref threadinfo object after finding it");
02403    return res;
02404 
02405 tcptls_write_setup_error:
02406    if (th) {
02407       ao2_t_ref(th, -1, "In sip_tcptls_write, unref threadinfo obj, could not create packet");
02408    }
02409    if (packet) {
02410       ao2_t_ref(packet, -1, "could not allocate packet's data");
02411    }
02412    ast_mutex_unlock(&tcptls_session->lock);
02413 
02414    return XMIT_ERROR;
02415 }
02416 
02417 /*! \brief SIP TCP connection handler */
02418 static void *sip_tcp_worker_fn(void *data)
02419 {
02420    struct ast_tcptls_session_instance *tcptls_session = data;
02421 
02422    return _sip_tcp_helper_thread(NULL, tcptls_session);
02423 }
02424 
02425 /*! \brief SIP TCP thread management function
02426    This function reads from the socket, parses the packet into a request
02427 */
02428 static void *_sip_tcp_helper_thread(struct sip_pvt *pvt, struct ast_tcptls_session_instance *tcptls_session)
02429 {
02430    int res, cl;
02431    struct sip_request req = { 0, } , reqcpy = { 0, };
02432    struct sip_threadinfo *me = NULL;
02433    char buf[1024] = "";
02434    struct pollfd fds[2] = { { 0 }, { 0 }, };
02435    struct ast_tcptls_session_args *ca = NULL;
02436 
02437    /* If this is a server session, then the connection has already been setup,
02438     * simply create the threadinfo object so we can access this thread for writing.
02439     * 
02440     * if this is a client connection more work must be done.
02441     * 1. We own the parent session args for a client connection.  This pointer needs
02442     *    to be held on to so we can decrement it's ref count on thread destruction.
02443     * 2. The threadinfo object was created before this thread was launched, however
02444     *    it must be found within the threadt table.
02445     * 3. Last, the tcptls_session must be started.
02446     */
02447    if (!tcptls_session->client) {
02448       if (!(me = sip_threadinfo_create(tcptls_session, tcptls_session->ssl ? SIP_TRANSPORT_TLS : SIP_TRANSPORT_TCP))) {
02449          goto cleanup;
02450       }
02451       ao2_t_ref(me, +1, "Adding threadinfo ref for tcp_helper_thread");
02452    } else {
02453       struct sip_threadinfo tmp = {
02454          .tcptls_session = tcptls_session,
02455       };
02456 
02457       if ((!(ca = tcptls_session->parent)) ||
02458          (!(me = ao2_t_find(threadt, &tmp, OBJ_POINTER, "ao2_find, getting sip_threadinfo in tcp helper thread"))) ||
02459          (!(tcptls_session = ast_tcptls_client_start(tcptls_session)))) {
02460          goto cleanup;
02461       }
02462    }
02463 
02464    me->threadid = pthread_self();
02465    ast_debug(2, "Starting thread for %s server\n", tcptls_session->ssl ? "SSL" : "TCP");
02466 
02467    /* set up pollfd to watch for reads on both the socket and the alert_pipe */
02468    fds[0].fd = tcptls_session->fd;
02469    fds[1].fd = me->alert_pipe[0];
02470    fds[0].events = fds[1].events = POLLIN | POLLPRI;
02471 
02472    if (!(req.data = ast_str_create(SIP_MIN_PACKET))) {
02473       goto cleanup;
02474    }
02475    if (!(reqcpy.data = ast_str_create(SIP_MIN_PACKET))) {
02476       goto cleanup;
02477    }
02478 
02479    for (;;) {
02480       struct ast_str *str_save;
02481 
02482       res = ast_poll(fds, 2, -1); /* polls for both socket and alert_pipe */
02483       if (res < 0) {
02484          ast_debug(2, "SIP %s server :: ast_wait_for_input returned %d\n", tcptls_session->ssl ? "SSL": "TCP", res);
02485          goto cleanup;
02486       }
02487 
02488       /* handle the socket event, check for both reads from the socket fd,
02489        * and writes from alert_pipe fd */
02490       if (fds[0].revents) { /* there is data on the socket to be read */
02491 
02492          fds[0].revents = 0;
02493 
02494          /* clear request structure */
02495          str_save = req.data;
02496          memset(&req, 0, sizeof(req));
02497          req.data = str_save;
02498          ast_str_reset(req.data);
02499 
02500          str_save = reqcpy.data;
02501          memset(&reqcpy, 0, sizeof(reqcpy));
02502          reqcpy.data = str_save;
02503          ast_str_reset(reqcpy.data);
02504 
02505          memset(buf, 0, sizeof(buf));
02506 
02507          if (tcptls_session->ssl) {
02508             set_socket_transport(&req.socket, SIP_TRANSPORT_TLS);
02509             req.socket.port = htons(ourport_tls);
02510          } else {
02511             set_socket_transport(&req.socket, SIP_TRANSPORT_TCP);
02512             req.socket.port = htons(ourport_tcp);
02513          }
02514          req.socket.fd = tcptls_session->fd;
02515 
02516          /* Read in headers one line at a time */
02517          while (req.len < 4 || strncmp(REQ_OFFSET_TO_STR(&req, len - 4), "\r\n\r\n", 4)) {
02518             ast_mutex_lock(&tcptls_session->lock);
02519             if (!fgets(buf, sizeof(buf), tcptls_session->f)) {
02520                ast_mutex_unlock(&tcptls_session->lock);
02521                goto cleanup;
02522             }
02523             ast_mutex_unlock(&tcptls_session->lock);
02524             if (me->stop) {
02525                 goto cleanup;
02526             }
02527             ast_str_append(&req.data, 0, "%s", buf);
02528             req.len = req.data->used;
02529          }
02530          copy_request(&reqcpy, &req);
02531          parse_request(&reqcpy);
02532          /* In order to know how much to read, we need the content-length header */
02533          if (sscanf(get_header(&reqcpy, "Content-Length"), "%30d", &cl)) {
02534             while (cl > 0) {
02535                size_t bytes_read;
02536                ast_mutex_lock(&tcptls_session->lock);
02537                if (!(bytes_read = fread(buf, 1, MIN(sizeof(buf) - 1, cl), tcptls_session->f))) {
02538                   ast_mutex_unlock(&tcptls_session->lock);
02539                   goto cleanup;
02540                }
02541                buf[bytes_read] = '\0';
02542                ast_mutex_unlock(&tcptls_session->lock);
02543                if (me->stop) {
02544                   goto cleanup;
02545                }
02546                cl -= strlen(buf);
02547                ast_str_append(&req.data, 0, "%s", buf);
02548                req.len = req.data->used;
02549             }
02550          }
02551          /*! \todo XXX If there's no Content-Length or if the content-length and what
02552                we receive is not the same - we should generate an error */
02553 
02554          req.socket.tcptls_session = tcptls_session;
02555          handle_request_do(&req, &tcptls_session->remote_address);
02556       }
02557 
02558       if (fds[1].revents) { /* alert_pipe indicates there is data in the send queue to be sent */
02559          enum sip_tcptls_alert alert;
02560          struct tcptls_packet *packet;
02561 
02562          fds[1].revents = 0;
02563 
02564          if (read(me->alert_pipe[0], &alert, sizeof(alert)) == -1) {
02565             ast_log(LOG_ERROR, "read() failed: %s\n", strerror(errno));
02566             continue;
02567          }
02568 
02569          switch (alert) {
02570          case TCPTLS_ALERT_STOP:
02571             goto cleanup;
02572          case TCPTLS_ALERT_DATA:
02573             ao2_lock(me);
02574             if (!(packet = AST_LIST_REMOVE_HEAD(&me->packet_q, entry))) {
02575                ast_log(LOG_WARNING, "TCPTLS thread alert_pipe indicated packet should be sent, but frame_q is empty");
02576             } else if (ast_tcptls_server_write(tcptls_session, ast_str_buffer(packet->data), packet->len) == -1) {
02577                ast_log(LOG_WARNING, "Failure to write to tcp/tls socket\n");
02578             }
02579 
02580             if (packet) {
02581                ao2_t_ref(packet, -1, "tcptls packet sent, this is no longer needed");
02582             }
02583             ao2_unlock(me);
02584             break;
02585          default:
02586             ast_log(LOG_ERROR, "Unknown tcptls thread alert '%d'\n", alert);
02587          }
02588       }
02589    }
02590 
02591    ast_debug(2, "Shutting down thread for %s server\n", tcptls_session->ssl ? "SSL" : "TCP");
02592 
02593 cleanup:
02594    if (me) {
02595       ao2_t_unlink(threadt, me, "Removing tcptls helper thread, thread is closing");
02596       ao2_t_ref(me, -1, "Removing tcp_helper_threads threadinfo ref");
02597    }
02598    deinit_req(&reqcpy);
02599    deinit_req(&req);
02600 
02601    /* if client, we own the parent session arguments and must decrement ref */
02602    if (ca) {
02603       ao2_t_ref(ca, -1, "closing tcptls thread, getting rid of client tcptls_session arguments");
02604    }
02605 
02606    if (tcptls_session) {
02607       ast_mutex_lock(&tcptls_session->lock);
02608       if (tcptls_session->f) {
02609          fclose(tcptls_session->f);
02610          tcptls_session->f = NULL;
02611       }
02612       if (tcptls_session->fd != -1) {
02613          close(tcptls_session->fd);
02614          tcptls_session->fd = -1;
02615       }
02616       tcptls_session->parent = NULL;
02617       ast_mutex_unlock(&tcptls_session->lock);
02618 
02619       ao2_ref(tcptls_session, -1);
02620       tcptls_session = NULL;
02621    }
02622    return NULL;
02623 }
02624 
02625 /* this func is used with ao2_callback to unlink/delete all marked
02626    peers */
02627 static int peer_is_marked(void *peerobj, void *arg, int flags)
02628 {
02629    struct sip_peer *peer = peerobj;
02630    return peer->the_mark ? CMP_MATCH : 0;
02631 }
02632 
02633 
02634 /* \brief Unlink all marked peers from ao2 containers */
02635 static void unlink_marked_peers_from_tables(void)
02636 {
02637    ao2_t_callback(peers, OBJ_NODATA | OBJ_UNLINK | OBJ_MULTIPLE, peer_is_marked, NULL,
02638                   "initiating callback to remove marked peers");
02639    ao2_t_callback(peers_by_ip, OBJ_NODATA | OBJ_UNLINK | OBJ_MULTIPLE, peer_is_marked, NULL,
02640                   "initiating callback to remove marked peers");
02641 }
02642 
02643 /* \brief Unlink single peer from all ao2 containers */
02644 static void unlink_peer_from_tables(struct sip_peer *peer)
02645 {
02646    ao2_t_unlink(peers, peer, "ao2_unlink of peer from peers table");
02647    if (!ast_sockaddr_isnull(&peer->addr)) {
02648       ao2_t_unlink(peers_by_ip, peer, "ao2_unlink of peer from peers_by_ip table");
02649    }
02650 }
02651 
02652 /*!
02653  * helper functions to unreference various types of objects.
02654  * By handling them this way, we don't have to declare the
02655  * destructor on each call, which removes the chance of errors.
02656  */
02657 static void *unref_peer(struct sip_peer *peer, char *tag)
02658 {
02659    ao2_t_ref(peer, -1, tag);
02660    return NULL;
02661 }
02662 
02663 static struct sip_peer *ref_peer(struct sip_peer *peer, char *tag)
02664 {
02665    ao2_t_ref(peer, 1, tag);
02666    return peer;
02667 }
02668 
02669 /*! \brief maintain proper refcounts for a sip_pvt's outboundproxy
02670  *
02671  * This function sets pvt's outboundproxy pointer to the one referenced
02672  * by the proxy parameter. Because proxy may be a refcounted object, and
02673  * because pvt's old outboundproxy may also be a refcounted object, we need
02674  * to maintain the proper refcounts.
02675  *
02676  * \param pvt The sip_pvt for which we wish to set the outboundproxy
02677  * \param proxy The sip_proxy which we will point pvt towards.
02678  * \return Returns void
02679  */
02680 static void ref_proxy(struct sip_pvt *pvt, struct sip_proxy *proxy)
02681 {
02682    struct sip_proxy *old_obproxy = pvt->outboundproxy;
02683    /* The sip_cfg.outboundproxy is statically allocated, and so
02684     * we don't ever need to adjust refcounts for it
02685     */
02686    if (proxy && proxy != &sip_cfg.outboundproxy) {
02687       ao2_ref(proxy, +1);
02688    }
02689    pvt->outboundproxy = proxy;
02690    if (old_obproxy && old_obproxy != &sip_cfg.outboundproxy) {
02691       ao2_ref(old_obproxy, -1);
02692    }
02693 }
02694 
02695 /*!
02696  * \brief Unlink a dialog from the dialogs container, as well as any other places
02697  * that it may be currently stored.
02698  *
02699  * \note A reference to the dialog must be held before calling this function, and this
02700  * function does not release that reference.
02701  */
02702 void *dialog_unlink_all(struct sip_pvt *dialog, int lockowner, int lockdialoglist)
02703 {
02704    struct sip_pkt *cp;
02705 
02706    dialog_ref(dialog, "Let's bump the count in the unlink so it doesn't accidentally become dead before we are done");
02707 
02708    ao2_t_unlink(dialogs, dialog, "unlinking dialog via ao2_unlink");
02709 
02710    /* Unlink us from the owner (channel) if we have one */
02711    if (dialog->owner) {
02712       if (lockowner)
02713          ast_channel_lock(dialog->owner);
02714       ast_debug(1, "Detaching from channel %s\n", dialog->owner->name);
02715       dialog->owner->tech_pvt = dialog_unref(dialog->owner->tech_pvt, "resetting channel dialog ptr in unlink_all");
02716       if (lockowner) {
02717          ast_channel_unlock(dialog->owner);
02718       }
02719    }
02720    if (dialog->registry) {
02721       if (dialog->registry->call == dialog) {
02722          dialog->registry->call = dialog_unref(dialog->registry->call, "nulling out the registry's call dialog field in unlink_all");
02723       }
02724       dialog->registry = registry_unref(dialog->registry, "delete dialog->registry");
02725    }
02726    if (dialog->stateid > -1) {
02727       ast_extension_state_del(dialog->stateid, NULL);
02728       dialog_unref(dialog, "removing extension_state, should unref the associated dialog ptr that was stored there.");
02729       dialog->stateid = -1; /* shouldn't we 'zero' this out? */
02730    }
02731    /* Remove link from peer to subscription of MWI */
02732    if (dialog->relatedpeer && dialog->relatedpeer->mwipvt == dialog) {
02733       dialog->relatedpeer->mwipvt = dialog_unref(dialog->relatedpeer->mwipvt, "delete ->relatedpeer->mwipvt");
02734    }
02735    if (dialog->relatedpeer && dialog->relatedpeer->call == dialog) {
02736       dialog->relatedpeer->call = dialog_unref(dialog->relatedpeer->call, "unset the relatedpeer->call field in tandem with relatedpeer field itself");
02737    }
02738 
02739    /* remove all current packets in this dialog */
02740    while((cp = dialog->packets)) {
02741       dialog->packets = dialog->packets->next;
02742       AST_SCHED_DEL(sched, cp->retransid);
02743       dialog_unref(cp->owner, "remove all current packets in this dialog, and the pointer to the dialog too as part of __sip_destroy");
02744       if (cp->data) {
02745          ast_free(cp->data);
02746       }
02747       ast_free(cp);
02748    }
02749 
02750    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"));
02751 
02752    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"));
02753    
02754    if (dialog->autokillid > -1) {
02755       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"));
02756    }
02757 
02758    if (dialog->request_queue_sched_id > -1) {
02759       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"));
02760    }
02761 
02762    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"));
02763 
02764    if (dialog->t38id > -1) {
02765       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"));
02766    }
02767 
02768    dialog_unref(dialog, "Let's unbump the count in the unlink so the poor pvt can disappear if it is time");
02769    return NULL;
02770 }
02771 
02772 void *registry_unref(struct sip_registry *reg, char *tag)
02773 {
02774    ast_debug(3, "SIP Registry %s: refcount now %d\n", reg->hostname, reg->refcount - 1);
02775    ASTOBJ_UNREF(reg, sip_registry_destroy);
02776    return NULL;
02777 }
02778 
02779 /*! \brief Add object reference to SIP registry */
02780 static struct sip_registry *registry_addref(struct sip_registry *reg, char *tag)
02781 {
02782    ast_debug(3, "SIP Registry %s: refcount now %d\n", reg->hostname, reg->refcount + 1);
02783    return ASTOBJ_REF(reg); /* Add pointer to registry in packet */
02784 }
02785 
02786 /*! \brief Interface structure with callbacks used to connect to UDPTL module*/
02787 static struct ast_udptl_protocol sip_udptl = {
02788    type: "SIP",
02789    get_udptl_info: sip_get_udptl_peer,
02790    set_udptl_peer: sip_set_udptl_peer,
02791 };
02792 
02793 static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
02794    __attribute__((format(printf, 2, 3)));
02795 
02796 
02797 /*! \brief Convert transfer status to string */
02798 static const char *referstatus2str(enum referstatus rstatus)
02799 {
02800    return map_x_s(referstatusstrings, rstatus, "");
02801 }
02802 
02803 static inline void pvt_set_needdestroy(struct sip_pvt *pvt, const char *reason)
02804 {
02805    if (pvt->final_destruction_scheduled) {
02806       return; /* This is already scheduled for final destruction, let the scheduler take care of it. */
02807    }
02808    append_history(pvt, "NeedDestroy", "Setting needdestroy because %s", reason);
02809    pvt->needdestroy = 1;
02810 }
02811 
02812 /*! \brief Initialize the initital request packet in the pvt structure.
02813    This packet is used for creating replies and future requests in
02814    a dialog */
02815 static void initialize_initreq(struct sip_pvt *p, struct sip_request *req)
02816 {
02817    if (p->initreq.headers) {
02818       ast_debug(1, "Initializing already initialized SIP dialog %s (presumably reinvite)\n", p->callid);
02819    } else {
02820       ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
02821    }
02822    /* Use this as the basis */
02823    copy_request(&p->initreq, req);
02824    parse_request(&p->initreq);
02825    if (req->debug) {
02826       ast_verbose("Initreq: %d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
02827    }
02828 }
02829 
02830 /*! \brief Encapsulate setting of SIP_ALREADYGONE to be able to trace it with debugging */
02831 static void sip_alreadygone(struct sip_pvt *dialog)
02832 {
02833    ast_debug(3, "Setting SIP_ALREADYGONE on dialog %s\n", dialog->callid);
02834    dialog->alreadygone = 1;
02835 }
02836 
02837 /*! Resolve DNS srv name or host name in a sip_proxy structure */
02838 static int proxy_update(struct sip_proxy *proxy)
02839 {
02840    /* if it's actually an IP address and not a name,
02841            there's no need for a managed lookup */
02842    if (!ast_sockaddr_parse(&proxy->ip, proxy->name, 0)) {
02843       /* Ok, not an IP address, then let's check if it's a domain or host */
02844       /* XXX Todo - if we have proxy port, don't do SRV */
02845       proxy->ip.ss.ss_family = get_address_family_filter(&bindaddr); /* Filter address family */
02846       if (ast_get_ip_or_srv(&proxy->ip, proxy->name, sip_cfg.srvlookup ? "_sip._udp" : NULL) < 0) {
02847             ast_log(LOG_WARNING, "Unable to locate host '%s'\n", proxy->name);
02848             return FALSE;
02849       }
02850 
02851    }
02852 
02853    ast_sockaddr_set_port(&proxy->ip, proxy->port);
02854 
02855    proxy->last_dnsupdate = time(NULL);
02856    return TRUE;
02857 }
02858 
02859 /*! \brief converts ascii port to int representation. If no
02860  *  pt buffer is provided or the pt has errors when being converted
02861  *  to an int value, the port provided as the standard is used.
02862  */
02863 unsigned int port_str2int(const char *pt, unsigned int standard)
02864 {
02865    int port = standard;
02866    if (ast_strlen_zero(pt) || (sscanf(pt, "%30d", &port) != 1) || (port < 1) || (port > 65535)) {
02867       port = standard;
02868    }
02869 
02870    return port;
02871 }
02872 
02873 /*! \brief Get default outbound proxy or global proxy */
02874 static struct sip_proxy *obproxy_get(struct sip_pvt *dialog, struct sip_peer *peer)
02875 {
02876    if (peer && peer->outboundproxy) {
02877       if (sipdebug) {
02878          ast_debug(1, "OBPROXY: Applying peer OBproxy to this call\n");
02879       }
02880       append_history(dialog, "OBproxy", "Using peer obproxy %s", peer->outboundproxy->name);
02881       return peer->outboundproxy;
02882    }
02883    if (sip_cfg.outboundproxy.name[0]) {
02884       if (sipdebug) {
02885          ast_debug(1, "OBPROXY: Applying global OBproxy to this call\n");
02886       }
02887       append_history(dialog, "OBproxy", "Using global obproxy %s", sip_cfg.outboundproxy.name);
02888       return &sip_cfg.outboundproxy;
02889    }
02890    if (sipdebug) {
02891       ast_debug(1, "OBPROXY: Not applying OBproxy to this call\n");
02892    }
02893    return NULL;
02894 }
02895 
02896 /*! \brief returns true if 'name' (with optional trailing whitespace)
02897  * matches the sip method 'id'.
02898  * Strictly speaking, SIP methods are case SENSITIVE, but we do
02899  * a case-insensitive comparison to be more tolerant.
02900  * following Jon Postel's rule: Be gentle in what you accept, strict with what you send
02901  */
02902 static int method_match(enum sipmethod id, const char *name)
02903 {
02904    int len = strlen(sip_methods[id].text);
02905    int l_name = name ? strlen(name) : 0;
02906    /* true if the string is long enough, and ends with whitespace, and matches */
02907    return (l_name >= len && name[len] < 33 &&
02908       !strncasecmp(sip_methods[id].text, name, len));
02909 }
02910 
02911 /*! \brief  find_sip_method: Find SIP method from header */
02912 static int find_sip_method(const char *msg)
02913 {
02914    int i, res = 0;
02915    
02916    if (ast_strlen_zero(msg)) {
02917       return 0;
02918    }
02919    for (i = 1; i < ARRAY_LEN(sip_methods) && !res; i++) {
02920       if (method_match(i, msg)) {
02921          res = sip_methods[i].id;
02922       }
02923    }
02924    return res;
02925 }
02926 
02927 /*! \brief See if we pass debug IP filter */
02928 static inline int sip_debug_test_addr(const struct ast_sockaddr *addr)
02929 {
02930    /* Can't debug if sipdebug is not enabled */
02931    if (!sipdebug) {
02932       return 0;
02933    }
02934 
02935    /* A null debug_addr means we'll debug any address */
02936    if (ast_sockaddr_isnull(&debugaddr)) {
02937       return 1;
02938    }
02939 
02940    /* If no port was specified for a debug address, just compare the
02941     * addresses, otherwise compare the address and port
02942     */
02943    if (ast_sockaddr_port(&debugaddr)) {
02944       return !ast_sockaddr_cmp(&debugaddr, addr);
02945    } else {
02946       return !ast_sockaddr_cmp_addr(&debugaddr, addr);
02947    }
02948 }
02949 
02950 /*! \brief The real destination address for a write */
02951 static const struct ast_sockaddr *sip_real_dst(const struct sip_pvt *p)
02952 {
02953    if (p->outboundproxy) {
02954       return &p->outboundproxy->ip;
02955    }
02956 
02957    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;
02958 }
02959 
02960 /*! \brief Display SIP nat mode */
02961 static const char *sip_nat_mode(const struct sip_pvt *p)
02962 {
02963    return ast_test_flag(&p->flags[0], SIP_NAT_FORCE_RPORT) ? "NAT" : "no NAT";
02964 }
02965 
02966 /*! \brief Test PVT for debugging output */
02967 static inline int sip_debug_test_pvt(struct sip_pvt *p)
02968 {
02969    if (!sipdebug) {
02970       return 0;
02971    }
02972    return sip_debug_test_addr(sip_real_dst(p));
02973 }
02974 
02975 /*! \brief Return int representing a bit field of transport types found in const char *transport */
02976 static int get_transport_str2enum(const char *transport)
02977 {
02978    int res = 0;
02979 
02980    if (ast_strlen_zero(transport)) {
02981       return res;
02982    }
02983 
02984    if (!strcasecmp(transport, "udp")) {
02985       res |= SIP_TRANSPORT_UDP;
02986    }
02987    if (!strcasecmp(transport, "tcp")) {
02988       res |= SIP_TRANSPORT_TCP;
02989    }
02990    if (!strcasecmp(transport, "tls")) {
02991       res |= SIP_TRANSPORT_TLS;
02992    }
02993 
02994    return res;
02995 }
02996 
02997 /*! \brief Return configuration of transports for a device */
02998 static inline const char *get_transport_list(unsigned int transports) {
02999    switch (transports) {
03000       case SIP_TRANSPORT_UDP:
03001          return "UDP";
03002       case SIP_TRANSPORT_TCP:
03003          return "TCP";
03004       case SIP_TRANSPORT_TLS:
03005          return "TLS";
03006       case SIP_TRANSPORT_UDP | SIP_TRANSPORT_TCP:
03007          return "TCP,UDP";
03008       case SIP_TRANSPORT_UDP | SIP_TRANSPORT_TLS:
03009          return "TLS,UDP";
03010       case SIP_TRANSPORT_TCP | SIP_TRANSPORT_TLS:
03011          return "TLS,TCP";
03012       default:
03013          return transports ?
03014             "TLS,TCP,UDP" : "UNKNOWN"; 
03015    }
03016 }
03017 
03018 /*! \brief Return transport as string */
03019 static inline const char *get_transport(enum sip_transport t)
03020 {
03021    switch (t) {
03022    case SIP_TRANSPORT_UDP:
03023       return "UDP";
03024    case SIP_TRANSPORT_TCP:
03025       return "TCP";
03026    case SIP_TRANSPORT_TLS:
03027       return "TLS";
03028    }
03029 
03030    return "UNKNOWN";
03031 }
03032 
03033 /*! \brief Return protocol string for srv dns query */
03034 static inline const char *get_srv_protocol(enum sip_transport t)
03035 {
03036    switch (t) {
03037    case SIP_TRANSPORT_UDP:
03038       return "udp";
03039    case SIP_TRANSPORT_TLS:
03040    case SIP_TRANSPORT_TCP:
03041       return "tcp";
03042    }
03043 
03044    return "udp";
03045 }
03046 
03047 /*! \brief Return service string for srv dns query */
03048 static inline const char *get_srv_service(enum sip_transport t)
03049 {
03050    switch (t) {
03051    case SIP_TRANSPORT_TCP:
03052    case SIP_TRANSPORT_UDP:
03053       return "sip";
03054    case SIP_TRANSPORT_TLS:
03055       return "sips";
03056    }
03057    return "sip";
03058 }
03059 
03060 /*! \brief Return transport of dialog.
03061    \note this is based on a false assumption. We don't always use the
03062    outbound proxy for all requests in a dialog. It depends on the
03063    "force" parameter. The FIRST request is always sent to the ob proxy.
03064    \todo Fix this function to work correctly
03065 */
03066 static inline const char *get_transport_pvt(struct sip_pvt *p)
03067 {
03068    if (p->outboundproxy && p->outboundproxy->transport) {
03069       set_socket_transport(&p->socket, p->outboundproxy->transport);
03070    }
03071 
03072    return get_transport(p->socket.type);
03073 }
03074 
03075 /*! \brief Transmit SIP message
03076    Sends a SIP request or response on a given socket (in the pvt)
03077    Called by retrans_pkt, send_request, send_response and
03078    __sip_reliable_xmit
03079    \return length of transmitted message, XMIT_ERROR on known network failures -1 on other failures.
03080 */
03081 static int __sip_xmit(struct sip_pvt *p, struct ast_str *data, int len)
03082 {
03083    int res = 0;
03084    const struct ast_sockaddr *dst = sip_real_dst(p);
03085 
03086    ast_debug(2, "Trying to put '%.11s' onto %s socket destined for %s\n", data->str, get_transport_pvt(p), ast_sockaddr_stringify(dst));
03087 
03088    if (sip_prepare_socket(p) < 0) {
03089       return XMIT_ERROR;
03090    }
03091 
03092    if (p->socket.type == SIP_TRANSPORT_UDP) {
03093       res = ast_sendto(p->socket.fd, data->str, len, 0, dst);
03094    } else if (p->socket.tcptls_session) {
03095       res = sip_tcptls_write(p->socket.tcptls_session, data->str, len);
03096    } else {
03097       ast_debug(2, "Socket type is TCP but no tcptls_session is present to write to\n");
03098       return XMIT_ERROR;
03099    }
03100 
03101    if (res == -1) {
03102       switch (errno) {
03103       case EBADF:       /* Bad file descriptor - seems like this is generated when the host exist, but doesn't accept the UDP packet */
03104       case EHOSTUNREACH:   /* Host can't be reached */
03105       case ENETDOWN:       /* Interface down */
03106       case ENETUNREACH: /* Network failure */
03107       case ECONNREFUSED:      /* ICMP port unreachable */
03108          res = XMIT_ERROR; /* Don't bother with trying to transmit again */
03109       }
03110    }
03111    if (res != len) {
03112       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));
03113    }
03114 
03115    return res;
03116 }
03117 
03118 /*! \brief Build a Via header for a request */
03119 static void build_via(struct sip_pvt *p)
03120 {
03121    /* Work around buggy UNIDEN UIP200 firmware */
03122    const char *rport = (ast_test_flag(&p->flags[0], SIP_NAT_FORCE_RPORT) || ast_test_flag(&p->flags[0], SIP_NAT_RPORT_PRESENT)) ? ";rport" : "";
03123 
03124    /* z9hG4bK is a magic cookie.  See RFC 3261 section 8.1.1.7 */
03125    snprintf(p->via, sizeof(p->via), "SIP/2.0/%s %s;branch=z9hG4bK%08x%s",
03126        get_transport_pvt(p),
03127        ast_sockaddr_stringify(&p->ourip),
03128        (int) p->branch, rport);
03129 }
03130 
03131 /*! \brief NAT fix - decide which IP address to use for Asterisk server?
03132  *
03133  * Using the localaddr structure built up with localnet statements in sip.conf
03134  * apply it to their address to see if we need to substitute our
03135  * externaddr or can get away with our internal bindaddr
03136  * 'us' is always overwritten.
03137  */
03138 static void ast_sip_ouraddrfor(const struct ast_sockaddr *them, struct ast_sockaddr *us, struct sip_pvt *p)
03139 {
03140    struct ast_sockaddr theirs;
03141 
03142    /* Set want_remap to non-zero if we want to remap 'us' to an externally
03143     * reachable IP address and port. This is done if:
03144     * 1. we have a localaddr list (containing 'internal' addresses marked
03145     *    as 'deny', so ast_apply_ha() will return AST_SENSE_DENY on them,
03146     *    and AST_SENSE_ALLOW on 'external' ones);
03147     * 2. externaddr is set, so we know what to use as the
03148     *    externally visible address;
03149     * 3. the remote address, 'them', is external;
03150     * 4. the address returned by ast_ouraddrfor() is 'internal' (AST_SENSE_DENY
03151     *    when passed to ast_apply_ha() so it does need to be remapped.
03152     *    This fourth condition is checked later.
03153     */
03154    int want_remap = 0;
03155 
03156    ast_sockaddr_copy(us, &internip); /* starting guess for the internal address */
03157    /* now ask the system what would it use to talk to 'them' */
03158    ast_ouraddrfor(them, us);
03159    ast_sockaddr_copy(&theirs, them);
03160 
03161    if (ast_sockaddr_is_ipv6(&theirs)) {
03162       if (localaddr && !ast_sockaddr_isnull(&externaddr)) {
03163          ast_log(LOG_WARNING, "Address remapping activated in sip.conf "
03164             "but we're using IPv6, which doesn't need it. Please "
03165             "remove \"localnet\" and/or \"externaddr\" settings.\n");
03166       }
03167    } else {
03168       want_remap = localaddr &&
03169          !ast_sockaddr_isnull(&externaddr) &&
03170          ast_apply_ha(localaddr, &theirs) == AST_SENSE_ALLOW ;
03171    }
03172 
03173    if (want_remap &&
03174        (!sip_cfg.matchexternaddrlocally || !ast_apply_ha(localaddr, us)) ) {
03175       /* if we used externhost, see if it is time to refresh the info */
03176       if (externexpire && time(NULL) >= externexpire) {
03177          if (ast_sockaddr_resolve_first(&externaddr, externhost, 0)) {
03178             ast_log(LOG_NOTICE, "Warning: Re-lookup of '%s' failed!\n", externhost);
03179          }
03180          externexpire = time(NULL) + externrefresh;
03181       }
03182       if (!ast_sockaddr_isnull(&externaddr)) {
03183          ast_sockaddr_copy(us, &externaddr);
03184          switch (p->socket.type) {
03185          case SIP_TRANSPORT_TCP:
03186             if (!externtcpport && ast_sockaddr_port(&externaddr)) {
03187                /* for consistency, default to the externaddr port */
03188                externtcpport = ast_sockaddr_port(&externaddr);
03189             }
03190             ast_sockaddr_set_port(us, externtcpport);
03191             break;
03192          case SIP_TRANSPORT_TLS:
03193             ast_sockaddr_set_port(us, externtlsport);
03194             break;
03195          case SIP_TRANSPORT_UDP:
03196             if (!ast_sockaddr_port(&externaddr)) {
03197                ast_sockaddr_set_port(us, ast_sockaddr_port(&bindaddr));
03198             }
03199             break;
03200          default:
03201             break;
03202          }
03203       }
03204       ast_debug(1, "Target address %s is not local, substituting externaddr\n",
03205            ast_sockaddr_stringify(them));
03206    } else if (p) {
03207       /* no remapping, but we bind to a specific address, so use it. */
03208       switch (p->socket.type) {
03209       case SIP_TRANSPORT_TCP:
03210          if (!ast_sockaddr_is_any(&sip_tcp_desc.local_address)) {
03211             ast_sockaddr_copy(us,
03212                     &sip_tcp_desc.local_address);
03213          } else {
03214             ast_sockaddr_set_port(us,
03215                         ast_sockaddr_port(&sip_tcp_desc.local_address));
03216          }
03217          break;
03218       case SIP_TRANSPORT_TLS:
03219          if (!ast_sockaddr_is_any(&sip_tls_desc.local_address)) {
03220             ast_sockaddr_copy(us,
03221                     &sip_tls_desc.local_address);
03222          } else {
03223             ast_sockaddr_set_port(us,
03224                         ast_sockaddr_port(&sip_tls_desc.local_address));
03225          }
03226          break;
03227       case SIP_TRANSPORT_UDP:
03228          /* fall through on purpose */
03229       default:
03230          if (!ast_sockaddr_is_any(&bindaddr)) {
03231             ast_sockaddr_copy(us, &bindaddr);
03232          }
03233          if (!ast_sockaddr_port(us)) {
03234             ast_sockaddr_set_port(us, ast_sockaddr_port(&bindaddr));
03235          }
03236       }
03237    } else if (!ast_sockaddr_is_any(&bindaddr)) {
03238       ast_sockaddr_copy(us, &bindaddr);
03239    }
03240    ast_debug(3, "Setting SIP_TRANSPORT_%s with address %s\n", get_transport(p->socket.type), ast_sockaddr_stringify(us));
03241 }
03242 
03243 /*! \brief Append to SIP dialog history with arg list  */
03244 static __attribute__((format(printf, 2, 0))) void append_history_va(struct sip_pvt *p, const char *fmt, va_list ap)
03245 {
03246    char buf[80], *c = buf; /* max history length */
03247    struct sip_history *hist;
03248    int l;
03249 
03250    vsnprintf(buf, sizeof(buf), fmt, ap);
03251    strsep(&c, "\r\n"); /* Trim up everything after \r or \n */
03252    l = strlen(buf) + 1;
03253    if (!(hist = ast_calloc(1, sizeof(*hist) + l))) {
03254       return;
03255    }
03256    if (!p->history && !(p->history = ast_calloc(1, sizeof(*p->history)))) {
03257       ast_free(hist);
03258       return;
03259    }
03260    memcpy(hist->event, buf, l);
03261    if (p->history_entries == MAX_HISTORY_ENTRIES) {
03262       struct sip_history *oldest;
03263       oldest = AST_LIST_REMOVE_HEAD(p->history, list);
03264       p->history_entries--;
03265       ast_free(oldest);
03266    }
03267    AST_LIST_INSERT_TAIL(p->history, hist, list);
03268    p->history_entries++;
03269 }
03270 
03271 /*! \brief Append to SIP dialog history with arg list  */
03272 static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
03273 {
03274    va_list ap;
03275 
03276    if (!p) {
03277       return;
03278    }
03279 
03280    if (!p->do_history && !recordhistory && !dumphistory) {
03281       return;
03282    }
03283 
03284    va_start(ap, fmt);
03285    append_history_va(p, fmt, ap);
03286    va_end(ap);
03287 
03288    return;
03289 }
03290 
03291 /*! \brief Retransmit SIP message if no answer (Called from scheduler) */
03292 static int retrans_pkt(const void *data)
03293 {
03294    struct sip_pkt *pkt = (struct sip_pkt *)data, *prev, *cur = NULL;
03295    int reschedule = DEFAULT_RETRANS;
03296    int xmitres = 0;
03297    /* how many ms until retrans timeout is reached */
03298    int64_t diff = pkt->retrans_stop_time - ast_tvdiff_ms(ast_tvnow(), pkt->time_sent);
03299 
03300    /* Do not retransmit if time out is reached. This will be negative if the time between
03301     * the first transmission and now is larger than our timeout period. This is a fail safe
03302     * check in case the scheduler gets behind or the clock is changed. */
03303    if ((diff <= 0) || (diff > pkt->retrans_stop_time)) {
03304       pkt->retrans_stop = 1;
03305    }
03306 
03307    /* Lock channel PVT */
03308    sip_pvt_lock(pkt->owner);
03309 
03310    if (!pkt->retrans_stop) {
03311       pkt->retrans++;
03312       if (!pkt->timer_t1) {   /* Re-schedule using timer_a and timer_t1 */
03313          if (sipdebug) {
03314             ast_debug(4, "SIP TIMER: Not rescheduling id #%d:%s (Method %d) (No timer T1)\n",
03315                pkt->retransid,
03316                sip_methods[pkt->method].text,
03317                pkt->method);
03318          }
03319       } else {
03320          int siptimer_a;
03321 
03322          if (sipdebug) {
03323             ast_debug(4, "SIP TIMER: Rescheduling retransmission #%d (%d) %s - %d\n",
03324                pkt->retransid,
03325                pkt->retrans,
03326                sip_methods[pkt->method].text,
03327                pkt->method);
03328          }
03329          if (!pkt->timer_a) {
03330             pkt->timer_a = 2 ;
03331          } else {
03332             pkt->timer_a = 2 * pkt->timer_a;
03333          }
03334 
03335          /* For non-invites, a maximum of 4 secs */
03336          siptimer_a = pkt->timer_t1 * pkt->timer_a;   /* Double each time */
03337          if (pkt->method != SIP_INVITE && siptimer_a > 4000) {
03338             siptimer_a = 4000;
03339          }
03340 
03341          /* Reschedule re-transmit */
03342          reschedule = siptimer_a;
03343          ast_debug(4, "** SIP timers: Rescheduling retransmission %d to %d ms (t1 %d ms (Retrans id #%d)) \n",
03344             pkt->retrans + 1,
03345             siptimer_a,
03346             pkt->timer_t1,
03347             pkt->retransid);
03348       }
03349 
03350       if (sip_debug_test_pvt(pkt->owner)) {
03351          const struct ast_sockaddr *dst = sip_real_dst(pkt->owner);
03352          ast_verbose("Retransmitting #%d (%s) to %s:\n%s\n---\n",
03353             pkt->retrans, sip_nat_mode(pkt->owner),
03354             ast_sockaddr_stringify(dst),
03355             pkt->data->str);
03356       }
03357 
03358       append_history(pkt->owner, "ReTx", "%d %s", reschedule, pkt->data->str);
03359       xmitres = __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
03360 
03361       /* If there was no error during the network transmission, schedule the next retransmission,
03362        * but if the next retransmission is going to be beyond our timeout period, mark the packet's
03363        * stop_retrans value and set the next retransmit to be the exact time of timeout.  This will
03364        * allow any responses to the packet to be processed before the packet is destroyed on the next
03365        * call to this function by the scheduler. */
03366       if (xmitres != XMIT_ERROR) {
03367          if (reschedule >= diff) {
03368             pkt->retrans_stop = 1;
03369             reschedule = diff;
03370          }
03371          sip_pvt_unlock(pkt->owner);
03372          return  reschedule;
03373       }
03374    }
03375 
03376    /* At this point, either the packet's retransmission timed out, or there was a
03377     * transmission error, either way destroy the scheduler item and this packet. */
03378 
03379    pkt->retransid = -1; /* Kill this scheduler item */
03380 
03381    if (pkt->owner && pkt->method != SIP_OPTIONS && xmitres == 0) {
03382       if (pkt->is_fatal || sipdebug) { /* Tell us if it's critical or if we're debugging */
03383          ast_log(LOG_WARNING, "Retransmission timeout reached on transmission %s for seqno %d (%s %s) -- See doc/sip-retransmit.txt.\n"
03384             "Packet timed out after %dms with no response\n",
03385             pkt->owner->callid,
03386             pkt->seqno,
03387             pkt->is_fatal ? "Critical" : "Non-critical",
03388             pkt->is_resp ? "Response" : "Request",
03389             (int) ast_tvdiff_ms(ast_tvnow(), pkt->time_sent));
03390       }
03391    } else if (pkt->method == SIP_OPTIONS && sipdebug) {
03392       ast_log(LOG_WARNING, "Cancelling retransmit of OPTIONs (call id %s)  -- See doc/sip-retransmit.txt.\n", pkt->owner->callid);
03393    }
03394 
03395    if (xmitres == XMIT_ERROR) {
03396       ast_log(LOG_WARNING, "Transmit error :: Cancelling transmission on Call ID %s\n", pkt->owner->callid);
03397       append_history(pkt->owner, "XmitErr", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
03398    } else {
03399       append_history(pkt->owner, "MaxRetries", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
03400    }
03401 
03402    if (pkt->is_fatal) {
03403       while(pkt->owner->owner && ast_channel_trylock(pkt->owner->owner)) {
03404          sip_pvt_unlock(pkt->owner);   /* SIP_PVT, not channel */
03405          usleep(1);
03406          sip_pvt_lock(pkt->owner);
03407       }
03408       if (pkt->owner->owner && !pkt->owner->owner->hangupcause) {
03409          pkt->owner->owner->hangupcause = AST_CAUSE_NO_USER_RESPONSE;
03410       }
03411       if (pkt->owner->owner) {
03412          ast_log(LOG_WARNING, "Hanging up call %s - no reply to our critical packet (see doc/sip-retransmit.txt).\n", pkt->owner->callid);
03413 
03414          if (pkt->is_resp &&
03415             (pkt->response_code >= 200) &&
03416             (pkt->response_code < 300) &&
03417             pkt->owner->pendinginvite &&
03418             ast_test_flag(&pkt->owner->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED)) {
03419             /* This is a timeout of the 2XX response to a pending INVITE.  In this case terminate the INVITE
03420              * transaction just as if we received the ACK, but immediately hangup with a BYE (sip_hangup
03421              * will send the BYE as long as the dialog is not set as "alreadygone")
03422              * RFC 3261 section 13.3.1.4.
03423              * "If the server retransmits the 2xx response for 64*T1 seconds without receiving
03424              * an ACK, the dialog is confirmed, but the session SHOULD be terminated.  This is
03425              * accomplished with a BYE, as described in Section 15." */
03426             pkt->owner->invitestate = INV_TERMINATED;
03427             pkt->owner->pendinginvite = 0;
03428          } else {
03429             /* there is nothing left to do, mark the dialog as gone */
03430             sip_alreadygone(pkt->owner);
03431          }
03432          ast_queue_hangup_with_cause(pkt->owner->owner, AST_CAUSE_PROTOCOL_ERROR);
03433          ast_channel_unlock(pkt->owner->owner);
03434       } else {
03435          /* If no channel owner, destroy now */
03436 
03437          /* Let the peerpoke system expire packets when the timer expires for poke_noanswer */
03438          if (pkt->method != SIP_OPTIONS && pkt->method != SIP_REGISTER) {
03439             pvt_set_needdestroy(pkt->owner, "no response to critical packet");
03440             sip_alreadygone(pkt->owner);
03441             append_history(pkt->owner, "DialogKill", "Killing this failed dialog immediately");
03442          }
03443       }
03444    }
03445 
03446    if (pkt->method == SIP_BYE) {
03447       /* We're not getting answers on SIP BYE's.  Tear down the call anyway. */
03448       if (pkt->owner->owner) {
03449          ast_channel_unlock(pkt->owner->owner);
03450       }
03451       append_history(pkt->owner, "ByeFailure", "Remote peer doesn't respond to bye. Destroying call anyway.");
03452       pvt_set_needdestroy(pkt->owner, "no response to BYE");
03453    }
03454 
03455    /* Remove the packet */
03456    for (prev = NULL, cur = pkt->owner->packets; cur; prev = cur, cur = cur->next) {
03457       if (cur == pkt) {
03458          UNLINK(cur, pkt->owner->packets, prev);
03459          sip_pvt_unlock(pkt->owner);
03460          if (pkt->owner) {
03461             pkt->owner = dialog_unref(pkt->owner,"pkt is being freed, its dialog ref is dead now");
03462          }
03463          if (pkt->data) {
03464             ast_free(pkt->data);
03465          }
03466          pkt->data = NULL;
03467          ast_free(pkt);
03468          return 0;
03469       }
03470    }
03471    /* error case */
03472    ast_log(LOG_WARNING, "Weird, couldn't find packet owner!\n");
03473    sip_pvt_unlock(pkt->owner);
03474    return 0;
03475 }
03476 
03477 /*! \brief Transmit packet with retransmits
03478    \return 0 on success, -1 on failure to allocate packet
03479 */
03480 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)
03481 {
03482    struct sip_pkt *pkt = NULL;
03483    int siptimer_a = DEFAULT_RETRANS;
03484    int xmitres = 0;
03485    int respid;
03486 
03487    if (sipmethod == SIP_INVITE) {
03488       /* Note this is a pending invite */
03489       p->pendinginvite = seqno;
03490    }
03491 
03492    /* If the transport is something reliable (TCP or TLS) then don't really send this reliably */
03493    /* I removed the code from retrans_pkt that does the same thing so it doesn't get loaded into the scheduler */
03494    /*! \todo According to the RFC some packets need to be retransmitted even if its TCP, so this needs to get revisited */
03495    if (!(p->socket.type & SIP_TRANSPORT_UDP)) {
03496       xmitres = __sip_xmit(p, data, len); /* Send packet */
03497       if (xmitres == XMIT_ERROR) {  /* Serious network trouble, no need to try again */
03498          append_history(p, "XmitErr", "%s", fatal ? "(Critical)" : "(Non-critical)");
03499          return AST_FAILURE;
03500       } else {
03501          return AST_SUCCESS;
03502       }
03503    }
03504 
03505    if (!(pkt = ast_calloc(1, sizeof(*pkt) + len + 1))) {
03506       return AST_FAILURE;
03507    }
03508    /* copy data, add a terminator and save length */
03509    if (!(pkt->data = ast_str_create(len))) {
03510       ast_free(pkt);
03511       return AST_FAILURE;
03512    }
03513    ast_str_set(&pkt->data, 0, "%s%s", data->str, "\0");
03514    pkt->packetlen = len;
03515    /* copy other parameters from the caller */
03516    pkt->method = sipmethod;
03517    pkt->seqno = seqno;
03518    pkt->is_resp = resp;
03519    pkt->is_fatal = fatal;
03520    pkt->owner = dialog_ref(p, "__sip_reliable_xmit: setting pkt->owner");
03521    pkt->next = p->packets;
03522    p->packets = pkt; /* Add it to the queue */
03523    if (resp) {
03524       /* Parse out the response code */
03525       if (sscanf(ast_str_buffer(pkt->data), "SIP/2.0 %30u", &respid) == 1) {
03526          pkt->response_code = respid;
03527       }
03528    }
03529    pkt->timer_t1 = p->timer_t1;  /* Set SIP timer T1 */
03530    pkt->retransid = -1;
03531    if (pkt->timer_t1) {
03532       siptimer_a = pkt->timer_t1;
03533    }
03534 
03535    pkt->time_sent = ast_tvnow(); /* time packet was sent */
03536    pkt->retrans_stop_time = 64 * (pkt->timer_t1 ? pkt->timer_t1 : DEFAULT_TIMER_T1); /* time in ms after pkt->time_sent to stop retransmission */
03537 
03538    /* Schedule retransmission */
03539    AST_SCHED_REPLACE_VARIABLE(pkt->retransid, sched, siptimer_a, retrans_pkt, pkt, 1);
03540    if (sipdebug) {
03541       ast_debug(4, "*** SIP TIMER: Initializing retransmit timer on packet: Id  #%d\n", pkt->retransid);
03542    }
03543 
03544    xmitres = __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);   /* Send packet */
03545 
03546    if (xmitres == XMIT_ERROR) {  /* Serious network trouble, no need to try again */
03547       append_history(pkt->owner, "XmitErr", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
03548       ast_log(LOG_ERROR, "Serious Network Trouble; __sip_xmit returns error for pkt data\n");
03549       AST_SCHED_DEL(sched, pkt->retransid);
03550       p->packets = pkt->next;
03551       pkt->owner = dialog_unref(pkt->owner,"pkt is being freed, its dialog ref is dead now");
03552       ast_free(pkt->data);
03553       ast_free(pkt);
03554       return AST_FAILURE;
03555    } else {
03556       /* This is odd, but since the retrans timer starts at 500ms and the do_monitor thread
03557        * only wakes up every 1000ms by default, we have to poke the thread here to make
03558        * sure it successfully detects this must be retransmitted in less time than
03559        * it usually sleeps for. Otherwise it might not retransmit this packet for 1000ms. */
03560       if (monitor_thread != AST_PTHREADT_NULL) {
03561          pthread_kill(monitor_thread, SIGURG);
03562       }
03563       return AST_SUCCESS;
03564    }
03565 }
03566 
03567 /*! \brief Kill a SIP dialog (called only by the scheduler)
03568  * The scheduler has a reference to this dialog when p->autokillid != -1,
03569  * and we are called using that reference. So if the event is not
03570  * rescheduled, we need to call dialog_unref().
03571  */
03572 static int __sip_autodestruct(const void *data)
03573 {
03574    struct sip_pvt *p = (struct sip_pvt *)data;
03575 
03576    /* If this is a subscription, tell the phone that we got a timeout */
03577    if (p->subscribed && p->subscribed != MWI_NOTIFICATION && p->subscribed != CALL_COMPLETION) {
03578       transmit_state_notify(p, AST_EXTENSION_DEACTIVATED, 1, TRUE);  /* Send last notification */
03579       p->subscribed = NONE;
03580       append_history(p, "Subscribestatus", "timeout");
03581       ast_debug(3, "Re-scheduled destruction of SIP subscription %s\n", p->callid ? p->callid : "<unknown>");
03582       return 10000;  /* Reschedule this destruction so that we know that it's gone */
03583    }
03584 
03585    /* If there are packets still waiting for delivery, delay the destruction */
03586    if (p->packets) {
03587       if (!p->needdestroy) {
03588          char method_str[31];
03589          ast_debug(3, "Re-scheduled destruction of SIP call %s\n", p->callid ? p->callid : "<unknown>");
03590          append_history(p, "ReliableXmit", "timeout");
03591          if (sscanf(p->lastmsg, "Tx: %30s", method_str) == 1 || sscanf(p->lastmsg, "Rx: %30s", method_str) == 1) {
03592             if (method_match(SIP_CANCEL, method_str) || method_match(SIP_BYE, method_str)) {
03593                pvt_set_needdestroy(p, "autodestruct");
03594             }
03595          }
03596          return 10000;
03597       } else {
03598          /* They've had their chance to respond. Time to bail */
03599          __sip_pretend_ack(p);
03600       }
03601    }
03602 
03603    /* Reset schedule ID */
03604    p->autokillid = -1;
03605 
03606 
03607    /*
03608     * Lock both the pvt and the channel safely so that we can queue up a frame.
03609     */
03610    sip_pvt_lock(p);
03611    while (p->owner && ast_channel_trylock(p->owner)) {
03612       sip_pvt_unlock(p);
03613       sched_yield();
03614       sip_pvt_lock(p);
03615    }
03616 
03617    if (p->owner) {
03618       ast_log(LOG_WARNING, "Autodestruct on dialog '%s' with owner in place (Method: %s)\n", p->callid, sip_methods[p->method].text);
03619       ast_queue_hangup_with_cause(p->owner, AST_CAUSE_PROTOCOL_ERROR);
03620       ast_channel_unlock(p->owner);
03621    } else if (p->refer && !p->alreadygone) {
03622       ast_debug(3, "Finally hanging up channel after transfer: %s\n", p->callid);
03623       transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
03624       append_history(p, "ReferBYE", "Sending BYE on transferer call leg %s", p->callid);
03625       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
03626    } else {
03627       append_history(p, "AutoDestroy", "%s", p->callid);
03628       ast_debug(3, "Auto destroying SIP dialog '%s'\n", p->callid);
03629       dialog_unlink_all(p, TRUE, TRUE); /* once it's unlinked and unrefd everywhere, it'll be freed automagically */
03630       /* dialog_unref(p, "unref dialog-- no other matching conditions"); -- unlink all now should finish off the dialog's references and free it. */
03631       /* sip_destroy(p); */      /* Go ahead and destroy dialog. All attempts to recover is done */
03632       /* sip_destroy also absorbs the reference */
03633    }
03634 
03635    sip_pvt_unlock(p);
03636 
03637    dialog_unref(p, "The ref to a dialog passed to this sched callback is going out of scope; unref it.");
03638 
03639    return 0;
03640 }
03641 
03642 /*! \brief Schedule final destruction of SIP dialog.  This can not be canceled.
03643  *  This function is used to keep a dialog around for a period of time in order
03644  *  to properly respond to any retransmits. */
03645 void sip_scheddestroy_final(struct sip_pvt *p, int ms)
03646 {
03647    if (p->final_destruction_scheduled) {
03648       return; /* already set final destruction */
03649    }
03650 
03651    sip_scheddestroy(p, ms);
03652    if (p->autokillid != -1) {
03653       p->final_destruction_scheduled = 1;
03654    }
03655 }
03656 
03657 /*! \brief Schedule destruction of SIP dialog */
03658 void sip_scheddestroy(struct sip_pvt *p, int ms)
03659 {
03660    if (p->final_destruction_scheduled) {
03661       return; /* already set final destruction */
03662    }
03663 
03664    if (ms < 0) {
03665       if (p->timer_t1 == 0) {
03666          p->timer_t1 = global_t1;   /* Set timer T1 if not set (RFC 3261) */
03667       }
03668       if (p->timer_b == 0) {
03669          p->timer_b = global_timer_b;  /* Set timer B if not set (RFC 3261) */
03670       }
03671       ms = p->timer_t1 * 64;
03672    }
03673    if (sip_debug_test_pvt(p)) {
03674       ast_verbose("Scheduling destruction of SIP dialog '%s' in %d ms (Method: %s)\n", p->callid, ms, sip_methods[p->method].text);
03675    }
03676    if (sip_cancel_destroy(p)) {
03677       ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
03678    }
03679 
03680    if (p->do_history) {
03681       append_history(p, "SchedDestroy", "%d ms", ms);
03682    }
03683    p->autokillid = ast_sched_add(sched, ms, __sip_autodestruct, dialog_ref(p, "setting ref as passing into ast_sched_add for __sip_autodestruct"));
03684 
03685    if (p->stimer && p->stimer->st_active == TRUE && p->stimer->st_schedid > 0) {
03686       stop_session_timer(p);
03687    }
03688 }
03689 
03690 /*! \brief Cancel destruction of SIP dialog.
03691  * Be careful as this also absorbs the reference - if you call it
03692  * from within the scheduler, this might be the last reference.
03693  */
03694 int sip_cancel_destroy(struct sip_pvt *p)
03695 {
03696    int res = 0;
03697 
03698    if (p->final_destruction_scheduled) {
03699       return res;
03700    }
03701 
03702    if (p->autokillid > -1) {
03703       int res3;
03704 
03705       if (!(res3 = ast_sched_del(sched, p->autokillid))) {
03706          append_history(p, "CancelDestroy", "");
03707          p->autokillid = -1;
03708          dialog_unref(p, "dialog unrefd because autokillid is de-sched'd");
03709       }
03710    }
03711    return res;
03712 }
03713 
03714 /*! \brief Acknowledges receipt of a packet and stops retransmission
03715  * called with p locked*/
03716 int __sip_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod)
03717 {
03718    struct sip_pkt *cur, *prev = NULL;
03719    const char *msg = "Not Found";   /* used only for debugging */
03720    int res = FALSE;
03721 
03722    /* If we have an outbound proxy for this dialog, then delete it now since
03723      the rest of the requests in this dialog needs to follow the routing.
03724      If obforcing is set, we will keep the outbound proxy during the whole
03725      dialog, regardless of what the SIP rfc says
03726    */
03727    if (p->outboundproxy && !p->outboundproxy->force){
03728       ref_proxy(p, NULL);
03729    }
03730 
03731    for (cur = p->packets; cur; prev = cur, cur = cur->next) {
03732       if (cur->seqno != seqno || cur->is_resp != resp) {
03733          continue;
03734       }
03735       if (cur->is_resp || cur->method == sipmethod) {
03736          res = TRUE;
03737          msg = "Found";
03738          if (!resp && (seqno == p->pendinginvite)) {
03739             ast_debug(1, "Acked pending invite %d\n", p->pendinginvite);
03740             p->pendinginvite = 0;
03741          }
03742          if (cur->retransid > -1) {
03743             if (sipdebug)
03744                ast_debug(4, "** SIP TIMER: Cancelling retransmit of packet (reply received) Retransid #%d\n", cur->retransid);
03745          }
03746          /* This odd section is designed to thwart a
03747           * race condition in the packet scheduler. There are
03748           * two conditions under which deleting the packet from the
03749           * scheduler can fail.
03750           *
03751           * 1. The packet has been removed from the scheduler because retransmission
03752           * is being attempted. The problem is that if the packet is currently attempting
03753           * retransmission and we are at this point in the code, then that MUST mean
03754           * that retrans_pkt is waiting on p's lock. Therefore we will relinquish the
03755           * lock temporarily to allow retransmission.
03756           *
03757           * 2. The packet has reached its maximum number of retransmissions and has
03758           * been permanently removed from the packet scheduler. If this is the case, then
03759           * the packet's retransid will be set to -1. The atomicity of the setting and checking
03760           * of the retransid to -1 is ensured since in both cases p's lock is held.
03761           */
03762          while (cur->retransid > -1 && ast_sched_del(sched, cur->retransid)) {
03763             sip_pvt_unlock(p);
03764             usleep(1);
03765             sip_pvt_lock(p);
03766          }
03767          UNLINK(cur, p->packets, prev);
03768          dialog_unref(cur->owner, "unref pkt cur->owner dialog from sip ack before freeing pkt");
03769          if (cur->data) {
03770             ast_free(cur->data);
03771          }
03772          ast_free(cur);
03773          break;
03774       }
03775    }
03776    ast_debug(1, "Stopping retransmission on '%s' of %s %d: Match %s\n",
03777       p->callid, resp ? "Response" : "Request", seqno, msg);
03778    return res;
03779 }
03780 
03781 /*! \brief Pretend to ack all packets
03782  * called with p locked */
03783 void __sip_pretend_ack(struct sip_pvt *p)
03784 {
03785    struct sip_pkt *cur = NULL;
03786 
03787    while (p->packets) {
03788       int method;
03789       if (cur == p->packets) {
03790          ast_log(LOG_WARNING, "Have a packet that doesn't want to give up! %s\n", sip_methods[cur->method].text);
03791          return;
03792       }
03793       cur = p->packets;
03794       method = (cur->method) ? cur->method : find_sip_method(cur->data->str);
03795       __sip_ack(p, cur->seqno, cur->is_resp, method);
03796    }
03797 }
03798 
03799 /*! \brief Acks receipt of packet, keep it around (used for provisional responses) */
03800 int __sip_semi_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod)
03801 {
03802    struct sip_pkt *cur;
03803    int res = FALSE;
03804 
03805    for (cur = p->packets; cur; cur = cur->next) {
03806       if (cur->seqno == seqno && cur->is_resp == resp &&
03807          (cur->is_resp || method_match(sipmethod, cur->data->str))) {
03808          /* this is our baby */
03809          if (cur->retransid > -1) {
03810             if (sipdebug)
03811                ast_debug(4, "*** SIP TIMER: Cancelling retransmission #%d - %s (got response)\n", cur->retransid, sip_methods[sipmethod].text);
03812          }
03813          AST_SCHED_DEL(sched, cur->retransid);
03814          res = TRUE;
03815          break;
03816       }
03817    }
03818    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");
03819    return res;
03820 }
03821 
03822 
03823 /*! \brief Copy SIP request, parse it */
03824 static void parse_copy(struct sip_request *dst, const struct sip_request *src)
03825 {
03826    copy_request(dst, src);
03827    parse_request(dst);
03828 }
03829 
03830 /*! \brief add a blank line if no body */
03831 static void add_blank(struct sip_request *req)
03832 {
03833    if (!req->lines) {
03834       /* Add extra empty return. add_header() reserves 4 bytes so cannot be truncated */
03835       ast_str_append(&req->data, 0, "\r\n");
03836       req->len = ast_str_strlen(req->data);
03837    }
03838 }
03839 
03840 static int send_provisional_keepalive_full(struct sip_pvt *pvt, int with_sdp)
03841 {
03842    const char *msg = NULL;
03843 
03844    if (!pvt->last_provisional || !strncasecmp(pvt->last_provisional, "100", 3)) {
03845       msg = "183 Session Progress";
03846    }
03847 
03848    if (pvt->invitestate < INV_COMPLETED) {
03849       if (with_sdp) {
03850          transmit_response_with_sdp(pvt, S_OR(msg, pvt->last_provisional), &pvt->initreq, XMIT_UNRELIABLE, FALSE, FALSE);
03851       } else {
03852          transmit_response(pvt, S_OR(msg, pvt->last_provisional), &pvt->initreq);
03853       }
03854       return PROVIS_KEEPALIVE_TIMEOUT;
03855    }
03856 
03857    return 0;
03858 }
03859 
03860 static int send_provisional_keepalive(const void *data) {
03861    struct sip_pvt *pvt = (struct sip_pvt *) data;
03862 
03863    return send_provisional_keepalive_full(pvt, 0);
03864 }
03865 
03866 static int send_provisional_keepalive_with_sdp(const void *data) {
03867    struct sip_pvt *pvt = (void *)data;
03868 
03869    return send_provisional_keepalive_full(pvt, 1);
03870 }
03871 
03872 static void update_provisional_keepalive(struct sip_pvt *pvt, int with_sdp)
03873 {
03874    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"));
03875 
03876    pvt->provisional_keepalive_sched_id = ast_sched_add(sched, PROVIS_KEEPALIVE_TIMEOUT,
03877       with_sdp ? send_provisional_keepalive_with_sdp : send_provisional_keepalive, dialog_ref(pvt, "Increment refcount to pass dialog pointer to sched callback"));
03878 }
03879 
03880 /*! \brief Transmit response on SIP request*/
03881 static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno)
03882 {
03883    int res;
03884 
03885    finalize_content(req);
03886    add_blank(req);
03887    if (sip_debug_test_pvt(p)) {
03888       const struct ast_sockaddr *dst = sip_real_dst(p);
03889 
03890       ast_verbose("\n<--- %sTransmitting (%s) to %s --->\n%s\n<------------>\n",
03891          reliable ? "Reliably " : "", sip_nat_mode(p),
03892          ast_sockaddr_stringify(dst),
03893          req->data->str);
03894    }
03895    if (p->do_history) {
03896       struct sip_request tmp = { .rlPart1 = 0, };
03897       parse_copy(&tmp, req);
03898       append_history(p, reliable ? "TxRespRel" : "TxResp", "%s / %s - %s", tmp.data->str, get_header(&tmp, "CSeq"),
03899          (tmp.method == SIP_RESPONSE || tmp.method == SIP_UNKNOWN) ? REQ_OFFSET_TO_STR(&tmp, rlPart2) : sip_methods[tmp.method].text);
03900       deinit_req(&tmp);
03901    }
03902 
03903    /* If we are sending a final response to an INVITE, stop retransmitting provisional responses */
03904    if (p->initreq.method == SIP_INVITE && reliable == XMIT_CRITICAL) {
03905       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"));
03906    }
03907 
03908    res = (reliable) ?
03909        __sip_reliable_xmit(p, seqno, 1, req->data, req->len, (reliable == XMIT_CRITICAL), req->method) :
03910       __sip_xmit(p, req->data, req->len);
03911    deinit_req(req);
03912    if (res > 0) {
03913       return 0;
03914    }
03915    return res;
03916 }
03917 
03918 /*! \brief Send SIP Request to the other part of the dialogue 
03919    \return see \ref __sip_xmit
03920 */
03921 static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno)
03922 {
03923    int res;
03924 
03925    /* If we have an outbound proxy, reset peer address
03926       Only do this once.
03927    */
03928    if (p->outboundproxy) {
03929       p->sa = p->outboundproxy->ip;
03930    }
03931 
03932    finalize_content(req);
03933    add_blank(req);
03934    if (sip_debug_test_pvt(p)) {
03935       if (ast_test_flag(&p->flags[0], SIP_NAT_FORCE_RPORT)) {
03936          ast_verbose("%sTransmitting (NAT) to %s:\n%s\n---\n", reliable ? "Reliably " : "", ast_sockaddr_stringify(&p->recv), req->data->str);
03937       } else {
03938          ast_verbose("%sTransmitting (no NAT) to %s:\n%s\n---\n", reliable ? "Reliably " : "", ast_sockaddr_stringify(&p->sa), req->data->str);
03939       }
03940    }
03941    if (p->do_history) {
03942       struct sip_request tmp = { .rlPart1 = 0, };
03943       parse_copy(&tmp, req);
03944       append_history(p, reliable ? "TxReqRel" : "TxReq", "%s / %s - %s", tmp.data->str, get_header(&tmp, "CSeq"), sip_methods[tmp.method].text);
03945       deinit_req(&tmp);
03946    }
03947    res = (reliable) ?
03948       __sip_reliable_xmit(p, seqno, 0, req->data, req->len, (reliable == XMIT_CRITICAL), req->method) :
03949       __sip_xmit(p, req->data, req->len);
03950    deinit_req(req);
03951    return res;
03952 }
03953 
03954 static void enable_dsp_detect(struct sip_pvt *p)
03955 {
03956    int features = 0;
03957 
03958    if (p->dsp) {
03959       return;
03960    }
03961 
03962    if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) ||
03963             (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO)) {
03964       if (!p->rtp || ast_rtp_instance_dtmf_mode_set(p->rtp, AST_RTP_DTMF_MODE_INBAND)) {
03965          features |= DSP_FEATURE_DIGIT_DETECT;
03966                 }
03967    }
03968 
03969    if (ast_test_flag(&p->flags[1], SIP_PAGE2_FAX_DETECT_CNG)) {
03970       features |= DSP_FEATURE_FAX_DETECT;
03971    }
03972 
03973    if (!features) {
03974       return;
03975    }
03976 
03977    if (!(p->dsp = ast_dsp_new())) {
03978       return;
03979    }
03980 
03981    ast_dsp_set_features(p->dsp, features);
03982    if (global_relaxdtmf) {
03983       ast_dsp_set_digitmode(p->dsp, DSP_DIGITMODE_DTMF | DSP_DIGITMODE_RELAXDTMF);
03984    }
03985 }
03986 
03987 static void disable_dsp_detect(struct sip_pvt *p)
03988 {
03989    if (p->dsp) {
03990       ast_dsp_free(p->dsp);
03991       p->dsp = NULL;
03992    }
03993 }
03994 
03995 /*! \brief Set an option on a SIP dialog */
03996 static int sip_setoption(struct ast_channel *chan, int option, void *data, int datalen)
03997 {
03998    int res = -1;
03999    struct sip_pvt *p = chan->tech_pvt;
04000 
04001    switch (option) {
04002    case AST_OPTION_FORMAT_READ:
04003       res = ast_rtp_instance_set_read_format(p->rtp, *(int *) data);
04004       break;
04005    case AST_OPTION_FORMAT_WRITE:
04006       res = ast_rtp_instance_set_write_format(p->rtp, *(int *) data);
04007       break;
04008    case AST_OPTION_MAKE_COMPATIBLE:
04009       res = ast_rtp_instance_make_compatible(chan, p->rtp, (struct ast_channel *) data);
04010       break;
04011    case AST_OPTION_DIGIT_DETECT:
04012       if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) ||
04013           (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO)) {
04014          char *cp = (char *) data;
04015 
04016          ast_debug(1, "%sabling digit detection on %s\n", *cp ? "En" : "Dis", chan->name);
04017          if (*cp) {
04018             enable_dsp_detect(p);
04019          } else {
04020             disable_dsp_detect(p);
04021          }
04022          res = 0;
04023       }
04024       break;
04025    case AST_OPTION_SECURE_SIGNALING:
04026       p->req_secure_signaling = *(unsigned int *) data;
04027       res = 0;
04028       break;
04029    case AST_OPTION_SECURE_MEDIA:
04030       ast_set2_flag(&p->flags[1], *(unsigned int *) data, SIP_PAGE2_USE_SRTP);
04031       res = 0;
04032       break;
04033    default:
04034       ast_log(LOG_NOTICE, "Unknown option: %d\n", option);
04035       break;
04036    }
04037 
04038    return res;
04039 }
04040 
04041 /*! \brief Query an option on a SIP dialog */
04042 static int sip_queryoption(struct ast_channel *chan, int option, void *data, int *datalen)
04043 {
04044    int res = -1;
04045    enum ast_t38_state state = T38_STATE_UNAVAILABLE;
04046    struct sip_pvt *p = (struct sip_pvt *) chan->tech_pvt;
04047    char *cp;
04048 
04049    switch (option) {
04050    case AST_OPTION_T38_STATE:
04051       /* Make sure we got an ast_t38_state enum passed in */
04052       if (*datalen != sizeof(enum ast_t38_state)) {
04053          ast_log(LOG_ERROR, "Invalid datalen for AST_OPTION_T38_STATE option. Expected %d, got %d\n", (int)sizeof(enum ast_t38_state), *datalen);
04054          return -1;
04055       }
04056 
04057       sip_pvt_lock(p);
04058 
04059       /* 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 */
04060       if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT)) {
04061          switch (p->t38.state) {
04062          case T38_LOCAL_REINVITE:
04063          case T38_PEER_REINVITE:
04064             state = T38_STATE_NEGOTIATING;
04065             break;
04066          case T38_ENABLED:
04067             state = T38_STATE_NEGOTIATED;
04068             break;
04069          default:
04070             state = T38_STATE_UNKNOWN;
04071          }
04072       }
04073 
04074       sip_pvt_unlock(p);
04075 
04076       *((enum ast_t38_state *) data) = state;
04077       res = 0;
04078 
04079       break;
04080    case AST_OPTION_DIGIT_DETECT:
04081       cp = (char *) data;
04082       *cp = p->dsp ? 1 : 0;
04083       ast_debug(1, "Reporting digit detection %sabled on %s\n", *cp ? "en" : "dis", chan->name);
04084       break;
04085    case AST_OPTION_SECURE_SIGNALING:
04086       *((unsigned int *) data) = p->req_secure_signaling;
04087       res = 0;
04088       break;
04089    case AST_OPTION_SECURE_MEDIA:
04090       *((unsigned int *) data) = ast_test_flag(&p->flags[1], SIP_PAGE2_USE_SRTP) ? 1 : 0;
04091       res = 0;
04092       break;
04093    case AST_OPTION_DEVICE_NAME:
04094       if (p && p->outgoing_call) {
04095          cp = (char *) data;
04096          ast_copy_string(cp, p->dialstring, *datalen);
04097          res = 0;
04098       }
04099       /* We purposely break with a return of -1 in the
04100        * implied else case here
04101        */
04102       break;
04103    default:
04104       break;
04105    }
04106 
04107    return res;
04108 }
04109 
04110 /*! \brief Locate closing quote in a string, skipping escaped quotes.
04111  * optionally with a limit on the search.
04112  * start must be past the first quote.
04113  */
04114 const char *find_closing_quote(const char *start, const char *lim)
04115 {
04116    char last_char = '\0';
04117    const char *s;
04118    for (s = start; *s && s != lim; last_char = *s++) {
04119       if (*s == '"' && last_char != '\\')
04120          break;
04121    }
04122    return s;
04123 }
04124 
04125 /*! \brief Send message with Access-URL header, if this is an HTML URL only! */
04126 static int sip_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen)
04127 {
04128    struct sip_pvt *p = chan->tech_pvt;
04129 
04130    if (subclass != AST_HTML_URL)
04131       return -1;
04132 
04133    ast_string_field_build(p, url, "<%s>;mode=active", data);
04134 
04135    if (sip_debug_test_pvt(p))
04136       ast_debug(1, "Send URL %s, state = %d!\n", data, chan->_state);
04137 
04138    switch (chan->_state) {
04139    case AST_STATE_RING:
04140       transmit_response(p, "100 Trying", &p->initreq);
04141       break;
04142    case AST_STATE_RINGING:
04143       transmit_response(p, "180 Ringing", &p->initreq);
04144       break;
04145    case AST_STATE_UP:
04146       if (!p->pendinginvite) {      /* We are up, and have no outstanding invite */
04147          transmit_reinvite_with_sdp(p, FALSE, FALSE);
04148       } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
04149          ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);   
04150       }  
04151       break;
04152    default:
04153       ast_log(LOG_WARNING, "Don't know how to send URI when state is %d!\n", chan->_state);
04154    }
04155 
04156    return 0;
04157 }
04158 
04159 /*! \brief Deliver SIP call ID for the call */
04160 static const char *sip_get_callid(struct ast_channel *chan)
04161 {
04162    return chan->tech_pvt ? ((struct sip_pvt *) chan->tech_pvt)->callid : "";
04163 }
04164 
04165 /*! \brief Send SIP MESSAGE text within a call
04166    Called from PBX core sendtext() application */
04167 static int sip_sendtext(struct ast_channel *ast, const char *text)
04168 {
04169    struct sip_pvt *dialog = ast->tech_pvt;
04170    int debug = sip_debug_test_pvt(dialog);
04171 
04172    if (!dialog)
04173       return -1;
04174    /* NOT ast_strlen_zero, because a zero-length message is specifically
04175     * allowed by RFC 3428 (See section 10, Examples) */
04176    if (!text)
04177       return 0;
04178    if(!is_method_allowed(&dialog->allowed_methods, SIP_MESSAGE)) {
04179       ast_debug(2, "Trying to send MESSAGE to device that does not support it.\n");
04180       return(0);
04181    }
04182    if (debug)
04183       ast_verbose("Sending text %s on %s\n", text, ast->name);
04184    transmit_message_with_text(dialog, text);
04185    return 0;   
04186 }
04187 
04188 /*! \brief Update peer object in realtime storage
04189    If the Asterisk system name is set in asterisk.conf, we will use
04190    that name and store that in the "regserver" field in the sippeers
04191    table to facilitate multi-server setups.
04192 */
04193 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)
04194 {
04195    char port[10];
04196    char ipaddr[INET_ADDRSTRLEN];
04197    char regseconds[20];
04198    char *tablename = NULL;
04199    char str_lastms[20];
04200 
04201    const char *sysname = ast_config_AST_SYSTEM_NAME;
04202    char *syslabel = NULL;
04203 
04204    time_t nowtime = time(NULL) + expirey;
04205    const char *fc = fullcontact ? "fullcontact" : NULL;
04206 
04207    int realtimeregs = ast_check_realtime("sipregs");
04208 
04209    tablename = realtimeregs ? "sipregs" : "sippeers";
04210    
04211 
04212    snprintf(str_lastms, sizeof(str_lastms), "%d", lastms);
04213    snprintf(regseconds, sizeof(regseconds), "%d", (int)nowtime);  /* Expiration time */
04214    ast_copy_string(ipaddr, ast_sockaddr_stringify_addr(addr), sizeof(ipaddr));
04215    ast_copy_string(port, ast_sockaddr_stringify_port(addr), sizeof(port));
04216 
04217    if (ast_strlen_zero(sysname)) /* No system name, disable this */
04218       sysname = NULL;
04219    else if (sip_cfg.rtsave_sysname)
04220       syslabel = "regserver";
04221 
04222    if (fc) {
04223       ast_update_realtime(tablename, "name", peername, "ipaddr", ipaddr,
04224          "port", port, "regseconds", regseconds,
04225          deprecated_username ? "username" : "defaultuser", defaultuser,
04226          "useragent", useragent, "lastms", str_lastms,
04227          fc, fullcontact, syslabel, sysname, SENTINEL); /* note fc and syslabel _can_ be NULL */
04228    } else {
04229       ast_update_realtime(tablename, "name", peername, "ipaddr", ipaddr,
04230          "port", port, "regseconds", regseconds,
04231          "useragent", useragent, "lastms", str_lastms,
04232          deprecated_username ? "username" : "defaultuser", defaultuser,
04233          syslabel, sysname, SENTINEL); /* note syslabel _can_ be NULL */
04234    }
04235 }
04236 
04237 /*! \brief Automatically add peer extension to dial plan */
04238 static void register_peer_exten(struct sip_peer *peer, int onoff)
04239 {
04240    char multi[256];
04241    char *stringp, *ext, *context;
04242    struct pbx_find_info q = { .stacklen = 0 };
04243 
04244    /* XXX note that sip_cfg.regcontext is both a global 'enable' flag and
04245     * the name of the global regexten context, if not specified
04246     * individually.
04247     */
04248    if (ast_strlen_zero(sip_cfg.regcontext))
04249       return;
04250 
04251    ast_copy_string(multi, S_OR(peer->regexten, peer->name), sizeof(multi));
04252    stringp = multi;
04253    while ((ext = strsep(&stringp, "&"))) {
04254       if ((context = strchr(ext, '@'))) {
04255          *context++ = '\0';   /* split ext@context */
04256          if (!ast_context_find(context)) {
04257             ast_log(LOG_WARNING, "Context %s must exist in regcontext= in sip.conf!\n", context);
04258             continue;
04259          }
04260       } else {
04261          context = sip_cfg.regcontext;
04262       }
04263       if (onoff) {
04264          if (!ast_exists_extension(NULL, context, ext, 1, NULL)) {
04265             ast_add_extension(context, 1, ext, 1, NULL, NULL, "Noop",
04266                 ast_strdup(peer->name), ast_free_ptr, "SIP");
04267          }
04268       } else if (pbx_find_extension(NULL, NULL, &q, context, ext, 1, NULL, "", E_MATCH)) {
04269          ast_context_remove_extension(context, ext, 1, NULL);
04270       }
04271    }
04272 }
04273 
04274 /*! Destroy mailbox subscriptions */
04275 static void destroy_mailbox(struct sip_mailbox *mailbox)
04276 {
04277    if (mailbox->event_sub)
04278       ast_event_unsubscribe(mailbox->event_sub);
04279    ast_free(mailbox);
04280 }
04281 
04282 /*! Destroy all peer-related mailbox subscriptions */
04283 static void clear_peer_mailboxes(struct sip_peer *peer)
04284 {
04285    struct sip_mailbox *mailbox;
04286 
04287    while ((mailbox = AST_LIST_REMOVE_HEAD(&peer->mailboxes, entry)))
04288       destroy_mailbox(mailbox);
04289 }
04290 
04291 static void sip_destroy_peer_fn(void *peer)
04292 {
04293    sip_destroy_peer(peer);
04294 }
04295 
04296 /*! \brief Destroy peer object from memory */
04297 static void sip_destroy_peer(struct sip_peer *peer)
04298 {
04299    ast_debug(3, "Destroying SIP peer %s\n", peer->name);
04300    if (peer->outboundproxy)
04301       ao2_ref(peer->outboundproxy, -1);
04302    peer->outboundproxy = NULL;
04303 
04304    /* Delete it, it needs to disappear */
04305    if (peer->call) {
04306       dialog_unlink_all(peer->call, TRUE, TRUE);
04307       peer->call = dialog_unref(peer->call, "peer->call is being unset");
04308    }
04309    
04310 
04311    if (peer->mwipvt) {  /* We have an active subscription, delete it */
04312       dialog_unlink_all(peer->mwipvt, TRUE, TRUE);
04313       peer->mwipvt = dialog_unref(peer->mwipvt, "unreffing peer->mwipvt");
04314    }
04315    
04316    if (peer->chanvars) {
04317       ast_variables_destroy(peer->chanvars);
04318       peer->chanvars = NULL;
04319    }
04320    
04321    register_peer_exten(peer, FALSE);
04322    ast_free_ha(peer->ha);
04323    ast_free_ha(peer->directmediaha);
04324    if (peer->selfdestruct)
04325       ast_atomic_fetchadd_int(&apeerobjs, -1);
04326    else if (peer->is_realtime) {
04327       ast_atomic_fetchadd_int(&rpeerobjs, -1);
04328       ast_debug(3, "-REALTIME- peer Destroyed. Name: %s. Realtime Peer objects: %d\n", peer->name, rpeerobjs);
04329    } else
04330       ast_atomic_fetchadd_int(&speerobjs, -1);
04331    clear_realm_authentication(peer->auth);
04332    peer->auth = NULL;
04333    if (peer->dnsmgr)
04334       ast_dnsmgr_release(peer->dnsmgr);
04335    clear_peer_mailboxes(peer);
04336 
04337    if (peer->socket.tcptls_session) {
04338       ao2_ref(peer->socket.tcptls_session, -1);
04339       peer->socket.tcptls_session = NULL;
04340    }
04341 
04342    ast_cc_config_params_destroy(peer->cc_params);
04343 
04344    ast_string_field_free_memory(peer);
04345 }
04346 
04347 /*! \brief Update peer data in database (if used) */
04348 static void update_peer(struct sip_peer *p, int expire)
04349 {
04350    int rtcachefriends = ast_test_flag(&p->flags[1], SIP_PAGE2_RTCACHEFRIENDS);
04351    if (sip_cfg.peer_rtupdate &&
04352        (p->is_realtime || rtcachefriends)) {
04353       realtime_update_peer(p->name, &p->addr, p->username, rtcachefriends ? p->fullcontact : NULL, p->useragent, expire, p->deprecated_username, p->lastms);
04354    }
04355 }
04356 
04357 static struct ast_variable *get_insecure_variable_from_config(struct ast_config *cfg)
04358 {
04359    struct ast_variable *var = NULL;
04360    struct ast_flags flags = {0};
04361    char *cat = NULL;
04362    const char *insecure;
04363    while ((cat = ast_category_browse(cfg, cat))) {
04364       insecure = ast_variable_retrieve(cfg, cat, "insecure");
04365       set_insecure_flags(&flags, insecure, -1);
04366       if (ast_test_flag(&flags, SIP_INSECURE_PORT)) {
04367          var = ast_category_root(cfg, cat);
04368          break;
04369       }
04370    }
04371    return var;
04372 }
04373 
04374 static const char *get_name_from_variable(struct ast_variable *var, const char *newpeername)
04375 {
04376    struct ast_variable *tmp;
04377    for (tmp = var; tmp; tmp = tmp->next) {
04378       if (!newpeername && !strcasecmp(tmp->name, "name"))
04379          newpeername = tmp->value;
04380    }
04381    return newpeername;
04382 }
04383 
04384 /*! \brief  realtime_peer: Get peer from realtime storage
04385  * Checks the "sippeers" realtime family from extconfig.conf
04386  * Checks the "sipregs" realtime family from extconfig.conf if it's configured.
04387  * This returns a pointer to a peer and because we use build_peer, we can rest
04388  * assured that the refcount is bumped.
04389 */
04390 static struct sip_peer *realtime_peer(const char *newpeername, struct ast_sockaddr *addr, int devstate_only)
04391 {
04392    struct sip_peer *peer;
04393    struct ast_variable *var = NULL;
04394    struct ast_variable *varregs = NULL;
04395    struct ast_variable *tmp;
04396    struct ast_config *peerlist = NULL;
04397    char ipaddr[INET_ADDRSTRLEN];
04398    char portstring[6]; /*up to 5 digits plus null terminator*/
04399    char *cat = NULL;
04400    int realtimeregs = ast_check_realtime("sipregs");
04401 
04402    /* First check on peer name */
04403    if (newpeername) {
04404       if (realtimeregs)
04405          varregs = ast_load_realtime("sipregs", "name", newpeername, SENTINEL);
04406 
04407       var = ast_load_realtime("sippeers", "name", newpeername, "host", "dynamic", SENTINEL);
04408       if (!var && addr) {
04409          var = ast_load_realtime("sippeers", "name", newpeername, "host", ast_sockaddr_stringify_addr(addr), SENTINEL);
04410       }
04411       if (!var) {
04412          var = ast_load_realtime("sippeers", "name", newpeername, SENTINEL);
04413          /*!\note
04414           * If this one loaded something, then we need to ensure that the host
04415           * field matched.  The only reason why we can't have this as a criteria
04416           * is because we only have the IP address and the host field might be
04417           * set as a name (and the reverse PTR might not match).
04418           */
04419          if (var && addr) {
04420             for (tmp = var; tmp; tmp = tmp->next) {
04421                if (!strcasecmp(tmp->name, "host")) {
04422                   struct ast_sockaddr *addrs = NULL;
04423 
04424                   if (ast_sockaddr_resolve(&addrs,
04425                             tmp->value,
04426                             PARSE_PORT_FORBID,
04427                             get_address_family_filter(&bindaddr)) <= 0 ||
04428                       ast_sockaddr_cmp(&addrs[0], addr)) {
04429                      /* No match */
04430                      ast_variables_destroy(var);
04431                      var = NULL;
04432                   }
04433                   ast_free(addrs);
04434                   break;
04435                }
04436             }
04437          }
04438       }
04439    }
04440 
04441    if (!var && addr) {  /* Then check on IP address for dynamic peers */
04442       ast_copy_string(ipaddr, ast_sockaddr_stringify_addr(addr), sizeof(ipaddr));
04443       ast_copy_string(portstring, ast_sockaddr_stringify_port(addr), sizeof(portstring));
04444       var = ast_load_realtime("sippeers", "host", ipaddr, "port", portstring, SENTINEL);  /* First check for fixed IP hosts */
04445       if (var) {
04446          if (realtimeregs) {
04447             newpeername = get_name_from_variable(var, newpeername);
04448             varregs = ast_load_realtime("sipregs", "name", newpeername, SENTINEL);
04449          }
04450       } else {
04451          if (realtimeregs)
04452             varregs = ast_load_realtime("sipregs", "ipaddr", ipaddr, "port", portstring, SENTINEL); /* Then check for registered hosts */
04453          else
04454             var = ast_load_realtime("sippeers", "ipaddr", ipaddr, "port", portstring, SENTINEL); /* Then check for registered hosts */
04455          if (varregs) {
04456             newpeername = get_name_from_variable(varregs, newpeername);
04457             var = ast_load_realtime("sippeers", "name", newpeername, SENTINEL);
04458          }
04459       }
04460       if (!var) { /*We couldn't match on ipaddress and port, so we need to check if port is insecure*/
04461          peerlist = ast_load_realtime_multientry("sippeers", "host", ipaddr, SENTINEL);
04462          if (peerlist) {
04463             var = get_insecure_variable_from_config(peerlist);
04464             if(var) {
04465                if (realtimeregs) {
04466                   newpeername = get_name_from_variable(var, newpeername);
04467                   varregs = ast_load_realtime("sipregs", "name", newpeername, SENTINEL);
04468                }
04469             } else { /*var wasn't found in the list of "hosts", so try "ipaddr"*/
04470                peerlist = NULL;
04471                cat = NULL;
04472                peerlist = ast_load_realtime_multientry("sippeers", "ipaddr", ipaddr, SENTINEL);
04473                if(peerlist) {
04474                   var = get_insecure_variable_from_config(peerlist);
04475                   if(var) {
04476                      if (realtimeregs) {
04477                         newpeername = get_name_from_variable(var, newpeername);
04478                         varregs = ast_load_realtime("sipregs", "name", newpeername, SENTINEL);
04479                      }
04480                   }
04481                }
04482             }
04483          } else {
04484             if (realtimeregs) {
04485                peerlist = ast_load_realtime_multientry("sipregs", "ipaddr", ipaddr, SENTINEL);
04486                if (peerlist) {
04487                   varregs = get_insecure_variable_from_config(peerlist);
04488                   if (varregs) {
04489                      newpeername = get_name_from_variable(varregs, newpeername);
04490                      var = ast_load_realtime("sippeers", "name", newpeername, SENTINEL);
04491                   }
04492                }
04493             } else {
04494                peerlist = ast_load_realtime_multientry("sippeers", "ipaddr", ipaddr, SENTINEL);
04495                if (peerlist) {
04496                   var = get_insecure_variable_from_config(peerlist);
04497                   if (var) {
04498                      newpeername = get_name_from_variable(var, newpeername);
04499                      varregs = ast_load_realtime("sipregs", "name", newpeername, SENTINEL);
04500                   }
04501                }
04502             }
04503          }
04504       }
04505    }
04506 
04507    if (!var) {
04508       if (peerlist)
04509          ast_config_destroy(peerlist);
04510       return NULL;
04511    }
04512 
04513    for (tmp = var; tmp; tmp = tmp->next) {
04514       if (!newpeername && !strcasecmp(tmp->name, "name")) {
04515          newpeername = tmp->value;
04516       }
04517    }
04518    
04519    if (!newpeername) {  /* Did not find peer in realtime */
04520       ast_log(LOG_WARNING, "Cannot Determine peer name ip=%s\n", ipaddr);
04521       if(peerlist)
04522          ast_config_destroy(peerlist);
04523       else
04524          ast_variables_destroy(var);
04525       return NULL;
04526    }
04527 
04528 
04529    /* Peer found in realtime, now build it in memory */
04530    peer = build_peer(newpeername, var, varregs, TRUE, devstate_only);
04531    if (!peer) {
04532       if(peerlist)
04533          ast_config_destroy(peerlist);
04534       else {
04535          ast_variables_destroy(var);
04536          ast_variables_destroy(varregs);
04537       }
04538       return NULL;
04539    }
04540 
04541    ast_debug(3, "-REALTIME- loading peer from database to memory. Name: %s. Peer objects: %d\n", peer->name, rpeerobjs);
04542 
04543    if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) && !devstate_only) {
04544       /* Cache peer */
04545       ast_copy_flags(&peer->flags[1], &global_flags[1], SIP_PAGE2_RTAUTOCLEAR|SIP_PAGE2_RTCACHEFRIENDS);
04546       if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTAUTOCLEAR)) {
04547          AST_SCHED_REPLACE_UNREF(peer->expire, sched, sip_cfg.rtautoclear * 1000, expire_register, peer,
04548                unref_peer(_data, "remove registration ref"),
04549                unref_peer(peer, "remove registration ref"),
04550                ref_peer(peer, "add registration ref"));
04551       }
04552       ao2_t_link(peers, peer, "link peer into peers table");
04553       if (!ast_sockaddr_isnull(&peer->addr)) {
04554          ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
04555       }
04556    }
04557    peer->is_realtime = 1;
04558    if (peerlist)
04559       ast_config_destroy(peerlist);
04560    else {
04561       ast_variables_destroy(var);
04562       ast_variables_destroy(varregs);
04563    }
04564 
04565    return peer;
04566 }
04567 
04568 /* Function to assist finding peers by name only */
04569 static int find_by_name(void *obj, void *arg, void *data, int flags)
04570 {
04571    struct sip_peer *search = obj, *match = arg;
04572    int *which_objects = data;
04573 
04574    /* Usernames in SIP uri's are case sensitive. Domains are not */
04575    if (strcmp(search->name, match->name)) {
04576       return 0;
04577    }
04578 
04579    switch (*which_objects) {
04580    case FINDUSERS:
04581       if (!(search->type & SIP_TYPE_USER)) {
04582          return 0;
04583       }
04584       break;
04585    case FINDPEERS:
04586       if (!(search->type & SIP_TYPE_PEER)) {
04587          return 0;
04588       }
04589       break;
04590    case FINDALLDEVICES:
04591       break;
04592    }
04593 
04594    return CMP_MATCH | CMP_STOP;
04595 }
04596 
04597 /*!
04598  * \brief Locate device by name or ip address
04599  * \param peer, sin, realtime, devstate_only, transport
04600  * \param which_objects Define which objects should be matched when doing a lookup
04601  *        by name.  Valid options are FINDUSERS, FINDPEERS, or FINDALLDEVICES.
04602  *        Note that this option is not used at all when doing a lookup by IP.
04603  *
04604  * This is used on find matching device on name or ip/port.
04605  * If the device was declared as type=peer, we don't match on peer name on incoming INVITEs.
04606  *
04607  * \note Avoid using this function in new functions if there is a way to avoid it,
04608  * since it might cause a database lookup.
04609  */
04610 static struct sip_peer *find_peer(const char *peer, struct ast_sockaddr *addr, int realtime, int which_objects, int devstate_only, int transport)
04611 {
04612    struct sip_peer *p = NULL;
04613    struct sip_peer tmp_peer;
04614 
04615    if (peer) {
04616       ast_copy_string(tmp_peer.name, peer, sizeof(tmp_peer.name));
04617       p = ao2_t_callback_data(peers, OBJ_POINTER, find_by_name, &tmp_peer, &which_objects, "ao2_find in peers table");
04618    } else if (addr) { /* search by addr? */
04619       ast_sockaddr_copy(&tmp_peer.addr, addr);
04620       tmp_peer.flags[0].flags = 0;
04621       tmp_peer.transports = transport;
04622       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); */
04623       if (!p) {
04624          ast_set_flag(&tmp_peer.flags[0], SIP_INSECURE_PORT);
04625          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); */
04626          if (p) {
04627             return p;
04628          }
04629       }
04630    }
04631 
04632    if (!p && (realtime || devstate_only)) {
04633       p = realtime_peer(peer, addr, devstate_only);
04634       if (p) {
04635          switch (which_objects) {
04636          case FINDUSERS:
04637             if (!(p->type & SIP_TYPE_USER)) {
04638                unref_peer(p, "Wrong type of realtime SIP endpoint");
04639                return NULL;
04640             }
04641             break;
04642          case FINDPEERS:
04643             if (!(p->type & SIP_TYPE_PEER)) {
04644                unref_peer(p, "Wrong type of realtime SIP endpoint");
04645                return NULL;
04646             }
04647             break;
04648          case FINDALLDEVICES:
04649             break;
04650          }
04651       }
04652    }
04653 
04654    return p;
04655 }
04656 
04657 /*! \brief Set nat mode on the various data sockets */
04658 static void do_setnat(struct sip_pvt *p)
04659 {
04660    const char *mode;
04661    int natflags;
04662 
04663    natflags = ast_test_flag(&p->flags[1], SIP_PAGE2_SYMMETRICRTP);
04664    mode = natflags ? "On" : "Off";
04665 
04666    if (p->rtp) {
04667       ast_debug(1, "Setting NAT on RTP to %s\n", mode);
04668       ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_NAT, natflags);
04669    }
04670    if (p->vrtp) {
04671       ast_debug(1, "Setting NAT on VRTP to %s\n", mode);
04672       ast_rtp_instance_set_prop(p->vrtp, AST_RTP_PROPERTY_NAT, natflags);
04673    }
04674    if (p->udptl) {
04675       ast_debug(1, "Setting NAT on UDPTL to %s\n", mode);
04676       ast_udptl_setnat(p->udptl, natflags);
04677    }
04678    if (p->trtp) {
04679       ast_debug(1, "Setting NAT on TRTP to %s\n", mode);
04680       ast_rtp_instance_set_prop(p->trtp, AST_RTP_PROPERTY_NAT, natflags);
04681    }
04682 }
04683 
04684 /*! \brief Change the T38 state on a SIP dialog */
04685 static void change_t38_state(struct sip_pvt *p, int state)
04686 {
04687    int old = p->t38.state;
04688    struct ast_channel *chan = p->owner;
04689    struct ast_control_t38_parameters parameters = { .request_response = 0 };
04690 
04691    /* Don't bother changing if we are already in the state wanted */
04692    if (old == state)
04693       return;
04694 
04695    p->t38.state = state;
04696    ast_debug(2, "T38 state changed to %d on channel %s\n", p->t38.state, chan ? chan->name : "<none>");
04697 
04698    /* If no channel was provided we can't send off a control frame */
04699    if (!chan)
04700       return;
04701 
04702    /* Given the state requested and old state determine what control frame we want to queue up */
04703    switch (state) {
04704    case T38_PEER_REINVITE:
04705       parameters = p->t38.their_parms;
04706       parameters.max_ifp = ast_udptl_get_far_max_ifp(p->udptl);
04707       parameters.request_response = AST_T38_REQUEST_NEGOTIATE;
04708       ast_udptl_set_tag(p->udptl, "SIP/%s", p->username);
04709       break;
04710    case T38_ENABLED:
04711       parameters = p->t38.their_parms;
04712       parameters.max_ifp = ast_udptl_get_far_max_ifp(p->udptl);
04713       parameters.request_response = AST_T38_NEGOTIATED;
04714       ast_udptl_set_tag(p->udptl, "SIP/%s", p->username);
04715       break;
04716    case T38_DISABLED:
04717       if (old == T38_ENABLED) {
04718          parameters.request_response = AST_T38_TERMINATED;
04719       } else if (old == T38_LOCAL_REINVITE) {
04720          parameters.request_response = AST_T38_REFUSED;
04721       }
04722       break;
04723    case T38_LOCAL_REINVITE:
04724       /* wait until we get a peer response before responding to local reinvite */
04725       break;
04726    }
04727 
04728    /* Woot we got a message, create a control frame and send it on! */
04729    if (parameters.request_response)
04730       ast_queue_control_data(chan, AST_CONTROL_T38_PARAMETERS, &parameters, sizeof(parameters));
04731 }
04732 
04733 /*! \brief Set the global T38 capabilities on a SIP dialog structure */
04734 static void set_t38_capabilities(struct sip_pvt *p)
04735 {
04736    if (p->udptl) {
04737       if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) == SIP_PAGE2_T38SUPPORT_UDPTL_REDUNDANCY) {
04738                         ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_REDUNDANCY);
04739       } else if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) == SIP_PAGE2_T38SUPPORT_UDPTL_FEC) {
04740          ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_FEC);
04741       } else if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) == SIP_PAGE2_T38SUPPORT_UDPTL) {
04742          ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_NONE);
04743       }
04744    }
04745 }
04746 
04747 static void copy_socket_data(struct sip_socket *to_sock, const struct sip_socket *from_sock)
04748 {
04749    if (to_sock->tcptls_session) {
04750       ao2_ref(to_sock->tcptls_session, -1);
04751       to_sock->tcptls_session = NULL;
04752    }
04753 
04754    if (from_sock->tcptls_session) {
04755       ao2_ref(from_sock->tcptls_session, +1);
04756    }
04757 
04758    *to_sock = *from_sock;
04759 }
04760 
04761 /*! \brief Initialize RTP portion of a dialog
04762  * \return -1 on failure, 0 on success
04763  */
04764 static int dialog_initialize_rtp(struct sip_pvt *dialog)
04765 {
04766    struct ast_sockaddr bindaddr_tmp;
04767 
04768    if (!sip_methods[dialog->method].need_rtp) {
04769       return 0;
04770    }
04771 
04772    ast_sockaddr_copy(&bindaddr_tmp, &bindaddr);
04773    if (!(dialog->rtp = ast_rtp_instance_new(dialog->engine, sched, &bindaddr_tmp, NULL))) {
04774       return -1;
04775    }
04776 
04777    if (ast_test_flag(&dialog->flags[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS) ||
04778          (ast_test_flag(&dialog->flags[1], SIP_PAGE2_VIDEOSUPPORT) && (dialog->capability & AST_FORMAT_VIDEO_MASK))) {
04779       if (!(dialog->vrtp = ast_rtp_instance_new(dialog->engine, sched, &bindaddr_tmp, NULL))) {
04780          return -1;
04781       }
04782       ast_rtp_instance_set_timeout(dialog->vrtp, global_rtptimeout);
04783       ast_rtp_instance_set_hold_timeout(dialog->vrtp, global_rtpholdtimeout);
04784 
04785       ast_rtp_instance_set_prop(dialog->vrtp, AST_RTP_PROPERTY_RTCP, 1);
04786    }
04787 
04788    if (ast_test_flag(&dialog->flags[1], SIP_PAGE2_TEXTSUPPORT)) {
04789       if (!(dialog->trtp = ast_rtp_instance_new(dialog->engine, sched, &bindaddr_tmp, NULL))) {
04790          return -1;
04791       }
04792       ast_rtp_instance_set_timeout(dialog->trtp, global_rtptimeout);
04793       ast_rtp_instance_set_hold_timeout(dialog->trtp, global_rtpholdtimeout);
04794 
04795       ast_rtp_instance_set_prop(dialog->trtp, AST_RTP_PROPERTY_RTCP, 1);
04796    }
04797 
04798    ast_rtp_instance_set_timeout(dialog->rtp, global_rtptimeout);
04799    ast_rtp_instance_set_hold_timeout(dialog->rtp, global_rtpholdtimeout);
04800 
04801    ast_rtp_instance_set_prop(dialog->rtp, AST_RTP_PROPERTY_RTCP, 1);
04802    ast_rtp_instance_set_prop(dialog->rtp, AST_RTP_PROPERTY_DTMF, ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
04803    ast_rtp_instance_set_prop(dialog->rtp, AST_RTP_PROPERTY_DTMF_COMPENSATE, ast_test_flag(&dialog->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
04804 
04805    ast_rtp_instance_set_qos(dialog->rtp, global_tos_audio, global_cos_audio, "SIP RTP");
04806 
04807    do_setnat(dialog);
04808 
04809    return 0;
04810 }
04811 
04812 /*! \brief Create address structure from peer reference.
04813  * This function copies data from peer to the dialog, so we don't have to look up the peer
04814  * again from memory or database during the life time of the dialog.
04815  *
04816  * \return -1 on error, 0 on success.
04817  *
04818  */
04819 static int create_addr_from_peer(struct sip_pvt *dialog, struct sip_peer *peer)
04820 {
04821    /* this checks that the dialog is contacting the peer on a valid
04822     * transport type based on the peers transport configuration,
04823     * otherwise, this function bails out */
04824    if (dialog->socket.type && check_request_transport(peer, dialog))
04825       return -1;
04826    copy_socket_data(&dialog->socket, &peer->socket);
04827 
04828    if (!(ast_sockaddr_isnull(&peer->addr) && ast_sockaddr_isnull(&peer->defaddr)) &&
04829        (!peer->maxms || ((peer->lastms >= 0)  && (peer->lastms <= peer->maxms)))) {
04830       dialog->sa = ast_sockaddr_isnull(&peer->addr) ? peer->defaddr : peer->addr;
04831       dialog->recv = dialog->sa;
04832    } else
04833       return -1;
04834 
04835    /* XXX TODO: get flags directly from peer only as they are needed using dialog->relatedpeer */
04836    ast_copy_flags(&dialog->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
04837    ast_copy_flags(&dialog->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
04838    ast_copy_flags(&dialog->flags[2], &peer->flags[2], SIP_PAGE3_FLAGS_TO_COPY);
04839    dialog->capability = peer->capability;
04840    dialog->prefs = peer->prefs;
04841    if (ast_test_flag(&dialog->flags[1], SIP_PAGE2_T38SUPPORT)) {
04842       /* t38pt_udptl was enabled in the peer and not in [general] */
04843       if (dialog->udptl || (!dialog->udptl && (dialog->udptl = ast_udptl_new_with_bindaddr(sched, io, 0, &bindaddr)))) {
04844          dialog->t38_maxdatagram = peer->t38_maxdatagram;
04845          set_t38_capabilities(dialog);
04846       } else {
04847          /* It is impossible to support T38 without udptl */
04848          ast_debug(1, "UDPTL creation failed on dialog.\n");
04849          ast_clear_flag(&dialog->flags[1], SIP_PAGE2_T38SUPPORT);
04850       }
04851    } else if (dialog->udptl) {
04852       ast_udptl_destroy(dialog->udptl);
04853       dialog->udptl = NULL;
04854    }
04855 
04856    ast_string_field_set(dialog, engine, peer->engine);
04857 
04858    if (dialog_initialize_rtp(dialog)) {
04859       return -1;
04860    }
04861 
04862    if (dialog->rtp) { /* Audio */
04863       ast_rtp_instance_set_prop(dialog->rtp, AST_RTP_PROPERTY_DTMF, ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
04864       ast_rtp_instance_set_prop(dialog->rtp, AST_RTP_PROPERTY_DTMF_COMPENSATE, ast_test_flag(&dialog->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
04865       ast_rtp_instance_set_timeout(dialog->rtp, peer->rtptimeout);
04866       ast_rtp_instance_set_hold_timeout(dialog->rtp, peer->rtpholdtimeout);
04867       /* Set Frame packetization */
04868       ast_rtp_codecs_packetization_set(ast_rtp_instance_get_codecs(dialog->rtp), dialog->rtp, &dialog->prefs);
04869       dialog->autoframing = peer->autoframing;
04870    }
04871    if (dialog->vrtp) { /* Video */
04872       ast_rtp_instance_set_timeout(dialog->vrtp, peer->rtptimeout);
04873       ast_rtp_instance_set_hold_timeout(dialog->vrtp, peer->rtpholdtimeout);
04874    }
04875    if (dialog->trtp) { /* Realtime text */
04876       ast_rtp_instance_set_timeout(dialog->trtp, peer->rtptimeout);
04877       ast_rtp_instance_set_hold_timeout(dialog->trtp, peer->rtpholdtimeout);
04878    }
04879 
04880    /* XXX TODO: get fields directly from peer only as they are needed using dialog->relatedpeer */
04881    ast_string_field_set(dialog, peername, peer->name);
04882    ast_string_field_set(dialog, authname, peer->username);
04883    ast_string_field_set(dialog, username, peer->username);
04884    ast_string_field_set(dialog, peersecret, peer->secret);
04885    ast_string_field_set(dialog, peermd5secret, peer->md5secret);
04886    ast_string_field_set(dialog, mohsuggest, peer->mohsuggest);
04887    ast_string_field_set(dialog, mohinterpret, peer->mohinterpret);
04888    ast_string_field_set(dialog, tohost, peer->tohost);
04889    ast_string_field_set(dialog, fullcontact, peer->fullcontact);
04890    ast_string_field_set(dialog, accountcode, peer->accountcode);
04891    ast_string_field_set(dialog, context, peer->context);
04892    ast_string_field_set(dialog, cid_num, peer->cid_num);
04893    ast_string_field_set(dialog, cid_name, peer->cid_name);
04894    ast_string_field_set(dialog, cid_tag, peer->cid_tag);
04895    ast_string_field_set(dialog, mwi_from, peer->mwi_from);
04896    if (!ast_strlen_zero(peer->parkinglot)) {
04897       ast_string_field_set(dialog, parkinglot, peer->parkinglot);
04898    }
04899    ast_string_field_set(dialog, engine, peer->engine);
04900    ref_proxy(dialog, obproxy_get(dialog, peer));
04901    dialog->callgroup = peer->callgroup;
04902    dialog->pickupgroup = peer->pickupgroup;
04903    dialog->allowtransfer = peer->allowtransfer;
04904    dialog->jointnoncodeccapability = dialog->noncodeccapability;
04905    dialog->rtptimeout = peer->rtptimeout;
04906    dialog->peerauth = peer->auth;
04907    dialog->maxcallbitrate = peer->maxcallbitrate;
04908    dialog->disallowed_methods = peer->disallowed_methods;
04909    ast_cc_copy_config_params(dialog->cc_params, peer->cc_params);
04910    if (ast_strlen_zero(dialog->tohost))
04911       ast_string_field_set(dialog, tohost, ast_sockaddr_stringify_host(&dialog->sa));
04912    if (!ast_strlen_zero(peer->fromdomain)) {
04913       ast_string_field_set(dialog, fromdomain, peer->fromdomain);
04914       if (!dialog->initreq.headers) {
04915          char *c;
04916          char *tmpcall = ast_strdupa(dialog->callid);
04917          /* this sure looks to me like we are going to change the callid on this dialog!! */
04918          c = strchr(tmpcall, '@');
04919          if (c) {
04920             *c = '\0';
04921             ao2_t_unlink(dialogs, dialog, "About to change the callid -- remove the old name");
04922             ast_string_field_build(dialog, callid, "%s@%s", tmpcall, peer->fromdomain);
04923             ao2_t_link(dialogs, dialog, "New dialog callid -- inserted back into table");
04924          }
04925       }
04926    }
04927    if (!ast_strlen_zero(peer->fromuser))
04928       ast_string_field_set(dialog, fromuser, peer->fromuser);
04929    if (!ast_strlen_zero(peer->language))
04930       ast_string_field_set(dialog, language, peer->language);
04931    /* Set timer T1 to RTT for this peer (if known by qualify=) */
04932    /* Minimum is settable or default to 100 ms */
04933    /* If there is a maxms and lastms from a qualify use that over a manual T1
04934       value. Otherwise, use the peer's T1 value. */
04935    if (peer->maxms && peer->lastms)
04936       dialog->timer_t1 = peer->lastms < global_t1min ? global_t1min : peer->lastms;
04937    else
04938       dialog->timer_t1 = peer->timer_t1;
04939 
04940    /* Set timer B to control transaction timeouts, the peer setting is the default and overrides
04941       the known timer */
04942    if (peer->timer_b)
04943       dialog->timer_b = peer->timer_b;
04944    else
04945       dialog->timer_b = 64 * dialog->timer_t1;
04946 
04947    if ((ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
04948        (ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
04949       dialog->noncodeccapability |= AST_RTP_DTMF;
04950    else
04951       dialog->noncodeccapability &= ~AST_RTP_DTMF;
04952    dialog->directmediaha = ast_duplicate_ha_list(peer->directmediaha);
04953    if (peer->call_limit)
04954       ast_set_flag(&dialog->flags[0], SIP_CALL_LIMIT);
04955    if (!dialog->portinuri)
04956       dialog->portinuri = peer->portinuri;
04957    dialog->chanvars = copy_vars(peer->chanvars);
04958    if (peer->fromdomainport)
04959       dialog->fromdomainport = peer->fromdomainport;
04960 
04961    return 0;
04962 }
04963 
04964 /*! \brief create address structure from device name
04965  *      Or, if peer not found, find it in the global DNS
04966  *      returns TRUE (-1) on failure, FALSE on success */
04967 static int create_addr(struct sip_pvt *dialog, const char *opeer, struct ast_sockaddr *addr, int newdialog, struct ast_sockaddr *remote_address)
04968 {
04969    struct sip_peer *peer;
04970    char *peername, *peername2, *hostn;
04971    char host[MAXHOSTNAMELEN];
04972    char service[MAXHOSTNAMELEN];
04973    int srv_ret = 0;
04974    int tportno;
04975 
04976    AST_DECLARE_APP_ARGS(hostport,
04977       AST_APP_ARG(host);
04978       AST_APP_ARG(port);
04979    );
04980 
04981    peername = ast_strdupa(opeer);
04982    peername2 = ast_strdupa(opeer);
04983    AST_NONSTANDARD_RAW_ARGS(hostport, peername2, ':');
04984 
04985    if (hostport.port)
04986       dialog->portinuri = 1;
04987 
04988    dialog->timer_t1 = global_t1; /* Default SIP retransmission timer T1 (RFC 3261) */
04989    dialog->timer_b = global_timer_b; /* Default SIP transaction timer B (RFC 3261) */
04990    peer = find_peer(peername, NULL, TRUE, FINDPEERS, FALSE, 0);
04991 
04992    if (peer) {
04993       int res;
04994       if (newdialog) {
04995          set_socket_transport(&dialog->socket, 0);
04996       }
04997       res = create_addr_from_peer(dialog, peer);
04998       if (!ast_sockaddr_isnull(remote_address)) {
04999          ast_sockaddr_copy(&dialog->sa, remote_address);
05000       }
05001       dialog->relatedpeer = ref_peer(peer, "create_addr: setting dialog's relatedpeer pointer");
05002       unref_peer(peer, "create_addr: unref peer from find_peer hashtab lookup");
05003       return res;
05004    }
05005 
05006    if (dialog_initialize_rtp(dialog)) {
05007       return -1;
05008    }
05009 
05010    ast_string_field_set(dialog, tohost, hostport.host);
05011    dialog->allowed_methods &= ~sip_cfg.disallowed_methods;
05012 
05013    /* Get the outbound proxy information */
05014    ref_proxy(dialog, obproxy_get(dialog, NULL));
05015 
05016    if (addr) {
05017       /* This address should be updated using dnsmgr */
05018       ast_sockaddr_copy(&dialog->sa, addr);
05019    } else {
05020 
05021       /* Let's see if we can find the host in DNS. First try DNS SRV records,
05022          then hostname lookup */
05023       /*! \todo Fix this function. When we ask for SRV, we should check all transports
05024            In the future, we should first check NAPTR to find out transport preference
05025        */
05026       hostn = peername;
05027       /* Section 4.2 of RFC 3263 specifies that if a port number is specified, then
05028        * an A record lookup should be used instead of SRV.
05029        */
05030       if (!hostport.port && sip_cfg.srvlookup) {
05031          snprintf(service, sizeof(service), "_%s._%s.%s", 
05032              get_srv_service(dialog->socket.type),
05033              get_srv_protocol(dialog->socket.type), peername);
05034          if ((srv_ret = ast_get_srv(NULL, host, sizeof(host), &tportno,
05035                      service)) > 0) {
05036             hostn = host;
05037          }
05038       }
05039 
05040       if (ast_sockaddr_resolve_first(&dialog->sa, hostn, 0)) {
05041          ast_log(LOG_WARNING, "No such host: %s\n", peername);
05042       }
05043 
05044       if (srv_ret > 0) {
05045          ast_sockaddr_set_port(&dialog->sa, tportno);
05046       }
05047    }
05048 
05049    if (!dialog->socket.type)
05050       set_socket_transport(&dialog->socket, SIP_TRANSPORT_UDP);
05051    if (!dialog->socket.port) {
05052       dialog->socket.port = htons(ast_sockaddr_port(&bindaddr));
05053    }
05054 
05055    if (!ast_sockaddr_port(&dialog->sa)) {
05056       ast_sockaddr_set_port(&dialog->sa,
05057                   (dialog->socket.type == SIP_TRANSPORT_TLS) ?
05058                   STANDARD_TLS_PORT : STANDARD_SIP_PORT);
05059    }
05060    ast_sockaddr_copy(&dialog->recv, &dialog->sa);
05061    return 0;
05062 }
05063 
05064 /*! \brief Scheduled congestion on a call.
05065  * Only called by the scheduler, must return the reference when done.
05066  */
05067 static int auto_congest(const void *arg)
05068 {
05069    struct sip_pvt *p = (struct sip_pvt *)arg;
05070 
05071    sip_pvt_lock(p);
05072    p->initid = -1;   /* event gone, will not be rescheduled */
05073    if (p->owner) {
05074       /* XXX fails on possible deadlock */
05075       if (!ast_channel_trylock(p->owner)) {
05076          append_history(p, "Cong", "Auto-congesting (timer)");
05077          ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
05078          ast_channel_unlock(p->owner);
05079       }
05080 
05081       /* Give the channel a chance to act before we proceed with destruction */
05082       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
05083    }
05084    sip_pvt_unlock(p);
05085    dialog_unref(p, "unreffing arg passed into auto_congest callback (p->initid)");
05086    return 0;
05087 }
05088 
05089 
05090 /*! \brief Initiate SIP call from PBX
05091  *      used from the dial() application      */
05092 static int sip_call(struct ast_channel *ast, char *dest, int timeout)
05093 {
05094    int res;
05095    struct sip_pvt *p = ast->tech_pvt;  /* chan is locked, so the reference cannot go away */
05096    struct varshead *headp;
05097    struct ast_var_t *current;
05098    const char *referer = NULL;   /* SIP referrer */
05099    int cc_core_id;
05100    char uri[SIPBUFSIZE] = "";
05101 
05102    if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
05103       ast_log(LOG_WARNING, "sip_call called on %s, neither down nor reserved\n", ast->name);
05104       return -1;
05105    }
05106 
05107    if (ast_cc_is_recall(ast, &cc_core_id, "SIP")) {
05108       char device_name[AST_CHANNEL_NAME];
05109       struct ast_cc_monitor *recall_monitor;
05110       struct sip_monitor_instance *monitor_instance;
05111       ast_channel_get_device_name(ast, device_name, sizeof(device_name));
05112       if ((recall_monitor = ast_cc_get_monitor_by_recall_core_id(cc_core_id, device_name))) {
05113          monitor_instance = recall_monitor->private_data;
05114          ast_copy_string(uri, monitor_instance->notify_uri, sizeof(uri));
05115          ao2_t_ref(recall_monitor, -1, "Got the URI we need so unreffing monitor");
05116       }
05117    }
05118 
05119    /* Check whether there is vxml_url, distinctive ring variables */
05120    headp=&ast->varshead;
05121    AST_LIST_TRAVERSE(headp, current, entries) {
05122       /* Check whether there is a VXML_URL variable */
05123       if (!p->options->vxml_url && !strcasecmp(ast_var_name(current), "VXML_URL")) {
05124          p->options->vxml_url = ast_var_value(current);
05125       } else if (!p->options->uri_options && !strcasecmp(ast_var_name(current), "SIP_URI_OPTIONS")) {
05126          p->options->uri_options = ast_var_value(current);
05127       } else if (!p->options->addsipheaders && !strncasecmp(ast_var_name(current), "SIPADDHEADER", strlen("SIPADDHEADER"))) {
05128          /* Check whether there is a variable with a name starting with SIPADDHEADER */
05129          p->options->addsipheaders = 1;
05130       } else if (!strcasecmp(ast_var_name(current), "SIPFROMDOMAIN")) {
05131          ast_string_field_set(p, fromdomain, ast_var_value(current));
05132       } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER")) {
05133          /* This is a transfered call */
05134          p->options->transfer = 1;
05135       } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER_REFERER")) {
05136          /* This is the referrer */
05137          referer = ast_var_value(current);
05138       } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER_REPLACES")) {
05139          /* We're replacing a call. */
05140          p->options->replaces = ast_var_value(current);
05141       }
05142    }
05143 
05144    /* Check to see if we should try to force encryption */
05145    if (p->req_secure_signaling && p->socket.type != SIP_TRANSPORT_TLS) {
05146       ast_log(LOG_WARNING, "Encrypted signaling is required\n");
05147       ast->hangupcause = AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
05148       return -1;
05149    }
05150 
05151    if (ast_test_flag(&p->flags[1], SIP_PAGE2_USE_SRTP)) {
05152       if (ast_test_flag(&p->flags[0], SIP_REINVITE)) {
05153          ast_debug(1, "Direct media not possible when using SRTP, ignoring canreinvite setting\n");
05154          ast_clear_flag(&p->flags[0], SIP_REINVITE);
05155       }
05156 
05157       if (p->rtp && !p->srtp && setup_srtp(&p->srtp) < 0) {
05158          ast_log(LOG_WARNING, "SRTP audio setup failed\n");
05159          return -1;
05160       }
05161 
05162       if (p->vrtp && !p->vsrtp && setup_srtp(&p->vsrtp) < 0) {
05163          ast_log(LOG_WARNING, "SRTP video setup failed\n");
05164          return -1;
05165       }
05166 
05167       if (p->trtp && !p->vsrtp && setup_srtp(&p->tsrtp) < 0) {
05168          ast_log(LOG_WARNING, "SRTP text setup failed\n");
05169          return -1;
05170       }
05171    }
05172 
05173    res = 0;
05174    ast_set_flag(&p->flags[0], SIP_OUTGOING);
05175 
05176    /* T.38 re-INVITE FAX detection should never be done for outgoing calls,
05177     * so ensure it is disabled.
05178     */
05179    ast_clear_flag(&p->flags[1], SIP_PAGE2_FAX_DETECT_T38);
05180 
05181    if (p->options->transfer) {
05182       char buf[SIPBUFSIZE/2];
05183 
05184       if (referer) {
05185          if (sipdebug)
05186             ast_debug(3, "Call for %s transfered by %s\n", p->username, referer);
05187          snprintf(buf, sizeof(buf)-1, "-> %s (via %s)", p->cid_name, referer);
05188       } else
05189          snprintf(buf, sizeof(buf)-1, "-> %s", p->cid_name);
05190       ast_string_field_set(p, cid_name, buf);
05191    }
05192    ast_debug(1, "Outgoing Call for %s\n", p->username);
05193 
05194    res = update_call_counter(p, INC_CALL_RINGING);
05195 
05196    if (res == -1) {
05197       ast->hangupcause = AST_CAUSE_USER_BUSY;
05198       return res;
05199    }
05200    p->callingpres = ast_party_id_presentation(&ast->caller.id);
05201    p->jointcapability = ast_rtp_instance_available_formats(p->rtp, p->capability, p->prefcodec);
05202    p->jointnoncodeccapability = p->noncodeccapability;
05203 
05204    /* If there are no audio formats left to offer, punt */
05205    if (!(p->jointcapability & AST_FORMAT_AUDIO_MASK)) {
05206       ast_log(LOG_WARNING, "No audio format found to offer. Cancelling call to %s\n", p->username);
05207       res = -1;
05208    } else {
05209       int xmitres;
05210 
05211       sip_pvt_lock(p);
05212       xmitres = transmit_invite(p, SIP_INVITE, 1, 2, uri);
05213       sip_pvt_unlock(p);
05214       if (xmitres == XMIT_ERROR)
05215          return -1;
05216       p->invitestate = INV_CALLING;
05217 
05218       /* Initialize auto-congest time */
05219       AST_SCHED_REPLACE_UNREF(p->initid, sched, p->timer_b, auto_congest, p,
05220                         dialog_unref(_data, "dialog ptr dec when SCHED_REPLACE del op succeeded"),
05221                         dialog_unref(p, "dialog ptr dec when SCHED_REPLACE add failed"),
05222                         dialog_ref(p, "dialog ptr inc when SCHED_REPLACE add succeeded") );
05223    }
05224    return res;
05225 }
05226 
05227 /*! \brief Destroy registry object
05228    Objects created with the register= statement in static configuration */
05229 static void sip_registry_destroy(struct sip_registry *reg)
05230 {
05231    /* Really delete */
05232    ast_debug(3, "Destroying registry entry for %s@%s\n", reg->username, reg->hostname);
05233 
05234    if (reg->call) {
05235       /* Clear registry before destroying to ensure
05236          we don't get reentered trying to grab the registry lock */
05237       reg->call->registry = registry_unref(reg->call->registry, "destroy reg->call->registry");
05238       ast_debug(3, "Destroying active SIP dialog for registry %s@%s\n", reg->username, reg->hostname);
05239       dialog_unlink_all(reg->call, TRUE, TRUE);
05240       reg->call = dialog_unref(reg->call, "unref reg->call");
05241       /* reg->call = sip_destroy(reg->call); */
05242    }
05243    AST_SCHED_DEL(sched, reg->expire);  
05244    AST_SCHED_DEL(sched, reg->timeout);
05245    
05246    ast_string_field_free_memory(reg);
05247    ast_atomic_fetchadd_int(&regobjs, -1);
05248    ast_dnsmgr_release(reg->dnsmgr);
05249    ast_free(reg);
05250 }
05251 
05252 /*! \brief Destroy MWI subscription object */
05253 static void sip_subscribe_mwi_destroy(struct sip_subscription_mwi *mwi)
05254 {
05255    if (mwi->call) {
05256       mwi->call->mwi = NULL;
05257       sip_destroy(mwi->call);
05258    }
05259    
05260    AST_SCHED_DEL(sched, mwi->resub);
05261    ast_string_field_free_memory(mwi);
05262    ast_dnsmgr_release(mwi->dnsmgr);
05263    ast_free(mwi);
05264 }
05265 
05266 /*! \brief Execute destruction of SIP dialog structure, release memory */
05267 void __sip_destroy(struct sip_pvt *p, int lockowner, int lockdialoglist)
05268 {
05269    struct sip_request *req;
05270 
05271    if (p->stimer) {
05272       ast_free(p->stimer);
05273       p->stimer = NULL;
05274    }
05275 
05276    if (sip_debug_test_pvt(p))
05277       ast_verbose("Really destroying SIP dialog '%s' Method: %s\n", p->callid, sip_methods[p->method].text);
05278 
05279    if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
05280       update_call_counter(p, DEC_CALL_LIMIT);
05281       ast_debug(2, "This call did not properly clean up call limits. Call ID %s\n", p->callid);
05282    }
05283 
05284    /* Unlink us from the owner if we have one */
05285    if (p->owner) {
05286       if (lockowner)
05287          ast_channel_lock(p->owner);
05288       ast_debug(1, "Detaching from %s\n", p->owner->name);
05289       p->owner->tech_pvt = NULL;
05290       /* Make sure that the channel knows its backend is going away */
05291       p->owner->_softhangup |= AST_SOFTHANGUP_DEV;
05292       if (lockowner)
05293          ast_channel_unlock(p->owner);
05294       /* Give the channel a chance to react before deallocation */
05295       usleep(1);
05296    }
05297 
05298    /* Remove link from peer to subscription of MWI */
05299    if (p->relatedpeer && p->relatedpeer->mwipvt)
05300       p->relatedpeer->mwipvt = dialog_unref(p->relatedpeer->mwipvt, "delete ->relatedpeer->mwipvt");
05301    if (p->relatedpeer && p->relatedpeer->call == p)
05302       p->relatedpeer->call = dialog_unref(p->relatedpeer->call, "unset the relatedpeer->call field in tandem with relatedpeer field itself");
05303    
05304    if (p->relatedpeer)
05305       p->relatedpeer = unref_peer(p->relatedpeer,"unsetting a dialog relatedpeer field in sip_destroy");
05306    
05307    if (p->registry) {
05308       if (p->registry->call == p)
05309          p->registry->call = dialog_unref(p->registry->call, "nulling out the registry's call dialog field in unlink_all");
05310       p->registry = registry_unref(p->registry, "delete p->registry");
05311    }
05312    
05313    if (p->mwi) {
05314       p->mwi->call = NULL;
05315    }
05316 
05317    if (dumphistory)
05318       sip_dump_history(p);
05319 
05320    if (p->options)
05321       ast_free(p->options);
05322 
05323    if (p->notify) {
05324       ast_variables_destroy(p->notify->headers);
05325       ast_free(p->notify->content);
05326       ast_free(p->notify);
05327    }
05328    if (p->rtp) {
05329       ast_rtp_instance_destroy(p->rtp);
05330    }
05331    if (p->vrtp) {
05332       ast_rtp_instance_destroy(p->vrtp);
05333    }
05334    if (p->trtp) {
05335       ast_rtp_instance_destroy(p->trtp);
05336    }
05337    if (p->udptl)
05338       ast_udptl_destroy(p->udptl);
05339    if (p->refer)
05340       ast_free(p->refer);
05341    if (p->route) {
05342       free_old_route(p->route);
05343       p->route = NULL;
05344    }
05345    deinit_req(&p->initreq);
05346 
05347    /* Destroy Session-Timers if allocated */
05348    if (p->stimer) {
05349       p->stimer->quit_flag = 1;
05350       if (p->stimer->st_active == TRUE && p->stimer->st_schedid > -1) {
05351          AST_SCHED_DEL_UNREF(sched, p->stimer->st_schedid,
05352                dialog_unref(p, "removing session timer ref"));
05353       }
05354       ast_free(p->stimer);
05355       p->stimer = NULL;
05356    }
05357 
05358    /* Clear history */
05359    if (p->history) {
05360       struct sip_history *hist;
05361       while ( (hist = AST_LIST_REMOVE_HEAD(p->history, list)) ) {
05362          ast_free(hist);
05363          p->history_entries--;
05364       }
05365       ast_free(p->history);
05366       p->history = NULL;
05367    }
05368 
05369    while ((req = AST_LIST_REMOVE_HEAD(&p->request_queue, next))) {
05370       ast_free(req);
05371    }
05372 
05373    if (p->chanvars) {
05374       ast_variables_destroy(p->chanvars);
05375       p->chanvars = NULL;
05376    }
05377 
05378    if (p->srtp) {
05379       sip_srtp_destroy(p->srtp);
05380       p->srtp = NULL;
05381    }
05382 
05383    if (p->vsrtp) {
05384       sip_srtp_destroy(p->vsrtp);
05385       p->vsrtp = NULL;
05386    }
05387 
05388    if (p->tsrtp) {
05389       sip_srtp_destroy(p->tsrtp);
05390       p->tsrtp = NULL;
05391    }
05392 
05393    if (p->directmediaha) {
05394       ast_free_ha(p->directmediaha);
05395       p->directmediaha = NULL;
05396    }
05397 
05398    ast_string_field_free_memory(p);
05399 
05400    ast_cc_config_params_destroy(p->cc_params);
05401 
05402    if (p->epa_entry) {
05403       ao2_ref(p->epa_entry, -1);
05404       p->epa_entry = NULL;
05405    }
05406 
05407    if (p->socket.tcptls_session) {
05408       ao2_ref(p->socket.tcptls_session, -1);
05409       p->socket.tcptls_session = NULL;
05410    }
05411 }
05412 
05413 /*! \brief  update_call_counter: Handle call_limit for SIP devices
05414  * Setting a call-limit will cause calls above the limit not to be accepted.
05415  *
05416  * Remember that for a type=friend, there's one limit for the user and
05417  * another for the peer, not a combined call limit.
05418  * This will cause unexpected behaviour in subscriptions, since a "friend"
05419  * is *two* devices in Asterisk, not one.
05420  *
05421  * Thought: For realtime, we should probably update storage with inuse counter...
05422  *
05423  * \return 0 if call is ok (no call limit, below threshold)
05424  * -1 on rejection of call
05425  *
05426  */
05427 static int update_call_counter(struct sip_pvt *fup, int event)
05428 {
05429    char name[256];
05430    int *inuse = NULL, *call_limit = NULL, *inringing = NULL;
05431    int outgoing = fup->outgoing_call;
05432    struct sip_peer *p = NULL;
05433 
05434    ast_debug(3, "Updating call counter for %s call\n", outgoing ? "outgoing" : "incoming");
05435 
05436 
05437    /* Test if we need to check call limits, in order to avoid
05438       realtime lookups if we do not need it */
05439    if (!ast_test_flag(&fup->flags[0], SIP_CALL_LIMIT) && !ast_test_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD))
05440       return 0;
05441 
05442    ast_copy_string(name, fup->username, sizeof(name));
05443 
05444    /* Check the list of devices */
05445    if (fup->relatedpeer) {
05446       p = ref_peer(fup->relatedpeer, "ref related peer for update_call_counter");
05447       inuse = &p->inUse;
05448       call_limit = &p->call_limit;
05449       inringing = &p->inRinging;
05450       ast_copy_string(name, fup->peername, sizeof(name));
05451    }
05452    if (!p) {
05453       ast_debug(2, "%s is not a local device, no call limit\n", name);
05454       return 0;
05455    }
05456 
05457    switch(event) {
05458    /* incoming and outgoing affects the inUse counter */
05459    case DEC_CALL_LIMIT:
05460       /* Decrement inuse count if applicable */
05461       if (inuse) {
05462          sip_pvt_lock(fup);
05463          ao2_lock(p);
05464          if (*inuse > 0) {
05465             if (ast_test_flag(&fup->flags[0], SIP_INC_COUNT)) {
05466                (*inuse)--;
05467                ast_clear_flag(&fup->flags[0], SIP_INC_COUNT);
05468             }
05469          } else {
05470             *inuse = 0;
05471          }
05472          ao2_unlock(p);
05473          sip_pvt_unlock(fup);
05474       }
05475 
05476       /* Decrement ringing count if applicable */
05477       if (inringing) {
05478          sip_pvt_lock(fup);
05479          ao2_lock(p);
05480          if (*inringing > 0) {
05481             if (ast_test_flag(&fup->flags[0], SIP_INC_RINGING)) {
05482                (*inringing)--;
05483                ast_clear_flag(&fup->flags[0], SIP_INC_RINGING);
05484             }
05485          } else {
05486             *inringing = 0;
05487          }
05488          ao2_unlock(p);
05489          sip_pvt_unlock(fup);
05490       }
05491 
05492       /* Decrement onhold count if applicable */
05493       sip_pvt_lock(fup);
05494       ao2_lock(p);
05495       if (ast_test_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD) && sip_cfg.notifyhold) {
05496          ast_clear_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD);
05497          ao2_unlock(p);
05498          sip_pvt_unlock(fup);
05499          sip_peer_hold(fup, FALSE);
05500       } else {
05501          ao2_unlock(p);
05502          sip_pvt_unlock(fup);
05503       }
05504       if (sipdebug)
05505          ast_debug(2, "Call %s %s '%s' removed from call limit %d\n", outgoing ? "to" : "from", "peer", name, *call_limit);
05506       break;
05507 
05508    case INC_CALL_RINGING:
05509    case INC_CALL_LIMIT:
05510       /* If call limit is active and we have reached the limit, reject the call */
05511       if (*call_limit > 0 ) {
05512          if (*inuse >= *call_limit) {
05513             ast_log(LOG_NOTICE, "Call %s %s '%s' rejected due to usage limit of %d\n", outgoing ? "to" : "from", "peer", name, *call_limit);
05514             unref_peer(p, "update_call_counter: unref peer p, call limit exceeded");
05515             return -1;
05516          }
05517       }
05518       if (inringing && (event == INC_CALL_RINGING)) {
05519          sip_pvt_lock(fup);
05520          ao2_lock(p);
05521          if (!ast_test_flag(&fup->flags[0], SIP_INC_RINGING)) {
05522             (*inringing)++;
05523             ast_set_flag(&fup->flags[0], SIP_INC_RINGING);
05524          }
05525          ao2_unlock(p);
05526          sip_pvt_unlock(fup);
05527       }
05528       if (inuse) {
05529          sip_pvt_lock(fup);
05530          ao2_lock(p);
05531          if (!ast_test_flag(&fup->flags[0], SIP_INC_COUNT)) {
05532             (*inuse)++;
05533             ast_set_flag(&fup->flags[0], SIP_INC_COUNT);
05534          }
05535          ao2_unlock(p);
05536          sip_pvt_unlock(fup);
05537       }
05538       if (sipdebug) {
05539          ast_debug(2, "Call %s %s '%s' is %d out of %d\n", outgoing ? "to" : "from", "peer", name, *inuse, *call_limit);
05540       }
05541       break;
05542 
05543    case DEC_CALL_RINGING:
05544       if (inringing) {
05545          sip_pvt_lock(fup);
05546          ao2_lock(p);
05547          if (ast_test_flag(&fup->flags[0], SIP_INC_RINGING)) {
05548             if (*inringing > 0) {
05549                (*inringing)--;
05550             }
05551             ast_clear_flag(&fup->flags[0], SIP_INC_RINGING);
05552          }
05553          ao2_unlock(p);
05554          sip_pvt_unlock(fup);
05555       }
05556       break;
05557 
05558    default:
05559       ast_log(LOG_ERROR, "update_call_counter(%s, %d) called with no event!\n", name, event);
05560    }
05561 
05562    if (p) {
05563       ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", p->name);
05564       unref_peer(p, "update_call_counter: unref_peer from call counter");
05565    }
05566    return 0;
05567 }
05568 
05569 
05570 static void sip_destroy_fn(void *p)
05571 {
05572    sip_destroy(p);
05573 }
05574 
05575 /*! \brief Destroy SIP call structure.
05576  * Make it return NULL so the caller can do things like
05577  * foo = sip_destroy(foo);
05578  * and reduce the chance of bugs due to dangling pointers.
05579  */
05580 struct sip_pvt *sip_destroy(struct sip_pvt *p)
05581 {
05582    ast_debug(3, "Destroying SIP dialog %s\n", p->callid);
05583    __sip_destroy(p, TRUE, TRUE);
05584    return NULL;
05585 }
05586 
05587 /*! \brief Convert SIP hangup causes to Asterisk hangup causes */
05588 int hangup_sip2cause(int cause)
05589 {
05590    /* Possible values taken from causes.h */
05591 
05592    switch(cause) {
05593       case 401:   /* Unauthorized */
05594          return AST_CAUSE_CALL_REJECTED;
05595       case 403:   /* Not found */
05596          return AST_CAUSE_CALL_REJECTED;
05597       case 404:   /* Not found */
05598          return AST_CAUSE_UNALLOCATED;
05599       case 405:   /* Method not allowed */
05600          return AST_CAUSE_INTERWORKING;
05601       case 407:   /* Proxy authentication required */
05602          return AST_CAUSE_CALL_REJECTED;
05603       case 408:   /* No reaction */
05604          return AST_CAUSE_NO_USER_RESPONSE;
05605       case 409:   /* Conflict */
05606          return AST_CAUSE_NORMAL_TEMPORARY_FAILURE;
05607       case 410:   /* Gone */
05608          return AST_CAUSE_NUMBER_CHANGED;
05609       case 411:   /* Length required */
05610          return AST_CAUSE_INTERWORKING;
05611       case 413:   /* Request entity too large */
05612          return AST_CAUSE_INTERWORKING;
05613       case 414:   /* Request URI too large */
05614          return AST_CAUSE_INTERWORKING;
05615       case 415:   /* Unsupported media type */
05616          return AST_CAUSE_INTERWORKING;
05617       case 420:   /* Bad extension */
05618          return AST_CAUSE_NO_ROUTE_DESTINATION;
05619       case 480:   /* No answer */
05620          return AST_CAUSE_NO_ANSWER;
05621       case 481:   /* No answer */
05622          return AST_CAUSE_INTERWORKING;
05623       case 482:   /* Loop detected */
05624          return AST_CAUSE_INTERWORKING;
05625       case 483:   /* Too many hops */
05626          return AST_CAUSE_NO_ANSWER;
05627       case 484:   /* Address incomplete */
05628          return AST_CAUSE_INVALID_NUMBER_FORMAT;
05629       case 485:   /* Ambiguous */
05630          return AST_CAUSE_UNALLOCATED;
05631       case 486:   /* Busy everywhere */
05632          return AST_CAUSE_BUSY;
05633       case 487:   /* Request terminated */
05634          return AST_CAUSE_INTERWORKING;
05635       case 488:   /* No codecs approved */
05636          return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
05637       case 491:   /* Request pending */
05638          return AST_CAUSE_INTERWORKING;
05639       case 493:   /* Undecipherable */
05640          return AST_CAUSE_INTERWORKING;
05641       case 500:   /* Server internal failure */
05642          return AST_CAUSE_FAILURE;
05643       case 501:   /* Call rejected */
05644          return AST_CAUSE_FACILITY_REJECTED;
05645       case 502:
05646          return AST_CAUSE_DESTINATION_OUT_OF_ORDER;
05647       case 503:   /* Service unavailable */
05648          return AST_CAUSE_CONGESTION;
05649       case 504:   /* Gateway timeout */
05650          return AST_CAUSE_RECOVERY_ON_TIMER_EXPIRE;
05651       case 505:   /* SIP version not supported */
05652          return AST_CAUSE_INTERWORKING;
05653       case 600:   /* Busy everywhere */
05654          return AST_CAUSE_USER_BUSY;
05655       case 603:   /* Decline */
05656          return AST_CAUSE_CALL_REJECTED;
05657       case 604:   /* Does not exist anywhere */
05658          return AST_CAUSE_UNALLOCATED;
05659       case 606:   /* Not acceptable */
05660          return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
05661       default:
05662          if (cause < 500 && cause >= 400) {
05663             /* 4xx class error that is unknown - someting wrong with our request */
05664             return AST_CAUSE_INTERWORKING;
05665          } else if (cause < 600 && cause >= 500) {
05666             /* 5xx class error - problem in the remote end */
05667             return AST_CAUSE_CONGESTION;
05668          } else if (cause < 700 && cause >= 600) {
05669             /* 6xx - global errors in the 4xx class */
05670             return AST_CAUSE_INTERWORKING;
05671          }
05672          return AST_CAUSE_NORMAL;
05673    }
05674    /* Never reached */
05675    return 0;
05676 }
05677 
05678 /*! \brief Convert Asterisk hangup causes to SIP codes
05679 \verbatim
05680  Possible values from causes.h
05681         AST_CAUSE_NOTDEFINED    AST_CAUSE_NORMAL        AST_CAUSE_BUSY
05682         AST_CAUSE_FAILURE       AST_CAUSE_CONGESTION    AST_CAUSE_UNALLOCATED
05683 
05684    In addition to these, a lot of PRI codes is defined in causes.h
05685    ...should we take care of them too ?
05686 
05687    Quote RFC 3398
05688 
05689    ISUP Cause value                        SIP response
05690    ----------------                        ------------
05691    1  unallocated number                   404 Not Found
05692    2  no route to network                  404 Not found
05693    3  no route to destination              404 Not found
05694    16 normal call clearing                 --- (*)
05695    17 user busy                            486 Busy here
05696    18 no user responding                   408 Request Timeout
05697    19 no answer from the user              480 Temporarily unavailable
05698    20 subscriber absent                    480 Temporarily unavailable
05699    21 call rejected                        403 Forbidden (+)
05700    22 number changed (w/o diagnostic)      410 Gone
05701    22 number changed (w/ diagnostic)       301 Moved Permanently
05702    23 redirection to new destination       410 Gone
05703    26 non-selected user clearing           404 Not Found (=)
05704    27 destination out of order             502 Bad Gateway
05705    28 address incomplete                   484 Address incomplete
05706    29 facility rejected                    501 Not implemented
05707    31 normal unspecified                   480 Temporarily unavailable
05708 \endverbatim
05709 */
05710 const char *hangup_cause2sip(int cause)
05711 {
05712    switch (cause) {
05713       case AST_CAUSE_UNALLOCATED:      /* 1 */
05714       case AST_CAUSE_NO_ROUTE_DESTINATION:   /* 3 IAX2: Can't find extension in context */
05715       case AST_CAUSE_NO_ROUTE_TRANSIT_NET:   /* 2 */
05716          return "404 Not Found";
05717       case AST_CAUSE_CONGESTION:    /* 34 */
05718       case AST_CAUSE_SWITCH_CONGESTION:   /* 42 */
05719          return "503 Service Unavailable";
05720       case AST_CAUSE_NO_USER_RESPONSE: /* 18 */
05721          return "408 Request Timeout";
05722       case AST_CAUSE_NO_ANSWER:     /* 19 */
05723       case AST_CAUSE_UNREGISTERED:        /* 20 */
05724          return "480 Temporarily unavailable";
05725       case AST_CAUSE_CALL_REJECTED:    /* 21 */
05726          return "403 Forbidden";
05727       case AST_CAUSE_NUMBER_CHANGED:      /* 22 */
05728          return "410 Gone";
05729       case AST_CAUSE_NORMAL_UNSPECIFIED:  /* 31 */
05730          return "480 Temporarily unavailable";
05731       case AST_CAUSE_INVALID_NUMBER_FORMAT:
05732          return "484 Address incomplete";
05733       case AST_CAUSE_USER_BUSY:
05734          return "486 Busy here";
05735       case AST_CAUSE_FAILURE:
05736          return "500 Server internal failure";
05737       case AST_CAUSE_FACILITY_REJECTED:   /* 29 */
05738          return "501 Not Implemented";
05739       case AST_CAUSE_CHAN_NOT_IMPLEMENTED:
05740          return "503 Service Unavailable";
05741       /* Used in chan_iax2 */
05742       case AST_CAUSE_DESTINATION_OUT_OF_ORDER:
05743          return "502 Bad Gateway";
05744       case AST_CAUSE_BEARERCAPABILITY_NOTAVAIL: /* Can't find codec to connect to host */
05745          return "488 Not Acceptable Here";
05746          
05747       case AST_CAUSE_NOTDEFINED:
05748       default:
05749          ast_debug(1, "AST hangup cause %d (no match found in SIP)\n", cause);
05750          return NULL;
05751    }
05752 
05753    /* Never reached */
05754    return 0;
05755 }
05756 
05757 /*! \brief  sip_hangup: Hangup SIP call
05758  * Part of PBX interface, called from ast_hangup */
05759 static int sip_hangup(struct ast_channel *ast)
05760 {
05761    struct sip_pvt *p = ast->tech_pvt;
05762    int needcancel = FALSE;
05763    int needdestroy = 0;
05764    struct ast_channel *oldowner = ast;
05765 
05766    if (!p) {
05767       ast_debug(1, "Asked to hangup channel that was not connected\n");
05768       return 0;
05769    }
05770    if (ast_test_flag(ast, AST_FLAG_ANSWERED_ELSEWHERE) || ast->hangupcause == AST_CAUSE_ANSWERED_ELSEWHERE) {
05771       ast_debug(1, "This call was answered elsewhere");
05772       if (ast->hangupcause == AST_CAUSE_ANSWERED_ELSEWHERE) {
05773          ast_debug(1, "####### It's the cause code, buddy. The cause code!!!\n");
05774       }
05775       append_history(p, "Cancel", "Call answered elsewhere");
05776       p->answered_elsewhere = TRUE;
05777    }
05778 
05779    /* Store hangupcause locally in PVT so we still have it before disconnect */
05780    if (p->owner)
05781       p->hangupcause = p->owner->hangupcause;
05782 
05783    if (ast_test_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER)) {
05784       if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
05785          if (sipdebug)
05786             ast_debug(1, "update_call_counter(%s) - decrement call limit counter on hangup\n", p->username);
05787          update_call_counter(p, DEC_CALL_LIMIT);
05788       }
05789       ast_debug(4, "SIP Transfer: Not hanging up right now... Rescheduling hangup for %s.\n", p->callid);
05790       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
05791       ast_clear_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER); /* Really hang up next time */
05792       p->needdestroy = 0;
05793       p->owner->tech_pvt = dialog_unref(p->owner->tech_pvt, "unref p->owner->tech_pvt");
05794       sip_pvt_lock(p);
05795       p->owner = NULL;  /* Owner will be gone after we return, so take it away */
05796       sip_pvt_unlock(p);
05797       ast_module_unref(ast_module_info->self);
05798       return 0;
05799    }
05800 
05801    if (ast_test_flag(ast, AST_FLAG_ZOMBIE)) {
05802       if (p->refer)
05803          ast_debug(1, "SIP Transfer: Hanging up Zombie channel %s after transfer ... Call-ID: %s\n", ast->name, p->callid);
05804       else
05805          ast_debug(1, "Hanging up zombie call. Be scared.\n");
05806    } else
05807       ast_debug(1, "Hangup call %s, SIP callid %s\n", ast->name, p->callid);
05808 
05809    sip_pvt_lock(p);
05810    if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
05811       if (sipdebug)
05812          ast_debug(1, "update_call_counter(%s) - decrement call limit counter on hangup\n", p->username);
05813       update_call_counter(p, DEC_CALL_LIMIT);
05814    }
05815 
05816    /* Determine how to disconnect */
05817    if (p->owner != ast) {
05818       ast_log(LOG_WARNING, "Huh?  We aren't the owner? Can't hangup call.\n");
05819       sip_pvt_unlock(p);
05820       return 0;
05821    }
05822    /* If the call is not UP, we need to send CANCEL instead of BYE */
05823    /* In case of re-invites, the call might be UP even though we have an incomplete invite transaction */
05824    if (p->invitestate < INV_COMPLETED && p->owner->_state != AST_STATE_UP) {
05825       needcancel = TRUE;
05826       ast_debug(4, "Hanging up channel in state %s (not UP)\n", ast_state2str(ast->_state));
05827    }
05828 
05829    stop_media_flows(p); /* Immediately stop RTP, VRTP and UDPTL as applicable */
05830 
05831    append_history(p, needcancel ? "Cancel" : "Hangup", "Cause %s", p->owner ? ast_cause2str(p->hangupcause) : "Unknown");
05832 
05833    /* Disconnect */
05834    disable_dsp_detect(p);
05835 
05836    p->owner = NULL;
05837    ast->tech_pvt = dialog_unref(ast->tech_pvt, "unref ast->tech_pvt");
05838 
05839    ast_module_unref(ast_module_info->self);
05840    /* Do not destroy this pvt until we have timeout or
05841       get an answer to the BYE or INVITE/CANCEL
05842       If we get no answer during retransmit period, drop the call anyway.
05843       (Sorry, mother-in-law, you can't deny a hangup by sending
05844       603 declined to BYE...)
05845    */
05846    if (p->alreadygone)
05847       needdestroy = 1;  /* Set destroy flag at end of this function */
05848    else if (p->invitestate != INV_CALLING)
05849       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
05850 
05851    /* Start the process if it's not already started */
05852    if (!p->alreadygone && p->initreq.data && !ast_strlen_zero(p->initreq.data->str)) {
05853       if (needcancel) { /* Outgoing call, not up */
05854          if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
05855             /* if we can't send right now, mark it pending */
05856             if (p->invitestate == INV_CALLING) {
05857                /* We can't send anything in CALLING state */
05858                ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
05859                /* 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. */
05860                sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
05861                append_history(p, "DELAY", "Not sending cancel, waiting for timeout");
05862             } else {
05863                struct sip_pkt *cur;
05864 
05865                for (cur = p->packets; cur; cur = cur->next) {
05866                   __sip_semi_ack(p, cur->seqno, cur->is_resp, cur->method ? cur->method : find_sip_method(cur->data->str));
05867                }
05868                p->invitestate = INV_CANCELLED;
05869                /* Send a new request: CANCEL */
05870                transmit_request(p, SIP_CANCEL, p->lastinvite, XMIT_RELIABLE, FALSE);
05871                /* Actually don't destroy us yet, wait for the 487 on our original
05872                   INVITE, but do set an autodestruct just in case we never get it. */
05873                needdestroy = 0;
05874                sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
05875             }
05876          } else { /* Incoming call, not up */
05877             const char *res;
05878             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"));
05879             if (p->hangupcause && (res = hangup_cause2sip(p->hangupcause)))
05880                transmit_response_reliable(p, res, &p->initreq);
05881             else
05882                transmit_response_reliable(p, "603 Declined", &p->initreq);
05883             p->invitestate = INV_TERMINATED;
05884          }
05885       } else { /* Call is in UP state, send BYE */
05886          if (p->stimer->st_active == TRUE) {
05887             stop_session_timer(p);
05888          }
05889 
05890          if (!p->pendinginvite) {
05891             struct ast_channel *bridge = ast_bridged_channel(oldowner);
05892             char quality_buf[AST_MAX_USER_FIELD], *quality;
05893 
05894             /* We need to get the lock on bridge because ast_rtp_instance_set_stats_vars will attempt
05895              * to lock the bridge. This may get hairy...
05896              */
05897             while (bridge && ast_channel_trylock(bridge)) {
05898                sip_pvt_unlock(p);
05899                do {
05900                   CHANNEL_DEADLOCK_AVOIDANCE(oldowner);
05901                } while (sip_pvt_trylock(p));
05902                bridge = ast_bridged_channel(oldowner);
05903             }
05904 
05905             if (p->rtp) {
05906                ast_rtp_instance_set_stats_vars(oldowner, p->rtp);
05907             }
05908 
05909             if (bridge) {
05910                struct sip_pvt *q = bridge->tech_pvt;
05911 
05912                if (IS_SIP_TECH(bridge->tech) && q && q->rtp) {
05913                   ast_rtp_instance_set_stats_vars(bridge, q->rtp);
05914                }
05915                ast_channel_unlock(bridge);
05916             }
05917 
05918             if (p->do_history || oldowner) {
05919                if (p->rtp && (quality = ast_rtp_instance_get_quality(p->rtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY, quality_buf, sizeof(quality_buf)))) {
05920                   if (p->do_history) {
05921                      append_history(p, "RTCPaudio", "Quality:%s", quality);
05922                   }
05923                   if (oldowner) {
05924                      pbx_builtin_setvar_helper(oldowner, "RTPAUDIOQOS", quality);
05925                   }
05926                }
05927                if (p->vrtp && (quality = ast_rtp_instance_get_quality(p->vrtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY, quality_buf, sizeof(quality_buf)))) {
05928                   if (p->do_history) {
05929                      append_history(p, "RTCPvideo", "Quality:%s", quality);
05930                   }
05931                   if (oldowner) {
05932                      pbx_builtin_setvar_helper(oldowner, "RTPVIDEOQOS", quality);
05933                   }
05934                }
05935                if (p->trtp && (quality = ast_rtp_instance_get_quality(p->trtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY, quality_buf, sizeof(quality_buf)))) {
05936                   if (p->do_history) {
05937                      append_history(p, "RTCPtext", "Quality:%s", quality);
05938                   }
05939                   if (oldowner) {
05940                      pbx_builtin_setvar_helper(oldowner, "RTPTEXTQOS", quality);
05941                   }
05942                }
05943             }
05944 
05945             /* Send a hangup */
05946             if (oldowner->_state == AST_STATE_UP) {
05947                transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
05948             }
05949 
05950          } else {
05951             /* Note we will need a BYE when this all settles out
05952                but we can't send one while we have "INVITE" outstanding. */
05953             ast_set_flag(&p->flags[0], SIP_PENDINGBYE);  
05954             ast_clear_flag(&p->flags[0], SIP_NEEDREINVITE); 
05955             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"));
05956             if (sip_cancel_destroy(p))
05957                ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
05958          }
05959       }
05960    }
05961    if (needdestroy) {
05962       pvt_set_needdestroy(p, "hangup");
05963    }
05964    sip_pvt_unlock(p);
05965    return 0;
05966 }
05967 
05968 /*! \brief Try setting codec suggested by the SIP_CODEC channel variable */
05969 static void try_suggested_sip_codec(struct sip_pvt *p)
05970 {
05971    format_t fmt;
05972    const char *codec;
05973 
05974    if (p->outgoing_call) {
05975       codec = pbx_builtin_getvar_helper(p->owner, "SIP_CODEC_OUTBOUND");
05976    } else if (!(codec = pbx_builtin_getvar_helper(p->owner, "SIP_CODEC_INBOUND"))) {
05977       codec = pbx_builtin_getvar_helper(p->owner, "SIP_CODEC");
05978    }
05979 
05980    if (!codec) 
05981       return;
05982 
05983    fmt = ast_getformatbyname(codec);
05984    if (fmt) {
05985       ast_log(LOG_NOTICE, "Changing codec to '%s' for this call because of ${SIP_CODEC} variable\n", codec);
05986       if (p->jointcapability & fmt) {
05987          p->jointcapability &= fmt;
05988          p->capability &= fmt;
05989       } else
05990          ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because it is not shared by both ends.\n");
05991    } else
05992       ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because of unrecognized/not configured codec (check allow/disallow in sip.conf): %s\n", codec);
05993    return;  
05994 }
05995 
05996 /*! \brief  sip_answer: Answer SIP call , send 200 OK on Invite
05997  * Part of PBX interface */
05998 static int sip_answer(struct ast_channel *ast)
05999 {
06000    int res = 0;
06001    struct sip_pvt *p = ast->tech_pvt;
06002 
06003    sip_pvt_lock(p);
06004    if (ast->_state != AST_STATE_UP) {
06005       try_suggested_sip_codec(p);   
06006 
06007       ast_setstate(ast, AST_STATE_UP);
06008       ast_debug(1, "SIP answering channel: %s\n", ast->name);
06009       ast_rtp_instance_update_source(p->rtp);
06010       res = transmit_response_with_sdp(p, "200 OK", &p->initreq, XMIT_CRITICAL, FALSE, TRUE);
06011       ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
06012    }
06013    sip_pvt_unlock(p);
06014    return res;
06015 }
06016 
06017 /*! \brief Send frame to media channel (rtp) */
06018 static int sip_write(struct ast_channel *ast, struct ast_frame *frame)
06019 {
06020    struct sip_pvt *p = ast->tech_pvt;
06021    int res = 0;
06022 
06023    switch (frame->frametype) {
06024    case AST_FRAME_VOICE:
06025       if (!(frame->subclass.codec & ast->nativeformats)) {
06026          char s1[512], s2[512], s3[512];
06027          ast_log(LOG_WARNING, "Asked to transmit frame type %s, while native formats is %s read/write = %s/%s\n",
06028             ast_getformatname(frame->subclass.codec),
06029             ast_getformatname_multiple(s1, sizeof(s1), ast->nativeformats & AST_FORMAT_AUDIO_MASK),
06030             ast_getformatname_multiple(s2, sizeof(s2), ast->readformat),
06031             ast_getformatname_multiple(s3, sizeof(s3), ast->writeformat));
06032          return 0;
06033       }
06034       if (p) {
06035          sip_pvt_lock(p);
06036          if (p->rtp) {
06037             /* If channel is not up, activate early media session */
06038             if ((ast->_state != AST_STATE_UP) &&
06039                 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
06040                 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06041                ast_rtp_instance_update_source(p->rtp);
06042                if (!global_prematuremediafilter) {
06043                   p->invitestate = INV_EARLY_MEDIA;
06044                   transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
06045                   ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
06046                }
06047             } else if (p->t38.state == T38_ENABLED) {
06048                /* drop frame, can't sent VOICE frames while in T.38 mode */
06049             } else {
06050                p->lastrtptx = time(NULL);
06051                res = ast_rtp_instance_write(p->rtp, frame);
06052             }
06053          }
06054          sip_pvt_unlock(p);
06055       }
06056       break;
06057    case AST_FRAME_VIDEO:
06058       if (p) {
06059          sip_pvt_lock(p);
06060          if (p->vrtp) {
06061             /* Activate video early media */
06062             if ((ast->_state != AST_STATE_UP) &&
06063                 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
06064                 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06065                p->invitestate = INV_EARLY_MEDIA;
06066                transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
06067                ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
06068             }
06069             p->lastrtptx = time(NULL);
06070             res = ast_rtp_instance_write(p->vrtp, frame);
06071          }
06072          sip_pvt_unlock(p);
06073       }
06074       break;
06075    case AST_FRAME_TEXT:
06076       if (p) {
06077          sip_pvt_lock(p);
06078          if (p->red) {
06079             ast_rtp_red_buffer(p->trtp, frame);
06080          } else {
06081             if (p->trtp) {
06082                /* Activate text early media */
06083                if ((ast->_state != AST_STATE_UP) &&
06084                    !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
06085                    !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06086                   p->invitestate = INV_EARLY_MEDIA;
06087                   transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
06088                   ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
06089                }
06090                p->lastrtptx = time(NULL);
06091                res = ast_rtp_instance_write(p->trtp, frame);
06092             }
06093          }
06094          sip_pvt_unlock(p);
06095       }
06096       break;
06097    case AST_FRAME_IMAGE:
06098       return 0;
06099       break;
06100    case AST_FRAME_MODEM:
06101       if (p) {
06102          sip_pvt_lock(p);
06103          /* UDPTL requires two-way communication, so early media is not needed here.
06104             we simply forget the frames if we get modem frames before the bridge is up.
06105             Fax will re-transmit.
06106          */
06107          if ((ast->_state == AST_STATE_UP) &&
06108              p->udptl &&
06109              (p->t38.state == T38_ENABLED)) {
06110             res = ast_udptl_write(p->udptl, frame);
06111          }
06112          sip_pvt_unlock(p);
06113       }
06114       break;
06115    default:
06116       ast_log(LOG_WARNING, "Can't send %d type frames with SIP write\n", frame->frametype);
06117       return 0;
06118    }
06119 
06120    return res;
06121 }
06122 
06123 /*! \brief  sip_fixup: Fix up a channel:  If a channel is consumed, this is called.
06124         Basically update any ->owner links */
06125 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
06126 {
06127    int ret = -1;
06128    struct sip_pvt *p;
06129 
06130    if (newchan && ast_test_flag(newchan, AST_FLAG_ZOMBIE))
06131       ast_debug(1, "New channel is zombie\n");
06132    if (oldchan && ast_test_flag(oldchan, AST_FLAG_ZOMBIE))
06133       ast_debug(1, "Old channel is zombie\n");
06134 
06135    if (!newchan || !newchan->tech_pvt) {
06136       if (!newchan)
06137          ast_log(LOG_WARNING, "No new channel! Fixup of %s failed.\n", oldchan->name);
06138       else
06139          ast_log(LOG_WARNING, "No SIP tech_pvt! Fixup of %s failed.\n", oldchan->name);
06140       return -1;
06141    }
06142    p = newchan->tech_pvt;
06143 
06144    sip_pvt_lock(p);
06145    append_history(p, "Masq", "Old channel: %s\n", oldchan->name);
06146    append_history(p, "Masq (cont)", "...new owner: %s\n", newchan->name);
06147    if (p->owner != oldchan)
06148       ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, p->owner);
06149    else {
06150       p->owner = newchan;
06151       /* Re-invite RTP back to Asterisk. Needed if channel is masqueraded out of a native
06152          RTP bridge (i.e., RTP not going through Asterisk): RTP bridge code might not be
06153          able to do this if the masquerade happens before the bridge breaks (e.g., AMI
06154          redirect of both channels). Note that a channel can not be masqueraded *into*
06155          a native bridge. So there is no danger that this breaks a native bridge that
06156          should stay up. */
06157       sip_set_rtp_peer(newchan, NULL, NULL, 0, 0, 0);
06158       ret = 0;
06159    }
06160    ast_debug(3, "SIP Fixup: New owner for dialogue %s: %s (Old parent: %s)\n", p->callid, p->owner->name, oldchan->name);
06161 
06162    sip_pvt_unlock(p);
06163    return ret;
06164 }
06165 
06166 static int sip_senddigit_begin(struct ast_channel *ast, char digit)
06167 {
06168    struct sip_pvt *p = ast->tech_pvt;
06169    int res = 0;
06170 
06171    sip_pvt_lock(p);
06172    switch (ast_test_flag(&p->flags[0], SIP_DTMF)) {
06173    case SIP_DTMF_INBAND:
06174       if (p->rtp && ast_rtp_instance_dtmf_mode_get(p->rtp) == AST_RTP_DTMF_MODE_INBAND) {
06175          ast_rtp_instance_dtmf_begin(p->rtp, digit);
06176       } else {
06177          res = -1; /* Tell Asterisk to generate inband indications */
06178       }
06179       break;
06180    case SIP_DTMF_RFC2833:
06181       if (p->rtp)
06182          ast_rtp_instance_dtmf_begin(p->rtp, digit);
06183       break;
06184    default:
06185       break;
06186    }
06187    sip_pvt_unlock(p);
06188 
06189    return res;
06190 }
06191 
06192 /*! \brief Send DTMF character on SIP channel
06193    within one call, we're able to transmit in many methods simultaneously */
06194 static int sip_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration)
06195 {
06196    struct sip_pvt *p = ast->tech_pvt;
06197    int res = 0;
06198 
06199    sip_pvt_lock(p);
06200    switch (ast_test_flag(&p->flags[0], SIP_DTMF)) {
06201    case SIP_DTMF_INFO:
06202    case SIP_DTMF_SHORTINFO:
06203       transmit_info_with_digit(p, digit, duration);
06204       break;
06205    case SIP_DTMF_RFC2833:
06206       if (p->rtp)
06207          ast_rtp_instance_dtmf_end_with_duration(p->rtp, digit, duration);
06208       break;
06209    case SIP_DTMF_INBAND:
06210       if (p->rtp && ast_rtp_instance_dtmf_mode_get(p->rtp) == AST_RTP_DTMF_MODE_INBAND) {
06211          ast_rtp_instance_dtmf_end(p->rtp, digit);
06212       } else {
06213          res = -1; /* Tell Asterisk to stop inband indications */
06214       }
06215       break;
06216    }
06217    sip_pvt_unlock(p);
06218 
06219    return res;
06220 }
06221 
06222 /*! \brief Transfer SIP call */
06223 static int sip_transfer(struct ast_channel *ast, const char *dest)
06224 {
06225    struct sip_pvt *p = ast->tech_pvt;
06226    int res;
06227 
06228    if (dest == NULL) /* functions below do not take a NULL */
06229       dest = "";
06230    sip_pvt_lock(p);
06231    if (ast->_state == AST_STATE_RING)
06232       res = sip_sipredirect(p, dest);
06233    else
06234       res = transmit_refer(p, dest);
06235    sip_pvt_unlock(p);
06236    return res;
06237 }
06238 
06239 /*! \brief Helper function which updates T.38 capability information and triggers a reinvite */
06240 static int interpret_t38_parameters(struct sip_pvt *p, const struct ast_control_t38_parameters *parameters)
06241 {
06242    int res = 0;
06243 
06244    if (!ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) || !p->udptl) {
06245       return -1;
06246    }
06247    switch (parameters->request_response) {
06248    case AST_T38_NEGOTIATED:
06249    case AST_T38_REQUEST_NEGOTIATE:         /* Request T38 */
06250       /* Negotiation can not take place without a valid max_ifp value. */
06251       if (!parameters->max_ifp) {
06252          change_t38_state(p, T38_DISABLED);
06253          if (p->t38.state == T38_PEER_REINVITE) {
06254             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"));
06255             transmit_response_reliable(p, "488 Not acceptable here", &p->initreq);
06256          }
06257          break;
06258       } else if (p->t38.state == T38_PEER_REINVITE) {
06259          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"));
06260          p->t38.our_parms = *parameters;
06261          /* modify our parameters to conform to the peer's parameters,
06262           * based on the rules in the ITU T.38 recommendation
06263           */
06264          if (!p->t38.their_parms.fill_bit_removal) {
06265             p->t38.our_parms.fill_bit_removal = FALSE;
06266          }
06267          if (!p->t38.their_parms.transcoding_mmr) {
06268             p->t38.our_parms.transcoding_mmr = FALSE;
06269          }
06270          if (!p->t38.their_parms.transcoding_jbig) {
06271             p->t38.our_parms.transcoding_jbig = FALSE;
06272          }
06273          p->t38.our_parms.version = MIN(p->t38.our_parms.version, p->t38.their_parms.version);
06274          p->t38.our_parms.rate_management = p->t38.their_parms.rate_management;
06275          ast_udptl_set_local_max_ifp(p->udptl, p->t38.our_parms.max_ifp);
06276          change_t38_state(p, T38_ENABLED);
06277          transmit_response_with_t38_sdp(p, "200 OK", &p->initreq, XMIT_CRITICAL);
06278       } else if (p->t38.state != T38_ENABLED) {
06279          p->t38.our_parms = *parameters;
06280          ast_udptl_set_local_max_ifp(p->udptl, p->t38.our_parms.max_ifp);
06281          change_t38_state(p, T38_LOCAL_REINVITE);
06282          if (!p->pendinginvite) {
06283             transmit_reinvite_with_sdp(p, TRUE, FALSE);
06284          } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
06285             ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
06286          }
06287       }
06288       break;
06289    case AST_T38_TERMINATED:
06290    case AST_T38_REFUSED:
06291    case AST_T38_REQUEST_TERMINATE:         /* Shutdown T38 */
06292       if (p->t38.state == T38_PEER_REINVITE) {
06293          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"));
06294          change_t38_state(p, T38_DISABLED);
06295          transmit_response_reliable(p, "488 Not acceptable here", &p->initreq);
06296       } else if (p->t38.state == T38_ENABLED)
06297          transmit_reinvite_with_sdp(p, FALSE, FALSE);
06298       break;
06299    case AST_T38_REQUEST_PARMS: {    /* Application wants remote's parameters re-sent */
06300       struct ast_control_t38_parameters parameters = p->t38.their_parms;
06301 
06302       if (p->t38.state == T38_PEER_REINVITE) {
06303          AST_SCHED_DEL(sched, p->t38id);
06304          parameters.max_ifp = ast_udptl_get_far_max_ifp(p->udptl);
06305          parameters.request_response = AST_T38_REQUEST_NEGOTIATE;
06306          ast_queue_control_data(p->owner, AST_CONTROL_T38_PARAMETERS, &parameters, sizeof(parameters));
06307          /* we need to return a positive value here, so that applications that
06308           * send this request can determine conclusively whether it was accepted or not...
06309           * older versions of chan_sip would just silently accept it and return zero.
06310           */
06311          res = AST_T38_REQUEST_PARMS;
06312       }
06313       break;
06314    }
06315    default:
06316       res = -1;
06317       break;
06318    }
06319 
06320    return res;
06321 }
06322 
06323 /*! \brief Play indication to user
06324  * With SIP a lot of indications is sent as messages, letting the device play
06325    the indication - busy signal, congestion etc
06326    \return -1 to force ast_indicate to send indication in audio, 0 if SIP can handle the indication by sending a message
06327 */
06328 static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen)
06329 {
06330    struct sip_pvt *p = ast->tech_pvt;
06331    int res = 0;
06332 
06333    sip_pvt_lock(p);
06334    switch(condition) {
06335    case AST_CONTROL_RINGING:
06336       if (ast->_state == AST_STATE_RING) {
06337          p->invitestate = INV_EARLY_MEDIA;
06338          if (!ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) ||
06339              (ast_test_flag(&p->flags[0], SIP_PROG_INBAND) == SIP_PROG_INBAND_NEVER)) {            
06340             /* Send 180 ringing if out-of-band seems reasonable */
06341             transmit_provisional_response(p, "180 Ringing", &p->initreq, 0);
06342             ast_set_flag(&p->flags[0], SIP_RINGING);
06343             if (ast_test_flag(&p->flags[0], SIP_PROG_INBAND) != SIP_PROG_INBAND_YES)
06344                break;
06345          } else {
06346             /* Well, if it's not reasonable, just send in-band */
06347          }
06348       }
06349       res = -1;
06350       break;
06351    case AST_CONTROL_BUSY:
06352       if (ast->_state != AST_STATE_UP) {
06353          transmit_response_reliable(p, "486 Busy Here", &p->initreq);
06354          p->invitestate = INV_COMPLETED;
06355          sip_alreadygone(p);
06356          ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
06357          break;
06358       }
06359       res = -1;
06360       break;
06361    case AST_CONTROL_CONGESTION:
06362       if (ast->_state != AST_STATE_UP) {
06363          transmit_response_reliable(p, "503 Service Unavailable", &p->initreq);
06364          p->invitestate = INV_COMPLETED;
06365          sip_alreadygone(p);
06366          ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
06367          break;
06368       }
06369       res = -1;
06370       break;
06371    case AST_CONTROL_PROCEEDING:
06372       if ((ast->_state != AST_STATE_UP) &&
06373           !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
06374           !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06375          transmit_response(p, "100 Trying", &p->initreq);
06376          p->invitestate = INV_PROCEEDING;
06377          break;
06378       }
06379       res = -1;
06380       break;
06381    case AST_CONTROL_PROGRESS:
06382       if ((ast->_state != AST_STATE_UP) &&
06383           !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
06384           !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06385          p->invitestate = INV_EARLY_MEDIA;
06386          transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
06387          ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
06388          break;
06389       }
06390       res = -1;
06391       break;
06392    case AST_CONTROL_HOLD:
06393       ast_rtp_instance_update_source(p->rtp);
06394       ast_moh_start(ast, data, p->mohinterpret);
06395       break;
06396    case AST_CONTROL_UNHOLD:
06397       ast_rtp_instance_update_source(p->rtp);
06398       ast_moh_stop(ast);
06399       break;
06400    case AST_CONTROL_VIDUPDATE:   /* Request a video frame update */
06401       if (p->vrtp && !p->novideo) {
06402          transmit_info_with_vidupdate(p);
06403          /* ast_rtcp_send_h261fur(p->vrtp); */
06404       } else
06405          res = -1;
06406       break;
06407    case AST_CONTROL_T38_PARAMETERS:
06408       if (datalen != sizeof(struct ast_control_t38_parameters)) {
06409          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);
06410          res = -1;
06411       } else {
06412          const struct ast_control_t38_parameters *parameters = data;
06413          res = interpret_t38_parameters(p, parameters);
06414       }
06415       break;
06416    case AST_CONTROL_SRCUPDATE:
06417       ast_rtp_instance_update_source(p->rtp);
06418       break;
06419    case AST_CONTROL_SRCCHANGE:
06420       ast_rtp_instance_change_source(p->rtp);
06421       break;
06422    case AST_CONTROL_CONNECTED_LINE:
06423       update_connectedline(p, data, datalen);
06424       break;
06425    case AST_CONTROL_REDIRECTING:
06426       update_redirecting(p, data, datalen);
06427       break;
06428    case AST_CONTROL_AOC:
06429       {
06430          struct ast_aoc_decoded *decoded = ast_aoc_decode((struct ast_aoc_encoded *) data, datalen, ast);
06431          if (!decoded) {
06432             ast_log(LOG_ERROR, "Error decoding indicated AOC data\n");
06433             res = -1;
06434             break;
06435          }
06436          switch (ast_aoc_get_msg_type(decoded)) {
06437          case AST_AOC_REQUEST:
06438             if (ast_aoc_get_termination_request(decoded)) {
06439                /* TODO, once there is a way to get AOC-E on hangup, attempt that here
06440                 * before hanging up the channel.*/
06441 
06442                /* The other side has already initiated the hangup. This frame
06443                 * just says they are waiting to get AOC-E before completely tearing
06444                 * the call down.  Since SIP does not support this at the moment go
06445                 * ahead and terminate the call here to avoid an unnecessary timeout. */
06446                ast_debug(1, "AOC-E termination request received on %s. This is not yet supported on sip. Continue with hangup \n", p->owner->name);
06447                ast_softhangup_nolock(p->owner, AST_SOFTHANGUP_DEV);
06448             }
06449             break;
06450          case AST_AOC_D:
06451          case AST_AOC_E:
06452             if (ast_test_flag(&p->flags[2], SIP_PAGE3_SNOM_AOC)) {
06453                transmit_info_with_aoc(p, decoded);
06454             }
06455             break;
06456          case AST_AOC_S: /* S not supported yet */
06457          default:
06458             break;
06459          }
06460          ast_aoc_destroy_decoded(decoded);
06461       }
06462       break;
06463    case -1:
06464       res = -1;
06465       break;
06466    default:
06467       ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", condition);
06468       res = -1;
06469       break;
06470    }
06471    sip_pvt_unlock(p);
06472    return res;
06473 }
06474 
06475 /*! \brief Initiate a call in the SIP channel
06476    called from sip_request_call (calls from the pbx ) for outbound channels
06477    and from handle_request_invite for inbound channels
06478    
06479 */
06480 static struct ast_channel *sip_new(struct sip_pvt *i, int state, const char *title, const char *linkedid)
06481 {
06482    struct ast_channel *tmp;
06483    struct ast_variable *v = NULL;
06484    format_t fmt;
06485    format_t what;
06486    format_t video;
06487    format_t text;
06488    format_t needvideo = 0;
06489    int needtext = 0;
06490    char buf[SIPBUFSIZE];
06491    char *decoded_exten;
06492 
06493    {
06494       const char *my_name; /* pick a good name */
06495    
06496       if (title) {
06497          my_name = title;
06498       } else {
06499          my_name = ast_strdupa(i->fromdomain);
06500       }
06501 
06502       sip_pvt_unlock(i);
06503       /* Don't hold a sip pvt lock while we allocate a channel */
06504       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));
06505    }
06506    if (!tmp) {
06507       ast_log(LOG_WARNING, "Unable to allocate AST channel structure for SIP channel\n");
06508       sip_pvt_lock(i);
06509       return NULL;
06510    }
06511    ast_channel_lock(tmp);
06512    sip_pvt_lock(i);
06513    ast_channel_cc_params_init(tmp, i->cc_params);
06514    tmp->caller.id.tag = ast_strdup(i->cid_tag);
06515    ast_channel_unlock(tmp);
06516 
06517    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;
06518 
06519    /* Select our native format based on codec preference until we receive
06520       something from another device to the contrary. */
06521    if (i->jointcapability) {  /* The joint capabilities of us and peer */
06522       what = i->jointcapability;
06523       video = i->jointcapability & AST_FORMAT_VIDEO_MASK;
06524       text = i->jointcapability & AST_FORMAT_TEXT_MASK;
06525    } else if (i->capability) {      /* Our configured capability for this peer */
06526       what = i->capability;
06527       video = i->capability & AST_FORMAT_VIDEO_MASK;
06528       text = i->capability & AST_FORMAT_TEXT_MASK;
06529    } else {
06530       what = sip_cfg.capability; /* Global codec support */
06531       video = sip_cfg.capability & AST_FORMAT_VIDEO_MASK;
06532       text = sip_cfg.capability & AST_FORMAT_TEXT_MASK;
06533    }
06534 
06535    /* Set the native formats for audio  and merge in video */
06536    tmp->nativeformats = ast_codec_choose(&i->prefs, what, 1) | video | text;
06537    ast_debug(3, "*** Our native formats are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, tmp->nativeformats));
06538    ast_debug(3, "*** Joint capabilities are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, i->jointcapability));
06539    ast_debug(3, "*** Our capabilities are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, i->capability));
06540    ast_debug(3, "*** AST_CODEC_CHOOSE formats are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, ast_codec_choose(&i->prefs, what, 1)));
06541    if (i->prefcodec)
06542       ast_debug(3, "*** Our preferred formats from the incoming channel are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, i->prefcodec));
06543 
06544    /* XXX Why are we choosing a codec from the native formats?? */
06545    fmt = ast_best_codec(tmp->nativeformats);
06546 
06547    /* If we have a prefcodec setting, we have an inbound channel that set a
06548       preferred format for this call. Otherwise, we check the jointcapability
06549       We also check for vrtp. If it's not there, we are not allowed do any video anyway.
06550     */
06551    if (i->vrtp) {
06552       if (ast_test_flag(&i->flags[1], SIP_PAGE2_VIDEOSUPPORT))
06553          needvideo = AST_FORMAT_VIDEO_MASK;
06554       else if (i->prefcodec)
06555          needvideo = i->prefcodec & AST_FORMAT_VIDEO_MASK;  /* Outbound call */
06556       else
06557          needvideo = i->jointcapability & AST_FORMAT_VIDEO_MASK;  /* Inbound call */
06558    }
06559 
06560    if (i->trtp) {
06561       if (i->prefcodec)
06562          needtext = i->prefcodec & AST_FORMAT_TEXT_MASK; /* Outbound call */
06563       else
06564          needtext = i->jointcapability & AST_FORMAT_TEXT_MASK; /* Inbound call */
06565    }
06566 
06567    if (needvideo)
06568       ast_debug(3, "This channel can handle video! HOLLYWOOD next!\n");
06569    else
06570       ast_debug(3, "This channel will not be able to handle video.\n");
06571 
06572    enable_dsp_detect(i);
06573 
06574    if ((ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) ||
06575        (ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_AUTO)) {
06576       if (!i->rtp || ast_rtp_instance_dtmf_mode_set(i->rtp, AST_RTP_DTMF_MODE_INBAND)) {
06577          enable_dsp_detect(i);
06578       }
06579    } else if (ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) {
06580       if (i->rtp) {
06581          ast_rtp_instance_dtmf_mode_set(i->rtp, AST_RTP_DTMF_MODE_RFC2833);
06582       }
06583    }
06584 
06585    /* Set file descriptors for audio, video, realtime text and UDPTL as needed */
06586    if (i->rtp) {
06587       ast_channel_set_fd(tmp, 0, ast_rtp_instance_fd(i->rtp, 0));
06588       ast_channel_set_fd(tmp, 1, ast_rtp_instance_fd(i->rtp, 1));
06589    }
06590    if (needvideo && i->vrtp) {
06591       ast_channel_set_fd(tmp, 2, ast_rtp_instance_fd(i->vrtp, 0));
06592       ast_channel_set_fd(tmp, 3, ast_rtp_instance_fd(i->vrtp, 1));
06593    }
06594    if (needtext && i->trtp)
06595       ast_channel_set_fd(tmp, 4, ast_rtp_instance_fd(i->trtp, 0));
06596    if (i->udptl)
06597       ast_channel_set_fd(tmp, 5, ast_udptl_fd(i->udptl));
06598 
06599    if (state == AST_STATE_RING)
06600       tmp->rings = 1;
06601    tmp->adsicpe = AST_ADSI_UNAVAILABLE;
06602 
06603    tmp->writeformat = fmt;
06604    tmp->rawwriteformat = fmt;
06605    ast_rtp_instance_set_write_format(i->rtp, fmt);
06606 
06607    tmp->readformat = fmt;
06608    tmp->rawreadformat = fmt;
06609    ast_rtp_instance_set_read_format(i->rtp, fmt);
06610 
06611    tmp->tech_pvt = dialog_ref(i, "sip_new: set chan->tech_pvt to i");
06612 
06613    tmp->callgroup = i->callgroup;
06614    tmp->pickupgroup = i->pickupgroup;
06615    tmp->caller.id.name.presentation = i->callingpres;
06616    tmp->caller.id.number.presentation = i->callingpres;
06617    if (!ast_strlen_zero(i->parkinglot))
06618       ast_string_field_set(tmp, parkinglot, i->parkinglot);
06619    if (!ast_strlen_zero(i->accountcode))
06620       ast_string_field_set(tmp, accountcode, i->accountcode);
06621    if (i->amaflags)
06622       tmp->amaflags = i->amaflags;
06623    if (!ast_strlen_zero(i->language))
06624       ast_string_field_set(tmp, language, i->language);
06625    i->owner = tmp;
06626    ast_module_ref(ast_module_info->self);
06627    ast_copy_string(tmp->context, i->context, sizeof(tmp->context));
06628    /*Since it is valid to have extensions in the dialplan that have unescaped characters in them
06629     * we should decode the uri before storing it in the channel, but leave it encoded in the sip_pvt
06630     * structure so that there aren't issues when forming URI's
06631     */
06632    if (ast_exists_extension(NULL, i->context, i->exten, 1, i->cid_num)) {
06633       /* encoded in dialplan, so keep extension encoded */
06634       ast_copy_string(tmp->exten, i->exten, sizeof(tmp->exten));
06635    } else {
06636       decoded_exten = ast_strdupa(i->exten);
06637       ast_uri_decode(decoded_exten);
06638       ast_copy_string(tmp->exten, decoded_exten, sizeof(tmp->exten));
06639    }
06640 
06641    /* Don't use ast_set_callerid() here because it will
06642     * generate an unnecessary NewCallerID event  */
06643    if (!ast_strlen_zero(i->cid_num)) {
06644       tmp->caller.ani.number.valid = 1;
06645       tmp->caller.ani.number.str = ast_strdup(i->cid_num);
06646    }
06647    if (!ast_strlen_zero(i->rdnis)) {
06648       tmp->redirecting.from.number.valid = 1;
06649       tmp->redirecting.from.number.str = ast_strdup(i->rdnis);
06650    }
06651 
06652    if (!ast_strlen_zero(i->exten) && strcmp(i->exten, "s")) {
06653       tmp->dialed.number.str = ast_strdup(i->exten);
06654    }
06655 
06656    tmp->priority = 1;
06657    if (!ast_strlen_zero(i->uri))
06658       pbx_builtin_setvar_helper(tmp, "SIPURI", i->uri);
06659    if (!ast_strlen_zero(i->domain))
06660       pbx_builtin_setvar_helper(tmp, "SIPDOMAIN", i->domain);
06661    if (!ast_strlen_zero(i->callid))
06662       pbx_builtin_setvar_helper(tmp, "SIPCALLID", i->callid);
06663    if (i->rtp)
06664       ast_jb_configure(tmp, &global_jbconf);
06665 
06666    /* Set channel variables for this call from configuration */
06667    for (v = i->chanvars ; v ; v = v->next) {
06668       char valuebuf[1024];
06669       pbx_builtin_setvar_helper(tmp, v->name, ast_get_encoded_str(v->value, valuebuf, sizeof(valuebuf)));
06670    }
06671 
06672    if (state != AST_STATE_DOWN && ast_pbx_start(tmp)) {
06673       ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
06674       tmp->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
06675       ast_hangup(tmp);
06676       tmp = NULL;
06677    }
06678 
06679    if (i->do_history)
06680       append_history(i, "NewChan", "Channel %s - from %s", tmp->name, i->callid);
06681 
06682    /* Inform manager user about new channel and their SIP call ID */
06683    if (sip_cfg.callevents)
06684       manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
06685          "Channel: %s\r\nUniqueid: %s\r\nChanneltype: %s\r\nSIPcallid: %s\r\nSIPfullcontact: %s\r\n",
06686          tmp->name, tmp->uniqueid, "SIP", i->callid, i->fullcontact);
06687 
06688    return tmp;
06689 }
06690 
06691 /*! \brief Reads one line of SIP message body */
06692 static char *get_body_by_line(const char *line, const char *name, int nameLen, char delimiter)
06693 {
06694    if (!strncasecmp(line, name, nameLen) && line[nameLen] == delimiter)
06695       return ast_skip_blanks(line + nameLen + 1);
06696 
06697    return "";
06698 }
06699 
06700 /*! \brief Lookup 'name' in the SDP starting
06701  * at the 'start' line. Returns the matching line, and 'start'
06702  * is updated with the next line number.
06703  */
06704 static const char *get_sdp_iterate(int *start, struct sip_request *req, const char *name)
06705 {
06706    int len = strlen(name);
06707 
06708    while (*start < (req->sdp_start + req->sdp_count)) {
06709       const char *r = get_body_by_line(REQ_OFFSET_TO_STR(req, line[(*start)++]), name, len, '=');
06710       if (r[0] != '\0')
06711          return r;
06712    }
06713 
06714    /* if the line was not found, ensure that *start points past the SDP */
06715    (*start)++;
06716 
06717    return "";
06718 }
06719 
06720 /*! \brief Fetches the next valid SDP line between the 'start' line
06721  * (inclusive) and the 'stop' line (exclusive). Returns the type
06722  * ('a', 'c', ...) and matching line in reference 'start' is updated
06723  * with the next line number.
06724  */
06725 static char get_sdp_line(int *start, int stop, struct sip_request *req, const char **value)
06726 {
06727    char type = '\0';
06728    const char *line = NULL;
06729 
06730    if (stop > (req->sdp_start + req->sdp_count)) {
06731       stop = req->sdp_start + req->sdp_count;
06732    }
06733 
06734    while (*start < stop) {
06735       line = REQ_OFFSET_TO_STR(req, line[(*start)++]);
06736       if (line[1] == '=') {
06737          type = line[0];
06738          *value = ast_skip_blanks(line + 2);
06739          break;
06740       }
06741    }
06742 
06743    return type;
06744 }
06745 
06746 /*! \brief Get a specific line from the message body */
06747 static char *get_body(struct sip_request *req, char *name, char delimiter)
06748 {
06749    int x;
06750    int len = strlen(name);
06751    char *r;
06752 
06753    for (x = 0; x < req->lines; x++) {
06754       r = get_body_by_line(REQ_OFFSET_TO_STR(req, line[x]), name, len, delimiter);
06755       if (r[0] != '\0')
06756          return r;
06757    }
06758 
06759    return "";
06760 }
06761 
06762 /*! \brief Find compressed SIP alias */
06763 static const char *find_alias(const char *name, const char *_default)
06764 {
06765    /*! \brief Structure for conversion between compressed SIP and "normal" SIP */
06766    static const struct cfalias {
06767       char * const fullname;
06768       char * const shortname;
06769    } aliases[] = {
06770       { "Content-Type",  "c" },
06771       { "Content-Encoding",    "e" },
06772       { "From",       "f" },
06773       { "Call-ID",       "i" },
06774       { "Contact",       "m" },
06775       { "Content-Length",   "l" },
06776       { "Subject",       "s" },
06777       { "To",         "t" },
06778       { "Supported",     "k" },
06779       { "Refer-To",      "r" },
06780       { "Referred-By",   "b" },
06781       { "Allow-Events",  "u" },
06782       { "Event",      "o" },
06783       { "Via",     "v" },
06784       { "Accept-Contact",      "a" },
06785       { "Reject-Contact",      "j" },
06786       { "Request-Disposition", "d" },
06787       { "Session-Expires",     "x" },
06788       { "Identity",            "y" },
06789       { "Identity-Info",       "n" },
06790    };
06791    int x;
06792 
06793    for (x = 0; x < ARRAY_LEN(aliases); x++) {
06794       if (!strcasecmp(aliases[x].fullname, name))
06795          return aliases[x].shortname;
06796    }
06797 
06798    return _default;
06799 }
06800 
06801 static const char *__get_header(const struct sip_request *req, const char *name, int *start)
06802 {
06803    int pass;
06804 
06805    /*
06806     * Technically you can place arbitrary whitespace both before and after the ':' in
06807     * a header, although RFC3261 clearly says you shouldn't before, and place just
06808     * one afterwards.  If you shouldn't do it, what absolute idiot decided it was
06809     * a good idea to say you can do it, and if you can do it, why in the hell would.
06810     * you say you shouldn't.
06811     * Anyways, pedanticsipchecking controls whether we allow spaces before ':',
06812     * and we always allow spaces after that for compatibility.
06813     */
06814    for (pass = 0; name && pass < 2;pass++) {
06815       int x, len = strlen(name);
06816       for (x = *start; x < req->headers; x++) {
06817          const char *header = REQ_OFFSET_TO_STR(req, header[x]);
06818          if (!strncasecmp(header, name, len)) {
06819             const char *r = header + len; /* skip name */
06820             if (sip_cfg.pedanticsipchecking)
06821                r = ast_skip_blanks(r);
06822 
06823             if (*r == ':') {
06824                *start = x+1;
06825                return ast_skip_blanks(r+1);
06826             }
06827          }
06828       }
06829       if (pass == 0) /* Try aliases */
06830          name = find_alias(name, NULL);
06831    }
06832 
06833    /* Don't return NULL, so get_header is always a valid pointer */
06834    return "";
06835 }
06836 
06837 /*! \brief Get header from SIP request
06838    \return Always return something, so don't check for NULL because it won't happen :-)
06839 */
06840 static const char *get_header(const struct sip_request *req, const char *name)
06841 {
06842    int start = 0;
06843    return __get_header(req, name, &start);
06844 }
06845 
06846 /*! \brief Read RTP from network */
06847 static struct ast_frame *sip_rtp_read(struct ast_channel *ast, struct sip_pvt *p, int *faxdetect)
06848 {
06849    /* Retrieve audio/etc from channel.  Assumes p->lock is already held. */
06850    struct ast_frame *f;
06851    
06852    if (!p->rtp) {
06853       /* We have no RTP allocated for this channel */
06854       return &ast_null_frame;
06855    }
06856 
06857    switch(ast->fdno) {
06858    case 0:
06859       f = ast_rtp_instance_read(p->rtp, 0);  /* RTP Audio */
06860       break;
06861    case 1:
06862       f = ast_rtp_instance_read(p->rtp, 1);  /* RTCP Control Channel */
06863       break;
06864    case 2:
06865       f = ast_rtp_instance_read(p->vrtp, 0); /* RTP Video */
06866       break;
06867    case 3:
06868       f = ast_rtp_instance_read(p->vrtp, 1); /* RTCP Control Channel for video */
06869       break;
06870    case 4:
06871       f = ast_rtp_instance_read(p->trtp, 0); /* RTP Text */
06872       if (sipdebug_text) {
06873          int i;
06874          unsigned char* arr = f->data.ptr;
06875          for (i=0; i < f->datalen; i++)
06876             ast_verbose("%c", (arr[i] > ' ' && arr[i] < '}') ? arr[i] : '.');
06877          ast_verbose(" -> ");
06878          for (i=0; i < f->datalen; i++)
06879             ast_verbose("%02X ", arr[i]);
06880          ast_verbose("\n");
06881       }
06882       break;
06883    case 5:
06884       f = ast_udptl_read(p->udptl); /* UDPTL for T.38 */
06885       break;
06886    default:
06887       f = &ast_null_frame;
06888    }
06889    /* Don't forward RFC2833 if we're not supposed to */
06890    if (f && (f->frametype == AST_FRAME_DTMF_BEGIN || f->frametype == AST_FRAME_DTMF_END) &&
06891        (ast_test_flag(&p->flags[0], SIP_DTMF) != SIP_DTMF_RFC2833)) {
06892       ast_debug(1, "Ignoring DTMF (%c) RTP frame because dtmfmode is not RFC2833\n", f->subclass.integer);
06893       return &ast_null_frame;
06894    }
06895 
06896    /* We already hold the channel lock */
06897    if (!p->owner || (f && f->frametype != AST_FRAME_VOICE))
06898       return f;
06899 
06900    if (f && f->subclass.codec != (p->owner->nativeformats & AST_FORMAT_AUDIO_MASK)) {
06901       if (!(f->subclass.codec & p->jointcapability)) {
06902          ast_debug(1, "Bogus frame of format '%s' received from '%s'!\n",
06903             ast_getformatname(f->subclass.codec), p->owner->name);
06904          return &ast_null_frame;
06905       }
06906       ast_debug(1, "Oooh, format changed to %s\n",
06907          ast_getformatname(f->subclass.codec));
06908       p->owner->nativeformats = (p->owner->nativeformats & (AST_FORMAT_VIDEO_MASK | AST_FORMAT_TEXT_MASK)) | f->subclass.codec;
06909       ast_set_read_format(p->owner, p->owner->readformat);
06910       ast_set_write_format(p->owner, p->owner->writeformat);
06911    }
06912 
06913    if (f && p->dsp) {
06914       f = ast_dsp_process(p->owner, p->dsp, f);
06915       if (f && f->frametype == AST_FRAME_DTMF) {
06916          if (f->subclass.integer == 'f') {
06917             ast_debug(1, "Fax CNG detected on %s\n", ast->name);
06918             *faxdetect = 1;
06919             /* If we only needed this DSP for fax detection purposes we can just drop it now */
06920             if (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) {
06921                ast_dsp_set_features(p->dsp, DSP_FEATURE_DIGIT_DETECT);
06922             } else {
06923                ast_dsp_free(p->dsp);
06924                p->dsp = NULL;
06925             }
06926          } else {
06927             ast_debug(1, "* Detected inband DTMF '%c'\n", f->subclass.integer);
06928          }
06929       }
06930    }
06931    
06932    return f;
06933 }
06934 
06935 /*! \brief Read SIP RTP from channel */
06936 static struct ast_frame *sip_read(struct ast_channel *ast)
06937 {
06938    struct ast_frame *fr;
06939    struct sip_pvt *p = ast->tech_pvt;
06940    int faxdetected = FALSE;
06941 
06942    sip_pvt_lock(p);
06943    fr = sip_rtp_read(ast, p, &faxdetected);
06944    p->lastrtprx = time(NULL);
06945 
06946    /* If we detect a CNG tone and fax detection is enabled then send us off to the fax extension */
06947    if (faxdetected && ast_test_flag(&p->flags[1], SIP_PAGE2_FAX_DETECT_CNG)) {
06948       ast_channel_lock(ast);
06949       if (strcmp(ast->exten, "fax")) {
06950          const char *target_context = S_OR(ast->macrocontext, ast->context);
06951          ast_channel_unlock(ast);
06952          if (ast_exists_extension(ast, target_context, "fax", 1,
06953             S_COR(ast->caller.id.number.valid, ast->caller.id.number.str, NULL))) {
06954             ast_verbose(VERBOSE_PREFIX_2 "Redirecting '%s' to fax extension due to CNG detection\n", ast->name);
06955             pbx_builtin_setvar_helper(ast, "FAXEXTEN", ast->exten);
06956             if (ast_async_goto(ast, target_context, "fax", 1)) {
06957                ast_log(LOG_NOTICE, "Failed to async goto '%s' into fax of '%s'\n", ast->name, target_context);
06958             }
06959             fr = &ast_null_frame;
06960          } else {
06961             ast_log(LOG_NOTICE, "FAX CNG detected but no fax extension\n");
06962          }
06963       } else {
06964          ast_channel_unlock(ast);
06965       }
06966    }
06967 
06968    /* Only allow audio through if they sent progress with SDP, or if the channel is actually answered */
06969    if (fr && fr->frametype == AST_FRAME_VOICE && p->invitestate != INV_EARLY_MEDIA && ast->_state != AST_STATE_UP) {
06970       fr = &ast_null_frame;
06971    }
06972 
06973    sip_pvt_unlock(p);
06974 
06975    return fr;
06976 }
06977 
06978 
06979 /*! \brief Generate 32 byte random string for callid's etc */
06980 static char *generate_random_string(char *buf, size_t size)
06981 {
06982    long val[4];
06983    int x;
06984 
06985    for (x=0; x<4; x++)
06986       val[x] = ast_random();
06987    snprintf(buf, size, "%08lx%08lx%08lx%08lx", val[0], val[1], val[2], val[3]);
06988 
06989    return buf;
06990 }
06991 
06992 static char *generate_uri(struct sip_pvt *pvt, char *buf, size_t size)
06993 {
06994    struct ast_str *uri = ast_str_alloca(size);
06995    ast_str_set(&uri, 0, "%s", pvt->socket.type == SIP_TRANSPORT_TLS ? "sips:" : "sip:");
06996    /* Here would be a great place to generate a UUID, but for now we'll
06997     * use the handy random string generation function we already have
06998     */
06999    ast_str_append(&uri, 0, "%s", generate_random_string(buf, size));
07000    ast_str_append(&uri, 0, "@%s", ast_sockaddr_stringify(&pvt->ourip));
07001    ast_copy_string(buf, ast_str_buffer(uri), size);
07002    return buf;
07003 }
07004 
07005 /*! \brief Build SIP Call-ID value for a non-REGISTER transaction */
07006 static void build_callid_pvt(struct sip_pvt *pvt)
07007 {
07008    char buf[33];
07009 
07010    const char *host = S_OR(pvt->fromdomain, ast_sockaddr_stringify(&pvt->ourip));
07011    
07012    ast_string_field_build(pvt, callid, "%s@%s", generate_random_string(buf, sizeof(buf)), host);
07013 
07014 }
07015 
07016 /*! \brief Build SIP Call-ID value for a REGISTER transaction */
07017 static void build_callid_registry(struct sip_registry *reg, const struct ast_sockaddr *ourip, const char *fromdomain)
07018 {
07019    char buf[33];
07020 
07021    const char *host = S_OR(fromdomain, ast_sockaddr_stringify_host(ourip));
07022 
07023    ast_string_field_build(reg, callid, "%s@%s", generate_random_string(buf, sizeof(buf)), host);
07024 }
07025 
07026 /*! \brief Make our SIP dialog tag */
07027 static void make_our_tag(char *tagbuf, size_t len)
07028 {
07029    snprintf(tagbuf, len, "as%08lx", ast_random());
07030 }
07031 
07032 /*! \brief Allocate Session-Timers struct w/in dialog */
07033 static struct sip_st_dlg* sip_st_alloc(struct sip_pvt *const p)
07034 {
07035    struct sip_st_dlg *stp;
07036 
07037    if (p->stimer) {
07038       ast_log(LOG_ERROR, "Session-Timer struct already allocated\n");
07039       return p->stimer;
07040    }
07041 
07042    if (!(stp = ast_calloc(1, sizeof(struct sip_st_dlg))))
07043       return NULL;
07044 
07045    p->stimer = stp;
07046 
07047    stp->st_schedid = -1;           /* Session-Timers ast_sched scheduler id */
07048 
07049    return p->stimer;
07050 }
07051 
07052 /*! \brief Allocate sip_pvt structure, set defaults and link in the container.
07053  * Returns a reference to the object so whoever uses it later must
07054  * remember to release the reference.
07055  */
07056 struct sip_pvt *sip_alloc(ast_string_field callid, struct ast_sockaddr *addr,
07057              int useglobal_nat, const int intended_method, struct sip_request *req)
07058 {
07059    struct sip_pvt *p;
07060 
07061    if (!(p = ao2_t_alloc(sizeof(*p), sip_destroy_fn, "allocate a dialog(pvt) struct")))
07062       return NULL;
07063 
07064    if (ast_string_field_init(p, 512)) {
07065       ao2_t_ref(p, -1, "failed to string_field_init, drop p");
07066       return NULL;
07067    }
07068 
07069    if (!(p->cc_params = ast_cc_config_params_init())) {
07070       ao2_t_ref(p, -1, "Yuck, couldn't allocate cc_params struct. Get rid o' p");
07071       return NULL;
07072    }
07073 
07074    /* If this dialog is created as the result of an incoming Request. Lets store
07075     * some information about that request */
07076    if (req) {
07077       char *sent_by, *branch;
07078       const char *cseq = get_header(req, "Cseq");
07079       unsigned int seqno;
07080 
07081       /* get branch parameter from initial Request that started this dialog */
07082       get_viabranch(ast_strdupa(get_header(req, "Via")), &sent_by, &branch);
07083       /* only store the branch if it begins with the magic prefix "z9hG4bK", otherwise
07084        * it is not useful to us to have it */
07085       if (!ast_strlen_zero(branch) && !strncasecmp(branch, "z9hG4bK", 7)) {
07086          ast_string_field_set(p, initviabranch, branch);
07087          ast_string_field_set(p, initviasentby, sent_by);
07088       }
07089 
07090       /* Store initial incoming cseq. An error in sscanf here is ignored.  There is no approperiate
07091        * except not storing the number.  CSeq validation must take place before dialog creation in find_call */
07092       if (!ast_strlen_zero(cseq) && (sscanf(cseq, "%30u", &seqno) == 1)) {
07093          p->init_icseq = seqno;
07094       }
07095       /* Later in ast_sip_ouraddrfor we need this to choose the right ip and port for the specific transport */
07096       set_socket_transport(&p->socket, req->socket.type);
07097    } else {
07098       set_socket_transport(&p->socket, SIP_TRANSPORT_UDP);
07099    }
07100 
07101    p->socket.fd = -1;
07102    p->method = intended_method;
07103    p->initid = -1;
07104    p->waitid = -1;
07105    p->autokillid = -1;
07106    p->request_queue_sched_id = -1;
07107    p->provisional_keepalive_sched_id = -1;
07108    p->t38id = -1;
07109    p->subscribed = NONE;
07110    p->stateid = -1;
07111    p->sessionversion_remote = -1;
07112    p->session_modify = TRUE;
07113    p->stimer = NULL;
07114    p->prefs = default_prefs;     /* Set default codecs for this call */
07115    p->maxforwards = sip_cfg.default_max_forwards;
07116 
07117    if (intended_method != SIP_OPTIONS) {  /* Peerpoke has it's own system */
07118       p->timer_t1 = global_t1;   /* Default SIP retransmission timer T1 (RFC 3261) */
07119       p->timer_b = global_timer_b;  /* Default SIP transaction timer B (RFC 3261) */
07120    }
07121 
07122    if (!addr) {
07123       p->ourip = internip;
07124    } else {
07125       ast_sockaddr_copy(&p->sa, addr);
07126       ast_sip_ouraddrfor(&p->sa, &p->ourip, p);
07127    }
07128 
07129    /* Copy global flags to this PVT at setup. */
07130    ast_copy_flags(&p->flags[0], &global_flags[0], SIP_FLAGS_TO_COPY);
07131    ast_copy_flags(&p->flags[1], &global_flags[1], SIP_PAGE2_FLAGS_TO_COPY);
07132    ast_copy_flags(&p->flags[2], &global_flags[2], SIP_PAGE3_FLAGS_TO_COPY);
07133 
07134    p->do_history = recordhistory;
07135 
07136    p->branch = ast_random();  
07137    make_our_tag(p->tag, sizeof(p->tag));
07138    p->ocseq = INITIAL_CSEQ;
07139    p->allowed_methods = UINT_MAX;
07140 
07141    if (sip_methods[intended_method].need_rtp) {
07142       if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT)) {
07143          if ((p->udptl = ast_udptl_new_with_bindaddr(sched, io, 0, &bindaddr))) {
07144             ast_udptl_setqos(p->udptl, global_tos_audio, global_cos_audio);
07145             p->t38_maxdatagram = global_t38_maxdatagram;
07146          } else {
07147             /* udptl creation failed, T38 can not be supported on this dialog */
07148             ast_log(LOG_ERROR, "UDPTL creation failed\n");
07149             ast_clear_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT);
07150          }
07151       }
07152       p->maxcallbitrate = default_maxcallbitrate;
07153       p->autoframing = global_autoframing;
07154    }
07155 
07156    if (useglobal_nat && addr) {
07157       /* Setup NAT structure according to global settings if we have an address */
07158       ast_copy_flags(&p->flags[0], &global_flags[0], SIP_NAT_FORCE_RPORT);
07159       ast_sockaddr_copy(&p->recv, addr);
07160 
07161       do_setnat(p);
07162    }
07163 
07164    if (p->method != SIP_REGISTER) {
07165       ast_string_field_set(p, fromdomain, default_fromdomain);
07166       p->fromdomainport = default_fromdomainport;
07167    }
07168    build_via(p);
07169    if (!callid)
07170       build_callid_pvt(p);
07171    else
07172       ast_string_field_set(p, callid, callid);
07173    /* Assign default music on hold class */
07174    ast_string_field_set(p, mohinterpret, default_mohinterpret);
07175    ast_string_field_set(p, mohsuggest, default_mohsuggest);
07176    p->capability = sip_cfg.capability;
07177    p->allowtransfer = sip_cfg.allowtransfer;
07178    if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
07179        (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
07180       p->noncodeccapability |= AST_RTP_DTMF;
07181    if (p->udptl) {
07182       p->t38_maxdatagram = global_t38_maxdatagram;
07183       set_t38_capabilities(p);
07184    }
07185    ast_string_field_set(p, context, sip_cfg.default_context);
07186    ast_string_field_set(p, parkinglot, default_parkinglot);
07187    ast_string_field_set(p, engine, default_engine);
07188 
07189    AST_LIST_HEAD_INIT_NOLOCK(&p->request_queue);
07190 
07191    /* Add to active dialog list */
07192 
07193    ao2_t_link(dialogs, p, "link pvt into dialogs table");
07194    
07195    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");
07196    return p;
07197 }
07198 
07199 /* \brief arguments used for Request/Response to matching */
07200 struct match_req_args {
07201    int method;
07202    const char *callid;
07203    const char *totag;
07204    const char *fromtag;
07205    unsigned int seqno;
07206 
07207    /* Set if the method is a Request */
07208    const char *ruri;
07209    const char *viabranch;
07210    const char *viasentby;
07211 
07212    /* Set this if the Authentication header is present in the Request. */
07213    int authentication_present;
07214 };
07215 
07216 enum match_req_res {
07217    SIP_REQ_MATCH,
07218    SIP_REQ_NOT_MATCH,
07219    SIP_REQ_LOOP_DETECTED,
07220 };
07221 
07222 /*
07223  * \brief Match a incoming Request/Response to a dialog
07224  *
07225  * \retval enum match_req_res indicating if the dialog matches the arg
07226  */
07227 static enum match_req_res match_req_to_dialog(struct sip_pvt *sip_pvt_ptr, struct match_req_args *arg)
07228 {
07229    const char *init_ruri = NULL;
07230    if (sip_pvt_ptr->initreq.headers) {
07231       init_ruri = REQ_OFFSET_TO_STR(&sip_pvt_ptr->initreq, rlPart2);
07232    }
07233 
07234    /*
07235     * Match Tags and call-id to Dialog
07236     */
07237    if (!ast_strlen_zero(arg->callid) && strcmp(sip_pvt_ptr->callid, arg->callid)) {
07238       /* call-id does not match. */
07239       return SIP_REQ_NOT_MATCH;
07240    }
07241    if (arg->method == SIP_RESPONSE) {
07242       /* Verify totag if we have one stored for this dialog, but never be strict about this for
07243        * a response until the dialog is established */
07244       if (!ast_strlen_zero(sip_pvt_ptr->theirtag) && ast_test_flag(&sip_pvt_ptr->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED)) {
07245          if (ast_strlen_zero(arg->totag)) {
07246             /* missing totag when they already gave us one earlier */
07247             return SIP_REQ_NOT_MATCH;
07248          }
07249          if (strcmp(arg->totag, sip_pvt_ptr->theirtag)) {
07250             /* The totag of the response does not match the one we have stored */
07251             return SIP_REQ_NOT_MATCH;
07252          }
07253       }
07254       /* Verify fromtag of response matches the tag we gave them. */
07255       if (strcmp(arg->fromtag, sip_pvt_ptr->tag)) {
07256          /* fromtag from response does not match our tag */
07257          return SIP_REQ_NOT_MATCH;
07258       }
07259    } else {
07260       /* Verify the fromtag of Request matches the tag they provided earlier.
07261        * If this is a Request with authentication credentials, forget their old
07262        * tag as it is not valid after the 401 or 407 response. */
07263       if (!arg->authentication_present && strcmp(arg->fromtag, sip_pvt_ptr->theirtag)) {
07264          /* their tag does not match the one was have stored for them */
07265          return SIP_REQ_NOT_MATCH;
07266       }
07267       /* Verify if totag is present in Request, that it matches what we gave them as our tag earlier */
07268       if (!ast_strlen_zero(arg->totag) && (strcmp(arg->totag, sip_pvt_ptr->tag))) {
07269          /* totag from Request does not match our tag */
07270          return SIP_REQ_NOT_MATCH;
07271       }
07272    }
07273 
07274    /*
07275     * Compare incoming request against initial transaction.
07276     * 
07277     * This is a best effort attempt at distinguishing forked requests from
07278     * our initial transaction.  If all the elements are NOT in place to evaluate
07279     * this, this block is ignored and the dialog match is made regardless.
07280     * Once the totag is established after the dialog is confirmed, this is not necessary.
07281     *
07282     * CRITERIA required for initial transaction matching.
07283     * 
07284     * 1. Is a Request
07285     * 2. Callid and theirtag match (this is done in the dialog matching block)
07286     * 3. totag is NOT present
07287     * 4. CSeq matchs our initial transaction's cseq number
07288     * 5. pvt has init via branch parameter stored
07289     */
07290    if ((arg->method != SIP_RESPONSE) &&                 /* must be a Request */
07291       ast_strlen_zero(arg->totag) &&                   /* must not have a totag */
07292       (sip_pvt_ptr->init_icseq == arg->seqno) &&       /* the cseq must be the same as this dialogs initial cseq */
07293       !ast_strlen_zero(sip_pvt_ptr->initviabranch) &&  /* The dialog must have started with a RFC3261 compliant branch tag */
07294       init_ruri) {                                     /* the dialog must have an initial request uri associated with it */
07295       /* This Request matches all the criteria required for Loop/Merge detection.
07296        * Now we must go down the path of comparing VIA's and RURIs. */
07297       if (ast_strlen_zero(arg->viabranch) ||
07298          strcmp(arg->viabranch, sip_pvt_ptr->initviabranch) ||
07299          ast_strlen_zero(arg->viasentby) ||
07300          strcmp(arg->viasentby, sip_pvt_ptr->initviasentby)) {
07301          /* At this point, this request does not match this Dialog.*/
07302 
07303          /* if methods are different this is just a mismatch */
07304          if ((sip_pvt_ptr->method != arg->method)) {
07305             return SIP_REQ_NOT_MATCH;
07306          }
07307 
07308          /* If RUIs are different, this is a forked request to a separate URI.
07309           * Returning a mismatch allows this Request to be processed separately. */
07310          if (sip_uri_cmp(init_ruri, arg->ruri)) {
07311             /* not a match, request uris are different */
07312             return SIP_REQ_NOT_MATCH;
07313          }
07314 
07315          /* Loop/Merge Detected
07316           *
07317           * ---Current Matches to Initial Request---
07318           * request uri
07319           * Call-id
07320           * their-tag
07321           * no totag present
07322           * method
07323           * cseq
07324           *
07325           * --- Does not Match Initial Request ---
07326           * Top Via
07327           *
07328           * Without the same Via, this can not match our initial transaction for this dialog,
07329           * but given that this Request matches everything else associated with that initial
07330           * Request this is most certainly a Forked request in which we have already received
07331           * part of the fork.
07332           */
07333          return SIP_REQ_LOOP_DETECTED;
07334       }
07335    } /* end of Request Via check */
07336 
07337    /* Match Authentication Request.
07338     *
07339     * A Request with an Authentication header must come back with the
07340     * same Request URI.  Otherwise it is not a match.
07341     */
07342    if ((arg->method != SIP_RESPONSE) &&      /* Must be a Request type to even begin checking this */
07343       ast_strlen_zero(arg->totag) &&        /* no totag is present to match */
07344       arg->authentication_present &&        /* Authentication header is present in Request */
07345       sip_uri_cmp(init_ruri, arg->ruri)) {  /* Compare the Request URI of both the last Request and this new one */
07346 
07347       /* Authentication was provided, but the Request URI did not match the last one on this dialog. */
07348       return SIP_REQ_NOT_MATCH;
07349    }
07350 
07351    return SIP_REQ_MATCH;
07352 }
07353 
07354 /*! \brief find or create a dialog structure for an incoming SIP message.
07355  * Connect incoming SIP message to current dialog or create new dialog structure
07356  * Returns a reference to the sip_pvt object, remember to give it back once done.
07357  *     Called by handle_incoming(), sipsock_read
07358  */
07359 static struct sip_pvt *find_call(struct sip_request *req, struct ast_sockaddr *addr, const int intended_method)
07360 {
07361    char totag[128];
07362    char fromtag[128];
07363    const char *callid = get_header(req, "Call-ID");
07364    const char *from = get_header(req, "From");
07365    const char *to = get_header(req, "To");
07366    const char *cseq = get_header(req, "Cseq");
07367    struct sip_pvt *sip_pvt_ptr;
07368    unsigned int seqno;
07369    /* Call-ID, to, from and Cseq are required by RFC 3261. (Max-forwards and via too - ignored now) */
07370    /* get_header always returns non-NULL so we must use ast_strlen_zero() */
07371    if (ast_strlen_zero(callid) || ast_strlen_zero(to) ||
07372          ast_strlen_zero(from) || ast_strlen_zero(cseq) ||
07373          (sscanf(cseq, "%30u", &seqno) != 1)) {
07374 
07375       /* RFC 3261 section 24.4.1.   Send a 400 Bad Request if the request is malformed. */
07376       if (intended_method != SIP_RESPONSE && intended_method != SIP_ACK) {
07377          transmit_response_using_temp(callid, addr, 1, intended_method,
07378                        req, "400 Bad Request");
07379       }
07380       return NULL;   /* Invalid packet */
07381    }
07382 
07383    if (sip_cfg.pedanticsipchecking) {
07384       /* In principle Call-ID's uniquely identify a call, but with a forking SIP proxy
07385          we need more to identify a branch - so we have to check branch, from
07386          and to tags to identify a call leg.
07387          For Asterisk to behave correctly, you need to turn on pedanticsipchecking
07388          in sip.conf
07389          */
07390       if (gettag(req, "To", totag, sizeof(totag)))
07391          req->has_to_tag = 1; /* Used in handle_request/response */
07392       gettag(req, "From", fromtag, sizeof(fromtag));
07393 
07394       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);
07395 
07396       /* All messages must always have From: tag */
07397       if (ast_strlen_zero(fromtag)) {
07398          ast_debug(5, "%s request has no from tag, dropping callid: %s from: %s\n", sip_methods[req->method].text , callid, from );
07399          return NULL;
07400       }
07401       /* reject requests that must always have a To: tag */
07402       if (ast_strlen_zero(totag) && (req->method == SIP_ACK || req->method == SIP_BYE || req->method == SIP_INFO )) {
07403          ast_debug(5, "%s must have a to tag. dropping callid: %s from: %s\n", sip_methods[req->method].text , callid, from );
07404          return NULL;
07405       }
07406    }
07407 
07408    if (!sip_cfg.pedanticsipchecking) {
07409       struct sip_pvt tmp_dialog = {
07410          .callid = callid,
07411       };
07412       sip_pvt_ptr = ao2_t_find(dialogs, &tmp_dialog, OBJ_POINTER, "ao2_find in dialogs");
07413       if (sip_pvt_ptr) {  /* well, if we don't find it-- what IS in there? */
07414          /* Found the call */
07415          sip_pvt_lock(sip_pvt_ptr);
07416          return sip_pvt_ptr;
07417       }
07418    } else { /* in pedantic mode! -- do the fancy search */
07419       struct sip_pvt tmp_dialog = {
07420          .callid = callid,
07421       };
07422       struct match_req_args args = { 0, };
07423       int found;
07424       struct ao2_iterator *iterator = ao2_t_callback(dialogs,
07425          OBJ_POINTER | OBJ_MULTIPLE,
07426          dialog_find_multiple,
07427          &tmp_dialog,
07428          "pedantic ao2_find in dialogs");
07429 
07430       args.method = req->method;
07431       args.callid = NULL; /* we already matched this. */
07432       args.totag = totag;
07433       args.fromtag = fromtag;
07434       args.seqno = seqno;
07435 
07436       /* If this is a Request, set the Via and Authorization header arguments */
07437       if (req->method != SIP_RESPONSE) {
07438          args.ruri = REQ_OFFSET_TO_STR(req, rlPart2);
07439          get_viabranch(ast_strdupa(get_header(req, "Via")), (char **) &args.viasentby, (char **) &args.viabranch);
07440          if (!ast_strlen_zero(get_header(req, "Authorization")) ||
07441             !ast_strlen_zero(get_header(req, "Proxy-Authorization"))) {
07442             args.authentication_present = 1;
07443          }
07444       }
07445 
07446       /* Iterate a list of dialogs already matched by Call-id */
07447       while (iterator && (sip_pvt_ptr = ao2_iterator_next(iterator))) {
07448          found = match_req_to_dialog(sip_pvt_ptr, &args);
07449 
07450          switch (found) {
07451          case SIP_REQ_MATCH:
07452             sip_pvt_lock(sip_pvt_ptr);
07453             ao2_iterator_destroy(iterator);
07454             return sip_pvt_ptr; /* return pvt with ref */
07455          case SIP_REQ_LOOP_DETECTED:
07456             /* This is likely a forked Request that somehow resulted in us receiving multiple parts of the fork.
07457             * RFC 3261 section 8.2.2.2, Indicate that we want to merge requests by sending a 482 response. */
07458             transmit_response_using_temp(callid, addr, 1, intended_method, req, "482 (Loop Detected)");
07459             dialog_unref(sip_pvt_ptr, "pvt did not match incoming SIP msg, unref from search.");
07460             ao2_iterator_destroy(iterator);
07461             return NULL;
07462          case SIP_REQ_NOT_MATCH:
07463          default:
07464             dialog_unref(sip_pvt_ptr, "pvt did not match incoming SIP msg, unref from search");
07465          }
07466       }
07467       if (iterator) {
07468          ao2_iterator_destroy(iterator);
07469       }
07470    } /* end of pedantic mode Request/Reponse to Dialog matching */
07471 
07472    /* See if the method is capable of creating a dialog */
07473    if (sip_methods[intended_method].can_create == CAN_CREATE_DIALOG) {
07474       struct sip_pvt *p = NULL;
07475 
07476       if (intended_method == SIP_REFER) {
07477          /* We do support REFER, but not outside of a dialog yet */
07478          transmit_response_using_temp(callid, addr, 1, intended_method, req, "603 Declined (no dialog)");
07479       } else {
07480          /* Ok, time to create a new SIP dialog object, a pvt */
07481          if ((p = sip_alloc(callid, addr, 1, intended_method, req)))  {
07482             /* Ok, we've created a dialog, let's go and process it */
07483             sip_pvt_lock(p);
07484          } else {
07485             /* We have a memory or file/socket error (can't allocate RTP sockets or something) so we're not
07486                getting a dialog from sip_alloc.
07487    
07488                Without a dialog we can't retransmit and handle ACKs and all that, but at least
07489                send an error message.
07490    
07491                Sorry, we apologize for the inconvienience
07492             */
07493             transmit_response_using_temp(callid, addr, 1, intended_method, req, "500 Server internal error");
07494             ast_debug(4, "Failed allocating SIP dialog, sending 500 Server internal error and giving up\n");
07495          }
07496       }
07497       return p; /* can be NULL */
07498    } else if( sip_methods[intended_method].can_create == CAN_CREATE_DIALOG_UNSUPPORTED_METHOD) {
07499       /* A method we do not support, let's take it on the volley */
07500       transmit_response_using_temp(callid, addr, 1, intended_method, req, "501 Method Not Implemented");
07501       ast_debug(2, "Got a request with unsupported SIP method.\n");
07502    } else if (intended_method != SIP_RESPONSE && intended_method != SIP_ACK) {
07503       /* This is a request outside of a dialog that we don't know about */
07504       transmit_response_using_temp(callid, addr, 1, intended_method, req, "481 Call leg/transaction does not exist");
07505       ast_debug(2, "That's odd...  Got a request in unknown dialog. Callid %s\n", callid ? callid : "<unknown>");
07506    }
07507    /* We do not respond to responses for dialogs that we don't know about, we just drop
07508       the session quickly */
07509    if (intended_method == SIP_RESPONSE)
07510       ast_debug(2, "That's odd...  Got a response on a call we don't know about. Callid %s\n", callid ? callid : "<unknown>");
07511 
07512    return NULL;
07513 }
07514 
07515 /*! \brief create sip_registry object from register=> line in sip.conf and link into reg container */
07516 static int sip_register(const char *value, int lineno)
07517 {
07518    struct sip_registry *reg;
07519 
07520    if (!(reg = ast_calloc_with_stringfields(1, struct sip_registry, 256))) {
07521       ast_log(LOG_ERROR, "Out of memory. Can't allocate SIP registry entry\n");
07522       return -1;
07523    }
07524 
07525    ast_atomic_fetchadd_int(&regobjs, 1);
07526    ASTOBJ_INIT(reg);
07527 
07528    if (sip_parse_register_line(reg, default_expiry, value, lineno)) {
07529       registry_unref(reg, "failure to parse, unref the reg pointer");
07530       return -1;
07531    }
07532 
07533    /* set default expiry if necessary */
07534    if (reg->refresh && !reg->expiry && !reg->configured_expiry) {
07535       reg->refresh = reg->expiry = reg->configured_expiry = default_expiry;
07536    }
07537 
07538    /* Add the new registry entry to the list */
07539    ASTOBJ_CONTAINER_LINK(&regl, reg);
07540 
07541    /* release the reference given by ASTOBJ_INIT. The container has another reference */
07542    registry_unref(reg, "unref the reg pointer");
07543 
07544    return 0;
07545 }
07546 
07547 /*! \brief Parse mwi=> line in sip.conf and add to list */
07548 static int sip_subscribe_mwi(const char *value, int lineno)
07549 {
07550    struct sip_subscription_mwi *mwi;
07551    int portnum = 0;
07552    enum sip_transport transport = SIP_TRANSPORT_UDP;
07553    char buf[256] = "";
07554    char *username = NULL, *hostname = NULL, *secret = NULL, *authuser = NULL, *porta = NULL, *mailbox = NULL;
07555    
07556    if (!value) {
07557       return -1;
07558    }
07559    
07560    ast_copy_string(buf, value, sizeof(buf));
07561 
07562    sip_parse_host(buf, lineno, &username, &portnum, &transport);
07563    
07564    if ((hostname = strrchr(username, '@'))) {
07565       *hostname++ = '\0';
07566    }
07567    
07568    if ((secret = strchr(username, ':'))) {
07569       *secret++ = '\0';
07570       if ((authuser = strchr(secret, ':'))) {
07571          *authuser++ = '\0';
07572       }
07573    }
07574    
07575    if ((mailbox = strchr(hostname, '/'))) {
07576       *mailbox++ = '\0';
07577    }
07578 
07579    if (ast_strlen_zero(username) || ast_strlen_zero(hostname) || ast_strlen_zero(mailbox)) {
07580       ast_log(LOG_WARNING, "Format for MWI subscription is user[:secret[:authuser]]@host[:port][/mailbox] at line %d\n", lineno);
07581       return -1;
07582    }
07583    
07584    if ((porta = strchr(hostname, ':'))) {
07585       *porta++ = '\0';
07586       if (!(portnum = atoi(porta))) {
07587          ast_log(LOG_WARNING, "%s is not a valid port number at line %d\n", porta, lineno);
07588          return -1;
07589       }
07590    }
07591    
07592    if (!(mwi = ast_calloc_with_stringfields(1, struct sip_subscription_mwi, 256))) {
07593       return -1;
07594    }
07595    
07596    ASTOBJ_INIT(mwi);
07597    ast_string_field_set(mwi, username, username);
07598    if (secret) {
07599       ast_string_field_set(mwi, secret, secret);
07600    }
07601    if (authuser) {
07602       ast_string_field_set(mwi, authuser, authuser);
07603    }
07604    ast_string_field_set(mwi, hostname, hostname);
07605    ast_string_field_set(mwi, mailbox, mailbox);
07606    mwi->resub = -1;
07607    mwi->portno = portnum;
07608    mwi->transport = transport;
07609    
07610    ASTOBJ_CONTAINER_LINK(&submwil, mwi);
07611    ASTOBJ_UNREF(mwi, sip_subscribe_mwi_destroy);
07612    
07613    return 0;
07614 }
07615 
07616 static void mark_method_allowed(unsigned int *allowed_methods, enum sipmethod method)
07617 {
07618    (*allowed_methods) |= (1 << method);
07619 }
07620 
07621 static void mark_method_unallowed(unsigned int *allowed_methods, enum sipmethod method)
07622 {
07623    (*allowed_methods) &= ~(1 << method);
07624 }
07625 
07626 /*! \brief Check if method is allowed for a device or a dialog */
07627 static int is_method_allowed(unsigned int *allowed_methods, enum sipmethod method)
07628 {
07629    return ((*allowed_methods) >> method) & 1;
07630 }
07631 
07632 static void mark_parsed_methods(unsigned int *methods, char *methods_str)
07633 {
07634    char *method;
07635    for (method = strsep(&methods_str, ","); !ast_strlen_zero(method); method = strsep(&methods_str, ",")) {
07636       int id = find_sip_method(ast_skip_blanks(method));
07637       if (id == SIP_UNKNOWN) {
07638          continue;
07639       }
07640       mark_method_allowed(methods, id);
07641    }
07642 }
07643 /*!
07644  * \brief parse the Allow header to see what methods the endpoint we
07645  * are communicating with allows.
07646  *
07647  * We parse the allow header on incoming Registrations and save the
07648  * result to the SIP peer that is registering. When the registration
07649  * expires, we clear what we know about the peer's allowed methods.
07650  * When the peer re-registers, we once again parse to see if the
07651  * list of allowed methods has changed.
07652  *
07653  * For peers that do not register, we parse the first message we receive
07654  * during a call to see what is allowed, and save the information
07655  * for the duration of the call.
07656  * \param req The SIP request we are parsing
07657  * \retval The methods allowed
07658  */
07659 static unsigned int parse_allowed_methods(struct sip_request *req)
07660 {
07661    char *allow = ast_strdupa(get_header(req, "Allow"));
07662    unsigned int allowed_methods = SIP_UNKNOWN;
07663 
07664    if (ast_strlen_zero(allow)) {
07665       /* I have witnessed that REGISTER requests from Polycom phones do not
07666        * place the phone's allowed methods in an Allow header. Instead, they place the
07667        * allowed methods in a methods= parameter in the Contact header.
07668        */
07669       char *contact = ast_strdupa(get_header(req, "Contact"));
07670       char *methods = strstr(contact, ";methods=");
07671 
07672       if (ast_strlen_zero(methods)) {
07673          /* RFC 3261 states:
07674           *
07675           * "The absence of an Allow header field MUST NOT be
07676           * interpreted to mean that the UA sending the message supports no
07677           * methods.   Rather, it implies that the UA is not providing any
07678           * information on what methods it supports."
07679           *
07680           * For simplicity, we'll assume that the peer allows all known
07681           * SIP methods if they have no Allow header. We can then clear out the necessary
07682           * bits if the peer lets us know that we have sent an unsupported method.
07683           */
07684          return UINT_MAX;
07685       }
07686       allow = ast_strip_quoted(methods + 9, "\"", "\"");
07687    }
07688    mark_parsed_methods(&allowed_methods, allow);
07689    return allowed_methods;
07690 }
07691 
07692 /*! A wrapper for parse_allowed_methods geared toward sip_pvts
07693  *
07694  * This function, in addition to setting the allowed methods for a sip_pvt
07695  * also will take into account the setting of the SIP_PAGE2_RPID_UPDATE flag.
07696  *
07697  * \param pvt The sip_pvt we are setting the allowed_methods for
07698  * \param req The request which we are parsing
07699  * \retval The methods alloweded by the sip_pvt
07700  */
07701 static unsigned int set_pvt_allowed_methods(struct sip_pvt *pvt, struct sip_request *req)
07702 {
07703    pvt->allowed_methods = parse_allowed_methods(req);
07704    
07705    if (ast_test_flag(&pvt->flags[1], SIP_PAGE2_RPID_UPDATE)) {
07706       mark_method_allowed(&pvt->allowed_methods, SIP_UPDATE);
07707    }
07708    pvt->allowed_methods &= ~(pvt->disallowed_methods);
07709 
07710    return pvt->allowed_methods;
07711 }
07712 
07713 /*! \brief  Parse multiline SIP headers into one header
07714    This is enabled if pedanticsipchecking is enabled */
07715 static int lws2sws(char *msgbuf, int len)
07716 {
07717    int h = 0, t = 0;
07718    int lws = 0;
07719 
07720    for (; h < len;) {
07721       /* Eliminate all CRs */
07722       if (msgbuf[h] == '\r') {
07723          h++;
07724          continue;
07725       }
07726       /* Check for end-of-line */
07727       if (msgbuf[h] == '\n') {
07728          /* Check for end-of-message */
07729          if (h + 1 == len)
07730             break;
07731          /* Check for a continuation line */
07732          if (msgbuf[h + 1] == ' ' || msgbuf[h + 1] == '\t') {
07733             /* Merge continuation line */
07734             h++;
07735             continue;
07736          }
07737          /* Propagate LF and start new line */
07738          msgbuf[t++] = msgbuf[h++];
07739          lws = 0;
07740          continue;
07741       }
07742       if (msgbuf[h] == ' ' || msgbuf[h] == '\t') {
07743          if (lws) {
07744             h++;
07745             continue;
07746          }
07747          msgbuf[t++] = msgbuf[h++];
07748          lws = 1;
07749          continue;
07750       }
07751       msgbuf[t++] = msgbuf[h++];
07752       if (lws)
07753          lws = 0;
07754    }
07755    msgbuf[t] = '\0';
07756    return t;
07757 }
07758 
07759 /*! \brief Parse a SIP message
07760    \note this function is used both on incoming and outgoing packets
07761 */
07762 static int parse_request(struct sip_request *req)
07763 {
07764    char *c = req->data->str;
07765    ptrdiff_t *dst = req->header;
07766    int i = 0, lim = SIP_MAX_HEADERS - 1;
07767    unsigned int skipping_headers = 0;
07768    ptrdiff_t current_header_offset = 0;
07769    char *previous_header = "";
07770 
07771    req->header[0] = 0;
07772    req->headers = -1;   /* mark that we are working on the header */
07773    for (; *c; c++) {
07774       if (*c == '\r') {    /* remove \r */
07775          *c = '\0';
07776       } else if (*c == '\n') {   /* end of this line */
07777          *c = '\0';
07778          current_header_offset = (c + 1) - req->data->str;
07779          previous_header = req->data->str + dst[i];
07780          if (skipping_headers) {
07781             /* check to see if this line is blank; if so, turn off
07782                the skipping flag, so the next line will be processed
07783                as a body line */
07784             if (ast_strlen_zero(previous_header)) {
07785                skipping_headers = 0;
07786             }
07787             dst[i] = current_header_offset; /* record start of next line */
07788             continue;
07789          }
07790          if (sipdebug) {
07791             ast_debug(4, "%7s %2d [%3d]: %s\n",
07792                  req->headers < 0 ? "Header" : "Body",
07793                  i, (int) strlen(previous_header), previous_header);
07794          }
07795          if (ast_strlen_zero(previous_header) && req->headers < 0) {
07796             req->headers = i; /* record number of header lines */
07797             dst = req->line;  /* start working on the body */
07798             i = 0;
07799             lim = SIP_MAX_LINES - 1;
07800          } else { /* move to next line, check for overflows */
07801             if (i++ == lim) {
07802                /* if we're processing headers, then skip any remaining
07803                   headers and move on to processing the body, otherwise
07804                   we're done */
07805                if (req->headers != -1) {
07806                   break;
07807                } else {
07808                   req->headers = i;
07809                   dst = req->line;
07810                   i = 0;
07811                   lim = SIP_MAX_LINES - 1;
07812                   skipping_headers = 1;
07813                }
07814             }
07815          }
07816          dst[i] = current_header_offset; /* record start of next line */
07817       }
07818    }
07819 
07820    /* Check for last header or body line without CRLF. The RFC for SDP requires CRLF,
07821       but since some devices send without, we'll be generous in what we accept. However,
07822       if we've already reached the maximum number of lines for portion of the message
07823       we were parsing, we can't accept any more, so just ignore it.
07824    */
07825    previous_header = req->data->str + dst[i];
07826    if ((i < lim) && !ast_strlen_zero(previous_header)) {
07827       if (sipdebug) {
07828          ast_debug(4, "%7s %2d [%3d]: %s\n",
07829               req->headers < 0 ? "Header" : "Body",
07830               i, (int) strlen(previous_header), previous_header );
07831       }
07832       i++;
07833    }
07834 
07835    /* update count of header or body lines */
07836    if (req->headers >= 0) {   /* we are in the body */
07837       req->lines = i;
07838    } else {       /* no body */
07839       req->headers = i;
07840       req->lines = 0;
07841       /* req->data->used will be a NULL byte */
07842       req->line[0] = ast_str_strlen(req->data);
07843    }
07844 
07845    if (*c) {
07846       ast_log(LOG_WARNING, "Too many lines, skipping <%s>\n", c);
07847    }
07848 
07849    /* Split up the first line parts */
07850    return determine_firstline_parts(req);
07851 }
07852 
07853 /*!
07854   \brief Determine whether a SIP message contains an SDP in its body
07855   \param req the SIP request to process
07856   \return 1 if SDP found, 0 if not found
07857 
07858   Also updates req->sdp_start and req->sdp_count to indicate where the SDP
07859   lives in the message body.
07860 */
07861 static int find_sdp(struct sip_request *req)
07862 {
07863    const char *content_type;
07864    const char *content_length;
07865    const char *search;
07866    char *boundary;
07867    unsigned int x;
07868    int boundaryisquoted = FALSE;
07869    int found_application_sdp = FALSE;
07870    int found_end_of_headers = FALSE;
07871 
07872    content_length = get_header(req, "Content-Length");
07873 
07874    if (!ast_strlen_zero(content_length)) {
07875       if (sscanf(content_length, "%30u", &x) != 1) {
07876          ast_log(LOG_WARNING, "Invalid Content-Length: %s\n", content_length);
07877          return 0;
07878       }
07879 
07880       /* Content-Length of zero means there can't possibly be an
07881          SDP here, even if the Content-Type says there is */
07882       if (x == 0)
07883          return 0;
07884    }
07885 
07886    content_type = get_header(req, "Content-Type");
07887 
07888    /* if the body contains only SDP, this is easy */
07889    if (!strncasecmp(content_type, "application/sdp", 15)) {
07890       req->sdp_start = 0;
07891       req->sdp_count = req->lines;
07892       return req->lines ? 1 : 0;
07893    }
07894 
07895    /* if it's not multipart/mixed, there cannot be an SDP */
07896    if (strncasecmp(content_type, "multipart/mixed", 15))
07897       return 0;
07898 
07899    /* if there is no boundary marker, it's invalid */
07900    if ((search = strcasestr(content_type, ";boundary=")))
07901       search += 10;
07902    else if ((search = strcasestr(content_type, "; boundary=")))
07903       search += 11;
07904    else
07905       return 0;
07906 
07907    if (ast_strlen_zero(search))
07908       return 0;
07909 
07910    /* If the boundary is quoted with ", remove quote */
07911    if (*search == '\"')  {
07912       search++;
07913       boundaryisquoted = TRUE;
07914    }
07915 
07916    /* make a duplicate of the string, with two extra characters
07917       at the beginning */
07918    boundary = ast_strdupa(search - 2);
07919    boundary[0] = boundary[1] = '-';
07920    /* Remove final quote */
07921    if (boundaryisquoted)
07922       boundary[strlen(boundary) - 1] = '\0';
07923 
07924    /* search for the boundary marker, the empty line delimiting headers from
07925       sdp part and the end boundry if it exists */
07926 
07927    for (x = 0; x < (req->lines); x++) {
07928       const char *line = REQ_OFFSET_TO_STR(req, line[x]);
07929       if (!strncasecmp(line, boundary, strlen(boundary))){
07930          if (found_application_sdp && found_end_of_headers) {
07931             req->sdp_count = (x - 1) - req->sdp_start;
07932             return 1;
07933          }
07934          found_application_sdp = FALSE;
07935       }
07936       if (!strcasecmp(line, "Content-Type: application/sdp"))
07937          found_application_sdp = TRUE;
07938       
07939       if (ast_strlen_zero(line)) {
07940          if (found_application_sdp && !found_end_of_headers){
07941             req->sdp_start = x;
07942             found_end_of_headers = TRUE;
07943          }
07944       }
07945    }
07946    if (found_application_sdp && found_end_of_headers) {
07947       req->sdp_count = x - req->sdp_start;
07948       return TRUE;
07949    }
07950    return FALSE;
07951 }
07952 
07953 
07954 static int get_ip_and_port_from_sdp(struct sip_request *req, const enum media_type media, struct ast_sockaddr *addr)
07955 {
07956    const char *m;
07957    const char *c;
07958    int miterator = req->sdp_start;
07959    int citerator = req->sdp_start;
07960    int x = 0;
07961    int numberofports;
07962    int len;
07963    int af;
07964    char proto[4], host[258] = ""; /*Initialize to empty so we will know if we have any input */
07965 
07966    c = get_sdp_iterate(&citerator, req, "c");
07967    if (sscanf(c, "IN %3s %256s", proto, host) != 2) {
07968          ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
07969          /* Continue since there may be a valid host in a c= line specific to the audio stream */
07970    }
07971    /* We only want the m and c lines for audio */
07972    for (m = get_sdp_iterate(&miterator, req, "m"); !ast_strlen_zero(m); m = get_sdp_iterate(&miterator, req, "m")) {
07973       if ((media == SDP_AUDIO && ((sscanf(m, "audio %30u/%30u RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
07974           (sscanf(m, "audio %30u RTP/AVP %n", &x, &len) == 1 && len > 0))) ||
07975          (media == SDP_VIDEO && ((sscanf(m, "video %30u/%30u RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
07976           (sscanf(m, "video %30u RTP/AVP %n", &x, &len) == 1 && len > 0)))) {
07977          /* See if there's a c= line for this media stream.
07978           * XXX There is no guarantee that we'll be grabbing the c= line for this
07979           * particular media stream here. However, this is the same logic used in process_sdp.
07980           */
07981          c = get_sdp_iterate(&citerator, req, "c");
07982          if (!ast_strlen_zero(c)) {
07983             sscanf(c, "IN %3s %256s", proto, host);
07984          }
07985          break;
07986       }
07987    }
07988 
07989    if (!strcmp("IP4", proto)) {
07990       af = AF_INET;
07991    } else if (!strcmp("IP6", proto)) {
07992       af = AF_INET6;
07993    } else {
07994       ast_log(LOG_WARNING, "Unknown protocol '%s'.\n", proto);
07995       return -1;
07996    }
07997 
07998    if (ast_strlen_zero(host) || x == 0) {
07999       ast_log(LOG_WARNING, "Failed to read an alternate host or port in SDP. Expect %s problems\n", media == SDP_AUDIO ? "audio" : "video");
08000       return -1;
08001    }
08002 
08003    if (ast_sockaddr_resolve_first_af(addr, host, 0, af)) {
08004       ast_log(LOG_WARNING, "Could not look up IP address of alternate hostname. Expect %s problems\n", media == SDP_AUDIO? "audio" : "video");
08005       return -1;
08006    }
08007 
08008    return 0;
08009 }
08010 
08011 /*! \brief Process SIP SDP offer, select formats and activate RTP channels
08012    If offer is rejected, we will not change any properties of the call
08013    Return 0 on success, a negative value on errors.
08014    Must be called after find_sdp().
08015 */
08016 static int process_sdp(struct sip_pvt *p, struct sip_request *req, int t38action)
08017 {
08018    /* Iterators for SDP parsing */
08019    int start = req->sdp_start;
08020    int next = start;
08021    int iterator = start;
08022 
08023    /* Temporary vars for SDP parsing */
08024    char type = '\0';
08025    const char *value = NULL;
08026    const char *m = NULL;           /* SDP media offer */
08027    const char *nextm = NULL;
08028    int len = -1;
08029 
08030    /* Host information */
08031    struct ast_sockaddr sessionsa;
08032    struct ast_sockaddr audiosa;
08033    struct ast_sockaddr videosa;
08034    struct ast_sockaddr textsa;
08035    struct ast_sockaddr imagesa;
08036    struct ast_sockaddr *sa = NULL;  /*!< RTP Audio host IP */
08037    struct ast_sockaddr *vsa = NULL; /*!< RTP video host IP */
08038    struct ast_sockaddr *tsa = NULL; /*!< RTP text host IP */
08039    struct ast_sockaddr *isa = NULL;     /*!< UDPTL host ip */
08040    int portno = -1;     /*!< RTP Audio port number */
08041    int vportno = -1;    /*!< RTP Video port number */
08042    int tportno = -1;    /*!< RTP Text port number */
08043    int udptlportno = -1;      /*!< UDPTL Image port number */
08044 
08045    /* Peer capability is the capability in the SDP, non codec is RFC2833 DTMF (101) */ 
08046    format_t peercapability = 0, vpeercapability = 0, tpeercapability = 0;
08047    int peernoncodeccapability = 0, vpeernoncodeccapability = 0, tpeernoncodeccapability = 0;
08048 
08049    struct ast_rtp_codecs newaudiortp, newvideortp, newtextrtp;
08050    format_t newjointcapability;           /* Negotiated capability */
08051    format_t newpeercapability;
08052    int newnoncodeccapability;
08053 
08054    const char *codecs;
08055    int codec;
08056 
08057    /* SRTP */
08058    int secure_audio = FALSE;
08059    int secure_video = FALSE;
08060 
08061    /* Others */
08062    int sendonly = -1;
08063    int vsendonly = -1;
08064    int numberofports;
08065    int numberofmediastreams = 0;
08066    int last_rtpmap_codec = 0;
08067    int red_data_pt[10];    /* For T.140 red */
08068    int red_num_gen = 0;    /* For T.140 red */
08069    char red_fmtp[100] = "empty"; /* For T.140 red */
08070    int debug = sip_debug_test_pvt(p);
08071 
08072    /* START UNKNOWN */
08073    char buf[SIPBUFSIZE];
08074    /* END UNKNOWN */
08075 
08076    /* Initial check */
08077    if (!p->rtp) {
08078       ast_log(LOG_ERROR, "Got SDP but have no RTP session allocated.\n");
08079       return -1;
08080    }
08081 
08082    /* Make sure that the codec structures are all cleared out */
08083    ast_rtp_codecs_payloads_clear(&newaudiortp, NULL);
08084    ast_rtp_codecs_payloads_clear(&newvideortp, NULL);
08085    ast_rtp_codecs_payloads_clear(&newtextrtp, NULL);
08086 
08087    /* Update our last rtprx when we receive an SDP, too */
08088    p->lastrtprx = p->lastrtptx = time(NULL); /* XXX why both ? */
08089 
08090    memset(p->offered_media, 0, sizeof(p->offered_media));
08091 
08092 
08093    /* default: novideo and notext set */
08094    p->novideo = TRUE;
08095    p->notext = TRUE;
08096 
08097    if (p->vrtp) {
08098       ast_rtp_codecs_payloads_clear(&newvideortp, NULL);
08099    }
08100 
08101    if (p->trtp) {
08102       ast_rtp_codecs_payloads_clear(&newtextrtp, NULL);
08103    }
08104 
08105    /* Scan for the first media stream (m=) line to limit scanning of globals */
08106    nextm = get_sdp_iterate(&next, req, "m");
08107    if (ast_strlen_zero(nextm)) {
08108       ast_log(LOG_WARNING, "Insufficient information for SDP (m= not found)\n");
08109       return -1;
08110    }
08111 
08112    /* Scan session level SDP parameters (lines before first media stream) */
08113    while ((type = get_sdp_line(&iterator, next - 1, req, &value)) != '\0') {
08114       int processed = FALSE;
08115       switch (type) {
08116       case 'o':
08117          /* If we end up receiving SDP that doesn't actually modify the session we don't want to treat this as a fatal
08118           * error. We just want to ignore the SDP and let the rest of the packet be handled as normal.
08119           */
08120          if (!process_sdp_o(value, p))
08121             return (p->session_modify == FALSE) ? 0 : -1;
08122          break;
08123       case 'c':
08124          if (process_sdp_c(value, &sessionsa)) {
08125             processed = TRUE;
08126             sa = &sessionsa;
08127             vsa = sa;
08128             tsa = sa;
08129             isa = sa;
08130          }
08131          break;
08132       case 'a':
08133          if (process_sdp_a_sendonly(value, &sendonly)) {
08134             processed = TRUE;
08135             vsendonly = sendonly;
08136          }
08137          else if (process_sdp_a_audio(value, p, &newaudiortp, &last_rtpmap_codec))
08138             processed = TRUE;
08139          else if (process_sdp_a_video(value, p, &newvideortp, &last_rtpmap_codec))
08140             processed = TRUE;
08141          else if (process_sdp_a_text(value, p, &newtextrtp, red_fmtp, &red_num_gen, red_data_pt, &last_rtpmap_codec))
08142             processed = TRUE;
08143          else if (process_sdp_a_image(value, p))
08144             processed = TRUE;
08145          break;
08146       }
08147 
08148       ast_debug(3, "Processing session-level SDP %c=%s... %s\n", type, value, (processed == TRUE)? "OK." : "UNSUPPORTED.");
08149    }
08150 
08151 
08152 
08153    /* Scan media stream (m=) specific parameters loop */
08154    while (!ast_strlen_zero(nextm)) {
08155       int audio = FALSE;
08156       int video = FALSE;
08157       int image = FALSE;
08158       int text = FALSE;
08159       char protocol[5] = {0,};
08160       int x;
08161 
08162       numberofports = 1;
08163       len = -1;
08164       start = next;
08165       m = nextm;
08166       iterator = next;
08167       nextm = get_sdp_iterate(&next, req, "m");
08168 
08169       /* Search for audio media definition */
08170       if ((sscanf(m, "audio %30u/%30u RTP/%4s %n", &x, &numberofports, protocol, &len) == 3 && len > 0) ||
08171           (sscanf(m, "audio %30u RTP/%4s %n", &x, protocol, &len) == 2 && len > 0)) {
08172          if (!strcmp(protocol, "SAVP")) {
08173             secure_audio = 1;
08174          } else if (strcmp(protocol, "AVP")) {
08175             ast_log(LOG_WARNING, "unknown SDP media protocol in offer: %s\n", protocol);
08176             continue;
08177          }
08178          audio = TRUE;
08179          p->offered_media[SDP_AUDIO].offered = TRUE;
08180          numberofmediastreams++;
08181          portno = x;
08182 
08183          /* Scan through the RTP payload types specified in a "m=" line: */
08184          codecs = m + len;
08185          ast_copy_string(p->offered_media[SDP_AUDIO].codecs, codecs, sizeof(p->offered_media[SDP_AUDIO].codecs));
08186          for (; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
08187             if (sscanf(codecs, "%30u%n", &codec, &len) != 1) {
08188                ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
08189                return -1;
08190             }
08191             if (debug)
08192                ast_verbose("Found RTP audio format %d\n", codec);
08193             
08194             ast_rtp_codecs_payloads_set_m_type(&newaudiortp, NULL, codec);
08195          }
08196       /* Search for video media definition */
08197       } else if ((sscanf(m, "video %30u/%30u RTP/%4s %n", &x, &numberofports, protocol, &len) == 3 && len > 0) ||
08198             (sscanf(m, "video %30u RTP/%4s %n", &x, protocol, &len) == 2 && len >= 0)) {
08199          if (!strcmp(protocol, "SAVP")) {
08200             secure_video = 1;
08201          } else if (strcmp(protocol, "AVP")) {
08202             ast_log(LOG_WARNING, "unknown SDP media protocol in offer: %s\n", protocol);
08203             continue;
08204          }
08205          video = TRUE;
08206          p->novideo = FALSE;
08207          p->offered_media[SDP_VIDEO].offered = TRUE;
08208          numberofmediastreams++;
08209          vportno = x;
08210 
08211          /* Scan through the RTP payload types specified in a "m=" line: */
08212          codecs = m + len;
08213          ast_copy_string(p->offered_media[SDP_VIDEO].codecs, codecs, sizeof(p->offered_media[SDP_VIDEO].codecs));
08214          for (; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
08215             if (sscanf(codecs, "%30u%n", &codec, &len) != 1) {
08216                ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
08217                return -1;
08218             }
08219             if (debug)
08220                ast_verbose("Found RTP video format %d\n", codec);
08221             ast_rtp_codecs_payloads_set_m_type(&newvideortp, NULL, codec);
08222          }
08223       /* Search for text media definition */
08224       } else if ((sscanf(m, "text %30u/%30u RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
08225             (sscanf(m, "text %30u RTP/AVP %n", &x, &len) == 1 && len > 0)) {
08226          text = TRUE;
08227          p->notext = FALSE;
08228          p->offered_media[SDP_TEXT].offered = TRUE;
08229          numberofmediastreams++;
08230          tportno = x;
08231 
08232          /* Scan through the RTP payload types specified in a "m=" line: */
08233          codecs = m + len;
08234          ast_copy_string(p->offered_media[SDP_TEXT].codecs, codecs, sizeof(p->offered_media[SDP_TEXT].codecs));
08235          for (; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
08236             if (sscanf(codecs, "%30u%n", &codec, &len) != 1) {
08237                ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
08238                return -1;
08239             }
08240             if (debug)
08241                ast_verbose("Found RTP text format %d\n", codec);
08242             ast_rtp_codecs_payloads_set_m_type(&newtextrtp, NULL, codec);
08243          }
08244       /* Search for image media definition */
08245       } else if (p->udptl && ((sscanf(m, "image %30u udptl t38%n", &x, &len) == 1 && len > 0) ||
08246                (sscanf(m, "image %30u UDPTL t38%n", &x, &len) == 1 && len > 0) )) {
08247          image = TRUE;
08248          if (debug)
08249             ast_verbose("Got T.38 offer in SDP in dialog %s\n", p->callid);
08250          p->offered_media[SDP_IMAGE].offered = TRUE;
08251          udptlportno = x;
08252          numberofmediastreams++;
08253 
08254          if (p->t38.state != T38_ENABLED) {
08255             memset(&p->t38.their_parms, 0, sizeof(p->t38.their_parms));
08256 
08257             /* default EC to none, the remote end should
08258              * respond with the EC they want to use */
08259             ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_NONE);
08260          }
08261       } else {
08262          ast_log(LOG_WARNING, "Unsupported SDP media type in offer: %s\n", m);
08263          continue;
08264       }
08265 
08266       /* Check for number of ports */
08267       if (numberofports > 1)
08268          ast_log(LOG_WARNING, "SDP offered %d ports for media, not supported by Asterisk. Will try anyway...\n", numberofports);
08269       
08270       /* Media stream specific parameters */
08271       while ((type = get_sdp_line(&iterator, next - 1, req, &value)) != '\0') {
08272          int processed = FALSE;
08273 
08274          switch (type) {
08275          case 'c':
08276             if (audio) {
08277                if (process_sdp_c(value, &audiosa)) {
08278                   processed = TRUE;
08279                   sa = &audiosa;
08280                }
08281             } else if (video) {
08282                if (process_sdp_c(value, &videosa)) {
08283                   processed = TRUE;
08284                   vsa = &videosa;
08285                }
08286             } else if (text) {
08287                if (process_sdp_c(value, &textsa)) {
08288                   processed = TRUE;
08289                   tsa = &textsa;
08290                }
08291             } else if (image) {
08292                if (process_sdp_c(value, &imagesa)) {
08293                   processed = TRUE;
08294                   isa = &imagesa;
08295                }
08296             }
08297             break;
08298          case 'a':
08299             /* Audio specific scanning */
08300             if (audio) {
08301                if (process_sdp_a_sendonly(value, &sendonly))
08302                   processed = TRUE;
08303                else if (process_crypto(p, p->rtp, &p->srtp, value))
08304                   processed = TRUE;
08305                else if (process_sdp_a_audio(value, p, &newaudiortp, &last_rtpmap_codec))
08306                   processed = TRUE;
08307             }
08308             /* Video specific scanning */
08309             else if (video) {
08310                if (process_sdp_a_sendonly(value, &vsendonly))
08311                   processed = TRUE;
08312                else if (process_crypto(p, p->vrtp, &p->vsrtp, value))
08313                   processed = TRUE;
08314                else if (process_sdp_a_video(value, p, &newvideortp, &last_rtpmap_codec))
08315                   processed = TRUE;
08316             }
08317             /* Text (T.140) specific scanning */
08318             else if (text) {
08319                if (process_sdp_a_text(value, p, &newtextrtp, red_fmtp, &red_num_gen, red_data_pt, &last_rtpmap_codec))
08320                   processed = TRUE;
08321                else if (process_crypto(p, p->trtp, &p->tsrtp, value))
08322                   processed = TRUE;
08323             }
08324             /* Image (T.38 FAX) specific scanning */
08325             else if (image) {
08326                if (process_sdp_a_image(value, p))
08327                   processed = TRUE;
08328             }
08329             break;
08330          }
08331 
08332          ast_debug(3, "Processing media-level (%s) SDP %c=%s... %s\n",
08333                (audio == TRUE)? "audio" : (video == TRUE)? "video" : "image",
08334                type, value,
08335                (processed == TRUE)? "OK." : "UNSUPPORTED.");
08336       }
08337    }
08338 
08339 
08340    /* Sanity checks */
08341    if (!sa && !vsa && !tsa && !isa) {
08342       ast_log(LOG_WARNING, "Insufficient information in SDP (c=)...\n");
08343       return -1;
08344    }
08345 
08346    if (portno == -1 && vportno == -1 && udptlportno == -1  && tportno == -1) {
08347       /* No acceptable offer found in SDP  - we have no ports */
08348       /* Do not change RTP or VRTP if this is a re-invite */
08349       ast_log(LOG_WARNING, "Failing due to no acceptable offer found\n");
08350       return -2;
08351    }
08352 
08353    if (numberofmediastreams > 3) {
08354       /* We have too many fax, audio and/or video and/or text media streams, fail this offer */
08355       ast_log(LOG_WARNING, "Faling due to too many media streams\n");
08356       return -3;
08357    }
08358 
08359    if (secure_audio && !(p->srtp && (ast_test_flag(p->srtp, SRTP_CRYPTO_OFFER_OK)))) {
08360       ast_log(LOG_WARNING, "Can't provide secure audio requested in SDP offer\n");
08361       return -4;
08362    }
08363 
08364    if (!secure_audio && p->srtp) {
08365       ast_log(LOG_WARNING, "We are requesting SRTP, but they responded without it!\n");
08366       return -4;
08367    }
08368 
08369    if (secure_video && !(p->vsrtp && (ast_test_flag(p->vsrtp, SRTP_CRYPTO_OFFER_OK)))) {
08370       ast_log(LOG_WARNING, "Can't provide secure video requested in SDP offer\n");
08371       return -4;
08372    }
08373 
08374    if (!p->novideo && !secure_video && p->vsrtp) {
08375       ast_log(LOG_WARNING, "We are requesting SRTP, but they responded without it!\n");
08376       return -4;
08377    }
08378 
08379    if (!(secure_audio || secure_video) && ast_test_flag(&p->flags[1], SIP_PAGE2_USE_SRTP)) {
08380       ast_log(LOG_WARNING, "Matched device setup to use SRTP, but request was not!\n");
08381       return -4;
08382    }
08383 
08384    if (udptlportno == -1) {
08385       change_t38_state(p, T38_DISABLED);
08386    }
08387 
08388    /* Now gather all of the codecs that we are asked for: */
08389    ast_rtp_codecs_payload_formats(&newaudiortp, &peercapability, &peernoncodeccapability);
08390    ast_rtp_codecs_payload_formats(&newvideortp, &vpeercapability, &vpeernoncodeccapability);
08391    ast_rtp_codecs_payload_formats(&newtextrtp, &tpeercapability, &tpeernoncodeccapability);
08392 
08393    newjointcapability = p->capability & (peercapability | vpeercapability | tpeercapability);
08394    newpeercapability = (peercapability | vpeercapability | tpeercapability);
08395    newnoncodeccapability = p->noncodeccapability & peernoncodeccapability;
08396 
08397    if (debug) {
08398       /* shame on whoever coded this.... */
08399       char s1[SIPBUFSIZE], s2[SIPBUFSIZE], s3[SIPBUFSIZE], s4[SIPBUFSIZE], s5[SIPBUFSIZE];
08400 
08401       ast_verbose("Capabilities: us - %s, peer - audio=%s/video=%s/text=%s, combined - %s\n",
08402              ast_getformatname_multiple(s1, SIPBUFSIZE, p->capability),
08403              ast_getformatname_multiple(s2, SIPBUFSIZE, peercapability),
08404              ast_getformatname_multiple(s3, SIPBUFSIZE, vpeercapability),
08405              ast_getformatname_multiple(s4, SIPBUFSIZE, tpeercapability),
08406              ast_getformatname_multiple(s5, SIPBUFSIZE, newjointcapability));
08407    }
08408    if (debug) {
08409       struct ast_str *s1 = ast_str_alloca(SIPBUFSIZE);
08410       struct ast_str *s2 = ast_str_alloca(SIPBUFSIZE);
08411       struct ast_str *s3 = ast_str_alloca(SIPBUFSIZE);
08412 
08413       ast_verbose("Non-codec capabilities (dtmf): us - %s, peer - %s, combined - %s\n",
08414              ast_rtp_lookup_mime_multiple2(s1, p->noncodeccapability, 0, 0),
08415              ast_rtp_lookup_mime_multiple2(s2, peernoncodeccapability, 0, 0),
08416              ast_rtp_lookup_mime_multiple2(s3, newnoncodeccapability, 0, 0));
08417    }
08418    if (!newjointcapability && (portno != -1)) {
08419       ast_log(LOG_NOTICE, "No compatible codecs, not accepting this offer!\n");
08420       /* Do NOT Change current setting */
08421       return -1;
08422    }
08423 
08424    /* Setup audio address and port */
08425    if (p->rtp) {
08426       if (portno > 0) {
08427          ast_sockaddr_set_port(sa, portno);
08428          ast_rtp_instance_set_remote_address(p->rtp, sa);
08429          if (debug) {
08430             ast_verbose("Peer audio RTP is at port %s\n",
08431                    ast_sockaddr_stringify(sa));
08432          }
08433          /* We are now ready to change the sip session and p->rtp and p->vrtp with the offered codecs, since
08434             they are acceptable */
08435          p->jointcapability = newjointcapability;                /* Our joint codec profile for this call */
08436          p->peercapability = newpeercapability;                  /* The other sides capability in latest offer */
08437          p->jointnoncodeccapability = newnoncodeccapability;     /* DTMF capabilities */
08438 
08439          if (ast_test_flag(&p->flags[1], SIP_PAGE2_PREFERRED_CODEC)) { /* respond with single most preferred joint codec, limiting the other side's choice */
08440             p->jointcapability = ast_codec_choose(&p->prefs, p->jointcapability, 1);
08441          }
08442 
08443          ast_rtp_codecs_payloads_copy(&newaudiortp, ast_rtp_instance_get_codecs(p->rtp), p->rtp);
08444 
08445          if (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO) {
08446             ast_clear_flag(&p->flags[0], SIP_DTMF);
08447             if (newnoncodeccapability & AST_RTP_DTMF) {
08448                /* XXX Would it be reasonable to drop the DSP at this point? XXX */
08449                ast_set_flag(&p->flags[0], SIP_DTMF_RFC2833);
08450                /* Since RFC2833 is now negotiated we need to change some properties of the RTP stream */
08451                ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_DTMF, 1);
08452                ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_DTMF_COMPENSATE, ast_test_flag(&p->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
08453             } else {
08454                ast_set_flag(&p->flags[0], SIP_DTMF_INBAND);
08455             }
08456          }
08457       } else if (udptlportno > 0) {
08458          if (debug)
08459             ast_verbose("Got T.38 Re-invite without audio. Keeping RTP active during T.38 session.\n");
08460       } else {
08461          ast_rtp_instance_stop(p->rtp);
08462          if (debug)
08463             ast_verbose("Peer doesn't provide audio\n");
08464       }
08465    }
08466 
08467    /* Setup video address and port */
08468    if (p->vrtp) {
08469       if (vportno > 0) {
08470          ast_sockaddr_set_port(vsa, vportno);
08471          ast_rtp_instance_set_remote_address(p->vrtp, vsa);
08472          if (debug) {
08473             ast_verbose("Peer video RTP is at port %s\n",
08474                    ast_sockaddr_stringify(vsa));
08475          }
08476          ast_rtp_codecs_payloads_copy(&newvideortp, ast_rtp_instance_get_codecs(p->vrtp), p->vrtp);
08477       } else {
08478          ast_rtp_instance_stop(p->vrtp);
08479          if (debug)
08480             ast_verbose("Peer doesn't provide video\n");
08481       }
08482    }
08483 
08484    /* Setup text address and port */
08485    if (p->trtp) {
08486       if (tportno > 0) {
08487          ast_sockaddr_set_port(tsa, tportno);
08488          ast_rtp_instance_set_remote_address(p->trtp, tsa);
08489          if (debug) {
08490             ast_verbose("Peer T.140 RTP is at port %s\n",
08491                    ast_sockaddr_stringify(tsa));
08492          }
08493          if ((p->jointcapability & AST_FORMAT_T140RED)) {
08494             p->red = 1;
08495             ast_rtp_red_init(p->trtp, 300, red_data_pt, 2);
08496          } else {
08497             p->red = 0;
08498          }
08499          ast_rtp_codecs_payloads_copy(&newtextrtp, ast_rtp_instance_get_codecs(p->trtp), p->trtp);
08500       } else {
08501          ast_rtp_instance_stop(p->trtp);
08502          if (debug)
08503             ast_verbose("Peer doesn't provide T.140\n");
08504       }
08505    }
08506    /* Setup image address and port */
08507    if (p->udptl) {
08508       if (udptlportno > 0) {
08509          if (ast_test_flag(&p->flags[1], SIP_PAGE2_SYMMETRICRTP) && ast_test_flag(&p->flags[1], SIP_PAGE2_UDPTL_DESTINATION)) {
08510             ast_rtp_instance_get_remote_address(p->rtp, isa);
08511             if (!ast_sockaddr_isnull(isa) && debug) {
08512                ast_debug(1, "Peer T.38 UDPTL is set behind NAT and with destination, destination address now %s\n", ast_sockaddr_stringify(isa));
08513             }
08514          }
08515          ast_sockaddr_set_port(isa, udptlportno);
08516          ast_udptl_set_peer(p->udptl, isa);
08517          if (debug)
08518             ast_debug(1,"Peer T.38 UDPTL is at port %s\n", ast_sockaddr_stringify(isa));
08519 
08520          /* verify the far max ifp can be calculated. this requires far max datagram to be set. */
08521          if (!ast_udptl_get_far_max_datagram(p->udptl)) {
08522             /* setting to zero will force a default if none was provided by the SDP */
08523             ast_udptl_set_far_max_datagram(p->udptl, 0);
08524          }
08525 
08526          /* Remote party offers T38, we need to update state */
08527          if ((t38action == SDP_T38_ACCEPT) &&
08528              (p->t38.state == T38_LOCAL_REINVITE)) {
08529             change_t38_state(p, T38_ENABLED);
08530          } else if ((t38action == SDP_T38_INITIATE) &&
08531                p->owner && p->lastinvite) {
08532             change_t38_state(p, T38_PEER_REINVITE); /* T38 Offered in re-invite from remote party */
08533             /* If fax detection is enabled then send us off to the fax extension */
08534             if (ast_test_flag(&p->flags[1], SIP_PAGE2_FAX_DETECT_T38)) {
08535                ast_channel_lock(p->owner);
08536                if (strcmp(p->owner->exten, "fax")) {
08537                   const char *target_context = S_OR(p->owner->macrocontext, p->owner->context);
08538                   ast_channel_unlock(p->owner);
08539                   if (ast_exists_extension(p->owner, target_context, "fax", 1,
08540                      S_COR(p->owner->caller.id.number.valid, p->owner->caller.id.number.str, NULL))) {
08541                      ast_verbose(VERBOSE_PREFIX_2 "Redirecting '%s' to fax extension due to peer T.38 re-INVITE\n", p->owner->name);
08542                      pbx_builtin_setvar_helper(p->owner, "FAXEXTEN", p->owner->exten);
08543                      if (ast_async_goto(p->owner, target_context, "fax", 1)) {
08544                         ast_log(LOG_NOTICE, "Failed to async goto '%s' into fax of '%s'\n", p->owner->name, target_context);
08545                      }
08546                   } else {
08547                      ast_log(LOG_NOTICE, "T.38 re-INVITE detected but no fax extension\n");
08548                   }
08549                } else {
08550                   ast_channel_unlock(p->owner);
08551                }
08552             }
08553          }
08554       } else {
08555          ast_udptl_stop(p->udptl);
08556          if (debug)
08557             ast_debug(1, "Peer doesn't provide T.38 UDPTL\n");
08558       }
08559    }
08560 
08561    if ((portno == -1) && (p->t38.state != T38_DISABLED)) {
08562       ast_debug(3, "Have T.38 but no audio, accepting offer anyway\n");
08563       return 0;
08564         }
08565 
08566    /* Ok, we're going with this offer */
08567    ast_debug(2, "We're settling with these formats: %s\n", ast_getformatname_multiple(buf, SIPBUFSIZE, p->jointcapability));
08568 
08569    if (!p->owner)    /* There's no open channel owning us so we can return here. For a re-invite or so, we proceed */
08570       return 0;
08571 
08572    ast_debug(4, "We have an owner, now see if we need to change this call\n");
08573 
08574    if (!(p->owner->nativeformats & p->jointcapability) && (p->jointcapability & AST_FORMAT_AUDIO_MASK)) {
08575       if (debug) {
08576          char s1[SIPBUFSIZE], s2[SIPBUFSIZE];
08577          ast_debug(1, "Oooh, we need to change our audio formats since our peer supports only %s and not %s\n",
08578             ast_getformatname_multiple(s1, SIPBUFSIZE, p->jointcapability),
08579             ast_getformatname_multiple(s2, SIPBUFSIZE, p->owner->nativeformats));
08580       }
08581       p->owner->nativeformats = ast_codec_choose(&p->prefs, p->jointcapability, 1) | (p->capability & vpeercapability) | (p->capability & tpeercapability);
08582       ast_set_read_format(p->owner, p->owner->readformat);
08583       ast_set_write_format(p->owner, p->owner->writeformat);
08584    }
08585    
08586    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)) {
08587       ast_queue_control(p->owner, AST_CONTROL_UNHOLD);
08588       /* Activate a re-invite */
08589       ast_queue_frame(p->owner, &ast_null_frame);
08590       /* Queue Manager Unhold event */
08591       append_history(p, "Unhold", "%s", req->data->str);
08592       if (sip_cfg.callevents)
08593          ast_manager_event(p->owner, EVENT_FLAG_CALL, "Hold",
08594                   "Status: Off\r\n"
08595                   "Channel: %s\r\n"
08596                   "Uniqueid: %s\r\n",
08597                   p->owner->name,
08598                   p->owner->uniqueid);
08599       if (sip_cfg.notifyhold)
08600          sip_peer_hold(p, FALSE);
08601       ast_clear_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD); /* Clear both flags */
08602    } else if ((ast_sockaddr_isnull(sa) && ast_sockaddr_isnull(vsa) && ast_sockaddr_isnull(tsa) && ast_sockaddr_isnull(isa)) || (sendonly && sendonly != -1)) {
08603       int already_on_hold = ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD);
08604       ast_queue_control_data(p->owner, AST_CONTROL_HOLD,
08605                    S_OR(p->mohsuggest, NULL),
08606                    !ast_strlen_zero(p->mohsuggest) ? strlen(p->mohsuggest) + 1 : 0);
08607       if (sendonly)
08608          ast_rtp_instance_stop(p->rtp);
08609       /* RTCP needs to go ahead, even if we're on hold!!! */
08610       /* Activate a re-invite */
08611       ast_queue_frame(p->owner, &ast_null_frame);
08612       /* Queue Manager Hold event */
08613       append_history(p, "Hold", "%s", req->data->str);
08614       if (sip_cfg.callevents && !ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
08615          ast_manager_event(p->owner, EVENT_FLAG_CALL, "Hold",
08616                   "Status: On\r\n"
08617                   "Channel: %s\r\n"
08618                   "Uniqueid: %s\r\n",
08619                   p->owner->name,
08620                   p->owner->uniqueid);
08621       }
08622       if (sendonly == 1)   /* One directional hold (sendonly/recvonly) */
08623          ast_set_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD_ONEDIR);
08624       else if (sendonly == 2) /* Inactive stream */
08625          ast_set_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD_INACTIVE);
08626       else
08627          ast_set_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD_ACTIVE);
08628       if (sip_cfg.notifyhold && !already_on_hold)
08629          sip_peer_hold(p, TRUE);
08630    }
08631    
08632    return 0;
08633 }
08634 
08635 static int process_sdp_o(const char *o, struct sip_pvt *p)
08636 {
08637    char *o_copy;
08638    char *token;
08639    int64_t rua_version;
08640 
08641    /* Store the SDP version number of remote UA. This will allow us to
08642    distinguish between session modifications and session refreshes. If
08643    the remote UA does not send an incremented SDP version number in a
08644    subsequent RE-INVITE then that means its not changing media session.
08645    The RE-INVITE may have been sent to update connected party, remote
08646    target or to refresh the session (Session-Timers).  Asterisk must not
08647    change media session and increment its own version number in answer
08648    SDP in this case. */
08649 
08650    p->session_modify = TRUE;
08651 
08652    if (ast_strlen_zero(o)) {
08653       ast_log(LOG_WARNING, "SDP syntax error. SDP without an o= line\n");
08654       return FALSE;
08655    }
08656 
08657    o_copy = ast_strdupa(o);
08658    token = strsep(&o_copy, " ");  /* Skip username   */
08659    if (!o_copy) {
08660       ast_log(LOG_WARNING, "SDP syntax error in o= line username\n");
08661       return FALSE;
08662    }
08663    token = strsep(&o_copy, " ");  /* Skip session-id */
08664    if (!o_copy) {
08665       ast_log(LOG_WARNING, "SDP syntax error in o= line session-id\n");
08666       return FALSE;
08667    }
08668    token = strsep(&o_copy, " ");  /* Version         */
08669    if (!o_copy) {
08670       ast_log(LOG_WARNING, "SDP syntax error in o= line\n");
08671       return FALSE;
08672    }
08673    if (!sscanf(token, "%30" SCNd64, &rua_version)) {
08674       ast_log(LOG_WARNING, "SDP syntax error in o= line version\n");
08675       return FALSE;
08676    }
08677 
08678    /* we need to check the SDP version number the other end sent us;
08679     * our rules for deciding what to accept are a bit complex.
08680     *
08681     * 1) if 'ignoresdpversion' has been set for this dialog, then
08682     *    we will just accept whatever they sent and assume it is
08683     *    a modification of the session, even if it is not
08684     * 2) otherwise, if this is the first SDP we've seen from them
08685     *    we accept it
08686     * 3) otherwise, if the new SDP version number is higher than the
08687     *    old one, we accept it
08688     * 4) otherwise, if this SDP is in response to us requesting a switch
08689     *    to T.38, we accept the SDP, but also generate a warning message
08690     *    that this peer should have the 'ignoresdpversion' option set,
08691     *    because it is not following the SDP offer/answer RFC; if we did
08692     *    not request a switch to T.38, then we stop parsing the SDP, as it
08693     *    has not changed from the previous version
08694     */
08695 
08696    if (ast_test_flag(&p->flags[1], SIP_PAGE2_IGNORESDPVERSION) ||
08697        (p->sessionversion_remote < 0) ||
08698        (p->sessionversion_remote < rua_version)) {
08699       p->sessionversion_remote = rua_version;
08700    } else {
08701       if (p->t38.state == T38_LOCAL_REINVITE) {
08702          p->sessionversion_remote = rua_version;
08703          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);
08704       } else {
08705          p->session_modify = FALSE;
08706          ast_debug(2, "Call %s responded to our reinvite without changing SDP version; ignoring SDP.\n", p->callid);
08707          return FALSE;
08708       }
08709    }
08710 
08711    return TRUE;
08712 }
08713 
08714 static int process_sdp_c(const char *c, struct ast_sockaddr *addr)
08715 {
08716    char proto[4], host[258];
08717    int af;
08718 
08719    /* Check for Media-description-level-address */
08720    if (sscanf(c, "IN %3s %255s", proto, host) == 2) {
08721       if (!strcmp("IP4", proto)) {
08722          af = AF_INET;
08723       } else if (!strcmp("IP6", proto)) {
08724          af = AF_INET6;
08725       } else {
08726          ast_log(LOG_WARNING, "Unknown protocol '%s'.\n", proto);
08727          return FALSE;
08728       }
08729       if (ast_sockaddr_resolve_first_af(addr, host, 0, af)) {
08730          ast_log(LOG_WARNING, "Unable to lookup RTP Audio host in c= line, '%s'\n", c);
08731          return FALSE;
08732       }
08733       return TRUE;
08734    } else {
08735       ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
08736       return FALSE;
08737    }
08738    return FALSE;
08739 }
08740 
08741 static int process_sdp_a_sendonly(const char *a, int *sendonly)
08742 {
08743    int found = FALSE;
08744 
08745    if (!strcasecmp(a, "sendonly")) {
08746       if (*sendonly == -1)
08747          *sendonly = 1;
08748       found = TRUE;
08749    } else if (!strcasecmp(a, "inactive")) {
08750       if (*sendonly == -1)
08751          *sendonly = 2;
08752       found = TRUE;
08753    }  else if (!strcasecmp(a, "sendrecv")) {
08754       if (*sendonly == -1)
08755          *sendonly = 0;
08756       found = TRUE;
08757    }
08758    return found;
08759 }
08760 
08761 static int process_sdp_a_audio(const char *a, struct sip_pvt *p, struct ast_rtp_codecs *newaudiortp, int *last_rtpmap_codec)
08762 {
08763    int found = FALSE;
08764    int codec;
08765    char mimeSubtype[128];
08766    char fmtp_string[64];
08767    unsigned int sample_rate;
08768    int debug = sip_debug_test_pvt(p);
08769 
08770    if (!strncasecmp(a, "ptime", 5)) {
08771       char *tmp = strrchr(a, ':');
08772       long int framing = 0;
08773       if (tmp) {
08774          tmp++;
08775          framing = strtol(tmp, NULL, 10);
08776          if (framing == LONG_MIN || framing == LONG_MAX) {
08777             framing = 0;
08778             ast_debug(1, "Can't read framing from SDP: %s\n", a);
08779          }
08780       }
08781       if (framing && p->autoframing) {
08782          struct ast_codec_pref *pref = &ast_rtp_instance_get_codecs(p->rtp)->pref;
08783          int codec_n;
08784          for (codec_n = 0; codec_n < AST_RTP_MAX_PT; codec_n++) {
08785             struct ast_rtp_payload_type format = ast_rtp_codecs_payload_lookup(ast_rtp_instance_get_codecs(p->rtp), codec_n);
08786             if (!format.asterisk_format || !format.code) /* non-codec or not found */
08787                continue;
08788             ast_debug(1, "Setting framing for %s to %ld\n", ast_getformatname(format.code), framing);
08789             ast_codec_pref_setsize(pref, format.code, framing);
08790          }
08791          ast_rtp_codecs_packetization_set(ast_rtp_instance_get_codecs(p->rtp), p->rtp, pref);
08792       }
08793       found = TRUE;
08794    } else if (sscanf(a, "rtpmap: %30u %127[^/]/%30u", &codec, mimeSubtype, &sample_rate) == 3) {
08795       /* We have a rtpmap to handle */
08796       if (*last_rtpmap_codec < SDP_MAX_RTPMAP_CODECS) {
08797          if (ast_rtp_codecs_payloads_set_rtpmap_type_rate(newaudiortp, NULL, codec, "audio", mimeSubtype,
08798              ast_test_flag(&p->flags[0], SIP_G726_NONSTANDARD) ? AST_RTP_OPT_G726_NONSTANDARD : 0, sample_rate) != -1) {
08799             if (debug)
08800                ast_verbose("Found audio description format %s for ID %d\n", mimeSubtype, codec);
08801             //found_rtpmap_codecs[last_rtpmap_codec] = codec;
08802             (*last_rtpmap_codec)++;
08803             found = TRUE;
08804          } else {
08805             ast_rtp_codecs_payloads_unset(newaudiortp, NULL, codec);
08806             if (debug)
08807                ast_verbose("Found unknown media description format %s for ID %d\n", mimeSubtype, codec);
08808          }
08809       } else {
08810          if (debug)
08811             ast_verbose("Discarded description format %s for ID %d\n", mimeSubtype, codec);
08812       }
08813    } else if (sscanf(a, "fmtp: %30u %63s", &codec, fmtp_string) == 2) {
08814       struct ast_rtp_payload_type payload;
08815 
08816       payload = ast_rtp_codecs_payload_lookup(newaudiortp, codec);
08817       if (payload.code && payload.asterisk_format) {
08818          unsigned int bit_rate;
08819 
08820          switch (payload.code) {
08821          case AST_FORMAT_SIREN7:
08822             if (sscanf(fmtp_string, "bitrate=%30u", &bit_rate) == 1) {
08823                if (bit_rate != 32000) {
08824                   ast_log(LOG_WARNING, "Got Siren7 offer at %d bps, but only 32000 bps supported; ignoring.\n", bit_rate);
08825                   ast_rtp_codecs_payloads_unset(newaudiortp, NULL, codec);
08826                } else {
08827                   found = TRUE;
08828                }
08829             }
08830             break;
08831          case AST_FORMAT_SIREN14:
08832             if (sscanf(fmtp_string, "bitrate=%30u", &bit_rate) == 1) {
08833                if (bit_rate != 48000) {
08834                   ast_log(LOG_WARNING, "Got Siren14 offer at %d bps, but only 48000 bps supported; ignoring.\n", bit_rate);
08835                   ast_rtp_codecs_payloads_unset(newaudiortp, NULL, codec);
08836                } else {
08837                   found = TRUE;
08838                }
08839             }
08840             break;
08841          case AST_FORMAT_G719:
08842             if (sscanf(fmtp_string, "bitrate=%30u", &bit_rate) == 1) {
08843                if (bit_rate != 64000) {
08844                   ast_log(LOG_WARNING, "Got G.719 offer at %d bps, but only 64000 bps supported; ignoring.\n", bit_rate);
08845                   ast_rtp_codecs_payloads_unset(newaudiortp, NULL, codec);
08846                } else {
08847                   found = TRUE;
08848                }
08849             }
08850          }
08851       }
08852    }
08853 
08854    return found;
08855 }
08856 
08857 static int process_sdp_a_video(const char *a, struct sip_pvt *p, struct ast_rtp_codecs *newvideortp, int *last_rtpmap_codec)
08858 {
08859    int found = FALSE;
08860    int codec;
08861    char mimeSubtype[128];
08862    unsigned int sample_rate;
08863    int debug = sip_debug_test_pvt(p);
08864 
08865    if (sscanf(a, "rtpmap: %30u %127[^/]/%30u", &codec, mimeSubtype, &sample_rate) == 3) {
08866       /* We have a rtpmap to handle */
08867       if (*last_rtpmap_codec < SDP_MAX_RTPMAP_CODECS) {
08868          /* Note: should really look at the '#chans' params too */
08869          if (!strncasecmp(mimeSubtype, "H26", 3) || !strncasecmp(mimeSubtype, "MP4", 3)) {
08870             if (ast_rtp_codecs_payloads_set_rtpmap_type_rate(newvideortp, NULL, codec, "video", mimeSubtype, 0, sample_rate) != -1) {
08871                if (debug)
08872                   ast_verbose("Found video description format %s for ID %d\n", mimeSubtype, codec);
08873                //found_rtpmap_codecs[last_rtpmap_codec] = codec;
08874                (*last_rtpmap_codec)++;
08875                found = TRUE;
08876             } else {
08877                ast_rtp_codecs_payloads_unset(newvideortp, NULL, codec);
08878                if (debug)
08879                   ast_verbose("Found unknown media description format %s for ID %d\n", mimeSubtype, codec);
08880             }
08881          }
08882       } else {
08883          if (debug)
08884             ast_verbose("Discarded description format %s for ID %d\n", mimeSubtype, codec);
08885       }
08886    }
08887 
08888    return found;
08889 }
08890 
08891 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)
08892 {
08893    int found = FALSE;
08894    int codec;
08895    char mimeSubtype[128];
08896    unsigned int sample_rate;
08897    char *red_cp;
08898    int debug = sip_debug_test_pvt(p);
08899 
08900    if (sscanf(a, "rtpmap: %30u %127[^/]/%30u", &codec, mimeSubtype, &sample_rate) == 3) {
08901       /* We have a rtpmap to handle */
08902       if (*last_rtpmap_codec < SDP_MAX_RTPMAP_CODECS) {
08903          if (!strncasecmp(mimeSubtype, "T140", 4)) { /* Text */
08904             if (p->trtp) {
08905                /* ast_verbose("Adding t140 mimeSubtype to textrtp struct\n"); */
08906                ast_rtp_codecs_payloads_set_rtpmap_type_rate(newtextrtp, NULL, codec, "text", mimeSubtype, 0, sample_rate);
08907                found = TRUE;
08908             }
08909          } else if (!strncasecmp(mimeSubtype, "RED", 3)) { /* Text with Redudancy */
08910             if (p->trtp) {
08911                ast_rtp_codecs_payloads_set_rtpmap_type_rate(newtextrtp, NULL, codec, "text", mimeSubtype, 0, sample_rate);
08912                sprintf(red_fmtp, "fmtp:%d ", codec);
08913                if (debug)
08914                   ast_verbose("RED submimetype has payload type: %d\n", codec);
08915                found = TRUE;
08916             }
08917          }
08918       } else {
08919          if (debug)
08920             ast_verbose("Discarded description format %s for ID %d\n", mimeSubtype, codec);
08921       }
08922    } else if (!strncmp(a, red_fmtp, strlen(red_fmtp))) {
08923       /* count numbers of generations in fmtp */
08924       red_cp = &red_fmtp[strlen(red_fmtp)];
08925       strncpy(red_fmtp, a, 100);
08926 
08927       sscanf(red_cp, "%30u", &red_data_pt[*red_num_gen]);
08928       red_cp = strtok(red_cp, "/");
08929       while (red_cp && (*red_num_gen)++ < AST_RED_MAX_GENERATION) {
08930          sscanf(red_cp, "%30u", &red_data_pt[*red_num_gen]);
08931          red_cp = strtok(NULL, "/");
08932       }
08933       red_cp = red_fmtp;
08934       found = TRUE;
08935    }
08936 
08937    return found;
08938 }
08939 
08940 static int process_sdp_a_image(const char *a, struct sip_pvt *p)
08941 {
08942    int found = FALSE;
08943    char s[256];
08944    unsigned int x;
08945 
08946    if ((sscanf(a, "T38FaxMaxBuffer:%30u", &x) == 1)) {
08947       ast_debug(3, "MaxBufferSize:%d\n", x);
08948       found = TRUE;
08949    } else if ((sscanf(a, "T38MaxBitRate:%30u", &x) == 1) || (sscanf(a, "T38FaxMaxRate:%30u", &x) == 1)) {
08950       ast_debug(3, "T38MaxBitRate: %d\n", x);
08951       switch (x) {
08952       case 14400:
08953          p->t38.their_parms.rate = AST_T38_RATE_14400;
08954          break;
08955       case 12000:
08956          p->t38.their_parms.rate = AST_T38_RATE_12000;
08957          break;
08958       case 9600:
08959          p->t38.their_parms.rate = AST_T38_RATE_9600;
08960          break;
08961       case 7200:
08962          p->t38.their_parms.rate = AST_T38_RATE_7200;
08963          break;
08964       case 4800:
08965          p->t38.their_parms.rate = AST_T38_RATE_4800;
08966          break;
08967       case 2400:
08968          p->t38.their_parms.rate = AST_T38_RATE_2400;
08969          break;
08970       }
08971       found = TRUE;
08972    } else if ((sscanf(a, "T38FaxVersion:%30u", &x) == 1)) {
08973       ast_debug(3, "FaxVersion: %u\n", x);
08974       p->t38.their_parms.version = x;
08975       found = TRUE;
08976    } else if ((sscanf(a, "T38FaxMaxDatagram:%30u", &x) == 1) || (sscanf(a, "T38MaxDatagram:%30u", &x) == 1)) {
08977       /* override the supplied value if the configuration requests it */
08978       if (((signed int) p->t38_maxdatagram >= 0) && ((unsigned int) p->t38_maxdatagram > x)) {
08979          ast_debug(1, "Overriding T38FaxMaxDatagram '%d' with '%d'\n", x, p->t38_maxdatagram);
08980          x = p->t38_maxdatagram;
08981       }
08982       ast_debug(3, "FaxMaxDatagram: %u\n", x);
08983       ast_udptl_set_far_max_datagram(p->udptl, x);
08984       found = TRUE;
08985    } else if ((strncmp(a, "T38FaxFillBitRemoval", 20) == 0)) {
08986       if (sscanf(a, "T38FaxFillBitRemoval:%30u", &x) == 1) {
08987          ast_debug(3, "FillBitRemoval: %d\n", x);
08988          if (x == 1) {
08989             p->t38.their_parms.fill_bit_removal = TRUE;
08990          }
08991       } else {
08992          ast_debug(3, "FillBitRemoval\n");
08993          p->t38.their_parms.fill_bit_removal = TRUE;
08994       }
08995       found = TRUE;
08996    } else if ((strncmp(a, "T38FaxTranscodingMMR", 20) == 0)) {
08997       if (sscanf(a, "T38FaxTranscodingMMR:%30u", &x) == 1) {
08998          ast_debug(3, "Transcoding MMR: %d\n", x);
08999          if (x == 1) {
09000             p->t38.their_parms.transcoding_mmr = TRUE;
09001          }
09002       } else {
09003          ast_debug(3, "Transcoding MMR\n");
09004          p->t38.their_parms.transcoding_mmr = TRUE;
09005       }
09006       found = TRUE;
09007    } else if ((strncmp(a, "T38FaxTranscodingJBIG", 21) == 0)) {
09008       if (sscanf(a, "T38FaxTranscodingJBIG:%30u", &x) == 1) {
09009          ast_debug(3, "Transcoding JBIG: %d\n", x);
09010          if (x == 1) {
09011             p->t38.their_parms.transcoding_jbig = TRUE;
09012          }
09013       } else {
09014          ast_debug(3, "Transcoding JBIG\n");
09015          p->t38.their_parms.transcoding_jbig = TRUE;
09016       }
09017       found = TRUE;
09018    } else if ((sscanf(a, "T38FaxRateManagement:%255s", s) == 1)) {
09019       ast_debug(3, "RateManagement: %s\n", s);
09020       if (!strcasecmp(s, "localTCF"))
09021          p->t38.their_parms.rate_management = AST_T38_RATE_MANAGEMENT_LOCAL_TCF;
09022       else if (!strcasecmp(s, "transferredTCF"))
09023          p->t38.their_parms.rate_management = AST_T38_RATE_MANAGEMENT_TRANSFERRED_TCF;
09024       found = TRUE;
09025    } else if ((sscanf(a, "T38FaxUdpEC:%255s", s) == 1)) {
09026       ast_debug(3, "UDP EC: %s\n", s);
09027       if (!strcasecmp(s, "t38UDPRedundancy")) {
09028          ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_REDUNDANCY);
09029       } else if (!strcasecmp(s, "t38UDPFEC")) {
09030          ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_FEC);
09031       } else {
09032          ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_NONE);
09033       }
09034       found = TRUE;
09035    }
09036 
09037    return found;
09038 }
09039 
09040 /*! \brief Add "Supported" header to sip message.  Since some options may
09041  *  be disabled in the config, the sip_pvt must be inspected to determine what
09042  *  is supported for this dialog. */
09043 static int add_supported_header(struct sip_pvt *pvt, struct sip_request *req)
09044 {
09045    int res;
09046    if (st_get_mode(pvt) != SESSION_TIMER_MODE_REFUSE) {
09047       res = add_header(req, "Supported", "replaces, timer");
09048    } else {
09049       res = add_header(req, "Supported", "replaces");
09050    }
09051    return res;
09052 }
09053 
09054 /*! \brief Add header to SIP message */
09055 static int add_header(struct sip_request *req, const char *var, const char *value)
09056 {
09057    if (req->headers == SIP_MAX_HEADERS) {
09058       ast_log(LOG_WARNING, "Out of SIP header space\n");
09059       return -1;
09060    }
09061 
09062    if (req->lines) {
09063       ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
09064       return -1;
09065    }
09066 
09067    if (sip_cfg.compactheaders) {
09068       var = find_alias(var, var);
09069    }
09070 
09071    ast_str_append(&req->data, 0, "%s: %s\r\n", var, value);
09072    req->header[req->headers] = req->len;
09073 
09074    req->len = ast_str_strlen(req->data);
09075    req->headers++;
09076 
09077    return 0;   
09078 }
09079 
09080 /*! \brief Add 'Max-Forwards' header to SIP message */
09081 static int add_header_max_forwards(struct sip_pvt *dialog, struct sip_request *req)
09082 {
09083    char clen[10];
09084    const char *max = NULL;
09085 
09086    /* deadlock avoidance */
09087    while (dialog->owner && ast_channel_trylock(dialog->owner)) {
09088       sip_pvt_unlock(dialog);
09089       usleep(1);
09090       sip_pvt_lock(dialog);
09091    }
09092 
09093    if (dialog->owner) {
09094       max = pbx_builtin_getvar_helper(dialog->owner, "SIP_MAX_FORWARDS");
09095       ast_channel_unlock(dialog->owner);
09096    }
09097 
09098    /* The channel variable overrides the peer/channel value */
09099    if (max == NULL) {
09100       snprintf(clen, sizeof(clen), "%d", dialog->maxforwards);
09101    }
09102    return add_header(req, "Max-Forwards", max != NULL ? max : clen);
09103 }
09104 
09105 /*! \brief Add 'Content-Length' header and content to SIP message */
09106 static int finalize_content(struct sip_request *req)
09107 {
09108    char clen[10];
09109 
09110    if (req->lines) {
09111       ast_log(LOG_WARNING, "finalize_content() called on a message that has already been finalized\n");
09112       return -1;
09113    }
09114 
09115    snprintf(clen, sizeof(clen), "%zd", ast_str_strlen(req->content));
09116    add_header(req, "Content-Length", clen);
09117 
09118    if (ast_str_strlen(req->content)) {
09119       ast_str_append(&req->data, 0, "\r\n%s", ast_str_buffer(req->content));
09120       req->len = ast_str_strlen(req->data);
09121    }
09122    req->lines = ast_str_strlen(req->content) ? 1 : 0;
09123    return 0;
09124 }
09125 
09126 /*! \brief Add content (not header) to SIP message */
09127 static int add_content(struct sip_request *req, const char *line)
09128 {
09129    if (req->lines) {
09130       ast_log(LOG_WARNING, "Can't add more content when the content has been finalized\n");
09131       return -1;
09132    }
09133 
09134    ast_str_append(&req->content, 0, "%s", line);
09135    return 0;
09136 }
09137 
09138 /*! \brief Copy one header field from one request to another */
09139 static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field)
09140 {
09141    const char *tmp = get_header(orig, field);
09142 
09143    if (!ast_strlen_zero(tmp)) /* Add what we're responding to */
09144       return add_header(req, field, tmp);
09145    ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
09146    return -1;
09147 }
09148 
09149 /*! \brief Copy all headers from one request to another */
09150 static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field)
09151 {
09152    int start = 0;
09153    int copied = 0;
09154    for (;;) {
09155       const char *tmp = __get_header(orig, field, &start);
09156 
09157       if (ast_strlen_zero(tmp))
09158          break;
09159       /* Add what we're responding to */
09160       add_header(req, field, tmp);
09161       copied++;
09162    }
09163    return copied ? 0 : -1;
09164 }
09165 
09166 /*! \brief Copy SIP VIA Headers from the request to the response
09167 \note If the client indicates that it wishes to know the port we received from,
09168    it adds ;rport without an argument to the topmost via header. We need to
09169    add the port number (from our point of view) to that parameter.
09170 \verbatim
09171    We always add ;received=<ip address> to the topmost via header.
09172 \endverbatim
09173    Received: RFC 3261, rport RFC 3581 */
09174 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field)
09175 {
09176    int copied = 0;
09177    int start = 0;
09178 
09179    for (;;) {
09180       char new[512];
09181       const char *oh = __get_header(orig, field, &start);
09182 
09183       if (ast_strlen_zero(oh))
09184          break;
09185 
09186       if (!copied) { /* Only check for empty rport in topmost via header */
09187          char leftmost[512], *others, *rport;
09188 
09189          /* Only work on leftmost value */
09190          ast_copy_string(leftmost, oh, sizeof(leftmost));
09191          others = strchr(leftmost, ',');
09192          if (others)
09193              *others++ = '\0';
09194 
09195          /* Find ;rport;  (empty request) */
09196          rport = strstr(leftmost, ";rport");
09197          if (rport && *(rport+6) == '=')
09198             rport = NULL;     /* We already have a parameter to rport */
09199 
09200          if (((ast_test_flag(&p->flags[0], SIP_NAT_FORCE_RPORT)) || (rport && ast_test_flag(&p->flags[0], SIP_NAT_RPORT_PRESENT)))) {
09201             /* We need to add received port - rport */
09202             char *end;
09203 
09204             rport = strstr(leftmost, ";rport");
09205 
09206             if (rport) {
09207                end = strchr(rport + 1, ';');
09208                if (end)
09209                   memmove(rport, end, strlen(end) + 1);
09210                else
09211                   *rport = '\0';
09212             }
09213 
09214             /* Add rport to first VIA header if requested */
09215             snprintf(new, sizeof(new), "%s;received=%s;rport=%d%s%s",
09216                leftmost, ast_sockaddr_stringify_addr(&p->recv),
09217                ast_sockaddr_port(&p->recv),
09218                others ? "," : "", others ? others : "");
09219          } else {
09220             /* We should *always* add a received to the topmost via */
09221             snprintf(new, sizeof(new), "%s;received=%s%s%s",
09222                leftmost, ast_sockaddr_stringify_addr(&p->recv),
09223                others ? "," : "", others ? others : "");
09224          }
09225          oh = new;   /* the header to copy */
09226       }  /* else add the following via headers untouched */
09227       add_header(req, field, oh);
09228       copied++;
09229    }
09230    if (!copied) {
09231       ast_log(LOG_NOTICE, "No header field '%s' present to copy\n", field);
09232       return -1;
09233    }
09234    return 0;
09235 }
09236 
09237 /*! \brief Add route header into request per learned route */
09238 static void add_route(struct sip_request *req, struct sip_route *route)
09239 {
09240    char r[SIPBUFSIZE*2], *p;
09241    int n, rem = sizeof(r);
09242 
09243    if (!route)
09244       return;
09245 
09246    p = r;
09247    for (;route ; route = route->next) {
09248       n = strlen(route->hop);
09249       if (rem < n+3) /* we need room for ",<route>" */
09250          break;
09251       if (p != r) {  /* add a separator after fist route */
09252          *p++ = ',';
09253          --rem;
09254       }
09255       *p++ = '<';
09256       ast_copy_string(p, route->hop, rem); /* cannot fail */
09257       p += n;
09258       *p++ = '>';
09259       rem -= (n+2);
09260    }
09261    *p = '\0';
09262    add_header(req, "Route", r);
09263 }
09264 
09265 /*! \brief Set destination from SIP URI
09266  *
09267  * Parse uri to h (host) and port - uri is already just the part inside the <>
09268  * general form we are expecting is sip[s]:username[:password][;parameter]@host[:port][;...]
09269  * If there's a port given, turn NAPTR/SRV off. NAPTR might indicate SIPS preference even
09270  * for SIP: uri's
09271  *
09272  * If there's a sips: uri scheme, TLS will be required.
09273  */
09274 static void set_destination(struct sip_pvt *p, char *uri)
09275 {
09276    char *h, *maddr, hostname[256];
09277    int hn;
09278    int debug=sip_debug_test_pvt(p);
09279    int tls_on = FALSE;
09280 
09281    if (debug)
09282       ast_verbose("set_destination: Parsing <%s> for address/port to send to\n", uri);
09283 
09284    /* Find and parse hostname */
09285    h = strchr(uri, '@');
09286    if (h)
09287       ++h;
09288    else {
09289       h = uri;
09290       if (!strncasecmp(h, "sip:", 4)) {
09291          h += 4;
09292       } else if (!strncasecmp(h, "sips:", 5)) {
09293          h += 5;
09294          tls_on = TRUE;
09295       }
09296    }
09297    hn = strcspn(h, ";>") + 1;
09298    if (hn > sizeof(hostname))
09299       hn = sizeof(hostname);
09300    ast_copy_string(hostname, h, hn);
09301    /* XXX bug here if string has been trimmed to sizeof(hostname) */
09302    h += hn - 1;
09303 
09304    /*! \todo XXX If we have sip_cfg.srvlookup on, then look for NAPTR/SRV,
09305     * otherwise, just look for A records */
09306    if (ast_sockaddr_resolve_first(&p->sa, hostname, 0)) {
09307       ast_log(LOG_WARNING, "Can't find address for host '%s'\n", hostname);
09308       return;
09309    }
09310 
09311    /* Got the hostname - but maybe there's a "maddr=" to override address? */
09312    maddr = strstr(h, "maddr=");
09313    if (maddr) {
09314       int port;
09315 
09316       maddr += 6;
09317       hn = strspn(maddr, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
09318                     "0123456789-.:[]") + 1;
09319       if (hn > sizeof(hostname))
09320          hn = sizeof(hostname);
09321       ast_copy_string(hostname, maddr, hn);
09322 
09323       port = ast_sockaddr_port(&p->sa);
09324 
09325       /*! \todo XXX If we have sip_cfg.srvlookup on, then look for
09326        * NAPTR/SRV, otherwise, just look for A records */
09327       if (ast_sockaddr_resolve_first(&p->sa, hostname, PARSE_PORT_FORBID)) {
09328          ast_log(LOG_WARNING, "Can't find address for host '%s'\n", hostname);
09329          return;
09330       }
09331 
09332       ast_sockaddr_set_port(&p->sa, port);
09333    }
09334 
09335    if (!ast_sockaddr_port(&p->sa)) {
09336       ast_sockaddr_set_port(&p->sa, tls_on ?
09337                   STANDARD_TLS_PORT : STANDARD_SIP_PORT);
09338    }
09339 
09340    if (debug) {
09341       ast_verbose("set_destination: set destination to %s\n",
09342              ast_sockaddr_stringify(&p->sa));
09343    }
09344 }
09345 
09346 /*! \brief Initialize SIP response, based on SIP request */
09347 static int init_resp(struct sip_request *resp, const char *msg)
09348 {
09349    /* Initialize a response */
09350    memset(resp, 0, sizeof(*resp));
09351    resp->method = SIP_RESPONSE;
09352    if (!(resp->data = ast_str_create(SIP_MIN_PACKET)))
09353       goto e_return;
09354    if (!(resp->content = ast_str_create(SIP_MIN_PACKET)))
09355       goto e_free_data;
09356    resp->header[0] = 0;
09357    ast_str_set(&resp->data, 0, "SIP/2.0 %s\r\n", msg);
09358    resp->len = resp->data->used;
09359    resp->headers++;
09360    return 0;
09361 
09362 e_free_data:
09363    ast_free(resp->data);
09364    resp->data = NULL;
09365 e_return:
09366    return -1;
09367 }
09368 
09369 /*! \brief Initialize SIP request */
09370 static int init_req(struct sip_request *req, int sipmethod, const char *recip)
09371 {
09372    /* Initialize a request */
09373    memset(req, 0, sizeof(*req));
09374    if (!(req->data = ast_str_create(SIP_MIN_PACKET)))
09375       goto e_return;
09376    if (!(req->content = ast_str_create(SIP_MIN_PACKET)))
09377       goto e_free_data;
09378    req->method = sipmethod;
09379    req->header[0] = 0;
09380    ast_str_set(&req->data, 0, "%s %s SIP/2.0\r\n", sip_methods[sipmethod].text, recip);
09381    req->len = ast_str_strlen(req->data);
09382    req->headers++;
09383    return 0;
09384 
09385 e_free_data:
09386    ast_free(req->data);
09387    req->data = NULL;
09388 e_return:
09389    return -1;
09390 }
09391 
09392 /*! \brief Deinitialize SIP response/request */
09393 static void deinit_req(struct sip_request *req)
09394 {
09395    if (req->data) {
09396       ast_free(req->data);
09397       req->data = NULL;
09398    }
09399    if (req->content) {
09400       ast_free(req->content);
09401       req->content = NULL;
09402    }
09403 }
09404 
09405 
09406 /*! \brief Test if this response needs a contact header */
09407 static inline int resp_needs_contact(const char *msg, enum sipmethod method) {
09408    /* Requirements for Contact header inclusion in responses generated
09409     * from the header tables found in the following RFCs.  Where the
09410     * Contact header was marked mandatory (m) or optional (o) this
09411     * function returns 1.
09412     *
09413     * - RFC 3261 (ACK, BYE, CANCEL, INVITE, OPTIONS, REGISTER)
09414     * - RFC 2976 (INFO)
09415     * - RFC 3262 (PRACK)
09416     * - RFC 3265 (SUBSCRIBE, NOTIFY)
09417     * - RFC 3311 (UPDATE)
09418     * - RFC 3428 (MESSAGE)
09419     * - RFC 3515 (REFER)
09420     * - RFC 3903 (PUBLISH)
09421     */
09422 
09423    switch (method) {
09424       /* 1xx, 2xx, 3xx, 485 */
09425       case SIP_INVITE:
09426       case SIP_UPDATE:
09427       case SIP_SUBSCRIBE:
09428       case SIP_NOTIFY:
09429          if ((msg[0] >= '1' && msg[0] <= '3') || !strncmp(msg, "485", 3))
09430             return 1;
09431          break;
09432 
09433       /* 2xx, 3xx, 485 */
09434       case SIP_REGISTER:
09435       case SIP_OPTIONS:
09436          if (msg[0] == '2' || msg[0] == '3' || !strncmp(msg, "485", 3))
09437             return 1;
09438          break;
09439 
09440       /* 3xx, 485 */
09441       case SIP_BYE:
09442       case SIP_PRACK:
09443       case SIP_MESSAGE:
09444       case SIP_PUBLISH:
09445          if (msg[0] == '3' || !strncmp(msg, "485", 3))
09446             return 1;
09447          break;
09448 
09449       /* 2xx, 3xx, 4xx, 5xx, 6xx */
09450       case SIP_REFER:
09451          if (msg[0] >= '2' && msg[0] <= '6')
09452             return 1;
09453          break;
09454 
09455       /* contact will not be included for everything else */
09456       case SIP_ACK:
09457       case SIP_CANCEL:
09458       case SIP_INFO:
09459       case SIP_PING:
09460       default:
09461          return 0;
09462    }
09463    return 0;
09464 }
09465 
09466 /*! \brief Prepare SIP response packet */
09467 static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req)
09468 {
09469    char newto[256];
09470    const char *ot;
09471 
09472    init_resp(resp, msg);
09473    copy_via_headers(p, resp, req, "Via");
09474    if (msg[0] == '1' || msg[0] == '2')
09475       copy_all_header(resp, req, "Record-Route");
09476    copy_header(resp, req, "From");
09477    ot = get_header(req, "To");
09478    if (!strcasestr(ot, "tag=") && strncmp(msg, "100", 3)) {
09479       /* Add the proper tag if we don't have it already.  If they have specified
09480          their tag, use it.  Otherwise, use our own tag */
09481       if (!ast_strlen_zero(p->theirtag) && ast_test_flag(&p->flags[0], SIP_OUTGOING))
09482          snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
09483       else if (p->tag && !ast_test_flag(&p->flags[0], SIP_OUTGOING))
09484          snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->tag);
09485       else
09486          ast_copy_string(newto, ot, sizeof(newto));
09487       ot = newto;
09488    }
09489    add_header(resp, "To", ot);
09490    copy_header(resp, req, "Call-ID");
09491    copy_header(resp, req, "CSeq");
09492    if (!ast_strlen_zero(global_useragent))
09493       add_header(resp, "Server", global_useragent);
09494    add_header(resp, "Allow", ALLOWED_METHODS);
09495    add_supported_header(p, resp);
09496 
09497    /* If this is an invite, add Session-Timers related headers if the feature is active for this session */
09498    if (p->method == SIP_INVITE && p->stimer && p->stimer->st_active == TRUE && p->stimer->st_active_peer_ua == TRUE) {
09499       char se_hdr[256];
09500       snprintf(se_hdr, sizeof(se_hdr), "%d;refresher=%s", p->stimer->st_interval,
09501          strefresher2str(p->stimer->st_ref));
09502       add_header(resp, "Session-Expires", se_hdr);
09503    }
09504 
09505    if (msg[0] == '2' && (p->method == SIP_SUBSCRIBE || p->method == SIP_REGISTER)) {
09506       /* For registration responses, we also need expiry and
09507          contact info */
09508       char tmp[256];
09509 
09510       snprintf(tmp, sizeof(tmp), "%d", p->expiry);
09511       add_header(resp, "Expires", tmp);
09512       if (p->expiry) {  /* Only add contact if we have an expiry time */
09513          char contact[SIPBUFSIZE];
09514          const char *contact_uri = p->method == SIP_SUBSCRIBE ? p->our_contact : p->fullcontact;
09515          char *brackets = strchr(contact_uri, '<');
09516          snprintf(contact, sizeof(contact), "%s%s%s;expires=%d", brackets ? "" : "<", contact_uri, brackets ? "" : ">", p->expiry);
09517          add_header(resp, "Contact", contact);  /* Not when we unregister */
09518       }
09519    } else if (!ast_strlen_zero(p->our_contact) && resp_needs_contact(msg, p->method)) {
09520       add_header(resp, "Contact", p->our_contact);
09521    }
09522 
09523    if (!ast_strlen_zero(p->url)) {
09524       add_header(resp, "Access-URL", p->url);
09525       ast_string_field_set(p, url, NULL);
09526    }
09527 
09528    return 0;
09529 }
09530 
09531 /*! \brief Initialize a SIP request message (not the initial one in a dialog) */
09532 static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, int seqno, int newbranch)
09533 {
09534    struct sip_request *orig = &p->initreq;
09535    char stripped[80];
09536    char tmp[80];
09537    char newto[256];
09538    const char *c;
09539    const char *ot, *of;
09540    int is_strict = FALSE;     /*!< Strict routing flag */
09541    int is_outbound = ast_test_flag(&p->flags[0], SIP_OUTGOING);   /* Session direction */
09542 
09543    memset(req, 0, sizeof(struct sip_request));
09544    
09545    snprintf(p->lastmsg, sizeof(p->lastmsg), "Tx: %s", sip_methods[sipmethod].text);
09546    
09547    if (!seqno) {
09548       p->ocseq++;
09549       seqno = p->ocseq;
09550    }
09551    
09552    /* A CANCEL must have the same branch as the INVITE that it is canceling. */
09553    if (sipmethod == SIP_CANCEL) {
09554       p->branch = p->invite_branch;
09555       build_via(p);
09556    } else if (newbranch && (sipmethod == SIP_INVITE)) {
09557       p->branch ^= ast_random();
09558       p->invite_branch = p->branch;
09559       build_via(p);
09560    } else if (newbranch) {
09561       p->branch ^= ast_random();
09562       build_via(p);
09563    }
09564 
09565    /* Check for strict or loose router */
09566    if (p->route && !ast_strlen_zero(p->route->hop) && strstr(p->route->hop, ";lr") == NULL) {
09567       is_strict = TRUE;
09568       if (sipdebug)
09569          ast_debug(1, "Strict routing enforced for session %s\n", p->callid);
09570    }
09571    
09572    if (sipmethod == SIP_CANCEL)
09573       c = REQ_OFFSET_TO_STR(&p->initreq, rlPart2); /* Use original URI */
09574    else if (sipmethod == SIP_ACK) {
09575       /* Use URI from Contact: in 200 OK (if INVITE)
09576       (we only have the contacturi on INVITEs) */
09577       if (!ast_strlen_zero(p->okcontacturi))
09578          c = is_strict ? p->route->hop : p->okcontacturi;
09579       else
09580          c = REQ_OFFSET_TO_STR(&p->initreq, rlPart2);
09581    } else if (!ast_strlen_zero(p->okcontacturi))
09582       c = is_strict ? p->route->hop : p->okcontacturi; /* Use for BYE or REINVITE */
09583    else if (!ast_strlen_zero(p->uri))
09584       c = p->uri;
09585    else {
09586       char *n;
09587       /* We have no URI, use To: or From:  header as URI (depending on direction) */
09588       ast_copy_string(stripped, get_header(orig, is_outbound ? "To" : "From"),
09589             sizeof(stripped));
09590       n = get_in_brackets(stripped);
09591       c = remove_uri_parameters(n);
09592    }  
09593    init_req(req, sipmethod, c);
09594 
09595    snprintf(tmp, sizeof(tmp), "%d %s", seqno, sip_methods[sipmethod].text);
09596 
09597    add_header(req, "Via", p->via);
09598    if (p->route) {
09599       set_destination(p, p->route->hop);
09600       add_route(req, is_strict ? p->route->next : p->route);
09601    }
09602    add_header_max_forwards(p, req);
09603 
09604    ot = get_header(orig, "To");
09605    of = get_header(orig, "From");
09606 
09607    /* Add tag *unless* this is a CANCEL, in which case we need to send it exactly
09608       as our original request, including tag (or presumably lack thereof) */
09609    if (!strcasestr(ot, "tag=") && sipmethod != SIP_CANCEL) {
09610       /* Add the proper tag if we don't have it already.  If they have specified
09611          their tag, use it.  Otherwise, use our own tag */
09612       if (is_outbound && !ast_strlen_zero(p->theirtag))
09613          snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
09614       else if (!is_outbound)
09615          snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->tag);
09616       else
09617          snprintf(newto, sizeof(newto), "%s", ot);
09618       ot = newto;
09619    }
09620 
09621    if (is_outbound) {
09622       add_header(req, "From", of);
09623       add_header(req, "To", ot);
09624    } else {
09625       add_header(req, "From", ot);
09626       add_header(req, "To", of);
09627    }
09628    /* Do not add Contact for MESSAGE, BYE and Cancel requests */
09629    if (sipmethod != SIP_BYE && sipmethod != SIP_CANCEL && sipmethod != SIP_MESSAGE)
09630       add_header(req, "Contact", p->our_contact);
09631 
09632    copy_header(req, orig, "Call-ID");
09633    add_header(req, "CSeq", tmp);
09634 
09635    if (!ast_strlen_zero(global_useragent))
09636       add_header(req, "User-Agent", global_useragent);
09637 
09638    if (!ast_strlen_zero(p->url)) {
09639       add_header(req, "Access-URL", p->url);
09640       ast_string_field_set(p, url, NULL);
09641    }
09642 
09643    /* Add Session-Timers related headers if the feature is active for this session.
09644       An exception to this behavior is the ACK request. Since Asterisk never requires
09645       session-timers support from a remote end-point (UAS) in an INVITE, it must
09646       not send 'Require: timer' header in the ACK request.
09647       This should only be added in the INVITE transactions, not MESSAGE or REFER or other
09648       in-dialog messages.
09649    */
09650    if (p->stimer && p->stimer->st_active == TRUE && p->stimer->st_active_peer_ua == TRUE
09651        && sipmethod == SIP_INVITE) {
09652       char se_hdr[256];
09653       snprintf(se_hdr, sizeof(se_hdr), "%d;refresher=%s", p->stimer->st_interval,
09654          strefresher2str(p->stimer->st_ref));
09655       add_header(req, "Require", "timer");
09656       add_header(req, "Session-Expires", se_hdr);
09657       snprintf(se_hdr, sizeof(se_hdr), "%d", st_get_se(p, FALSE));
09658       add_header(req, "Min-SE", se_hdr);
09659    }
09660 
09661    return 0;
09662 }
09663 
09664 /*! \brief Base transmit response function */
09665 static int __transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable)
09666 {
09667    struct sip_request resp;
09668    int seqno = 0;
09669 
09670    if (reliable && (sscanf(get_header(req, "CSeq"), "%30d ", &seqno) != 1)) {
09671       ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
09672       return -1;
09673    }
09674    respprep(&resp, p, msg, req);
09675 
09676    if (ast_test_flag(&p->flags[0], SIP_SENDRPID)
09677          && ast_test_flag(&p->flags[1], SIP_PAGE2_CONNECTLINEUPDATE_PEND)
09678          && (!strncmp(msg, "180", 3) || !strncmp(msg, "183", 3))) {
09679       ast_clear_flag(&p->flags[1], SIP_PAGE2_CONNECTLINEUPDATE_PEND);
09680       add_rpid(&resp, p);
09681    }
09682    if (ast_test_flag(&p->flags[0], SIP_OFFER_CC)) {
09683       add_cc_call_info_to_response(p, &resp);
09684    }
09685 
09686    /* If we are cancelling an incoming invite for some reason, add information
09687       about the reason why we are doing this in clear text */
09688    if (p->method == SIP_INVITE && msg[0] != '1') {
09689       char buf[20];
09690 
09691       if (ast_test_flag(&p->flags[1], SIP_PAGE2_Q850_REASON)) {
09692          int hangupcause = 0;
09693 
09694          if (p->owner && p->owner->hangupcause) {
09695             hangupcause = p->owner->hangupcause;
09696          } else if (p->hangupcause) {
09697             hangupcause = p->hangupcause;
09698          } else {
09699             int respcode;
09700             if (sscanf(msg, "%30d ", &respcode))
09701                hangupcause = hangup_sip2cause(respcode);
09702          }
09703 
09704          if (hangupcause) {
09705             sprintf(buf, "Q.850;cause=%i", hangupcause & 0x7f);
09706             add_header(&resp, "Reason", buf);
09707          }
09708       }
09709 
09710       if (p->owner && p->owner->hangupcause) {
09711          add_header(&resp, "X-Asterisk-HangupCause", ast_cause2str(p->owner->hangupcause));
09712          snprintf(buf, sizeof(buf), "%d", p->owner->hangupcause);
09713          add_header(&resp, "X-Asterisk-HangupCauseCode", buf);
09714       }
09715    }
09716    return send_response(p, &resp, reliable, seqno);
09717 }
09718 
09719 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)
09720 {
09721    struct sip_request resp;
09722 
09723    if (need_new_etag) {
09724       create_new_sip_etag(esc_entry, 1);
09725    }
09726    respprep(&resp, p, msg, req);
09727    add_header(&resp, "SIP-ETag", esc_entry->entity_tag);
09728 
09729    return send_response(p, &resp, 0, 0);
09730 }
09731 
09732 static int temp_pvt_init(void *data)
09733 {
09734    struct sip_pvt *p = data;
09735 
09736    p->do_history = 0;   /* XXX do we need it ? isn't already all 0 ? */
09737    return ast_string_field_init(p, 512);
09738 }
09739 
09740 static void temp_pvt_cleanup(void *data)
09741 {
09742    struct sip_pvt *p = data;
09743 
09744    ast_string_field_free_memory(p);
09745 
09746    ast_free(data);
09747 }
09748 
09749 /*! \brief Transmit response, no retransmits, using a temporary pvt structure */
09750 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)
09751 {
09752    struct sip_pvt *p = NULL;
09753 
09754    if (!(p = ast_threadstorage_get(&ts_temp_pvt, sizeof(*p)))) {
09755       ast_log(LOG_ERROR, "Failed to get temporary pvt\n");
09756       return -1;
09757    }
09758 
09759    /* XXX the structure may be dirty from previous usage.
09760     * Here we should state clearly how we should reinitialize it
09761     * before using it.
09762     * E.g. certainly the threadstorage should be left alone,
09763     * but other thihngs such as flags etc. maybe need cleanup ?
09764     */
09765 
09766    /* Initialize the bare minimum */
09767    p->method = intended_method;
09768 
09769    if (!addr) {
09770       ast_sockaddr_copy(&p->ourip, &internip);
09771    } else {
09772       ast_sockaddr_copy(&p->sa, addr);
09773       ast_sip_ouraddrfor(&p->sa, &p->ourip, p);
09774    }
09775 
09776    p->branch = ast_random();
09777    make_our_tag(p->tag, sizeof(p->tag));
09778    p->ocseq = INITIAL_CSEQ;
09779 
09780    if (useglobal_nat && addr) {
09781       ast_copy_flags(&p->flags[0], &global_flags[0], SIP_NAT_FORCE_RPORT);
09782       ast_sockaddr_copy(&p->recv, addr);
09783       do_setnat(p);
09784    }
09785 
09786    ast_string_field_set(p, fromdomain, default_fromdomain);
09787    p->fromdomainport = default_fromdomainport;
09788    build_via(p);
09789    ast_string_field_set(p, callid, callid);
09790 
09791    copy_socket_data(&p->socket, &req->socket);
09792 
09793    /* Use this temporary pvt structure to send the message */
09794    __transmit_response(p, msg, req, XMIT_UNRELIABLE);
09795 
09796    /* Free the string fields, but not the pool space */
09797    ast_string_field_init(p, 0);
09798 
09799    return 0;
09800 }
09801 
09802 /*! \brief Transmit response, no retransmits */
09803 static int transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req)
09804 {
09805    return __transmit_response(p, msg, req, XMIT_UNRELIABLE);
09806 }
09807 
09808 /*! \brief Transmit response, no retransmits */
09809 static int transmit_response_with_unsupported(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *unsupported)
09810 {
09811    struct sip_request resp;
09812    respprep(&resp, p, msg, req);
09813    append_date(&resp);
09814    add_header(&resp, "Unsupported", unsupported);
09815    return send_response(p, &resp, XMIT_UNRELIABLE, 0);
09816 }
09817 
09818 /*! \brief Transmit 422 response with Min-SE header (Session-Timers)  */
09819 static int transmit_response_with_minse(struct sip_pvt *p, const char *msg, const struct sip_request *req, int minse_int)
09820 {
09821    struct sip_request resp;
09822    char minse_str[20];
09823 
09824    respprep(&resp, p, msg, req);
09825    append_date(&resp);
09826 
09827    snprintf(minse_str, sizeof(minse_str), "%d", minse_int);
09828    add_header(&resp, "Min-SE", minse_str);
09829    return send_response(p, &resp, XMIT_UNRELIABLE, 0);
09830 }
09831 
09832 
09833 /*! \brief Transmit response, Make sure you get an ACK
09834    This is only used for responses to INVITEs, where we need to make sure we get an ACK
09835 */
09836 static int transmit_response_reliable(struct sip_pvt *p, const char *msg, const struct sip_request *req)
09837 {
09838    return __transmit_response(p, msg, req, req->ignore ? XMIT_UNRELIABLE : XMIT_CRITICAL);
09839 }
09840 
09841 /*! \brief Append date to SIP message */
09842 static void append_date(struct sip_request *req)
09843 {
09844    char tmpdat[256];
09845    struct tm tm;
09846    time_t t = time(NULL);
09847 
09848    gmtime_r(&t, &tm);
09849    strftime(tmpdat, sizeof(tmpdat), "%a, %d %b %Y %T GMT", &tm);
09850    add_header(req, "Date", tmpdat);
09851 }
09852 
09853 /*! \brief Append Retry-After header field when transmitting response */
09854 static int transmit_response_with_retry_after(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *seconds)
09855 {
09856    struct sip_request resp;
09857    respprep(&resp, p, msg, req);
09858    add_header(&resp, "Retry-After", seconds);
09859    return send_response(p, &resp, XMIT_UNRELIABLE, 0);
09860 }
09861 
09862 /*! \brief Append date and content length before transmitting response */
09863 static int transmit_response_with_date(struct sip_pvt *p, const char *msg, const struct sip_request *req)
09864 {
09865    struct sip_request resp;
09866    respprep(&resp, p, msg, req);
09867    append_date(&resp);
09868    return send_response(p, &resp, XMIT_UNRELIABLE, 0);
09869 }
09870 
09871 /*! \brief Append Accept header, content length before transmitting response */
09872 static int transmit_response_with_allow(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable)
09873 {
09874    struct sip_request resp;
09875    respprep(&resp, p, msg, req);
09876    add_header(&resp, "Accept", "application/sdp");
09877    return send_response(p, &resp, reliable, 0);
09878 }
09879 
09880 /*! \brief Append Min-Expires header, content length before transmitting response */
09881 static int transmit_response_with_minexpires(struct sip_pvt *p, const char *msg, const struct sip_request *req)
09882 {
09883    struct sip_request resp;
09884    char tmp[32];
09885 
09886    snprintf(tmp, sizeof(tmp), "%d", min_expiry);
09887    respprep(&resp, p, msg, req);
09888    add_header(&resp, "Min-Expires", tmp);
09889    return send_response(p, &resp, XMIT_UNRELIABLE, 0);
09890 }
09891 
09892 /*! \brief Respond with authorization request */
09893 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)
09894 {
09895    struct sip_request resp;
09896    char tmp[512];
09897    int seqno = 0;
09898 
09899    if (reliable && (sscanf(get_header(req, "CSeq"), "%30d ", &seqno) != 1)) {
09900       ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
09901       return -1;
09902    }
09903    /* Choose Realm */
09904    get_realm(p, req);
09905 
09906    /* Stale means that they sent us correct authentication, but
09907       based it on an old challenge (nonce) */
09908    snprintf(tmp, sizeof(tmp), "Digest algorithm=MD5, realm=\"%s\", nonce=\"%s\"%s", p->realm, randdata, stale ? ", stale=true" : "");
09909    respprep(&resp, p, msg, req);
09910    add_header(&resp, header, tmp);
09911    append_history(p, "AuthChal", "Auth challenge sent for %s - nc %d", p->username, p->noncecount);
09912    return send_response(p, &resp, reliable, seqno);
09913 }
09914 
09915 /*!
09916  \brief Extract domain from SIP To/From header
09917  \return -1 on error, 1 if domain string is empty, 0 if domain was properly extracted
09918  \note TODO: Such code is all over SIP channel, there is a sense to organize
09919       this patern in one function
09920 */
09921 static int get_domain(const char *str, char *domain, int len)
09922 {
09923    char tmpf[256];
09924    char *a, *from;
09925 
09926    *domain = '\0';
09927    ast_copy_string(tmpf, str, sizeof(tmpf));
09928    from = get_in_brackets(tmpf);
09929    if (!ast_strlen_zero(from)) {
09930       if (strncasecmp(from, "sip:", 4)) {
09931          ast_log(LOG_WARNING, "Huh?  Not a SIP header (%s)?\n", from);
09932          return -1;
09933       }
09934       from += 4;
09935    } else
09936       from = NULL;
09937 
09938    if (from) {
09939       int bracket = 0;
09940 
09941       /* Strip any params or options from user */
09942       if ((a = strchr(from, ';')))
09943          *a = '\0';
09944       /* Strip port from domain if present */
09945       for (a = from; *a != '\0'; ++a) {
09946          if (*a == ':' && bracket == 0) {
09947             *a = '\0';
09948             break;
09949          } else if (*a == '[') {
09950             ++bracket;
09951          } else if (*a == ']') {
09952             --bracket;
09953          }
09954       }
09955       if ((a = strchr(from, '@'))) {
09956          *a = '\0';
09957          ast_copy_string(domain, a + 1, len);
09958       } else
09959          ast_copy_string(domain, from, len);
09960    }
09961 
09962    return ast_strlen_zero(domain);
09963 }
09964 
09965 /*!
09966   \brief Choose realm based on From header and then To header or use globaly configured realm.
09967   Realm from From/To header should be listed among served domains in config file: domain=...
09968 */
09969 static void get_realm(struct sip_pvt *p, const struct sip_request *req)
09970 {
09971    char domain[MAXHOSTNAMELEN];
09972 
09973    if (!ast_strlen_zero(p->realm))
09974       return;
09975 
09976    if (sip_cfg.domainsasrealm &&
09977        !AST_LIST_EMPTY(&domain_list))
09978    {
09979       /* Check From header first */
09980       if (!get_domain(get_header(req, "From"), domain, sizeof(domain))) {
09981          if (check_sip_domain(domain, NULL, 0)) {
09982             ast_string_field_set(p, realm, domain);
09983             return;
09984          }
09985       }
09986       /* Check To header */
09987       if (!get_domain(get_header(req, "To"), domain, sizeof(domain))) {
09988          if (check_sip_domain(domain, NULL, 0)) {
09989             ast_string_field_set(p, realm, domain);
09990             return;
09991          }
09992       }
09993    }
09994    
09995    /* Use default realm from config file */
09996    ast_string_field_set(p, realm, sip_cfg.realm);
09997 }
09998 
09999 /* Only use a static string for the msg, here! */
10000 static int transmit_provisional_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, int with_sdp)
10001 {
10002    int res;
10003 
10004    if (!(res = with_sdp ? transmit_response_with_sdp(p, msg, req, XMIT_UNRELIABLE, FALSE, FALSE) : transmit_response(p, msg, req))) {
10005       p->last_provisional = msg;
10006       update_provisional_keepalive(p, with_sdp);
10007    }
10008 
10009    return res;
10010 }
10011 
10012 /*! \brief Add text body to SIP message */
10013 static int add_text(struct sip_request *req, const char *text)
10014 {
10015    /* XXX Convert \n's to \r\n's XXX */
10016    add_header(req, "Content-Type", "text/plain;charset=UTF-8");
10017    add_content(req, text);
10018    return 0;
10019 }
10020 
10021 /*! \brief Add DTMF INFO tone to sip message
10022    Mode =   0 for application/dtmf-relay (Cisco)
10023       1 for application/dtmf
10024 */
10025 static int add_digit(struct sip_request *req, char digit, unsigned int duration, int mode)
10026 {
10027    char tmp[256];
10028    int event;
10029    if (mode) {
10030       /* Application/dtmf short version used by some implementations */
10031       if (digit == '*')
10032          event = 10;
10033       else if (digit == '#')
10034          event = 11;
10035       else if ((digit >= 'A') && (digit <= 'D'))
10036          event = 12 + digit - 'A';
10037       else
10038          event = atoi(&digit);
10039       snprintf(tmp, sizeof(tmp), "%d\r\n", event);
10040       add_header(req, "Content-Type", "application/dtmf");
10041       add_content(req, tmp);
10042    } else {
10043       /* Application/dtmf-relay as documented by Cisco */
10044       snprintf(tmp, sizeof(tmp), "Signal=%c\r\nDuration=%u\r\n", digit, duration);
10045       add_header(req, "Content-Type", "application/dtmf-relay");
10046       add_content(req, tmp);
10047    }
10048    return 0;
10049 }
10050 
10051 /*!
10052  * \pre if p->owner exists, it must be locked
10053  * \brief Add Remote-Party-ID header to SIP message
10054  */
10055 static int add_rpid(struct sip_request *req, struct sip_pvt *p)
10056 {
10057    struct ast_str *tmp = ast_str_alloca(256);
10058    char tmp2[256];
10059    char *lid_num = NULL;
10060    char *lid_name = NULL;
10061    int lid_pres;
10062    const char *fromdomain;
10063    const char *privacy = NULL;
10064    const char *screen = NULL;
10065    const char *anonymous_string = "\"Anonymous\" <sip:anonymous@anonymous.invalid>";
10066 
10067    if (!ast_test_flag(&p->flags[0], SIP_SENDRPID)) {
10068       return 0;
10069    }
10070 
10071    if (p->owner && p->owner->connected.id.number.valid
10072       && p->owner->connected.id.number.str) {
10073       lid_num = p->owner->connected.id.number.str;
10074    }
10075    if (p->owner && p->owner->connected.id.name.valid
10076       && p->owner->connected.id.name.str) {
10077       lid_name = p->owner->connected.id.name.str;
10078    }
10079    lid_pres = (p->owner) ? ast_party_id_presentation(&p->owner->connected.id) : AST_PRES_NUMBER_NOT_AVAILABLE;
10080 
10081    if (ast_strlen_zero(lid_num))
10082       return 0;
10083    if (ast_strlen_zero(lid_name))
10084       lid_name = lid_num;
10085    fromdomain = S_OR(p->fromdomain, ast_sockaddr_stringify_host(&p->ourip));
10086 
10087    lid_num = ast_uri_encode(lid_num, tmp2, sizeof(tmp2), 1);
10088 
10089    if (ast_test_flag(&p->flags[0], SIP_SENDRPID_PAI)) {
10090       if ((lid_pres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED) {
10091          ast_str_set(&tmp, -1, "%s", anonymous_string);
10092       } else {
10093          ast_str_set(&tmp, -1, "\"%s\" <sip:%s@%s>", lid_name, lid_num, fromdomain);
10094       }
10095       add_header(req, "P-Asserted-Identity", ast_str_buffer(tmp));
10096    } else {
10097       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");
10098 
10099       switch (lid_pres) {
10100       case AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED:
10101       case AST_PRES_ALLOWED_USER_NUMBER_FAILED_SCREEN:
10102          privacy = "off";
10103          screen = "no";
10104          break;
10105       case AST_PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN:
10106       case AST_PRES_ALLOWED_NETWORK_NUMBER:
10107          privacy = "off";
10108          screen = "yes";
10109          break;
10110       case AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED:
10111       case AST_PRES_PROHIB_USER_NUMBER_FAILED_SCREEN:
10112          privacy = "full";
10113          screen = "no";
10114          break;
10115       case AST_PRES_PROHIB_USER_NUMBER_PASSED_SCREEN:
10116       case AST_PRES_PROHIB_NETWORK_NUMBER:
10117          privacy = "full";
10118          screen = "yes";
10119          break;
10120       case AST_PRES_NUMBER_NOT_AVAILABLE:
10121          break;
10122       default:
10123          if ((lid_pres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED) {
10124             privacy = "full";
10125          }
10126          else
10127             privacy = "off";
10128          screen = "no";
10129          break;
10130       }
10131 
10132       if (!ast_strlen_zero(privacy) && !ast_strlen_zero(screen)) {
10133          ast_str_append(&tmp, -1, ";privacy=%s;screen=%s", privacy, screen);
10134       }
10135 
10136       add_header(req, "Remote-Party-ID", ast_str_buffer(tmp));
10137    }
10138    return 0;
10139 }
10140 
10141 /*! \brief add XML encoded media control with update
10142    \note XML: The only way to turn 0 bits of information into a few hundred. (markster) */
10143 static int add_vidupdate(struct sip_request *req)
10144 {
10145    const char *xml_is_a_huge_waste_of_space =
10146       "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\r\n"
10147       " <media_control>\r\n"
10148       "  <vc_primitive>\r\n"
10149       "   <to_encoder>\r\n"
10150       "    <picture_fast_update>\r\n"
10151       "    </picture_fast_update>\r\n"
10152       "   </to_encoder>\r\n"
10153       "  </vc_primitive>\r\n"
10154       " </media_control>\r\n";
10155    add_header(req, "Content-Type", "application/media_control+xml");
10156    add_content(req, xml_is_a_huge_waste_of_space);
10157    return 0;
10158 }
10159 
10160 /*! \brief Add codec offer to SDP offer/answer body in INVITE or 200 OK */
10161 static void add_codec_to_sdp(const struct sip_pvt *p, format_t codec,
10162               struct ast_str **m_buf, struct ast_str **a_buf,
10163               int debug, int *min_packet_size)
10164 {
10165    int rtp_code;
10166    struct ast_format_list fmt;
10167 
10168 
10169    if (debug)
10170       ast_verbose("Adding codec 0x%" PRIx64 " (%s) to SDP\n", codec, ast_getformatname(codec));
10171    if ((rtp_code = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(p->rtp), 1, codec)) == -1)
10172       return;
10173 
10174    if (p->rtp) {
10175       struct ast_codec_pref *pref = &ast_rtp_instance_get_codecs(p->rtp)->pref;
10176       fmt = ast_codec_pref_getsize(pref, codec);
10177    } 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 */
10178       return;
10179    ast_str_append(m_buf, 0, " %d", rtp_code);
10180    ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%d\r\n", rtp_code,
10181              ast_rtp_lookup_mime_subtype2(1, codec,
10182                      ast_test_flag(&p->flags[0], SIP_G726_NONSTANDARD) ? AST_RTP_OPT_G726_NONSTANDARD : 0),
10183              ast_rtp_lookup_sample_rate2(1, codec));
10184 
10185    switch (codec) {
10186    case AST_FORMAT_G729A:
10187       /* Indicate that we don't support VAD (G.729 annex B) */
10188       ast_str_append(a_buf, 0, "a=fmtp:%d annexb=no\r\n", rtp_code);
10189       break;
10190    case AST_FORMAT_G723_1:
10191       /* Indicate that we don't support VAD (G.723.1 annex A) */
10192       ast_str_append(a_buf, 0, "a=fmtp:%d annexa=no\r\n", rtp_code);
10193       break;
10194    case AST_FORMAT_ILBC:
10195       /* Add information about us using only 20/30 ms packetization */
10196       ast_str_append(a_buf, 0, "a=fmtp:%d mode=%d\r\n", rtp_code, fmt.cur_ms);
10197       break;
10198    case AST_FORMAT_SIREN7:
10199       /* Indicate that we only expect 32Kbps */
10200       ast_str_append(a_buf, 0, "a=fmtp:%d bitrate=32000\r\n", rtp_code);
10201       break;
10202    case AST_FORMAT_SIREN14:
10203       /* Indicate that we only expect 48Kbps */
10204       ast_str_append(a_buf, 0, "a=fmtp:%d bitrate=48000\r\n", rtp_code);
10205       break;
10206    case AST_FORMAT_G719:
10207       /* Indicate that we only expect 64Kbps */
10208       ast_str_append(a_buf, 0, "a=fmtp:%d bitrate=64000\r\n", rtp_code);
10209       break;
10210    }
10211 
10212    if (fmt.cur_ms && (fmt.cur_ms < *min_packet_size))
10213       *min_packet_size = fmt.cur_ms;
10214 
10215    /* Our first codec packetization processed cannot be zero */
10216    if ((*min_packet_size)==0 && fmt.cur_ms)
10217       *min_packet_size = fmt.cur_ms;
10218 }
10219 
10220 /*! \brief Add video codec offer to SDP offer/answer body in INVITE or 200 OK */
10221 /* This is different to the audio one now so we can add more caps later */
10222 static void add_vcodec_to_sdp(const struct sip_pvt *p, format_t codec,
10223               struct ast_str **m_buf, struct ast_str **a_buf,
10224               int debug, int *min_packet_size)
10225 {
10226    int rtp_code;
10227 
10228    if (!p->vrtp)
10229       return;
10230 
10231    if (debug)
10232       ast_verbose("Adding video codec 0x%" PRIx64 " (%s) to SDP\n", codec, ast_getformatname(codec));
10233 
10234    if ((rtp_code = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(p->vrtp), 1, codec)) == -1)
10235       return;
10236 
10237    ast_str_append(m_buf, 0, " %d", rtp_code);
10238    ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%d\r\n", rtp_code,
10239              ast_rtp_lookup_mime_subtype2(1, codec, 0),
10240              ast_rtp_lookup_sample_rate2(1, codec));
10241    /* Add fmtp code here */
10242 }
10243 
10244 /*! \brief Add text codec offer to SDP offer/answer body in INVITE or 200 OK */
10245 static void add_tcodec_to_sdp(const struct sip_pvt *p, int codec,
10246               struct ast_str **m_buf, struct ast_str **a_buf,
10247               int debug, int *min_packet_size)
10248 {
10249    int rtp_code;
10250 
10251    if (!p->trtp)
10252       return;
10253 
10254    if (debug)
10255       ast_verbose("Adding text codec 0x%x (%s) to SDP\n", codec, ast_getformatname(codec));
10256 
10257    if ((rtp_code = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(p->trtp), 1, codec)) == -1)
10258       return;
10259 
10260    ast_str_append(m_buf, 0, " %d", rtp_code);
10261    ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%d\r\n", rtp_code,
10262              ast_rtp_lookup_mime_subtype2(1, codec, 0),
10263              ast_rtp_lookup_sample_rate2(1, codec));
10264    /* Add fmtp code here */
10265 
10266    if (codec == AST_FORMAT_T140RED) {
10267       int t140code = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(p->trtp), 1, AST_FORMAT_T140);
10268       ast_str_append(a_buf, 0, "a=fmtp:%d %d/%d/%d\r\n", rtp_code,
10269           t140code,
10270           t140code,
10271           t140code);
10272 
10273    }
10274 }
10275 
10276 
10277 /*! \brief Get Max T.38 Transmission rate from T38 capabilities */
10278 static unsigned int t38_get_rate(enum ast_control_t38_rate rate)
10279 {
10280    switch (rate) {
10281    case AST_T38_RATE_2400:
10282       return 2400;
10283    case AST_T38_RATE_4800:
10284       return 4800;
10285    case AST_T38_RATE_7200:
10286       return 7200;
10287    case AST_T38_RATE_9600:
10288       return 9600;
10289    case AST_T38_RATE_12000:
10290       return 12000;
10291    case AST_T38_RATE_14400:
10292       return 14400;
10293    default:
10294       return 0;
10295    }
10296 }
10297 
10298 /*! \brief Add RFC 2833 DTMF offer to SDP */
10299 static void add_noncodec_to_sdp(const struct sip_pvt *p, int format,
10300             struct ast_str **m_buf, struct ast_str **a_buf,
10301             int debug)
10302 {
10303    int rtp_code;
10304 
10305    if (debug)
10306       ast_verbose("Adding non-codec 0x%x (%s) to SDP\n", format, ast_rtp_lookup_mime_subtype2(0, format, 0));
10307    if ((rtp_code = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(p->rtp), 0, format)) == -1)
10308       return;
10309 
10310    ast_str_append(m_buf, 0, " %d", rtp_code);
10311    ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%d\r\n", rtp_code,
10312              ast_rtp_lookup_mime_subtype2(0, format, 0),
10313              ast_rtp_lookup_sample_rate2(0, format));
10314    if (format == AST_RTP_DTMF)   /* Indicate we support DTMF and FLASH... */
10315       ast_str_append(a_buf, 0, "a=fmtp:%d 0-16\r\n", rtp_code);
10316 }
10317 
10318 /*! \brief Set all IP media addresses for this call
10319    \note called from add_sdp()
10320 */
10321 static void get_our_media_address(struct sip_pvt *p, int needvideo, int needtext,
10322               struct ast_sockaddr *addr, struct ast_sockaddr *vaddr,
10323               struct ast_sockaddr *taddr, struct ast_sockaddr *dest,
10324               struct ast_sockaddr *vdest, struct ast_sockaddr *tdest)
10325 {
10326    int use_externip = 0;
10327 
10328    /* First, get our address */
10329    ast_rtp_instance_get_local_address(p->rtp, addr);
10330    if (p->vrtp) {
10331       ast_rtp_instance_get_local_address(p->vrtp, vaddr);
10332    }
10333    if (p->trtp) {
10334       ast_rtp_instance_get_local_address(p->trtp, taddr);
10335    }
10336 
10337    /* If our real IP differs from the local address returned by the RTP engine, use it. */
10338    /* The premise is that if we are already using that IP to communicate with the client, */
10339    /* we should be using it for RTP too. */
10340         use_externip = ast_sockaddr_cmp_addr(&p->ourip, addr);
10341 
10342    /* Now, try to figure out where we want them to send data */
10343    /* Is this a re-invite to move the media out, then use the original offer from caller  */
10344    if (!ast_sockaddr_isnull(&p->redirip)) {  /* If we have a redirection IP, use it */
10345       ast_sockaddr_copy(dest, &p->redirip);
10346    } else {
10347       /*
10348        * Audio Destination IP:
10349        *
10350        * 1. Specifically configured media address.
10351        * 2. Local address as specified by the RTP engine.
10352        * 3. The local IP as defined by chan_sip.
10353        *
10354        * Audio Destination Port:
10355        *
10356        * 1. Provided by the RTP engine.
10357        */
10358       ast_sockaddr_copy(dest,
10359               !ast_sockaddr_isnull(&media_address) ? &media_address :
10360               !ast_sockaddr_is_any(addr) && !use_externip ? addr    :
10361               &p->ourip);
10362       ast_sockaddr_set_port(dest, ast_sockaddr_port(addr));
10363    }
10364 
10365    if (needvideo) {
10366       /* Determine video destination */
10367       if (!ast_sockaddr_isnull(&p->vredirip)) {
10368          ast_sockaddr_copy(vdest, &p->vredirip);
10369       } else {
10370          /*
10371           * Video Destination IP:
10372           *
10373           * 1. Specifically configured media address.
10374           * 2. Local address as specified by the RTP engine.
10375           * 3. The local IP as defined by chan_sip.
10376           *
10377           * Video Destination Port:
10378           *
10379           * 1. Provided by the RTP engine.
10380           */
10381          ast_sockaddr_copy(vdest,
10382                  !ast_sockaddr_isnull(&media_address) ? &media_address :
10383                  !ast_sockaddr_is_any(vaddr) && !use_externip ? vaddr  :
10384                  &p->ourip);
10385          ast_sockaddr_set_port(vdest, ast_sockaddr_port(vaddr));
10386       }
10387    }
10388 
10389    if (needtext) {
10390       /* Determine text destination */
10391       if (!ast_sockaddr_isnull(&p->tredirip)) {
10392          ast_sockaddr_copy(tdest, &p->tredirip);
10393       } else {
10394          /*
10395           * Text Destination IP:
10396           *
10397           * 1. Specifically configured media address.
10398           * 2. Local address as specified by the RTP engine.
10399           * 3. The local IP as defined by chan_sip.
10400           *
10401           * Text Destination Port:
10402           *
10403           * 1. Provided by the RTP engine.
10404           */
10405          ast_sockaddr_copy(tdest,
10406                  !ast_sockaddr_isnull(&media_address) ? &media_address  :
10407                  !ast_sockaddr_is_any(taddr) && !use_externip ? taddr   :
10408                  &p->ourip);
10409          ast_sockaddr_set_port(tdest, ast_sockaddr_port(taddr));
10410       }
10411    }
10412 }
10413 
10414 static void get_crypto_attrib(struct sip_srtp *srtp, const char **a_crypto)
10415 {
10416    /* Set encryption properties */
10417    if (srtp) {
10418       if (!srtp->crypto) {
10419          srtp->crypto = sdp_crypto_setup();
10420       }
10421       if (srtp->crypto && (sdp_crypto_offer(srtp->crypto) >= 0)) {
10422          *a_crypto = sdp_crypto_attrib(srtp->crypto);
10423       }
10424 
10425       if (!*a_crypto) {
10426          ast_log(LOG_WARNING, "No SRTP key management enabled\n");
10427       }
10428    }
10429 }
10430 
10431 /*! \brief Add Session Description Protocol message
10432 
10433     If oldsdp is TRUE, then the SDP version number is not incremented. This mechanism
10434     is used in Session-Timers where RE-INVITEs are used for refreshing SIP sessions
10435     without modifying the media session in any way.
10436 */
10437 static enum sip_result add_sdp(struct sip_request *resp, struct sip_pvt *p, int oldsdp, int add_audio, int add_t38)
10438 {
10439    format_t alreadysent = 0;
10440 
10441    struct ast_sockaddr addr = { {0,} };
10442    struct ast_sockaddr vaddr = { {0,} };
10443    struct ast_sockaddr taddr = { {0,} };
10444    struct ast_sockaddr udptladdr = { {0,} };
10445    struct ast_sockaddr dest = { {0,} };
10446    struct ast_sockaddr vdest = { {0,} };
10447    struct ast_sockaddr tdest = { {0,} };
10448    struct ast_sockaddr udptldest = { {0,} };
10449 
10450    /* SDP fields */
10451    char *version =   "v=0\r\n";     /* Protocol version */
10452    char subject[256];            /* Subject of the session */
10453    char owner[256];           /* Session owner/creator */
10454    char connection[256];            /* Connection data */
10455    char *session_time = "t=0 0\r\n";         /* Time the session is active */
10456    char bandwidth[256] = "";        /* Max bitrate */
10457    char *hold = "";
10458    struct ast_str *m_audio = ast_str_alloca(256);  /* Media declaration line for audio */
10459    struct ast_str *m_video = ast_str_alloca(256);  /* Media declaration line for video */
10460    struct ast_str *m_text = ast_str_alloca(256);   /* Media declaration line for text */
10461    struct ast_str *m_modem = ast_str_alloca(256);  /* Media declaration line for modem */
10462    struct ast_str *a_audio = ast_str_alloca(1024); /* Attributes for audio */
10463    struct ast_str *a_video = ast_str_alloca(1024); /* Attributes for video */
10464    struct ast_str *a_text = ast_str_alloca(1024);  /* Attributes for text */
10465    struct ast_str *a_modem = ast_str_alloca(1024); /* Attributes for modem */
10466    const char *a_crypto = NULL;
10467    const char *v_a_crypto = NULL;
10468    const char *t_a_crypto = NULL;
10469 
10470    format_t x;
10471    format_t capability = 0;
10472    int needaudio = FALSE;
10473    int needvideo = FALSE;
10474    int needtext = FALSE;
10475    int debug = sip_debug_test_pvt(p);
10476    int min_audio_packet_size = 0;
10477    int min_video_packet_size = 0;
10478    int min_text_packet_size = 0;
10479 
10480    char codecbuf[SIPBUFSIZE];
10481    char buf[SIPBUFSIZE];
10482    char dummy_answer[256];
10483 
10484    /* Set the SDP session name */
10485    snprintf(subject, sizeof(subject), "s=%s\r\n", ast_strlen_zero(global_sdpsession) ? "-" : global_sdpsession);
10486 
10487    if (!p->rtp) {
10488       ast_log(LOG_WARNING, "No way to add SDP without an RTP structure\n");
10489       return AST_FAILURE;
10490    }
10491    /* XXX We should not change properties in the SIP dialog until
10492       we have acceptance of the offer if this is a re-invite */
10493 
10494    /* Set RTP Session ID and version */
10495    if (!p->sessionid) {
10496       p->sessionid = (int)ast_random();
10497       p->sessionversion = p->sessionid;
10498    } else {
10499       if (oldsdp == FALSE)
10500          p->sessionversion++;
10501    }
10502 
10503    if (add_audio) {
10504       /* Check if we need video in this call */
10505       if ((p->jointcapability & AST_FORMAT_VIDEO_MASK) && !p->novideo) {
10506          if (p->vrtp) {
10507             needvideo = TRUE;
10508             ast_debug(2, "This call needs video offers!\n");
10509          } else
10510             ast_debug(2, "This call needs video offers, but there's no video support enabled!\n");
10511       }
10512       /* Check if we need text in this call */
10513       if ((p->jointcapability & AST_FORMAT_TEXT_MASK) && !p->notext) {
10514          if (sipdebug_text)
10515             ast_verbose("We think we can do text\n");
10516          if (p->trtp) {
10517             if (sipdebug_text) {
10518                ast_verbose("And we have a text rtp object\n");
10519             }
10520             needtext = TRUE;
10521             ast_debug(2, "This call needs text offers! \n");
10522          } else {
10523             ast_debug(2, "This call needs text offers, but there's no text support enabled ! \n");
10524          }
10525       }
10526    }
10527 
10528    get_our_media_address(p, needvideo, needtext, &addr, &vaddr, &taddr, &dest, &vdest, &tdest);
10529 
10530    snprintf(owner, sizeof(owner), "o=%s %d %d IN %s %s\r\n",
10531        ast_strlen_zero(global_sdpowner) ? "-" : global_sdpowner,
10532        p->sessionid, p->sessionversion,
10533        (ast_sockaddr_is_ipv6(&dest) && !ast_sockaddr_is_ipv4_mapped(&dest)) ?
10534          "IP6" : "IP4",
10535        ast_sockaddr_stringify_addr(&dest));
10536 
10537    snprintf(connection, sizeof(connection), "c=IN %s %s\r\n",
10538        (ast_sockaddr_is_ipv6(&dest) && !ast_sockaddr_is_ipv4_mapped(&dest)) ?
10539          "IP6" : "IP4",
10540        ast_sockaddr_stringify_addr(&dest));
10541 
10542    if (add_audio) {
10543       capability = p->jointcapability;
10544 
10545       /* XXX note, Video and Text are negated - 'true' means 'no' */
10546       ast_debug(1, "** Our capability: %s Video flag: %s Text flag: %s\n", ast_getformatname_multiple(codecbuf, sizeof(codecbuf), capability),
10547            p->novideo ? "True" : "False", p->notext ? "True" : "False");
10548       ast_debug(1, "** Our prefcodec: %s \n", ast_getformatname_multiple(codecbuf, sizeof(codecbuf), p->prefcodec));
10549 
10550       /* Check if we need audio */
10551       if (capability & AST_FORMAT_AUDIO_MASK)
10552          needaudio = TRUE;
10553 
10554       if (debug) {
10555          ast_verbose("Audio is at %s\n", ast_sockaddr_stringify_port(&p->ourip));
10556       }
10557 
10558       /* Ok, we need video. Let's add what we need for video and set codecs.
10559          Video is handled differently than audio since we can not transcode. */
10560       if (needvideo) {
10561          get_crypto_attrib(p->vsrtp, &v_a_crypto);
10562          ast_str_append(&m_video, 0, "m=video %d RTP/%s", ast_sockaddr_port(&vdest),
10563             v_a_crypto ? "SAVP" : "AVP");
10564 
10565          /* Build max bitrate string */
10566          if (p->maxcallbitrate)
10567             snprintf(bandwidth, sizeof(bandwidth), "b=CT:%d\r\n", p->maxcallbitrate);
10568          if (debug) {
10569             ast_verbose("Video is at %s\n", ast_sockaddr_stringify(&p->ourip));
10570          }
10571       }
10572 
10573       /* Ok, we need text. Let's add what we need for text and set codecs.
10574          Text is handled differently than audio since we can not transcode. */
10575       if (needtext) {
10576          if (sipdebug_text)
10577             ast_verbose("Lets set up the text sdp\n");
10578          get_crypto_attrib(p->tsrtp, &t_a_crypto);
10579          ast_str_append(&m_text, 0, "m=text %d RTP/%s", ast_sockaddr_port(&tdest),
10580             t_a_crypto ? "SAVP" : "AVP");
10581          if (debug) {  /* XXX should I use tdest below ? */
10582             ast_verbose("Text is at %s\n", ast_sockaddr_stringify(&p->ourip));
10583          }
10584       }
10585 
10586       /* Start building generic SDP headers */
10587 
10588       /* We break with the "recommendation" and send our IP, in order that our
10589          peer doesn't have to ast_gethostbyname() us */
10590 
10591       get_crypto_attrib(p->srtp, &a_crypto);
10592       ast_str_append(&m_audio, 0, "m=audio %d RTP/%s", ast_sockaddr_port(&dest),
10593          a_crypto ? "SAVP" : "AVP");
10594 
10595       if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD) == SIP_PAGE2_CALL_ONHOLD_ONEDIR)
10596          hold = "a=recvonly\r\n";
10597       else if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD) == SIP_PAGE2_CALL_ONHOLD_INACTIVE)
10598          hold = "a=inactive\r\n";
10599       else
10600          hold = "a=sendrecv\r\n";
10601 
10602       /* Now, start adding audio codecs. These are added in this order:
10603          - First what was requested by the calling channel
10604          - Then preferences in order from sip.conf device config for this peer/user
10605          - Then other codecs in capabilities, including video
10606       */
10607 
10608       /* Prefer the audio codec we were requested to use, first, no matter what
10609          Note that p->prefcodec can include video codecs, so mask them out
10610       */
10611       if (capability & p->prefcodec) {
10612          format_t codec = p->prefcodec & AST_FORMAT_AUDIO_MASK;
10613 
10614          add_codec_to_sdp(p, codec, &m_audio, &a_audio, debug, &min_audio_packet_size);
10615          alreadysent |= codec;
10616       }
10617 
10618       /* Start by sending our preferred audio/video codecs */
10619       for (x = 0; x < 64; x++) {
10620          format_t codec;
10621 
10622          if (!(codec = ast_codec_pref_index(&p->prefs, x)))
10623             break;
10624 
10625          if (!(capability & codec))
10626             continue;
10627 
10628          if (alreadysent & codec)
10629             continue;
10630 
10631          add_codec_to_sdp(p, codec, &m_audio, &a_audio, debug, &min_audio_packet_size);
10632          alreadysent |= codec;
10633       }
10634 
10635       /* Now send any other common audio and video codecs, and non-codec formats: */
10636       for (x = 1ULL; x <= (needtext ? AST_FORMAT_TEXT_MASK : (needvideo ? AST_FORMAT_VIDEO_MASK : AST_FORMAT_AUDIO_MASK)); x <<= 1) {
10637          if (!(capability & x))  /* Codec not requested */
10638             continue;
10639 
10640          if (alreadysent & x) /* Already added to SDP */
10641             continue;
10642 
10643          if (x & AST_FORMAT_AUDIO_MASK)
10644             add_codec_to_sdp(p, x, &m_audio, &a_audio, debug, &min_audio_packet_size);
10645          else if (x & AST_FORMAT_VIDEO_MASK)
10646             add_vcodec_to_sdp(p, x, &m_video, &a_video, debug, &min_video_packet_size);
10647          else if (x & AST_FORMAT_TEXT_MASK)
10648             add_tcodec_to_sdp(p, x, &m_text, &a_text, debug, &min_text_packet_size);
10649       }
10650 
10651       /* Now add DTMF RFC2833 telephony-event as a codec */
10652       for (x = 1LL; x <= AST_RTP_MAX; x <<= 1) {
10653          if (!(p->jointnoncodeccapability & x))
10654             continue;
10655 
10656          add_noncodec_to_sdp(p, x, &m_audio, &a_audio, debug);
10657       }
10658 
10659       ast_debug(3, "-- Done with adding codecs to SDP\n");
10660 
10661       if (!p->owner || !ast_internal_timing_enabled(p->owner))
10662          ast_str_append(&a_audio, 0, "a=silenceSupp:off - - - -\r\n");
10663 
10664       if (min_audio_packet_size)
10665          ast_str_append(&a_audio, 0, "a=ptime:%d\r\n", min_audio_packet_size);
10666 
10667       /* XXX don't think you can have ptime for video */
10668       if (min_video_packet_size)
10669          ast_str_append(&a_video, 0, "a=ptime:%d\r\n", min_video_packet_size);
10670 
10671       /* XXX don't think you can have ptime for text */
10672       if (min_text_packet_size)
10673          ast_str_append(&a_text, 0, "a=ptime:%d\r\n", min_text_packet_size);
10674 
10675       if (m_audio->len - m_audio->used < 2 || m_video->len - m_video->used < 2 ||
10676           m_text->len - m_text->used < 2 || a_text->len - a_text->used < 2 ||
10677           a_audio->len - a_audio->used < 2 || a_video->len - a_video->used < 2)
10678          ast_log(LOG_WARNING, "SIP SDP may be truncated due to undersized buffer!!\n");
10679    }
10680 
10681    if (add_t38) {
10682       /* Our T.38 end is */
10683       ast_udptl_get_us(p->udptl, &udptladdr);
10684 
10685       /* Determine T.38 UDPTL destination */
10686       if (!ast_sockaddr_isnull(&p->udptlredirip)) {
10687          ast_sockaddr_copy(&udptldest, &p->udptlredirip);
10688       } else {
10689          ast_sockaddr_copy(&udptldest, &p->ourip);
10690          ast_sockaddr_set_port(&udptldest, ast_sockaddr_port(&udptladdr));
10691       }
10692 
10693       if (debug) {
10694          ast_debug(1, "T.38 UDPTL is at %s port %d\n", ast_sockaddr_stringify_addr(&p->ourip), ast_sockaddr_port(&udptladdr));
10695       }
10696 
10697       /* We break with the "recommendation" and send our IP, in order that our
10698          peer doesn't have to ast_gethostbyname() us */
10699 
10700       ast_str_append(&m_modem, 0, "m=image %d udptl t38\r\n", ast_sockaddr_port(&udptldest));
10701 
10702       if (!ast_sockaddr_cmp(&udptldest, &dest)) {
10703          ast_str_append(&m_modem, 0, "c=IN %s %s\r\n",
10704                (ast_sockaddr_is_ipv6(&dest) && !ast_sockaddr_is_ipv4_mapped(&dest)) ?
10705                "IP6" : "IP4", ast_sockaddr_stringify_addr(&udptldest));
10706       }
10707 
10708       ast_str_append(&a_modem, 0, "a=T38FaxVersion:%d\r\n", p->t38.our_parms.version);
10709       ast_str_append(&a_modem, 0, "a=T38MaxBitRate:%d\r\n", t38_get_rate(p->t38.our_parms.rate));
10710       if (p->t38.our_parms.fill_bit_removal) {
10711          ast_str_append(&a_modem, 0, "a=T38FaxFillBitRemoval\r\n");
10712       }
10713       if (p->t38.our_parms.transcoding_mmr) {
10714          ast_str_append(&a_modem, 0, "a=T38FaxTranscodingMMR\r\n");
10715       }
10716       if (p->t38.our_parms.transcoding_jbig) {
10717          ast_str_append(&a_modem, 0, "a=T38FaxTranscodingJBIG\r\n");
10718       }
10719       switch (p->t38.our_parms.rate_management) {
10720       case AST_T38_RATE_MANAGEMENT_TRANSFERRED_TCF:
10721          ast_str_append(&a_modem, 0, "a=T38FaxRateManagement:transferredTCF\r\n");
10722          break;
10723       case AST_T38_RATE_MANAGEMENT_LOCAL_TCF:
10724          ast_str_append(&a_modem, 0, "a=T38FaxRateManagement:localTCF\r\n");
10725          break;
10726       }
10727       ast_str_append(&a_modem, 0, "a=T38FaxMaxDatagram:%u\r\n", ast_udptl_get_local_max_datagram(p->udptl));
10728       switch (ast_udptl_get_error_correction_scheme(p->udptl)) {
10729       case UDPTL_ERROR_CORRECTION_NONE:
10730          break;
10731       case UDPTL_ERROR_CORRECTION_FEC:
10732          ast_str_append(&a_modem, 0, "a=T38FaxUdpEC:t38UDPFEC\r\n");
10733          break;
10734       case UDPTL_ERROR_CORRECTION_REDUNDANCY:
10735          ast_str_append(&a_modem, 0, "a=T38FaxUdpEC:t38UDPRedundancy\r\n");
10736          break;
10737       }
10738    }
10739 
10740    if (needaudio)
10741       ast_str_append(&m_audio, 0, "\r\n");
10742    if (needvideo)
10743       ast_str_append(&m_video, 0, "\r\n");
10744    if (needtext)
10745       ast_str_append(&m_text, 0, "\r\n");
10746 
10747    add_header(resp, "Content-Type", "application/sdp");
10748    add_content(resp, version);
10749    add_content(resp, owner);
10750    add_content(resp, subject);
10751    add_content(resp, connection);
10752    if (needvideo)    /* only if video response is appropriate */
10753       add_content(resp, bandwidth);
10754    add_content(resp, session_time);
10755    if (needaudio) {
10756       add_content(resp, m_audio->str);
10757       add_content(resp, a_audio->str);
10758       add_content(resp, hold);
10759       if (a_crypto) {
10760          add_content(resp, a_crypto);
10761       }
10762    } else if (p->offered_media[SDP_AUDIO].offered) {
10763       snprintf(dummy_answer, sizeof(dummy_answer), "m=audio 0 RTP/AVP %s\r\n", p->offered_media[SDP_AUDIO].codecs);
10764       add_content(resp, dummy_answer);
10765    }
10766    if (needvideo) { /* only if video response is appropriate */
10767       add_content(resp, m_video->str);
10768       add_content(resp, a_video->str);
10769       add_content(resp, hold);   /* Repeat hold for the video stream */
10770       if (v_a_crypto) {
10771          add_content(resp, v_a_crypto);
10772       }
10773    } else if (p->offered_media[SDP_VIDEO].offered) {
10774       snprintf(dummy_answer, sizeof(dummy_answer), "m=video 0 RTP/AVP %s\r\n", p->offered_media[SDP_VIDEO].codecs);
10775       add_content(resp, dummy_answer);
10776    }
10777    if (needtext) { /* only if text response is appropriate */
10778       add_content(resp, m_text->str);
10779       add_content(resp, a_text->str);
10780       add_content(resp, hold);   /* Repeat hold for the text stream */
10781       if (t_a_crypto) {
10782          add_content(resp, t_a_crypto);
10783       }
10784    } else if (p->offered_media[SDP_TEXT].offered) {
10785       snprintf(dummy_answer, sizeof(dummy_answer), "m=text 0 RTP/AVP %s\r\n", p->offered_media[SDP_TEXT].codecs);
10786       add_content(resp, dummy_answer);
10787    }
10788    if (add_t38) {
10789       add_content(resp, m_modem->str);
10790       add_content(resp, a_modem->str);
10791    } else if (p->offered_media[SDP_IMAGE].offered) {
10792       add_content(resp, "m=image 0 udptl t38\r\n");
10793    }
10794 
10795    /* Update lastrtprx when we send our SDP */
10796    p->lastrtprx = p->lastrtptx = time(NULL); /* XXX why both ? */
10797 
10798    ast_debug(3, "Done building SDP. Settling with this capability: %s\n", ast_getformatname_multiple(buf, SIPBUFSIZE, capability));
10799 
10800    return AST_SUCCESS;
10801 }
10802 
10803 /*! \brief Used for 200 OK and 183 early media */
10804 static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans)
10805 {
10806    struct sip_request resp;
10807    int seqno;
10808    
10809    if (sscanf(get_header(req, "CSeq"), "%30d ", &seqno) != 1) {
10810       ast_log(LOG_WARNING, "Unable to get seqno from '%s'\n", get_header(req, "CSeq"));
10811       return -1;
10812    }
10813    respprep(&resp, p, msg, req);
10814    if (p->udptl) {
10815       add_sdp(&resp, p, 0, 0, 1);
10816    } else
10817       ast_log(LOG_ERROR, "Can't add SDP to response, since we have no UDPTL session allocated. Call-ID %s\n", p->callid);
10818    if (retrans && !p->pendinginvite)
10819       p->pendinginvite = seqno;     /* Buggy clients sends ACK on RINGING too */
10820    return send_response(p, &resp, retrans, seqno);
10821 }
10822 
10823 /*! \brief copy SIP request (mostly used to save request for responses) */
10824 static void copy_request(struct sip_request *dst, const struct sip_request *src)
10825 {
10826    /* XXX this function can encounter memory allocation errors, perhaps it
10827     * should return a value */
10828 
10829    struct ast_str *duplicate = dst->data;
10830    struct ast_str *duplicate_content = dst->content;
10831 
10832    /* copy the entire request then restore the original data and content
10833     * members from the dst request */
10834    memcpy(dst, src, sizeof(*dst));
10835    dst->data = duplicate;
10836    dst->content = duplicate_content;
10837 
10838    /* copy the data into the dst request */
10839    if (!dst->data && !(dst->data = ast_str_create(ast_str_strlen(src->data) + 1)))
10840       return;
10841    ast_str_copy_string(&dst->data, src->data);
10842 
10843    /* copy the content into the dst request (if it exists) */
10844    if (src->content) {
10845       if (!dst->content && !(dst->content = ast_str_create(ast_str_strlen(src->content) + 1)))
10846          return;
10847       ast_str_copy_string(&dst->content, src->content);
10848    }
10849 }
10850 
10851 static void add_cc_call_info_to_response(struct sip_pvt *p, struct sip_request *resp)
10852 {
10853    char uri[SIPBUFSIZE];
10854    struct ast_str *header = ast_str_alloca(SIPBUFSIZE);
10855    struct ast_cc_agent *agent = find_sip_cc_agent_by_original_callid(p);
10856    struct sip_cc_agent_pvt *agent_pvt;
10857 
10858    if (!agent) {
10859       /* Um, what? How could the SIP_OFFER_CC flag be set but there not be an
10860        * agent? Oh well, we'll just warn and return without adding the header.
10861        */
10862       ast_log(LOG_WARNING, "Can't find SIP CC agent for call '%s' even though OFFER_CC flag was set?\n", p->callid);
10863       return;
10864    }
10865 
10866    agent_pvt = agent->private_data;
10867 
10868    if (!ast_strlen_zero(agent_pvt->subscribe_uri)) {
10869       ast_copy_string(uri, agent_pvt->subscribe_uri, sizeof(uri));
10870    } else {
10871       generate_uri(p, uri, sizeof(uri));
10872       ast_copy_string(agent_pvt->subscribe_uri, uri, sizeof(agent_pvt->subscribe_uri));
10873    }
10874    /* XXX Hardcode "NR" as the m reason for now. This should perhaps be changed
10875     * to be more accurate. This parameter has no bearing on the actual operation
10876     * of the feature; it's just there for informational purposes.
10877     */
10878    ast_str_set(&header, 0, "<%s>;purpose=call-completion;m=%s", uri, "NR");
10879    add_header(resp, "Call-Info", ast_str_buffer(header));
10880    ao2_ref(agent, -1);
10881 }
10882 
10883 /*! \brief Used for 200 OK and 183 early media
10884    \return Will return XMIT_ERROR for network errors.
10885 */
10886 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)
10887 {
10888    struct sip_request resp;
10889    int seqno;
10890    if (sscanf(get_header(req, "CSeq"), "%30d ", &seqno) != 1) {
10891       ast_log(LOG_WARNING, "Unable to get seqno from '%s'\n", get_header(req, "CSeq"));
10892       return -1;
10893    }
10894    respprep(&resp, p, msg, req);
10895    if (rpid == TRUE) {
10896       add_rpid(&resp, p);
10897    }
10898    if (ast_test_flag(&p->flags[0], SIP_OFFER_CC)) {
10899       add_cc_call_info_to_response(p, &resp);
10900    }
10901    if (p->rtp) {
10902       if (!p->autoframing && !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
10903          ast_debug(1, "Setting framing from config on incoming call\n");
10904          ast_rtp_codecs_packetization_set(ast_rtp_instance_get_codecs(p->rtp), p->rtp, &p->prefs);
10905       }
10906       ast_rtp_instance_activate(p->rtp);
10907       try_suggested_sip_codec(p);
10908       if (p->t38.state == T38_ENABLED) {
10909          add_sdp(&resp, p, oldsdp, TRUE, TRUE);
10910       } else {
10911          add_sdp(&resp, p, oldsdp, TRUE, FALSE);
10912       }
10913    } else
10914       ast_log(LOG_ERROR, "Can't add SDP to response, since we have no RTP session allocated. Call-ID %s\n", p->callid);
10915    if (reliable && !p->pendinginvite)
10916       p->pendinginvite = seqno;     /* Buggy clients sends ACK on RINGING too */
10917    return send_response(p, &resp, reliable, seqno);
10918 }
10919 
10920 /*! \brief Parse first line of incoming SIP request */
10921 static int determine_firstline_parts(struct sip_request *req)
10922 {
10923    char *e = ast_skip_blanks(req->data->str);   /* there shouldn't be any */
10924    char *local_rlPart1;
10925 
10926    if (!*e)
10927       return -1;
10928    req->rlPart1 = e - req->data->str;  /* method or protocol */
10929    local_rlPart1 = e;
10930    e = ast_skip_nonblanks(e);
10931    if (*e)
10932       *e++ = '\0';
10933    /* Get URI or status code */
10934    e = ast_skip_blanks(e);
10935    if ( !*e )
10936       return -1;
10937    ast_trim_blanks(e);
10938 
10939    if (!strcasecmp(local_rlPart1, "SIP/2.0") ) { /* We have a response */
10940       if (strlen(e) < 3)   /* status code is 3 digits */
10941          return -1;
10942       req->rlPart2 = e - req->data->str;
10943    } else { /* We have a request */
10944       if ( *e == '<' ) { /* XXX the spec says it must not be in <> ! */
10945          ast_debug(3, "Oops. Bogus uri in <> %s\n", e);
10946          e++;
10947          if (!*e)
10948             return -1;
10949       }
10950       req->rlPart2 = e - req->data->str;  /* URI */
10951       e = ast_skip_nonblanks(e);
10952       if (*e)
10953          *e++ = '\0';
10954       e = ast_skip_blanks(e);
10955       if (strcasecmp(e, "SIP/2.0") ) {
10956          ast_debug(3, "Skipping packet - Bad request protocol %s\n", e);
10957          return -1;
10958       }
10959    }
10960    return 1;
10961 }
10962 
10963 /*! \brief Transmit reinvite with SDP
10964 \note    A re-invite is basically a new INVITE with the same CALL-ID and TAG as the
10965    INVITE that opened the SIP dialogue
10966    We reinvite so that the audio stream (RTP) go directly between
10967    the SIP UAs. SIP Signalling stays with * in the path.
10968    
10969    If t38version is TRUE, we send T38 SDP for re-invite from audio/video to
10970    T38 UDPTL transmission on the channel
10971 
10972     If oldsdp is TRUE then the SDP version number is not incremented. This
10973     is needed for Session-Timers so we can send a re-invite to refresh the
10974     SIP session without modifying the media session.
10975 */
10976 static int transmit_reinvite_with_sdp(struct sip_pvt *p, int t38version, int oldsdp)
10977 {
10978    struct sip_request req;
10979    
10980    reqprep(&req, p, ast_test_flag(&p->flags[0], SIP_REINVITE_UPDATE) ?  SIP_UPDATE : SIP_INVITE, 0, 1);
10981 
10982    add_header(&req, "Allow", ALLOWED_METHODS);
10983    add_supported_header(p, &req);
10984    if (sipdebug) {
10985       if (oldsdp == TRUE)
10986          add_header(&req, "X-asterisk-Info", "SIP re-invite (Session-Timers)");
10987       else
10988          add_header(&req, "X-asterisk-Info", "SIP re-invite (External RTP bridge)");
10989    }
10990 
10991    if (ast_test_flag(&p->flags[0], SIP_SENDRPID))
10992       add_rpid(&req, p);
10993 
10994    if (p->do_history) {
10995       append_history(p, "ReInv", "Re-invite sent");
10996    }
10997    memset(p->offered_media, 0, sizeof(p->offered_media));
10998 
10999    try_suggested_sip_codec(p);
11000    if (t38version) {
11001       add_sdp(&req, p, oldsdp, FALSE, TRUE);
11002    } else {
11003       add_sdp(&req, p, oldsdp, TRUE, FALSE);
11004    }
11005 
11006    /* Use this as the basis */
11007    initialize_initreq(p, &req);
11008    p->lastinvite = p->ocseq;
11009    ast_set_flag(&p->flags[0], SIP_OUTGOING);       /* Change direction of this dialog */
11010 
11011    return send_request(p, &req, XMIT_CRITICAL, p->ocseq);
11012 }
11013 
11014 /* \brief Remove URI parameters at end of URI, not in username part though */
11015 static char *remove_uri_parameters(char *uri)
11016 {
11017    char *atsign;
11018    atsign = strchr(uri, '@'); /* First, locate the at sign */
11019    if (!atsign) {
11020       atsign = uri;  /* Ok hostname only, let's stick with the rest */
11021    }
11022    atsign = strchr(atsign, ';'); /* Locate semi colon */
11023    if (atsign)
11024       *atsign = '\0';   /* Kill at the semi colon */
11025    return uri;
11026 }
11027 
11028 /*! \brief Check Contact: URI of SIP message */
11029 static void extract_uri(struct sip_pvt *p, struct sip_request *req)
11030 {
11031    char stripped[SIPBUFSIZE];
11032    char *c;
11033 
11034    ast_copy_string(stripped, get_header(req, "Contact"), sizeof(stripped));
11035    c = get_in_brackets(stripped);
11036    /* Cut the URI at the at sign after the @, not in the username part */
11037    c = remove_uri_parameters(c);
11038    if (!ast_strlen_zero(c)) {
11039       ast_string_field_set(p, uri, c);
11040    }
11041 
11042 }
11043 
11044 /*! \brief Build contact header - the contact header we send out */
11045 static void build_contact(struct sip_pvt *p)
11046 {
11047    if (p->socket.type == SIP_TRANSPORT_UDP) {
11048       ast_string_field_build(p, our_contact, "<sip:%s%s%s>", p->exten,
11049          ast_strlen_zero(p->exten) ? "" : "@", ast_sockaddr_stringify(&p->ourip));
11050    } else {
11051       ast_string_field_build(p, our_contact, "<sip:%s%s%s;transport=%s>", p->exten,
11052          ast_strlen_zero(p->exten) ? "" : "@", ast_sockaddr_stringify(&p->ourip),
11053          get_transport(p->socket.type));
11054    }
11055 }
11056 
11057 /*! \brief Initiate new SIP request to peer/user */
11058 static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, const char * const explicit_uri)
11059 {
11060    struct ast_str *invite = ast_str_alloca(256);
11061    char from[256];
11062    char to[256];
11063    char tmp_n[SIPBUFSIZE/2];  /* build a local copy of 'n' if needed */
11064    char tmp_l[SIPBUFSIZE/2];  /* build a local copy of 'l' if needed */
11065    const char *l = NULL;   /* XXX what is this, exactly ? */
11066    const char *n = NULL;   /* XXX what is this, exactly ? */
11067    const char *d = NULL;   /* domain in from header */
11068    const char *urioptions = "";
11069    int ourport;
11070 
11071    if (ast_test_flag(&p->flags[0], SIP_USEREQPHONE)) {
11072       const char *s = p->username;  /* being a string field, cannot be NULL */
11073 
11074       /* Test p->username against allowed characters in AST_DIGIT_ANY
11075          If it matches the allowed characters list, then sipuser = ";user=phone"
11076          If not, then sipuser = ""
11077       */
11078       /* + is allowed in first position in a tel: uri */
11079       if (*s == '+')
11080          s++;
11081       for (; *s; s++) {
11082          if (!strchr(AST_DIGIT_ANYNUM, *s) )
11083             break;
11084       }
11085       /* If we have only digits, add ;user=phone to the uri */
11086       if (!*s)
11087          urioptions = ";user=phone";
11088    }
11089 
11090 
11091    snprintf(p->lastmsg, sizeof(p->lastmsg), "Init: %s", sip_methods[sipmethod].text);
11092 
11093    d = S_OR(p->fromdomain, ast_sockaddr_stringify_host(&p->ourip));
11094    if (p->owner) {
11095       if ((ast_party_id_presentation(&p->owner->connected.id) & AST_PRES_RESTRICTION) == AST_PRES_ALLOWED) {
11096          l = p->owner->connected.id.number.valid ? p->owner->connected.id.number.str : NULL;
11097          n = p->owner->connected.id.name.valid ? p->owner->connected.id.name.str : NULL;
11098       } else if (!ast_test_flag(&p->flags[0], SIP_SENDRPID)) {
11099          /* if we are not sending RPID and user wants his callerid restricted */    
11100          l = CALLERID_UNKNOWN;
11101          n = l;
11102          d = FROMDOMAIN_INVALID;
11103       }
11104    }
11105 
11106    /* Hey, it's a NOTIFY! See if they've configured a mwi_from.
11107     * XXX Right now, this logic works because the only place that mwi_from
11108     * is set on the sip_pvt is in sip_send_mwi_to_peer. If things changed, then
11109     * we might end up putting the mwi_from setting into other types of NOTIFY
11110     * messages as well.
11111     */
11112    if (sipmethod == SIP_NOTIFY && !ast_strlen_zero(p->mwi_from)) {
11113       l = p->mwi_from;
11114    }
11115 
11116    if (ast_strlen_zero(l))
11117       l = default_callerid;
11118    if (ast_strlen_zero(n))
11119       n = l;
11120    /* Allow user to be overridden */
11121    if (!ast_strlen_zero(p->fromuser))
11122       l = p->fromuser;
11123    else /* Save for any further attempts */
11124       ast_string_field_set(p, fromuser, l);
11125 
11126    /* Allow user to be overridden */
11127    if (!ast_strlen_zero(p->fromname))
11128       n = p->fromname;
11129    else /* Save for any further attempts */
11130       ast_string_field_set(p, fromname, n);
11131 
11132    if (sip_cfg.pedanticsipchecking) {
11133       ast_uri_encode(n, tmp_n, sizeof(tmp_n), 0);
11134       n = tmp_n;
11135       ast_uri_encode(l, tmp_l, sizeof(tmp_l), 0);
11136       l = tmp_l;
11137    }
11138 
11139    ourport = (p->fromdomainport) ? p->fromdomainport : ast_sockaddr_port(&p->ourip);
11140    if (!sip_standard_port(p->socket.type, ourport)) {
11141       snprintf(from, sizeof(from), "\"%s\" <sip:%s@%s:%d>;tag=%s", n, l, d, ourport, p->tag);
11142    } else {
11143       snprintf(from, sizeof(from), "\"%s\" <sip:%s@%s>;tag=%s", n, l, d, p->tag);
11144    }
11145 
11146    if (!ast_strlen_zero(explicit_uri)) {
11147       ast_str_set(&invite, 0, "%s", explicit_uri);
11148    } else {
11149       /* If we're calling a registered SIP peer, use the fullcontact to dial to the peer */
11150       if (!ast_strlen_zero(p->fullcontact)) {
11151          /* If we have full contact, trust it */
11152          ast_str_append(&invite, 0, "%s", p->fullcontact);
11153       } else {
11154          /* Otherwise, use the username while waiting for registration */
11155          ast_str_append(&invite, 0, "sip:");
11156          if (!ast_strlen_zero(p->username)) {
11157             n = p->username;
11158             if (sip_cfg.pedanticsipchecking) {
11159                ast_uri_encode(n, tmp_n, sizeof(tmp_n), 0);
11160                n = tmp_n;
11161             }
11162             ast_str_append(&invite, 0, "%s@", n);
11163          }
11164          ast_str_append(&invite, 0, "%s", p->tohost);
11165          if (p->portinuri) {
11166             ast_str_append(&invite, 0, ":%d", ast_sockaddr_port(&p->sa));
11167          }
11168          ast_str_append(&invite, 0, "%s", urioptions);
11169       }
11170    }
11171 
11172    /* If custom URI options have been provided, append them */
11173    if (p->options && !ast_strlen_zero(p->options->uri_options))
11174       ast_str_append(&invite, 0, ";%s", p->options->uri_options);
11175    
11176    /* This is the request URI, which is the next hop of the call
11177       which may or may not be the destination of the call
11178    */
11179    ast_string_field_set(p, uri, invite->str);
11180 
11181    if (!ast_strlen_zero(p->todnid)) {
11182       /*! \todo Need to add back the VXML URL here at some point, possibly use build_string for all this junk */
11183       if (!strchr(p->todnid, '@')) {
11184          /* We have no domain in the dnid */
11185          snprintf(to, sizeof(to), "<sip:%s@%s>%s%s", p->todnid, p->tohost, ast_strlen_zero(p->theirtag) ? "" : ";tag=", p->theirtag);
11186       } else {
11187          snprintf(to, sizeof(to), "<sip:%s>%s%s", p->todnid, ast_strlen_zero(p->theirtag) ? "" : ";tag=", p->theirtag);
11188       }
11189    } else {
11190       if (sipmethod == SIP_NOTIFY && !ast_strlen_zero(p->theirtag)) {
11191          /* If this is a NOTIFY, use the From: tag in the subscribe (RFC 3265) */
11192          snprintf(to, sizeof(to), "<%s%s>;tag=%s", (strncasecmp(p->uri, "sip:", 4) ? "sip:" : ""), p->uri, p->theirtag);
11193       } else if (p->options && p->options->vxml_url) {
11194          /* If there is a VXML URL append it to the SIP URL */
11195          snprintf(to, sizeof(to), "<%s>;%s", p->uri, p->options->vxml_url);
11196       } else {
11197          snprintf(to, sizeof(to), "<%s>", p->uri);
11198       }
11199    }
11200 
11201    init_req(req, sipmethod, p->uri);
11202    /* now tmp_n is available so reuse it to build the CSeq */
11203    snprintf(tmp_n, sizeof(tmp_n), "%d %s", ++p->ocseq, sip_methods[sipmethod].text);
11204 
11205    add_header(req, "Via", p->via);
11206    add_header_max_forwards(p, req);
11207    /* This will be a no-op most of the time. However, under certain circumstances,
11208     * NOTIFY messages will use this function for preparing the request and should
11209     * have Route headers present.
11210     */
11211    add_route(req, p->route);
11212 
11213    add_header(req, "From", from);
11214    add_header(req, "To", to);
11215    ast_string_field_set(p, exten, l);
11216    build_contact(p);
11217    add_header(req, "Contact", p->our_contact);
11218    add_header(req, "Call-ID", p->callid);
11219    add_header(req, "CSeq", tmp_n);
11220    if (!ast_strlen_zero(global_useragent)) {
11221       add_header(req, "User-Agent", global_useragent);
11222    }
11223 }
11224 
11225 /*! \brief Add "Diversion" header to outgoing message
11226  *
11227  * We need to add a Diversion header if the owner channel of
11228  * this dialog has redirecting information associated with it.
11229  *
11230  * \param req The request/response to which we will add the header
11231  * \param pvt The sip_pvt which represents the call-leg
11232  */
11233 static void add_diversion_header(struct sip_request *req, struct sip_pvt *pvt)
11234 {
11235    const char *diverting_number;
11236    const char *diverting_name;
11237    const char *reason;
11238    char header_text[256];
11239 
11240    if (!pvt->owner) {
11241       return;
11242    }
11243 
11244    diverting_number = pvt->owner->redirecting.from.number.str;
11245    if (!pvt->owner->redirecting.from.number.valid
11246       || ast_strlen_zero(diverting_number)) {
11247       return;
11248    }
11249 
11250    reason = sip_reason_code_to_str(pvt->owner->redirecting.reason);
11251 
11252    /* We at least have a number to place in the Diversion header, which is enough */
11253    diverting_name = pvt->owner->redirecting.from.name.str;
11254    if (!pvt->owner->redirecting.from.name.valid
11255       || ast_strlen_zero(diverting_name)) {
11256       snprintf(header_text, sizeof(header_text), "<sip:%s@%s>;reason=%s", diverting_number,
11257             ast_sockaddr_stringify_host(&pvt->ourip), reason);
11258    } else {
11259       snprintf(header_text, sizeof(header_text), "\"%s\" <sip:%s@%s>;reason=%s",
11260             diverting_name, diverting_number,
11261             ast_sockaddr_stringify_host(&pvt->ourip), reason);
11262    }
11263 
11264    add_header(req, "Diversion", header_text);
11265 }
11266 
11267 static int transmit_publish(struct sip_epa_entry *epa_entry, enum sip_publish_type publish_type, const char * const explicit_uri)
11268 {
11269    struct sip_pvt *pvt;
11270    int expires;
11271 
11272    epa_entry->publish_type = publish_type;
11273 
11274    if (!(pvt = sip_alloc(NULL, NULL, 0, SIP_PUBLISH, NULL))) {
11275       return -1;
11276    }
11277 
11278    sip_pvt_lock(pvt);
11279 
11280    if (create_addr(pvt, epa_entry->destination, NULL, TRUE, NULL)) {
11281       dialog_unlink_all(pvt, TRUE, TRUE);
11282       dialog_unref(pvt, "create_addr failed in transmit_publish. Unref dialog");
11283    }
11284    ast_sip_ouraddrfor(&pvt->sa, &pvt->ourip, pvt);
11285    ast_set_flag(&pvt->flags[0], SIP_OUTGOING);
11286    expires = (publish_type == SIP_PUBLISH_REMOVE) ? 0 : DEFAULT_PUBLISH_EXPIRES;
11287    pvt->expiry = expires;
11288 
11289    /* Bump refcount for sip_pvt's reference */
11290    ao2_ref(epa_entry, +1);
11291    pvt->epa_entry = epa_entry;
11292 
11293    transmit_invite(pvt, SIP_PUBLISH, FALSE, 2, explicit_uri);
11294    sip_pvt_unlock(pvt);
11295    sip_scheddestroy(pvt, DEFAULT_TRANS_TIMEOUT);
11296    dialog_unref(pvt, "Done with the sip_pvt allocated for transmitting PUBLISH");
11297    return 0;
11298 }
11299 
11300 /*! 
11301  * \brief Build REFER/INVITE/OPTIONS/SUBSCRIBE message and transmit it
11302  * \param p sip_pvt structure
11303  * \param sipmethod
11304  * \param sdp unknown
11305  * \param init 0 = Prepare request within dialog, 1= prepare request, new branch,
11306  *  2= prepare new request and new dialog. do_proxy_auth calls this with init!=2
11307  * \param explicit_uri
11308 */
11309 static int transmit_invite(struct sip_pvt *p, int sipmethod, int sdp, int init, const char * const explicit_uri)
11310 {
11311    struct sip_request req;
11312    struct ast_variable *var;
11313    
11314    req.method = sipmethod;
11315    if (init) {/* Bump branch even on initial requests */
11316       p->branch ^= ast_random();
11317       p->invite_branch = p->branch;
11318       build_via(p);
11319    }
11320    if (init > 1) {
11321       initreqprep(&req, p, sipmethod, explicit_uri);
11322    } else {
11323       /* If init=1, we should not generate a new branch. If it's 0, we need a new branch. */
11324       reqprep(&req, p, sipmethod, 0, init ? 0 : 1);
11325    }
11326       
11327    if (p->options && p->options->auth) {
11328       add_header(&req, p->options->authheader, p->options->auth);
11329    }
11330    append_date(&req);
11331    if (sipmethod == SIP_REFER) { /* Call transfer */
11332       if (p->refer) {
11333          char buf[SIPBUFSIZE];
11334          if (!ast_strlen_zero(p->refer->refer_to)) {
11335             add_header(&req, "Refer-To", p->refer->refer_to);
11336          }
11337          if (!ast_strlen_zero(p->refer->referred_by)) {
11338             snprintf(buf, sizeof(buf), "%s <%s>", p->refer->referred_by_name, p->refer->referred_by);
11339             add_header(&req, "Referred-By", buf);
11340          }
11341       }
11342    } else if (sipmethod == SIP_SUBSCRIBE) {
11343       char buf[SIPBUFSIZE];
11344       if (p->subscribed == MWI_NOTIFICATION) {
11345          add_header(&req, "Event", "message-summary");
11346          add_header(&req, "Accept", "application/simple-message-summary");
11347       } else if (p->subscribed == CALL_COMPLETION) {
11348          add_header(&req, "Event", "call-completion");
11349          add_header(&req, "Accept", "application/call-completion");
11350       }
11351       snprintf(buf, sizeof(buf), "%d", p->expiry);
11352       add_header(&req, "Expires", buf);
11353    }
11354 
11355    /* This new INVITE is part of an attended transfer. Make sure that the
11356    other end knows and replace the current call with this new call */
11357    if (p->options && !ast_strlen_zero(p->options->replaces)) {
11358       add_header(&req, "Replaces", p->options->replaces);
11359       add_header(&req, "Require", "replaces");
11360    }
11361 
11362    /* Add Session-Timers related headers */
11363    if (st_get_mode(p) == SESSION_TIMER_MODE_ORIGINATE) {
11364       char i2astr[10];
11365 
11366       if (!p->stimer->st_interval) {
11367          p->stimer->st_interval = st_get_se(p, TRUE);
11368       }
11369 
11370       p->stimer->st_active = TRUE;
11371       
11372       snprintf(i2astr, sizeof(i2astr), "%d", p->stimer->st_interval);
11373       add_header(&req, "Session-Expires", i2astr);
11374       snprintf(i2astr, sizeof(i2astr), "%d", st_get_se(p, FALSE));
11375       add_header(&req, "Min-SE", i2astr);
11376    }
11377 
11378    add_header(&req, "Allow", ALLOWED_METHODS);
11379    add_supported_header(p, &req);
11380 
11381    if (p->options && p->options->addsipheaders && p->owner) {
11382       struct ast_channel *chan = p->owner; /* The owner channel */
11383       struct varshead *headp;
11384    
11385       ast_channel_lock(chan);
11386 
11387       headp = &chan->varshead;
11388 
11389       if (!headp) {
11390          ast_log(LOG_WARNING, "No Headp for the channel...ooops!\n");
11391       } else {
11392          const struct ast_var_t *current;
11393          AST_LIST_TRAVERSE(headp, current, entries) {
11394             /* SIPADDHEADER: Add SIP header to outgoing call */
11395             if (!strncasecmp(ast_var_name(current), "SIPADDHEADER", strlen("SIPADDHEADER"))) {
11396                char *content, *end;
11397                const char *header = ast_var_value(current);
11398                char *headdup = ast_strdupa(header);
11399 
11400                /* Strip of the starting " (if it's there) */
11401                if (*headdup == '"') {
11402                   headdup++;
11403                }
11404                if ((content = strchr(headdup, ':'))) {
11405                   *content++ = '\0';
11406                   content = ast_skip_blanks(content); /* Skip white space */
11407                   /* Strip the ending " (if it's there) */
11408                   end = content + strlen(content) -1; 
11409                   if (*end == '"') {
11410                      *end = '\0';
11411                   }
11412                
11413                   add_header(&req, headdup, content);
11414                   if (sipdebug) {
11415                      ast_debug(1, "Adding SIP Header \"%s\" with content :%s: \n", headdup, content);
11416                   }
11417                }
11418             }
11419          }
11420       }
11421 
11422       ast_channel_unlock(chan);
11423    }
11424    if ((sipmethod == SIP_INVITE || sipmethod == SIP_UPDATE) && ast_test_flag(&p->flags[0], SIP_SENDRPID))
11425       add_rpid(&req, p);
11426    if (sipmethod == SIP_INVITE) {
11427       add_diversion_header(&req, p);
11428    }
11429    if (sdp) {
11430       memset(p->offered_media, 0, sizeof(p->offered_media));
11431       if (p->udptl && p->t38.state == T38_LOCAL_REINVITE) {
11432          ast_debug(1, "T38 is in state %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
11433          add_sdp(&req, p, FALSE, FALSE, TRUE);
11434       } else if (p->rtp) {
11435          try_suggested_sip_codec(p);
11436          add_sdp(&req, p, FALSE, TRUE, FALSE);
11437       }
11438    } else if (p->notify) {
11439       for (var = p->notify->headers; var; var = var->next) {
11440          add_header(&req, var->name, var->value);
11441       }
11442       if (ast_str_strlen(p->notify->content)) {
11443          add_content(&req, ast_str_buffer(p->notify->content));
11444       }
11445    } else if (sipmethod == SIP_PUBLISH) {
11446       char expires[SIPBUFSIZE];
11447 
11448       switch (p->epa_entry->static_data->event) {
11449       case CALL_COMPLETION:
11450          snprintf(expires, sizeof(expires), "%d", p->expiry);
11451          add_header(&req, "Event", "call-completion");
11452          add_header(&req, "Expires", expires);
11453          if (p->epa_entry->publish_type != SIP_PUBLISH_INITIAL) {
11454             add_header(&req, "SIP-If-Match", p->epa_entry->entity_tag);
11455          }
11456 
11457          if (!ast_strlen_zero(p->epa_entry->body)) {
11458             add_header(&req, "Content-Type", "application/pidf+xml");
11459             add_content(&req, p->epa_entry->body);
11460          }
11461       default:
11462          break;
11463       }
11464    }
11465 
11466    if (!p->initreq.headers || init > 2) {
11467       initialize_initreq(p, &req);
11468    }
11469    if (sipmethod == SIP_INVITE || sipmethod == SIP_SUBSCRIBE) {
11470       p->lastinvite = p->ocseq;
11471    }
11472    return send_request(p, &req, init ? XMIT_CRITICAL : XMIT_RELIABLE, p->ocseq);
11473 }
11474 
11475 /*! \brief Send a subscription or resubscription for MWI */
11476 static int sip_subscribe_mwi_do(const void *data)
11477 {
11478    struct sip_subscription_mwi *mwi = (struct sip_subscription_mwi*)data;
11479    
11480    if (!mwi) {
11481       return -1;
11482    }
11483    
11484    mwi->resub = -1;
11485    __sip_subscribe_mwi_do(mwi);
11486    ASTOBJ_UNREF(mwi, sip_subscribe_mwi_destroy);
11487    
11488    return 0;
11489 }
11490 
11491 /*! \brief Actually setup an MWI subscription or resubscribe */
11492 static int __sip_subscribe_mwi_do(struct sip_subscription_mwi *mwi)
11493 {
11494    /* If we have no DNS manager let's do a lookup */
11495    if (!mwi->dnsmgr) {
11496       char transport[MAXHOSTNAMELEN];
11497       snprintf(transport, sizeof(transport), "_%s._%s", get_srv_service(mwi->transport), get_srv_protocol(mwi->transport));
11498 
11499       mwi->us.ss.ss_family = get_address_family_filter(&bindaddr); /* Filter address family */
11500       ast_dnsmgr_lookup(mwi->hostname, &mwi->us, &mwi->dnsmgr, sip_cfg.srvlookup ? transport : NULL);
11501    }
11502 
11503    /* If we already have a subscription up simply send a resubscription */
11504    if (mwi->call) {
11505       transmit_invite(mwi->call, SIP_SUBSCRIBE, 0, 0, NULL);
11506       return 0;
11507    }
11508    
11509    /* Create a dialog that we will use for the subscription */
11510    if (!(mwi->call = sip_alloc(NULL, NULL, 0, SIP_SUBSCRIBE, NULL))) {
11511       return -1;
11512    }
11513 
11514    ref_proxy(mwi->call, obproxy_get(mwi->call, NULL));
11515 
11516    if (!ast_sockaddr_port(&mwi->us) && mwi->portno) {
11517       ast_sockaddr_set_port(&mwi->us, mwi->portno);
11518    }
11519    
11520    /* Setup the destination of our subscription */
11521    if (create_addr(mwi->call, mwi->hostname, &mwi->us, 0, NULL)) {
11522       dialog_unlink_all(mwi->call, TRUE, TRUE);
11523       mwi->call = dialog_unref(mwi->call, "unref dialog after unlink_all");
11524       return 0;
11525    }
11526 
11527    mwi->call->expiry = mwi_expiry;
11528    
11529    if (!mwi->dnsmgr && mwi->portno) {
11530       ast_sockaddr_set_port(&mwi->call->sa, mwi->portno);
11531       ast_sockaddr_set_port(&mwi->call->recv, mwi->portno);
11532    } else {
11533       mwi->portno = ast_sockaddr_port(&mwi->call->sa);
11534    }
11535    
11536    /* Set various other information */
11537    if (!ast_strlen_zero(mwi->authuser)) {
11538       ast_string_field_set(mwi->call, peername, mwi->authuser);
11539       ast_string_field_set(mwi->call, authname, mwi->authuser);
11540       ast_string_field_set(mwi->call, fromuser, mwi->authuser);
11541    } else {
11542       ast_string_field_set(mwi->call, peername, mwi->username);
11543       ast_string_field_set(mwi->call, authname, mwi->username);
11544       ast_string_field_set(mwi->call, fromuser, mwi->username);
11545    }
11546    ast_string_field_set(mwi->call, username, mwi->username);
11547    if (!ast_strlen_zero(mwi->secret)) {
11548       ast_string_field_set(mwi->call, peersecret, mwi->secret);
11549    }
11550    set_socket_transport(&mwi->call->socket, mwi->transport);
11551    mwi->call->socket.port = htons(mwi->portno);
11552    ast_sip_ouraddrfor(&mwi->call->sa, &mwi->call->ourip, mwi->call);
11553    build_contact(mwi->call);
11554    build_via(mwi->call);
11555    build_callid_pvt(mwi->call);
11556    ast_set_flag(&mwi->call->flags[0], SIP_OUTGOING);
11557    
11558    /* Associate the call with us */
11559    mwi->call->mwi = ASTOBJ_REF(mwi);
11560 
11561    mwi->call->subscribed = MWI_NOTIFICATION;
11562 
11563    /* Actually send the packet */
11564    transmit_invite(mwi->call, SIP_SUBSCRIBE, 0, 2, NULL);
11565 
11566    return 0;
11567 }
11568 
11569 /*! \brief Find the channel that is causing the RINGING update */
11570 static int find_calling_channel(void *obj, void *arg, void *data, int flags)
11571 {
11572    struct ast_channel *c = obj;
11573    struct sip_pvt *p = data;
11574    int res;
11575 
11576    ast_channel_lock(c);
11577 
11578    res = (c->pbx &&
11579          (!strcasecmp(c->macroexten, p->exten) || !strcasecmp(c->exten, p->exten)) &&
11580          (sip_cfg.notifycid == IGNORE_CONTEXT || !strcasecmp(c->context, p->context)));
11581 
11582    ast_channel_unlock(c);
11583 
11584    return res ? CMP_MATCH | CMP_STOP : 0;
11585 }
11586 
11587 /*! \brief Builds XML portion of NOTIFY messages for presence or dialog updates */
11588 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)
11589 {
11590    enum state { NOTIFY_OPEN, NOTIFY_INUSE, NOTIFY_CLOSED } local_state = NOTIFY_OPEN;
11591    const char *statestring = "terminated";
11592    const char *pidfstate = "--";
11593    const char *pidfnote= "Ready";
11594    char hint[AST_MAX_EXTENSION];
11595 
11596    switch (state) {
11597    case (AST_EXTENSION_RINGING | AST_EXTENSION_INUSE):
11598       statestring = (sip_cfg.notifyringing) ? "early" : "confirmed";
11599       local_state = NOTIFY_INUSE;
11600       pidfstate = "busy";
11601       pidfnote = "Ringing";
11602       break;
11603    case AST_EXTENSION_RINGING:
11604       statestring = "early";
11605       local_state = NOTIFY_INUSE;
11606       pidfstate = "busy";
11607       pidfnote = "Ringing";
11608       break;
11609    case AST_EXTENSION_INUSE:
11610       statestring = "confirmed";
11611       local_state = NOTIFY_INUSE;
11612       pidfstate = "busy";
11613       pidfnote = "On the phone";
11614       break;
11615    case AST_EXTENSION_BUSY:
11616       statestring = "confirmed";
11617       local_state = NOTIFY_CLOSED;
11618       pidfstate = "busy";
11619       pidfnote = "On the phone";
11620       break;
11621    case AST_EXTENSION_UNAVAILABLE:
11622       statestring = "terminated";
11623       local_state = NOTIFY_CLOSED;
11624       pidfstate = "away";
11625       pidfnote = "Unavailable";
11626       break;
11627    case AST_EXTENSION_ONHOLD:
11628       statestring = "confirmed";
11629       local_state = NOTIFY_CLOSED;
11630       pidfstate = "busy";
11631       pidfnote = "On hold";
11632       break;
11633    case AST_EXTENSION_NOT_INUSE:
11634    default:
11635       /* Default setting */
11636       break;
11637    }
11638 
11639    /* Check which device/devices we are watching  and if they are registered */
11640    if (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, context, exten)) {
11641       char *hint2 = hint, *individual_hint = NULL;
11642       int hint_count = 0, unavailable_count = 0;
11643 
11644       while ((individual_hint = strsep(&hint2, "&"))) {
11645          hint_count++;
11646 
11647          if (ast_device_state(individual_hint) == AST_DEVICE_UNAVAILABLE)
11648             unavailable_count++;
11649       }
11650 
11651       /* If none of the hinted devices are registered, we will
11652        * override notification and show no availability.
11653        */
11654       if (hint_count > 0 && hint_count == unavailable_count) {
11655          local_state = NOTIFY_CLOSED;
11656          pidfstate = "away";
11657          pidfnote = "Not online";
11658       }
11659    }
11660 
11661    switch (subscribed) {
11662    case XPIDF_XML:
11663    case CPIM_PIDF_XML:
11664       ast_str_append(tmp, 0,
11665          "<?xml version=\"1.0\"?>\n"
11666          "<!DOCTYPE presence PUBLIC \"-//IETF//DTD RFCxxxx XPIDF 1.0//EN\" \"xpidf.dtd\">\n"
11667          "<presence>\n");
11668       ast_str_append(tmp, 0, "<presentity uri=\"%s;method=SUBSCRIBE\" />\n", mfrom);
11669       ast_str_append(tmp, 0, "<atom id=\"%s\">\n", exten);
11670       ast_str_append(tmp, 0, "<address uri=\"%s;user=ip\" priority=\"0.800000\">\n", mto);
11671       ast_str_append(tmp, 0, "<status status=\"%s\" />\n", (local_state ==  NOTIFY_OPEN) ? "open" : (local_state == NOTIFY_INUSE) ? "inuse" : "closed");
11672       ast_str_append(tmp, 0, "<msnsubstatus substatus=\"%s\" />\n", (local_state == NOTIFY_OPEN) ? "online" : (local_state == NOTIFY_INUSE) ? "onthephone" : "offline");
11673       ast_str_append(tmp, 0, "</address>\n</atom>\n</presence>\n");
11674       break;
11675    case PIDF_XML: /* Eyebeam supports this format */
11676       ast_str_append(tmp, 0,
11677          "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n"
11678          "<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);
11679       ast_str_append(tmp, 0, "<pp:person><status>\n");
11680       if (pidfstate[0] != '-') {
11681          ast_str_append(tmp, 0, "<ep:activities><ep:%s/></ep:activities>\n", pidfstate);
11682       }
11683       ast_str_append(tmp, 0, "</status></pp:person>\n");
11684       ast_str_append(tmp, 0, "<note>%s</note>\n", pidfnote); /* Note */
11685       ast_str_append(tmp, 0, "<tuple id=\"%s\">\n", exten); /* Tuple start */
11686       ast_str_append(tmp, 0, "<contact priority=\"1\">%s</contact>\n", mto);
11687       if (pidfstate[0] == 'b') /* Busy? Still open ... */
11688          ast_str_append(tmp, 0, "<status><basic>open</basic></status>\n");
11689       else
11690          ast_str_append(tmp, 0, "<status><basic>%s</basic></status>\n", (local_state != NOTIFY_CLOSED) ? "open" : "closed");
11691       ast_str_append(tmp, 0, "</tuple>\n</presence>\n");
11692       break;
11693    case DIALOG_INFO_XML: /* SNOM subscribes in this format */
11694       ast_str_append(tmp, 0, "<?xml version=\"1.0\"?>");
11695       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);
11696       if ((state & AST_EXTENSION_RINGING) && sip_cfg.notifyringing) {
11697          const char *local_display = exten;
11698          char *local_target = ast_strdupa(mto);
11699 
11700          /* There are some limitations to how this works.  The primary one is that the
11701             callee must be dialing the same extension that is being monitored.  Simply dialing
11702             the hint'd device is not sufficient. */
11703          if (sip_cfg.notifycid) {
11704             struct ast_channel *caller;
11705 
11706             if ((caller = ast_channel_callback(find_calling_channel, NULL, p, 0))) {
11707                char *cid_num;
11708                int need;
11709 
11710                ast_channel_lock(caller);
11711                cid_num = S_COR(caller->caller.id.number.valid,
11712                   caller->caller.id.number.str, "");
11713                need = strlen(cid_num) + strlen(p->fromdomain) + sizeof("sip:@");
11714                local_target = alloca(need);
11715                snprintf(local_target, need, "sip:%s@%s", cid_num, p->fromdomain);
11716                local_display = ast_strdupa(S_COR(caller->caller.id.name.valid,
11717                   caller->caller.id.name.str, ""));
11718                ast_channel_unlock(caller);
11719                caller = ast_channel_unref(caller);
11720             }
11721 
11722             /* We create a fake call-id which the phone will send back in an INVITE
11723                Replaces header which we can grab and do some magic with. */
11724             if (sip_cfg.pedanticsipchecking) {
11725                ast_str_append(tmp, 0, "<dialog id=\"%s\" call-id=\"pickup-%s\" local-tag=\"%s\" remote-tag=\"%s\" direction=\"recipient\">\n",
11726                   exten, p->callid, p->theirtag, p->tag);
11727             } else {
11728                ast_str_append(tmp, 0, "<dialog id=\"%s\" call-id=\"pickup-%s\" direction=\"recipient\">\n",
11729                   exten, p->callid);
11730             }
11731             ast_str_append(tmp, 0,
11732                   "<remote>\n"
11733                   /* See the limitations of this above.  Luckily the phone seems to still be
11734                      happy when these values are not correct. */
11735                   "<identity display=\"%s\">%s</identity>\n"
11736                   "<target uri=\"%s\"/>\n"
11737                   "</remote>\n"
11738                   "<local>\n"
11739                   "<identity>%s</identity>\n"
11740                   "<target uri=\"%s\"/>\n"
11741                   "</local>\n",
11742                   local_display, local_target, local_target, mto, mto);
11743          } else {
11744             ast_str_append(tmp, 0, "<dialog id=\"%s\" direction=\"recipient\">\n", exten);
11745          }
11746 
11747       } else {
11748          ast_str_append(tmp, 0, "<dialog id=\"%s\">", exten);
11749       }
11750       ast_str_append(tmp, 0, "<state>%s</state>\n", statestring);
11751       if (state == AST_EXTENSION_ONHOLD) {
11752             ast_str_append(tmp, 0, "<local>\n<target uri=\"%s\">\n"
11753                                              "<param pname=\"+sip.rendering\" pvalue=\"no\"/>\n"
11754                                              "</target>\n</local>\n", mto);
11755       }
11756       ast_str_append(tmp, 0, "</dialog>\n</dialog-info>\n");
11757       break;
11758    case NONE:
11759    default:
11760       break;
11761    }
11762 }
11763 
11764 static int transmit_cc_notify(struct ast_cc_agent *agent, struct sip_pvt *subscription, enum sip_cc_notify_state state)
11765 {
11766    struct sip_request req;
11767    struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
11768    char uri[SIPBUFSIZE];
11769    char state_str[64];
11770 
11771    if (state < CC_QUEUED || state > CC_READY) {
11772       ast_log(LOG_WARNING, "Invalid state provided for transmit_cc_notify (%d)\n", state);
11773       return -1;
11774    }
11775 
11776    reqprep(&req, subscription, SIP_NOTIFY, 0, TRUE);
11777    snprintf(state_str, sizeof(state_str), "%s\r\n", sip_cc_notify_state_map[state].state_string);
11778    add_header(&req, "Event", "call-completion");
11779    add_header(&req, "Content-Type", "application/call-completion");
11780    if (state == CC_READY) {
11781       generate_uri(subscription, agent_pvt->notify_uri, sizeof(agent_pvt->notify_uri));
11782       snprintf(uri, sizeof(uri) - 1, "cc-URI: %s\r\n", agent_pvt->notify_uri);
11783    }
11784    add_content(&req, state_str);
11785    if (state == CC_READY) {
11786       add_content(&req, uri);
11787    }
11788    return send_request(subscription, &req, XMIT_RELIABLE, subscription->ocseq);
11789 }
11790 
11791 /*! \brief Used in the SUBSCRIBE notification subsystem (RFC3265) */
11792 static int transmit_state_notify(struct sip_pvt *p, int state, int full, int timeout)
11793 {
11794    struct ast_str *tmp = ast_str_alloca(4000);
11795    char from[256], to[256];
11796    char *c, *mfrom, *mto;
11797    struct sip_request req;
11798    const struct cfsubscription_types *subscriptiontype;
11799 
11800    memset(from, 0, sizeof(from));
11801    memset(to, 0, sizeof(to));
11802 
11803    subscriptiontype = find_subscription_type(p->subscribed);
11804 
11805    ast_copy_string(from, get_header(&p->initreq, "From"), sizeof(from));
11806    c = get_in_brackets(from);
11807    if (strncasecmp(c, "sip:", 4) && strncasecmp(c, "sips:", 5)) {
11808       ast_log(LOG_WARNING, "Huh?  Not a SIP header (%s)?\n", c);
11809       return -1;
11810    }
11811 
11812    mfrom = remove_uri_parameters(c);
11813 
11814    ast_copy_string(to, get_header(&p->initreq, "To"), sizeof(to));
11815    c = get_in_brackets(to);
11816    if (strncasecmp(c, "sip:", 4) && strncasecmp(c, "sips:", 5)) {
11817       ast_log(LOG_WARNING, "Huh?  Not a SIP header (%s)?\n", c);
11818       return -1;
11819    }
11820    mto = remove_uri_parameters(c);
11821 
11822    reqprep(&req, p, SIP_NOTIFY, 0, 1);
11823 
11824    switch(state) {
11825    case AST_EXTENSION_DEACTIVATED:
11826       if (timeout)
11827          add_header(&req, "Subscription-State", "terminated;reason=timeout");
11828       else {
11829          add_header(&req, "Subscription-State", "terminated;reason=probation");
11830          add_header(&req, "Retry-After", "60");
11831       }
11832       break;
11833    case AST_EXTENSION_REMOVED:
11834       add_header(&req, "Subscription-State", "terminated;reason=noresource");
11835       break;
11836    default:
11837       if (p->expiry)
11838          add_header(&req, "Subscription-State", "active");
11839       else  /* Expired */
11840          add_header(&req, "Subscription-State", "terminated;reason=timeout");
11841    }
11842 
11843    switch (p->subscribed) {
11844    case XPIDF_XML:
11845    case CPIM_PIDF_XML:
11846       add_header(&req, "Event", subscriptiontype->event);
11847       state_notify_build_xml(state, full, p->exten, p->context, &tmp, p, p->subscribed, mfrom, mto);
11848       add_header(&req, "Content-Type", subscriptiontype->mediatype);
11849       p->dialogver++;
11850       break;
11851    case PIDF_XML: /* Eyebeam supports this format */
11852       add_header(&req, "Event", subscriptiontype->event);
11853       state_notify_build_xml(state, full, p->exten, p->context, &tmp, p, p->subscribed, mfrom, mto);
11854       add_header(&req, "Content-Type", subscriptiontype->mediatype);
11855       p->dialogver++;
11856       break;
11857    case DIALOG_INFO_XML: /* SNOM subscribes in this format */
11858       add_header(&req, "Event", subscriptiontype->event);
11859       state_notify_build_xml(state, full, p->exten, p->context, &tmp, p, p->subscribed, mfrom, mto);
11860       add_header(&req, "Content-Type", subscriptiontype->mediatype);
11861       p->dialogver++;
11862       break;
11863    case NONE:
11864    default:
11865       break;
11866    }
11867 
11868    add_content(&req, tmp->str);
11869 
11870    p->pendinginvite = p->ocseq;  /* Remember that we have a pending NOTIFY in order not to confuse the NOTIFY subsystem */
11871 
11872    return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
11873 }
11874 
11875 /*! \brief Notify user of messages waiting in voicemail (RFC3842)
11876 \note - Notification only works for registered peers with mailbox= definitions
11877    in sip.conf
11878    - We use the SIP Event package message-summary
11879     MIME type defaults to  "application/simple-message-summary";
11880  */
11881 static int transmit_notify_with_mwi(struct sip_pvt *p, int newmsgs, int oldmsgs, const char *vmexten)
11882 {
11883    struct sip_request req;
11884    struct ast_str *out = ast_str_alloca(500);
11885    int ourport = (p->fromdomainport) ? p->fromdomainport : ast_sockaddr_port(&p->ourip);
11886    const char *domain = S_OR(p->fromdomain, ast_sockaddr_stringify_host(&p->ourip));
11887    const char *exten = S_OR(vmexten, default_vmexten);
11888 
11889    initreqprep(&req, p, SIP_NOTIFY, NULL);
11890    add_header(&req, "Event", "message-summary");
11891    add_header(&req, "Content-Type", default_notifymime);
11892    ast_str_append(&out, 0, "Messages-Waiting: %s\r\n", newmsgs ? "yes" : "no");
11893 
11894 
11895    if (!sip_standard_port(p->socket.type, ourport)) {
11896       if (p->socket.type == SIP_TRANSPORT_UDP) {
11897          ast_str_append(&out, 0, "Message-Account: sip:%s@%s:%d\r\n", exten, domain, ourport);
11898       } else {
11899          ast_str_append(&out, 0, "Message-Account: sip:%s@%s:%d;transport=%s\r\n", exten, domain, ourport, get_transport(p->socket.type));
11900       }
11901    } else {
11902       if (p->socket.type == SIP_TRANSPORT_UDP) {
11903          ast_str_append(&out, 0, "Message-Account: sip:%s@%s\r\n", exten, domain);
11904       } else {
11905          ast_str_append(&out, 0, "Message-Account: sip:%s@%s;transport=%s\r\n", exten, domain, get_transport(p->socket.type));
11906       }
11907    }
11908    /* Cisco has a bug in the SIP stack where it can't accept the
11909       (0/0) notification. This can temporarily be disabled in
11910       sip.conf with the "buggymwi" option */
11911    ast_str_append(&out, 0, "Voice-Message: %d/%d%s\r\n",
11912       newmsgs, oldmsgs, (ast_test_flag(&p->flags[1], SIP_PAGE2_BUGGY_MWI) ? "" : " (0/0)"));
11913 
11914    if (p->subscribed) {
11915       if (p->expiry) {
11916          add_header(&req, "Subscription-State", "active");
11917       } else { /* Expired */
11918          add_header(&req, "Subscription-State", "terminated;reason=timeout");
11919       }
11920    }
11921 
11922    add_content(&req, out->str);
11923 
11924    if (!p->initreq.headers) {
11925       initialize_initreq(p, &req);
11926    }
11927    return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
11928 }
11929 
11930 /*! \brief Notify a transferring party of the status of transfer (RFC3515) */
11931 static int transmit_notify_with_sipfrag(struct sip_pvt *p, int cseq, char *message, int terminate)
11932 {
11933    struct sip_request req;
11934    char tmp[SIPBUFSIZE/2];
11935    
11936    reqprep(&req, p, SIP_NOTIFY, 0, 1);
11937    snprintf(tmp, sizeof(tmp), "refer;id=%d", cseq);
11938    add_header(&req, "Event", tmp);
11939    add_header(&req, "Subscription-state", terminate ? "terminated;reason=noresource" : "active");
11940    add_header(&req, "Content-Type", "message/sipfrag;version=2.0");
11941    add_header(&req, "Allow", ALLOWED_METHODS);
11942    add_supported_header(p, &req);
11943 
11944    snprintf(tmp, sizeof(tmp), "SIP/2.0 %s\r\n", message);
11945    add_content(&req, tmp);
11946 
11947    if (!p->initreq.headers) {
11948       initialize_initreq(p, &req);
11949    }
11950 
11951    return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
11952 }
11953 
11954 static int manager_sipnotify(struct mansession *s, const struct message *m)
11955 {
11956    const char *channame = astman_get_header(m, "Channel");
11957    struct ast_variable *vars = astman_get_variables(m);
11958    struct sip_pvt *p;
11959    struct ast_variable *header, *var;
11960 
11961    if (ast_strlen_zero(channame)) {
11962       astman_send_error(s, m, "SIPNotify requires a channel name");
11963       return 0;
11964    }
11965 
11966    if (!strncasecmp(channame, "sip/", 4)) {
11967       channame += 4;
11968    }
11969 
11970    if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY, NULL))) {
11971       astman_send_error(s, m, "Unable to build sip pvt data for notify (memory/socket error)");
11972       return 0;
11973    }
11974 
11975    if (create_addr(p, channame, NULL, 0, NULL)) {
11976       /* Maybe they're not registered, etc. */
11977       dialog_unlink_all(p, TRUE, TRUE);
11978       dialog_unref(p, "unref dialog inside for loop" );
11979       /* sip_destroy(p); */
11980       astman_send_error(s, m, "Could not create address");
11981       return 0;
11982    }
11983 
11984    /* Notify is outgoing call */
11985    ast_set_flag(&p->flags[0], SIP_OUTGOING);
11986    sip_notify_allocate(p);
11987 
11988    p->notify->headers = header = ast_variable_new("Subscription-State", "terminated", "");
11989 
11990    for (var = vars; var; var = var->next) {
11991       if (!strcasecmp(var->name, "Content")) {
11992          if (ast_str_strlen(p->notify->content))
11993             ast_str_append(&p->notify->content, 0, "\r\n");
11994          ast_str_append(&p->notify->content, 0, "%s", var->value);
11995       } else if (!strcasecmp(var->name, "Content-Length")) {
11996          ast_log(LOG_WARNING, "it is not necessary to specify Content-Length, ignoring");
11997       } else {
11998          header->next = ast_variable_new(var->name, var->value, "");
11999          header = header->next;
12000       }
12001    }
12002 
12003    dialog_ref(p, "bump the count of p, which transmit_sip_request will decrement.");
12004    sip_scheddestroy(p, SIP_TRANS_TIMEOUT);
12005    transmit_invite(p, SIP_NOTIFY, 0, 2, NULL);
12006 
12007    astman_send_ack(s, m, "Notify Sent");
12008    ast_variables_destroy(vars);
12009    return 0;
12010 }
12011 
12012 /*! \brief Send a provisional response indicating that a call was redirected
12013  */
12014 static void update_redirecting(struct sip_pvt *p, const void *data, size_t datalen)
12015 {
12016    struct sip_request resp;
12017 
12018    if (p->owner->_state == AST_STATE_UP || ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
12019       return;
12020    }
12021 
12022    respprep(&resp, p, "181 Call is being forwarded", &p->initreq);
12023    add_diversion_header(&resp, p);
12024    send_response(p, &resp, XMIT_UNRELIABLE, 0);
12025 }
12026 
12027 /*! \brief Notify peer that the connected line has changed */
12028 static void update_connectedline(struct sip_pvt *p, const void *data, size_t datalen)
12029 {
12030 
12031    if (!ast_test_flag(&p->flags[0], SIP_SENDRPID)) {
12032       return;
12033    }
12034    if (!p->owner->connected.id.number.valid
12035       || ast_strlen_zero(p->owner->connected.id.number.str)) {
12036       return;
12037    }
12038 
12039    append_history(p, "ConnectedLine", "%s party is now %s <%s>",
12040       ast_test_flag(&p->flags[0], SIP_OUTGOING) ? "Calling" : "Called",
12041       S_COR(p->owner->connected.id.name.valid, p->owner->connected.id.name.str, ""),
12042       S_COR(p->owner->connected.id.number.valid, p->owner->connected.id.number.str, ""));
12043 
12044    if (p->owner->_state == AST_STATE_UP || ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
12045       struct sip_request req;
12046 
12047       if (p->invitestate == INV_CONFIRMED || p->invitestate == INV_TERMINATED) {
12048          reqprep(&req, p, ast_test_flag(&p->flags[0], SIP_REINVITE_UPDATE) ? SIP_UPDATE : SIP_INVITE, 0, 1);
12049 
12050          add_header(&req, "Allow", ALLOWED_METHODS);
12051          add_supported_header(p, &req);
12052          add_rpid(&req, p);
12053          add_sdp(&req, p, FALSE, TRUE, FALSE);
12054 
12055          initialize_initreq(p, &req);
12056          p->lastinvite = p->ocseq;
12057          ast_set_flag(&p->flags[0], SIP_OUTGOING);
12058          p->invitestate = INV_CALLING;
12059          send_request(p, &req, XMIT_CRITICAL, p->ocseq);
12060       } else if (is_method_allowed(&p->allowed_methods, SIP_UPDATE)) {
12061          reqprep(&req, p, SIP_UPDATE, 0, 1);
12062          add_rpid(&req, p);
12063          add_header(&req, "X-Asterisk-rpid-update", "Yes");
12064          send_request(p, &req, XMIT_CRITICAL, p->ocseq);
12065       } else {
12066          /* We cannot send the update yet, so we have to wait until we can */
12067          ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
12068       }
12069    } else {
12070       if (ast_test_flag(&p->flags[1], SIP_PAGE2_RPID_IMMEDIATE)) {
12071          struct sip_request resp;
12072 
12073          if ((p->owner->_state == AST_STATE_RING) && !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT)) {
12074             respprep(&resp, p, "180 Ringing", &p->initreq);
12075             add_rpid(&resp, p);
12076             send_response(p, &resp, XMIT_UNRELIABLE, 0);
12077             ast_set_flag(&p->flags[0], SIP_RINGING);
12078          } else if (p->owner->_state == AST_STATE_RINGING) {
12079             respprep(&resp, p, "183 Session Progress", &p->initreq);
12080             add_rpid(&resp, p);
12081             send_response(p, &resp, XMIT_UNRELIABLE, 0);
12082             ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
12083          } else {
12084             ast_debug(1, "Unable able to send update to '%s' in state '%s'\n", p->owner->name, ast_state2str(p->owner->_state));
12085          }
12086       } else {
12087          ast_set_flag(&p->flags[1], SIP_PAGE2_CONNECTLINEUPDATE_PEND);
12088       }
12089    }
12090 }
12091 
12092 static const struct _map_x_s regstatestrings[] = {
12093    { REG_STATE_FAILED,     "Failed" },
12094    { REG_STATE_UNREGISTERED, "Unregistered"},
12095    { REG_STATE_REGSENT, "Request Sent"},
12096    { REG_STATE_AUTHSENT, "Auth. Sent"},
12097    { REG_STATE_REGISTERED, "Registered"},
12098    { REG_STATE_REJECTED, "Rejected"},
12099    { REG_STATE_TIMEOUT, "Timeout"},
12100    { REG_STATE_NOAUTH, "No Authentication"},
12101    { -1, NULL } /* terminator */
12102 };
12103 
12104 /*! \brief Convert registration state status to string */
12105 static const char *regstate2str(enum sipregistrystate regstate)
12106 {
12107    return map_x_s(regstatestrings, regstate, "Unknown");
12108 }
12109 
12110 /*! \brief Update registration with SIP Proxy.
12111  * Called from the scheduler when the previous registration expires,
12112  * so we don't have to cancel the pending event.
12113  * We assume the reference so the sip_registry is valid, since it
12114  * is stored in the scheduled event anyways.
12115  */
12116 static int sip_reregister(const void *data)
12117 {
12118    /* if we are here, we know that we need to reregister. */
12119    struct sip_registry *r = (struct sip_registry *) data;
12120 
12121    /* if we couldn't get a reference to the registry object, punt */
12122    if (!r) {
12123       return 0;
12124    }
12125 
12126    if (r->call && r->call->do_history) {
12127       append_history(r->call, "RegistryRenew", "Account: %s@%s", r->username, r->hostname);
12128    }
12129    /* Since registry's are only added/removed by the the monitor thread, this
12130       may be overkill to reference/dereference at all here */
12131    if (sipdebug) {
12132       ast_log(LOG_NOTICE, "   -- Re-registration for  %s@%s\n", r->username, r->hostname);
12133    }
12134 
12135    r->expire = -1;
12136    r->expiry = r->configured_expiry;
12137    __sip_do_register(r);
12138    registry_unref(r, "unref the re-register scheduled event");
12139    return 0;
12140 }
12141 
12142 /*! \brief Register with SIP proxy 
12143    \return see \ref __sip_xmit 
12144 */
12145 static int __sip_do_register(struct sip_registry *r)
12146 {
12147    int res;
12148 
12149    res = transmit_register(r, SIP_REGISTER, NULL, NULL);
12150    return res;
12151 }
12152 
12153 /*! \brief Registration timeout, register again
12154  * Registered as a timeout handler during transmit_register(),
12155  * to retransmit the packet if a reply does not come back.
12156  * This is called by the scheduler so the event is not pending anymore when
12157  * we are called.
12158  */
12159 static int sip_reg_timeout(const void *data)
12160 {
12161 
12162    /* if we are here, our registration timed out, so we'll just do it over */
12163    struct sip_registry *r = (struct sip_registry *)data; /* the ref count should have been bumped when the sched item was added */
12164    struct sip_pvt *p;
12165    int res;
12166 
12167    /* if we couldn't get a reference to the registry object, punt */
12168    if (!r) {
12169       return 0;
12170    }
12171 
12172    if (r->dnsmgr) {
12173       /* If the registration has timed out, maybe the IP changed.  Force a refresh. */
12174       ast_dnsmgr_refresh(r->dnsmgr);
12175    }
12176 
12177    /* If the initial tranmission failed, we may not have an existing dialog,
12178     * so it is possible that r->call == NULL.
12179     * Otherwise destroy it, as we have a timeout so we don't want it.
12180     */
12181    if (r->call) {
12182       /* Unlink us, destroy old call.  Locking is not relevant here because all this happens
12183          in the single SIP manager thread. */
12184       p = r->call;
12185       sip_pvt_lock(p);
12186       pvt_set_needdestroy(p, "registration timeout");
12187       /* Pretend to ACK anything just in case */
12188       __sip_pretend_ack(p);
12189       sip_pvt_unlock(p);
12190 
12191       /* decouple the two objects */
12192       /* p->registry == r, so r has 2 refs, and the unref won't take the object away */
12193       if (p->registry) {
12194          p->registry = registry_unref(p->registry, "p->registry unreffed");
12195       }
12196       r->call = dialog_unref(r->call, "unrefing r->call");
12197    }
12198    /* If we have a limit, stop registration and give up */
12199    r->timeout = -1;
12200    if (global_regattempts_max && r->regattempts >= global_regattempts_max) {
12201       /* Ok, enough is enough. Don't try any more */
12202       /* We could add an external notification here...
12203          steal it from app_voicemail :-) */
12204       ast_log(LOG_NOTICE, "   -- Last Registration Attempt #%d failed, Giving up forever trying to register '%s@%s'\n", r->regattempts, r->username, r->hostname);
12205       r->regstate = REG_STATE_FAILED;
12206    } else {
12207       r->regstate = REG_STATE_UNREGISTERED;
12208       res = transmit_register(r, SIP_REGISTER, NULL, NULL);
12209       ast_log(LOG_NOTICE, "   -- Registration for '%s@%s' timed out, trying again (Attempt #%d)\n", r->username, r->hostname, r->regattempts);
12210    }
12211    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));
12212    registry_unref(r, "unreffing registry_unref r");
12213    return 0;
12214 }
12215 
12216 /*! \brief Transmit register to SIP proxy or UA
12217  * auth = NULL on the initial registration (from sip_reregister())
12218  */
12219 static int transmit_register(struct sip_registry *r, int sipmethod, const char *auth, const char *authheader)
12220 {
12221    struct sip_request req;
12222    char from[256];
12223    char to[256];
12224    char tmp[80];
12225    char addr[80];
12226    struct sip_pvt *p;
12227    struct sip_peer *peer = NULL;
12228    int res;
12229    int portno = 0;
12230 
12231    /* exit if we are already in process with this registrar ?*/
12232    if (r == NULL || ((auth == NULL) && (r->regstate == REG_STATE_REGSENT || r->regstate == REG_STATE_AUTHSENT))) {
12233       if (r) {
12234          ast_log(LOG_NOTICE, "Strange, trying to register %s@%s when registration already pending\n", r->username, r->hostname);
12235       }
12236       return 0;
12237    }
12238 
12239    if (r->dnsmgr == NULL) {
12240       char transport[MAXHOSTNAMELEN];
12241       peer = find_peer(r->hostname, NULL, TRUE, FINDPEERS, FALSE, 0);
12242       snprintf(transport, sizeof(transport), "_%s._%s",get_srv_service(r->transport), get_srv_protocol(r->transport)); /* have to use static get_transport function */
12243       r->us.ss.ss_family = get_address_family_filter(&bindaddr); /* Filter address family */
12244       ast_dnsmgr_lookup(peer ? peer->tohost : r->hostname, &r->us, &r->dnsmgr, sip_cfg.srvlookup ? transport : NULL);
12245       if (peer) {
12246          peer = unref_peer(peer, "removing peer ref for dnsmgr_lookup");
12247       }
12248    }
12249 
12250    if (r->call) { /* We have a registration */
12251       if (!auth) {
12252          ast_log(LOG_WARNING, "Already have a REGISTER going on to %s@%s?? \n", r->username, r->hostname);
12253          return 0;
12254       } else {
12255          p = dialog_ref(r->call, "getting a copy of the r->call dialog in transmit_register");
12256          make_our_tag(p->tag, sizeof(p->tag));  /* create a new local tag for every register attempt */
12257          ast_string_field_set(p, theirtag, NULL);  /* forget their old tag, so we don't match tags when getting response */
12258       }
12259    } else {
12260       /* Build callid for registration if we haven't registered before */
12261       if (!r->callid_valid) {
12262          build_callid_registry(r, &internip, default_fromdomain);
12263          r->callid_valid = TRUE;
12264       }
12265       /* Allocate SIP dialog for registration */
12266       if (!(p = sip_alloc( r->callid, NULL, 0, SIP_REGISTER, NULL))) {
12267          ast_log(LOG_WARNING, "Unable to allocate registration transaction (memory or socket error)\n");
12268          return 0;
12269       }
12270       
12271       if (p->do_history) {
12272          append_history(p, "RegistryInit", "Account: %s@%s", r->username, r->hostname);
12273       }
12274 
12275       /* Use port number specified if no SRV record was found */
12276       if (!ast_sockaddr_port(&r->us) && r->portno) {
12277          ast_sockaddr_set_port(&r->us, r->portno);
12278       }
12279 
12280       /* Find address to hostname */
12281       if (create_addr(p, S_OR(r->peername, r->hostname), &r->us, 0, NULL)) {
12282          /* we have what we hope is a temporary network error,
12283           * probably DNS.  We need to reschedule a registration try */
12284          dialog_unlink_all(p, TRUE, TRUE);
12285          p = dialog_unref(p, "unref dialog after unlink_all");
12286          if (r->timeout > -1) {
12287             AST_SCHED_REPLACE_UNREF(r->timeout, sched, global_reg_timeout * 1000, sip_reg_timeout, r,
12288                               registry_unref(_data, "del for REPLACE of registry ptr"),
12289                               registry_unref(r, "object ptr dec when SCHED_REPLACE add failed"),
12290                               registry_addref(r,"add for REPLACE registry ptr"));
12291             ast_log(LOG_WARNING, "Still have a registration timeout for %s@%s (create_addr() error), %d\n", r->username, r->hostname, r->timeout);
12292          } else {
12293             r->timeout = ast_sched_add(sched, global_reg_timeout * 1000, sip_reg_timeout, registry_addref(r, "add for REPLACE registry ptr"));
12294             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);
12295          }
12296          r->regattempts++;
12297          return 0;
12298       }
12299 
12300       /* Copy back Call-ID in case create_addr changed it */
12301       ast_string_field_set(r, callid, p->callid);
12302 
12303       if (!r->dnsmgr && r->portno) {
12304          ast_sockaddr_set_port(&p->sa, r->portno);
12305          ast_sockaddr_set_port(&p->recv, r->portno);
12306       }
12307       if (!ast_strlen_zero(p->fromdomain)) {
12308          portno = (p->fromdomainport) ? p->fromdomainport : STANDARD_SIP_PORT;
12309       } else if (!ast_strlen_zero(r->regdomain)) {
12310          portno = (r->regdomainport) ? r->regdomainport : STANDARD_SIP_PORT;
12311       } else {
12312          portno = ast_sockaddr_port(&p->sa);
12313       }
12314 
12315       ast_set_flag(&p->flags[0], SIP_OUTGOING); /* Registration is outgoing call */
12316       r->call = dialog_ref(p, "copying dialog into registry r->call");     /* Save pointer to SIP dialog */
12317       p->registry = registry_addref(r, "transmit_register: addref to p->registry in transmit_register"); /* Add pointer to registry in packet */
12318       if (!ast_strlen_zero(r->secret)) {  /* Secret (password) */
12319          ast_string_field_set(p, peersecret, r->secret);
12320       }
12321       if (!ast_strlen_zero(r->md5secret))
12322          ast_string_field_set(p, peermd5secret, r->md5secret);
12323       /* User name in this realm
12324       - if authuser is set, use that, otherwise use username */
12325       if (!ast_strlen_zero(r->authuser)) {
12326          ast_string_field_set(p, peername, r->authuser);
12327          ast_string_field_set(p, authname, r->authuser);
12328       } else if (!ast_strlen_zero(r->username)) {
12329          ast_string_field_set(p, peername, r->username);
12330          ast_string_field_set(p, authname, r->username);
12331          ast_string_field_set(p, fromuser, r->username);
12332       }
12333       if (!ast_strlen_zero(r->username)) {
12334          ast_string_field_set(p, username, r->username);
12335       }
12336       /* Save extension in packet */
12337       if (!ast_strlen_zero(r->callback)) {
12338          ast_string_field_set(p, exten, r->callback);
12339       }
12340 
12341       /* Set transport and port so the correct contact is built */
12342       set_socket_transport(&p->socket, r->transport);
12343       if (r->transport == SIP_TRANSPORT_TLS || r->transport == SIP_TRANSPORT_TCP) {
12344          p->socket.port =
12345              htons(ast_sockaddr_port(&sip_tcp_desc.local_address));
12346       }
12347 
12348       /*
12349         check which address we should use in our contact header
12350         based on whether the remote host is on the external or
12351         internal network so we can register through nat
12352        */
12353       ast_sip_ouraddrfor(&p->sa, &p->ourip, p);
12354       build_contact(p);
12355    }
12356 
12357    /* set up a timeout */
12358    if (auth == NULL)  {
12359       if (r->timeout > -1) {
12360          ast_log(LOG_WARNING, "Still have a registration timeout, #%d - deleting it\n", r->timeout);
12361       }
12362       AST_SCHED_REPLACE_UNREF(r->timeout, sched, global_reg_timeout * 1000, sip_reg_timeout, r,
12363                         registry_unref(_data,"reg ptr unrefed from del in SCHED_REPLACE"),
12364                         registry_unref(r,"reg ptr unrefed from add failure in SCHED_REPLACE"),
12365                         registry_addref(r,"reg ptr reffed from add in SCHED_REPLACE"));
12366       ast_debug(1, "Scheduled a registration timeout for %s id  #%d \n", r->hostname, r->timeout);
12367    }
12368 
12369    snprintf(from, sizeof(from), "<sip:%s@%s>;tag=%s", r->username, S_OR(r->regdomain,p->tohost), p->tag);
12370    if (!ast_strlen_zero(p->theirtag)) {
12371       snprintf(to, sizeof(to), "<sip:%s@%s>;tag=%s", r->username, S_OR(r->regdomain,p->tohost), p->theirtag);
12372    } else {
12373       snprintf(to, sizeof(to), "<sip:%s@%s>", r->username, S_OR(r->regdomain,p->tohost));
12374    }
12375 
12376    /* Fromdomain is what we are registering to, regardless of actual
12377       host name from SRV */
12378    if (portno && portno != STANDARD_SIP_PORT) {
12379       snprintf(addr, sizeof(addr), "sip:%s:%d", S_OR(p->fromdomain,S_OR(r->regdomain,r->hostname)), portno);
12380    } else {
12381       snprintf(addr, sizeof(addr), "sip:%s", S_OR(p->fromdomain,S_OR(r->regdomain,r->hostname)));
12382    }
12383 
12384    ast_string_field_set(p, uri, addr);
12385 
12386    p->branch ^= ast_random();
12387 
12388    init_req(&req, sipmethod, addr);
12389 
12390    /* Add to CSEQ */
12391    snprintf(tmp, sizeof(tmp), "%u %s", ++r->ocseq, sip_methods[sipmethod].text);
12392    p->ocseq = r->ocseq;
12393 
12394    build_via(p);
12395    add_header(&req, "Via", p->via);
12396    add_header_max_forwards(p, &req);
12397    add_header(&req, "From", from);
12398    add_header(&req, "To", to);
12399    add_header(&req, "Call-ID", p->callid);
12400    add_header(&req, "CSeq", tmp);
12401    if (!ast_strlen_zero(global_useragent))
12402       add_header(&req, "User-Agent", global_useragent);
12403 
12404    if (auth) {    /* Add auth header */
12405       add_header(&req, authheader, auth);
12406    } else if (!ast_strlen_zero(r->nonce)) {
12407       char digest[1024];
12408 
12409       /* We have auth data to reuse, build a digest header.
12410        * Note, this is not always useful because some parties do not
12411        * like nonces to be reused (for good reasons!) so they will
12412        * challenge us anyways.
12413        */
12414       if (sipdebug) {
12415          ast_debug(1, "   >>> Re-using Auth data for %s@%s\n", r->username, r->hostname);
12416       }
12417       ast_string_field_set(p, realm, r->realm);
12418       ast_string_field_set(p, nonce, r->nonce);
12419       ast_string_field_set(p, domain, r->authdomain);
12420       ast_string_field_set(p, opaque, r->opaque);
12421       ast_string_field_set(p, qop, r->qop);
12422       p->noncecount = ++r->noncecount;
12423 
12424       memset(digest, 0, sizeof(digest));
12425       if(!build_reply_digest(p, sipmethod, digest, sizeof(digest))) {
12426          add_header(&req, "Authorization", digest);
12427       } else {
12428          ast_log(LOG_NOTICE, "No authorization available for authentication of registration to %s@%s\n", r->username, r->hostname);
12429       }
12430    }
12431 
12432    snprintf(tmp, sizeof(tmp), "%d", r->expiry);
12433    add_header(&req, "Expires", tmp);
12434    add_header(&req, "Contact", p->our_contact);
12435 
12436    initialize_initreq(p, &req);
12437    if (sip_debug_test_pvt(p)) {
12438       ast_verbose("REGISTER %d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
12439    }
12440    r->regstate = auth ? REG_STATE_AUTHSENT : REG_STATE_REGSENT;
12441    r->regattempts++; /* Another attempt */
12442    ast_debug(4, "REGISTER attempt %d to %s@%s\n", r->regattempts, r->username, r->hostname);
12443    res = send_request(p, &req, XMIT_CRITICAL, p->ocseq);
12444    dialog_unref(p, "p is finished here at the end of transmit_register");
12445    return res;
12446 }
12447 
12448 /*! \brief Transmit text with SIP MESSAGE method */
12449 static int transmit_message_with_text(struct sip_pvt *p, const char *text)
12450 {
12451    struct sip_request req;
12452    
12453    reqprep(&req, p, SIP_MESSAGE, 0, 1);
12454    add_text(&req, text);
12455    return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
12456 }
12457 
12458 /*! \brief Allocate SIP refer structure */
12459 static int sip_refer_allocate(struct sip_pvt *p)
12460 {
12461    p->refer = ast_calloc(1, sizeof(struct sip_refer));
12462    return p->refer ? 1 : 0;
12463 }
12464 
12465 /*! \brief Allocate SIP refer structure */
12466 static int sip_notify_allocate(struct sip_pvt *p)
12467 {
12468    p->notify = ast_calloc(1, sizeof(struct sip_notify));
12469    if (p->notify) {
12470       p->notify->content = ast_str_create(128);
12471    }
12472    return p->notify ? 1 : 0;
12473 }
12474 
12475 /*! \brief Transmit SIP REFER message (initiated by the transfer() dialplan application
12476    \note this is currently broken as we have no way of telling the dialplan
12477    engine whether a transfer succeeds or fails.
12478    \todo Fix the transfer() dialplan function so that a transfer may fail
12479 */
12480 static int transmit_refer(struct sip_pvt *p, const char *dest)
12481 {
12482    struct sip_request req = {
12483       .headers = 0,  
12484    };
12485    char from[256];
12486    const char *of;
12487    char *c;
12488    char referto[256];
12489    char *ttag, *ftag;
12490    char *theirtag = ast_strdupa(p->theirtag);
12491    int   use_tls=FALSE;
12492 
12493    if (sipdebug) {
12494       ast_debug(1, "SIP transfer of %s to %s\n", p->callid, dest);
12495    }
12496 
12497    /* Are we transfering an inbound or outbound call ? */
12498    if (ast_test_flag(&p->flags[0], SIP_OUTGOING))  {
12499       of = get_header(&p->initreq, "To");
12500       ttag = theirtag;
12501       ftag = p->tag;
12502    } else {
12503       of = get_header(&p->initreq, "From");
12504       ftag = theirtag;
12505       ttag = p->tag;
12506    }
12507 
12508    ast_copy_string(from, of, sizeof(from));
12509    of = get_in_brackets(from);
12510    ast_string_field_set(p, from, of);
12511    if (!strncasecmp(of, "sip:", 4)) {
12512       of += 4;
12513    } else if (!strncasecmp(of, "sips:", 5)) {
12514       of += 5;
12515       use_tls = TRUE;
12516    } else {
12517       ast_log(LOG_NOTICE, "From address missing 'sip(s):', assuming sip:\n");
12518    }
12519    /* Get just the username part */
12520    if ((c = strchr(dest, '@'))) {
12521       c = NULL;
12522    } else if ((c = strchr(of, '@'))) {
12523       *c++ = '\0';
12524    }
12525    if (c) {
12526       snprintf(referto, sizeof(referto), "<sip%s:%s@%s>", use_tls ? "s" : "", dest, c);
12527    } else {
12528       snprintf(referto, sizeof(referto), "<sip%s:%s>", use_tls ? "s" : "", dest);
12529    }
12530 
12531    /* save in case we get 407 challenge */
12532    sip_refer_allocate(p);
12533    ast_copy_string(p->refer->refer_to, referto, sizeof(p->refer->refer_to));
12534    ast_copy_string(p->refer->referred_by, p->our_contact, sizeof(p->refer->referred_by));
12535    p->refer->status = REFER_SENT;   /* Set refer status */
12536 
12537    reqprep(&req, p, SIP_REFER, 0, 1);
12538 
12539    add_header(&req, "Refer-To", referto);
12540    add_header(&req, "Allow", ALLOWED_METHODS);
12541    add_supported_header(p, &req);
12542    if (!ast_strlen_zero(p->our_contact)) {
12543       add_header(&req, "Referred-By", p->our_contact);
12544    }
12545 
12546    return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
12547 
12548    /* We should propably wait for a NOTIFY here until we ack the transfer */
12549    /* Maybe fork a new thread and wait for a STATUS of REFER_200OK on the refer status before returning to app_transfer */
12550 
12551    /*! \todo In theory, we should hang around and wait for a reply, before
12552    returning to the dial plan here. Don't know really how that would
12553    affect the transfer() app or the pbx, but, well, to make this
12554    useful we should have a STATUS code on transfer().
12555    */
12556 }
12557 
12558 /*! \brief Send SIP INFO advice of charge message */
12559 static int transmit_info_with_aoc(struct sip_pvt *p, struct ast_aoc_decoded *decoded)
12560 {
12561    struct sip_request req;
12562    struct ast_str *str = ast_str_alloca(512);
12563    const struct ast_aoc_unit_entry *unit_entry = ast_aoc_get_unit_info(decoded, 0);
12564    enum ast_aoc_charge_type charging = ast_aoc_get_charge_type(decoded);
12565 
12566    reqprep(&req, p, SIP_INFO, 0, 1);
12567 
12568    if (ast_aoc_get_msg_type(decoded) == AST_AOC_D) {
12569       ast_str_append(&str, 0, "type=active;");
12570    } else if (ast_aoc_get_msg_type(decoded) == AST_AOC_E) {
12571       ast_str_append(&str, 0, "type=terminated;");
12572    } else {
12573       /* unsupported message type */
12574       return -1;
12575    }
12576 
12577    switch (charging) {
12578    case AST_AOC_CHARGE_FREE:
12579       ast_str_append(&str, 0, "free-of-charge;");
12580       break;
12581    case AST_AOC_CHARGE_CURRENCY:
12582       ast_str_append(&str, 0, "charging;");
12583       ast_str_append(&str, 0, "charging-info=currency;");
12584       ast_str_append(&str, 0, "amount=%u;", ast_aoc_get_currency_amount(decoded));
12585       ast_str_append(&str, 0, "multiplier=%s;", ast_aoc_get_currency_multiplier_decimal(decoded));
12586       if (!ast_strlen_zero(ast_aoc_get_currency_name(decoded))) {
12587          ast_str_append(&str, 0, "currency=%s;", ast_aoc_get_currency_name(decoded));
12588       }
12589       break;
12590    case AST_AOC_CHARGE_UNIT:
12591       ast_str_append(&str, 0, "charging;");
12592       ast_str_append(&str, 0, "charging-info=pulse;");
12593       if (unit_entry) {
12594          ast_str_append(&str, 0, "recorded-units=%u;", unit_entry->amount);
12595       }
12596       break;
12597    default:
12598       ast_str_append(&str, 0, "not-available;");
12599    };
12600 
12601    add_header(&req, "AOC", ast_str_buffer(str));
12602 
12603    return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
12604 }
12605 
12606 /*! \brief Send SIP INFO dtmf message, see Cisco documentation on cisco.com */
12607 static int transmit_info_with_digit(struct sip_pvt *p, const char digit, unsigned int duration)
12608 {
12609    struct sip_request req;
12610    
12611    reqprep(&req, p, SIP_INFO, 0, 1);
12612    add_digit(&req, digit, duration, (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_SHORTINFO));
12613    return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
12614 }
12615 
12616 /*! \brief Send SIP INFO with video update request */
12617 static int transmit_info_with_vidupdate(struct sip_pvt *p)
12618 {
12619    struct sip_request req;
12620    
12621    reqprep(&req, p, SIP_INFO, 0, 1);
12622    add_vidupdate(&req);
12623    return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
12624 }
12625 
12626 /*! \brief Transmit generic SIP request
12627    returns XMIT_ERROR if transmit failed with a critical error (don't retry)
12628 */
12629 static int transmit_request(struct sip_pvt *p, int sipmethod, int seqno, enum xmittype reliable, int newbranch)
12630 {
12631    struct sip_request resp;
12632    
12633    if (sipmethod == SIP_ACK) {
12634       p->invitestate = INV_CONFIRMED;
12635    }
12636 
12637    reqprep(&resp, p, sipmethod, seqno, newbranch);
12638    if (sipmethod == SIP_CANCEL && p->answered_elsewhere) {
12639       add_header(&resp, "Reason", "SIP;cause=200;text=\"Call completed elsewhere\"");
12640    }
12641 
12642    return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);
12643 }
12644 
12645 /*! \brief return the request and response heade for a 401 or 407 code */
12646 static void auth_headers(enum sip_auth_type code, char **header, char **respheader)
12647 {
12648    if (code == WWW_AUTH) {       /* 401 */
12649       *header = "WWW-Authenticate";
12650       *respheader = "Authorization";
12651    } else if (code == PROXY_AUTH) { /* 407 */
12652       *header = "Proxy-Authenticate";
12653       *respheader = "Proxy-Authorization";
12654    } else {
12655       ast_verbose("-- wrong response code %d\n", code);
12656       *header = *respheader = "Invalid";
12657    }
12658 }
12659 
12660 /*! \brief Transmit SIP request, auth added */
12661 static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, int seqno, enum xmittype reliable, int newbranch)
12662 {
12663    struct sip_request resp;
12664    
12665    reqprep(&resp, p, sipmethod, seqno, newbranch);
12666    if (!ast_strlen_zero(p->realm)) {
12667       char digest[1024];
12668 
12669       memset(digest, 0, sizeof(digest));
12670       if(!build_reply_digest(p, sipmethod, digest, sizeof(digest))) {
12671          char *dummy, *response;
12672          enum sip_auth_type code = p->options ? p->options->auth_type : PROXY_AUTH; /* XXX force 407 if unknown */
12673          auth_headers(code, &dummy, &response);
12674          add_header(&resp, response, digest);
12675       } else {
12676          ast_log(LOG_WARNING, "No authentication available for call %s\n", p->callid);
12677       }
12678    }
12679    /* If we are hanging up and know a cause for that, send it in clear text to make
12680       debugging easier. */
12681    if (sipmethod == SIP_BYE)  {
12682       char buf[20];
12683 
12684       if (ast_test_flag(&p->flags[1], SIP_PAGE2_Q850_REASON) && p->hangupcause) {
12685          sprintf(buf, "Q.850;cause=%i", p->hangupcause & 0x7f);
12686          add_header(&resp, "Reason", buf);
12687       }
12688 
12689       add_header(&resp, "X-Asterisk-HangupCause", ast_cause2str(p->hangupcause));
12690       snprintf(buf, sizeof(buf), "%d", p->hangupcause);
12691       add_header(&resp, "X-Asterisk-HangupCauseCode", buf);
12692    }
12693 
12694    return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);   
12695 }
12696 
12697 /*! \brief Remove registration data from realtime database or AST/DB when registration expires */
12698 static void destroy_association(struct sip_peer *peer)
12699 {
12700    int realtimeregs = ast_check_realtime("sipregs");
12701    char *tablename = (realtimeregs) ? "sipregs" : "sippeers";
12702 
12703    if (!sip_cfg.ignore_regexpire) {
12704       if (peer->rt_fromcontact && sip_cfg.peer_rtupdate) {
12705          ast_update_realtime(tablename, "name", peer->name, "fullcontact", "", "ipaddr", "", "port", "", "regseconds", "0", "regserver", "", "useragent", "", "lastms", "", SENTINEL);
12706       } else {
12707          ast_db_del("SIP/Registry", peer->name);
12708          ast_db_del("SIP/PeerMethods", peer->name);
12709       }
12710    }
12711 }
12712 
12713 static void set_socket_transport(struct sip_socket *socket, int transport)
12714 {
12715    /* if the transport type changes, clear all socket data */
12716    if (socket->type != transport) {
12717       socket->fd = -1;
12718       socket->type = transport;
12719       if (socket->tcptls_session) {
12720          ao2_ref(socket->tcptls_session, -1);
12721          socket->tcptls_session = NULL;
12722       }
12723    }
12724 }
12725 
12726 /*! \brief Expire registration of SIP peer */
12727 static int expire_register(const void *data)
12728 {
12729    struct sip_peer *peer = (struct sip_peer *)data;
12730 
12731    if (!peer) {      /* Hmmm. We have no peer. Weird. */
12732       return 0;
12733    }
12734 
12735    peer->expire = -1;
12736    peer->portinuri = 0;
12737 
12738    destroy_association(peer); /* remove registration data from storage */
12739    set_socket_transport(&peer->socket, peer->default_outbound_transport);
12740 
12741    if (peer->socket.tcptls_session) {
12742       ao2_ref(peer->socket.tcptls_session, -1);
12743       peer->socket.tcptls_session = NULL;
12744    }
12745 
12746    manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: Unregistered\r\nCause: Expired\r\n", peer->name);
12747    register_peer_exten(peer, FALSE);   /* Remove regexten */
12748    ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", peer->name);
12749 
12750    /* Do we need to release this peer from memory?
12751       Only for realtime peers and autocreated peers
12752    */
12753    if (peer->is_realtime) {
12754       ast_debug(3, "-REALTIME- peer expired registration. Name: %s. Realtime peer objects now %d\n", peer->name, rpeerobjs);
12755    }
12756 
12757    if (peer->selfdestruct ||
12758        ast_test_flag(&peer->flags[1], SIP_PAGE2_RTAUTOCLEAR)) {
12759       unlink_peer_from_tables(peer);
12760    }
12761 
12762    /* Only clear the addr after we check for destruction.  The addr must remain
12763     * in order to unlink from the peers_by_ip container correctly */
12764    memset(&peer->addr, 0, sizeof(peer->addr));
12765 
12766    unref_peer(peer, "removing peer ref for expire_register");
12767 
12768    return 0;
12769 }
12770 
12771 /*! \brief Poke peer (send qualify to check if peer is alive and well) */
12772 static int sip_poke_peer_s(const void *data)
12773 {
12774    struct sip_peer *peer = (struct sip_peer *)data;
12775 
12776    peer->pokeexpire = -1;
12777 
12778    sip_poke_peer(peer, 0);
12779 
12780    unref_peer(peer, "removing poke peer ref");
12781 
12782    return 0;
12783 }
12784 
12785 /*! \brief Get registration details from Asterisk DB */
12786 static void reg_source_db(struct sip_peer *peer)
12787 {
12788    char data[256];
12789    struct ast_sockaddr sa;
12790    int expire;
12791    char full_addr[128];
12792    AST_DECLARE_APP_ARGS(args,
12793       AST_APP_ARG(addr);
12794       AST_APP_ARG(port);
12795       AST_APP_ARG(expiry_str);
12796       AST_APP_ARG(username);
12797       AST_APP_ARG(contact);
12798    );
12799 
12800    if (peer->rt_fromcontact) {
12801       return;
12802    }
12803    if (ast_db_get("SIP/Registry", peer->name, data, sizeof(data))) {
12804       return;
12805    }
12806 
12807    AST_NONSTANDARD_RAW_ARGS(args, data, ':');
12808 
12809    snprintf(full_addr, sizeof(full_addr), "%s:%s", args.addr, args.port);
12810 
12811    if (!ast_sockaddr_parse(&sa, full_addr, 0)) {
12812       return;
12813    }
12814 
12815    if (args.expiry_str) {
12816       expire = atoi(args.expiry_str);
12817    } else {
12818       return;
12819    }
12820 
12821    if (args.username) {
12822       ast_string_field_set(peer, username, args.username);
12823    }
12824    if (args.contact) {
12825       ast_string_field_set(peer, fullcontact, args.contact);
12826    }
12827 
12828    ast_debug(2, "SIP Seeding peer from astdb: '%s' at %s@%s for %d\n",
12829        peer->name, peer->username, ast_sockaddr_stringify_host(&sa), expire);
12830 
12831    ast_sockaddr_copy(&peer->addr, &sa);
12832    if (sipsock < 0) {
12833       /* SIP isn't up yet, so schedule a poke only, pretty soon */
12834       AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched, ast_random() % 5000 + 1, sip_poke_peer_s, peer,
12835             unref_peer(_data, "removing poke peer ref"),
12836             unref_peer(peer, "removing poke peer ref"),
12837             ref_peer(peer, "adding poke peer ref"));
12838    } else {
12839       sip_poke_peer(peer, 0);
12840    }
12841    AST_SCHED_REPLACE_UNREF(peer->expire, sched, (expire + 10) * 1000, expire_register, peer,
12842          unref_peer(_data, "remove registration ref"),
12843          unref_peer(peer, "remove registration ref"),
12844          ref_peer(peer, "add registration ref"));
12845    register_peer_exten(peer, TRUE);
12846 }
12847 
12848 /*! \brief Save contact header for 200 OK on INVITE */
12849 static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req)
12850 {
12851    char contact[SIPBUFSIZE];
12852    char *c;
12853 
12854    /* Look for brackets */
12855    ast_copy_string(contact, get_header(req, "Contact"), sizeof(contact));
12856    c = get_in_brackets(contact);
12857 
12858    /* Save full contact to call pvt for later bye or re-invite */
12859    ast_string_field_set(pvt, fullcontact, c);
12860 
12861    /* Save URI for later ACKs, BYE or RE-invites */
12862    ast_string_field_set(pvt, okcontacturi, c);
12863 
12864    /* We should return false for URI:s we can't handle,
12865       like tel:, mailto:,ldap: etc */
12866    return TRUE;      
12867 }
12868 
12869 static int __set_address_from_contact(const char *fullcontact, struct ast_sockaddr *addr, int tcp)
12870 {
12871    char *domain, *transport;
12872    char contact_buf[256];
12873    char *contact;
12874 
12875    /* Work on a copy */
12876    ast_copy_string(contact_buf, fullcontact, sizeof(contact_buf));
12877    contact = contact_buf;
12878 
12879    /* 
12880     * We have only the part in <brackets> here so we just need to parse a SIP URI.
12881     *
12882     * Note: The outbound proxy could be using UDP between the proxy and Asterisk.
12883     * We still need to be able to send to the remote agent through the proxy.
12884     */
12885 
12886    if (parse_uri(contact, "sip:,sips:", &contact, NULL, &domain,
12887             &transport)) {
12888       ast_log(LOG_WARNING, "Invalid contact uri %s (missing sip: or sips:), attempting to use anyway\n", fullcontact);
12889    }
12890 
12891    /* XXX This could block for a long time XXX */
12892    /* We should only do this if it's a name, not an IP */
12893    /* \todo - if there's no PORT number in contact - we are required to check NAPTR/SRV records
12894       to find transport, port address and hostname. If there's a port number, we have to
12895       assume that the domain part is a host name and only look for an A/AAAA record in DNS.
12896    */
12897 
12898    if (ast_sockaddr_resolve_first(addr, domain, 0)) {
12899       ast_log(LOG_WARNING, "Invalid host name in Contact: (can't "
12900          "resolve in DNS) : '%s'\n", domain);
12901       return -1;
12902    }
12903 
12904    /* set port */
12905    if (!ast_sockaddr_port(addr)) {
12906       ast_sockaddr_set_port(addr,
12907                   (get_transport_str2enum(transport) ==
12908                    SIP_TRANSPORT_TLS ||
12909                    !strncasecmp(fullcontact, "sips", 4)) ?
12910                   STANDARD_TLS_PORT : STANDARD_SIP_PORT);
12911    }
12912 
12913    return 0;
12914 }
12915 
12916 /*! \brief Change the other partys IP address based on given contact */
12917 static int set_address_from_contact(struct sip_pvt *pvt)
12918 {
12919    if (ast_test_flag(&pvt->flags[0], SIP_NAT_FORCE_RPORT)) {
12920       /* NAT: Don't trust the contact field.  Just use what they came to us
12921          with. */
12922       /*! \todo We need to save the TRANSPORT here too */
12923       pvt->sa = pvt->recv;
12924       return 0;
12925    }
12926 
12927    return __set_address_from_contact(pvt->fullcontact, &pvt->sa, pvt->socket.type == SIP_TRANSPORT_TLS ? 1 : 0);
12928 }
12929 
12930 /*! \brief Parse contact header and save registration (peer registration) */
12931 static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *peer, struct sip_request *req)
12932 {
12933    char contact[SIPBUFSIZE];
12934    char data[SIPBUFSIZE];
12935    const char *expires = get_header(req, "Expires");
12936    int expire = atoi(expires);
12937    char *curi, *domain, *transport;
12938    int transport_type;
12939    const char *useragent;
12940    struct ast_sockaddr oldsin, testsa;
12941 
12942    ast_copy_string(contact, get_header(req, "Contact"), sizeof(contact));
12943 
12944    if (ast_strlen_zero(expires)) {  /* No expires header, try look in Contact: */
12945       char *s = strcasestr(contact, ";expires=");
12946       if (s) {
12947          expires = strsep(&s, ";"); /* trim ; and beyond */
12948          if (sscanf(expires + 9, "%30d", &expire) != 1) {
12949             expire = default_expiry;
12950          }
12951       } else {
12952          /* Nothing has been specified */
12953          expire = default_expiry;
12954       }
12955    }
12956 
12957    copy_socket_data(&pvt->socket, &req->socket);
12958 
12959    /* Look for brackets */
12960    curi = contact;
12961    if (strchr(contact, '<') == NULL)   /* No <, check for ; and strip it */
12962       strsep(&curi, ";");  /* This is Header options, not URI options */
12963    curi = get_in_brackets(contact);
12964 
12965    /* if they did not specify Contact: or Expires:, they are querying
12966       what we currently have stored as their contact address, so return
12967       it
12968    */
12969    if (ast_strlen_zero(curi) && ast_strlen_zero(expires)) {
12970       /* If we have an active registration, tell them when the registration is going to expire */
12971       if (peer->expire > -1 && !ast_strlen_zero(peer->fullcontact)) {
12972          pvt->expiry = ast_sched_when(sched, peer->expire);
12973       }
12974       return PARSE_REGISTER_QUERY;
12975    } else if (!strcasecmp(curi, "*") || !expire) { /* Unregister this peer */
12976       /* This means remove all registrations and return OK */
12977       memset(&peer->addr, 0, sizeof(peer->addr));
12978       set_socket_transport(&peer->socket, peer->default_outbound_transport);
12979 
12980       AST_SCHED_DEL_UNREF(sched, peer->expire,
12981             unref_peer(peer, "remove register expire ref"));
12982 
12983       destroy_association(peer);
12984 
12985       register_peer_exten(peer, FALSE);   /* Remove extension from regexten= setting in sip.conf */
12986       ast_string_field_set(peer, fullcontact, "");
12987       ast_string_field_set(peer, useragent, "");
12988       peer->sipoptions = 0;
12989       peer->lastms = 0;
12990       peer->portinuri = 0;
12991       pvt->expiry = 0;
12992 
12993       ast_verb(3, "Unregistered SIP '%s'\n", peer->name);
12994 
12995       manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: Unregistered\r\n", peer->name);
12996       return PARSE_REGISTER_UPDATE;
12997    }
12998 
12999    /* Store whatever we got as a contact from the client */
13000    ast_string_field_set(peer, fullcontact, curi);
13001 
13002    /* For the 200 OK, we should use the received contact */
13003    ast_string_field_build(pvt, our_contact, "<%s>", curi);
13004 
13005    /* Make sure it's a SIP URL */
13006    if (parse_uri(curi, "sip:,sips:", &curi, NULL, &domain, &transport)) {
13007       ast_log(LOG_NOTICE, "Not a valid SIP contact (missing sip:/sips:) trying to use anyway\n");
13008    }
13009 
13010    /* handle the transport type specified in Contact header. */
13011    if (!(transport_type = get_transport_str2enum(transport))) {
13012       transport_type = pvt->socket.type;
13013    }
13014 
13015    /* if the peer's socket type is different than the Registration
13016     * transport type, change it.  If it got this far, it is a
13017     * supported type, but check just in case */
13018    if ((peer->socket.type != transport_type) && (peer->transports & transport_type)) {
13019       set_socket_transport(&peer->socket, transport_type);
13020    }
13021 
13022    oldsin = peer->addr;
13023 
13024    /* If we were already linked into the peers_by_ip container unlink ourselves so nobody can find us */
13025    if (!ast_sockaddr_isnull(&peer->addr)) {
13026       ao2_t_unlink(peers_by_ip, peer, "ao2_unlink of peer from peers_by_ip table");
13027    }
13028 
13029    if (!ast_test_flag(&peer->flags[0], SIP_NAT_FORCE_RPORT) && !ast_test_flag(&peer->flags[0], SIP_NAT_RPORT_PRESENT)) {
13030        /* use the data provided in the Contact header for call routing */
13031       ast_debug(1, "Store REGISTER's Contact header for call routing.\n");
13032       /* XXX This could block for a long time XXX */
13033       /*! \todo Check NAPTR/SRV if we have not got a port in the URI */
13034       if (ast_sockaddr_resolve_first(&testsa, domain, 0)) {
13035          ast_log(LOG_WARNING, "Invalid domain '%s'\n", domain);
13036          ast_string_field_set(peer, fullcontact, "");
13037          ast_string_field_set(pvt, our_contact, "");
13038          return PARSE_REGISTER_FAILED;
13039       }
13040 
13041       /* If we have a port number in the given URI, make sure we do remember to not check for NAPTR/SRV records.
13042          The domain part is actually a host. */
13043       peer->portinuri = ast_sockaddr_port(&testsa) ? TRUE : FALSE;
13044 
13045       if (!ast_sockaddr_port(&testsa)) {
13046          ast_sockaddr_set_port(&testsa,
13047                     transport_type == SIP_TRANSPORT_TLS ?
13048                     STANDARD_TLS_PORT : STANDARD_SIP_PORT);
13049       }
13050 
13051       ast_sockaddr_copy(&peer->addr, &testsa);
13052    } else {
13053       /* Don't trust the contact field.  Just use what they came to us
13054          with */
13055       ast_debug(1, "Store REGISTER's src-IP:port for call routing.\n");
13056       peer->addr = pvt->recv;
13057    }
13058 
13059    /* Check that they're allowed to register at this IP */
13060    if (ast_apply_ha(sip_cfg.contact_ha, &peer->addr) != AST_SENSE_ALLOW ||
13061          ast_apply_ha(peer->contactha, &peer->addr) != AST_SENSE_ALLOW) {
13062       ast_log(LOG_WARNING, "Domain '%s' disallowed by contact ACL (violating IP %s)\n", domain,
13063          ast_sockaddr_stringify_addr(&testsa));
13064       ast_string_field_set(peer, fullcontact, "");
13065       ast_string_field_set(pvt, our_contact, "");
13066       return PARSE_REGISTER_DENIED;
13067    }
13068 
13069    /* if the Contact header information copied into peer->addr matches the
13070     * received address, and the transport types are the same, then copy socket
13071     * data into the peer struct */
13072    if ((peer->socket.type == pvt->socket.type) &&
13073       !ast_sockaddr_cmp(&peer->addr, &pvt->recv)) {
13074       copy_socket_data(&peer->socket, &pvt->socket);
13075    }
13076 
13077    /* Now that our address has been updated put ourselves back into the container for lookups */
13078    ao2_t_link(peers_by_ip, peer, "ao2_link into peers_by_ip table");
13079 
13080    /* Save SIP options profile */
13081    peer->sipoptions = pvt->sipoptions;
13082 
13083    if (!ast_strlen_zero(curi) && ast_strlen_zero(peer->username)) {
13084       ast_string_field_set(peer, username, curi);
13085    }
13086 
13087    AST_SCHED_DEL_UNREF(sched, peer->expire,
13088          unref_peer(peer, "remove register expire ref"));
13089 
13090    if (expire > max_expiry) {
13091       expire = max_expiry;
13092    }
13093    if (expire < min_expiry) {
13094       expire = min_expiry;
13095    }
13096    if (peer->is_realtime && !ast_test_flag(&peer->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
13097       peer->expire = -1;
13098    } else {
13099       peer->expire = ast_sched_add(sched, (expire + 10) * 1000, expire_register,
13100             ref_peer(peer, "add registration ref"));
13101       if (peer->expire == -1) {
13102          unref_peer(peer, "remote registration ref");
13103       }
13104    }
13105    pvt->expiry = expire;
13106    snprintf(data, sizeof(data), "%s:%d:%s:%s", ast_sockaddr_stringify(&peer->addr),
13107        expire, peer->username, peer->fullcontact);
13108    /* Saving TCP connections is useless, we won't be able to reconnect
13109       XXX WHY???? XXX
13110       \todo Fix this immediately.
13111    */
13112    if (!peer->rt_fromcontact && (peer->socket.type & SIP_TRANSPORT_UDP))
13113       ast_db_put("SIP/Registry", peer->name, data);
13114    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));
13115 
13116    /* Is this a new IP address for us? */
13117    if (VERBOSITY_ATLEAST(2) && ast_sockaddr_cmp(&peer->addr, &oldsin)) {
13118       ast_verbose(VERBOSE_PREFIX_3 "Registered SIP '%s' at %s\n", peer->name,
13119             ast_sockaddr_stringify(&peer->addr));
13120    }
13121    sip_poke_peer(peer, 0);
13122    register_peer_exten(peer, 1);
13123    
13124    /* Save User agent */
13125    useragent = get_header(req, "User-Agent");
13126    if (strcasecmp(useragent, peer->useragent)) {
13127       ast_string_field_set(peer, useragent, useragent);
13128       ast_verb(4, "Saved useragent \"%s\" for peer %s\n", peer->useragent, peer->name);
13129    }
13130    return PARSE_REGISTER_UPDATE;
13131 }
13132 
13133 /*! \brief Remove route from route list */
13134 static void free_old_route(struct sip_route *route)
13135 {
13136    struct sip_route *next;
13137 
13138    while (route) {
13139       next = route->next;
13140       ast_free(route);
13141       route = next;
13142    }
13143 }
13144 
13145 /*! \brief List all routes - mostly for debugging */
13146 static void list_route(struct sip_route *route)
13147 {
13148    if (!route) {
13149       ast_verbose("list_route: no route\n");
13150    } else {
13151       for (;route; route = route->next)
13152          ast_verbose("list_route: hop: <%s>\n", route->hop);
13153    }
13154 }
13155 
13156 /*! \brief Build route list from Record-Route header */
13157 static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards)
13158 {
13159    struct sip_route *thishop, *head, *tail;
13160    int start = 0;
13161    int len;
13162    const char *rr, *contact, *c;
13163 
13164    /* Once a persistent route is set, don't fool with it */
13165    if (p->route && p->route_persistent) {
13166       ast_debug(1, "build_route: Retaining previous route: <%s>\n", p->route->hop);
13167       return;
13168    }
13169 
13170    if (p->route) {
13171       free_old_route(p->route);
13172       p->route = NULL;
13173    }
13174 
13175    /* We only want to create the route set the first time this is called */
13176    p->route_persistent = 1;
13177    
13178    /* Build a tailq, then assign it to p->route when done.
13179     * If backwards, we add entries from the head so they end up
13180     * in reverse order. However, we do need to maintain a correct
13181     * tail pointer because the contact is always at the end.
13182     */
13183    head = NULL;
13184    tail = head;
13185    /* 1st we pass through all the hops in any Record-Route headers */
13186    for (;;) {
13187       /* Each Record-Route header */
13188       rr = __get_header(req, "Record-Route", &start);
13189       if (*rr == '\0') {
13190          break;
13191       }
13192       for (; (rr = strchr(rr, '<')) ; rr += len) { /* Each route entry */
13193          ++rr;
13194          len = strcspn(rr, ">") + 1;
13195          /* Make a struct route */
13196          if ((thishop = ast_malloc(sizeof(*thishop) + len))) {
13197             /* ast_calloc is not needed because all fields are initialized in this block */
13198             ast_copy_string(thishop->hop, rr, len);
13199             ast_debug(2, "build_route: Record-Route hop: <%s>\n", thishop->hop);
13200             /* Link in */
13201             if (backwards) {
13202                /* Link in at head so they end up in reverse order */
13203                thishop->next = head;
13204                head = thishop;
13205                /* If this was the first then it'll be the tail */
13206                if (!tail) {
13207                   tail = thishop;
13208                }
13209             } else {
13210                thishop->next = NULL;
13211                /* Link in at the end */
13212                if (tail) {
13213                   tail->next = thishop;
13214                } else {
13215                   head = thishop;
13216                }
13217                tail = thishop;
13218             }
13219          }
13220       }
13221    }
13222 
13223    /* Only append the contact if we are dealing with a strict router */
13224    if (!head || (!ast_strlen_zero(head->hop) && strstr(head->hop, ";lr") == NULL) ) {
13225       /* 2nd append the Contact: if there is one */
13226       /* Can be multiple Contact headers, comma separated values - we just take the first */
13227       contact = get_header(req, "Contact");
13228       if (!ast_strlen_zero(contact)) {
13229          ast_debug(2, "build_route: Contact hop: %s\n", contact);
13230          /* Look for <: delimited address */
13231          c = strchr(contact, '<');
13232          if (c) {
13233             /* Take to > */
13234             ++c;
13235             len = strcspn(c, ">") + 1;
13236          } else {
13237             /* No <> - just take the lot */
13238             c = contact;
13239             len = strlen(contact) + 1;
13240          }
13241          if ((thishop = ast_malloc(sizeof(*thishop) + len))) {
13242             /* ast_calloc is not needed because all fields are initialized in this block */
13243             ast_copy_string(thishop->hop, c, len);
13244             thishop->next = NULL;
13245             /* Goes at the end */
13246             if (tail) {
13247                tail->next = thishop;
13248             } else {
13249                head = thishop;
13250             }
13251          }
13252       }
13253    }
13254 
13255    /* Store as new route */
13256    p->route = head;
13257 
13258    /* For debugging dump what we ended up with */
13259    if (sip_debug_test_pvt(p)) {
13260       list_route(p->route);
13261    }
13262 }
13263 
13264 /*! \brief builds the sip_pvt's randdata field which is used for the nonce
13265  *  challenge.  When forceupdate is not set, the nonce is only updated if
13266  *  the current one is stale.  In this case, a stalenonce is one which
13267  *  has already received a response, if a nonce has not received a response
13268  *  it is not always necessary or beneficial to create a new one. */
13269 
13270 static void set_nonce_randdata(struct sip_pvt *p, int forceupdate)
13271 {
13272    if (p->stalenonce || forceupdate || ast_strlen_zero(p->randdata)) {
13273       ast_string_field_build(p, randdata, "%08lx", ast_random()); /* Create nonce for challenge */
13274       p->stalenonce = 0;
13275    }
13276 }
13277 
13278 AST_THREADSTORAGE(check_auth_buf);
13279 #define CHECK_AUTH_BUF_INITLEN   256
13280 
13281 /*! \brief  Check user authorization from peer definition
13282    Some actions, like REGISTER and INVITEs from peers require
13283    authentication (if peer have secret set)
13284     \return 0 on success, non-zero on error
13285 */
13286 static enum check_auth_result check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
13287                 const char *secret, const char *md5secret, int sipmethod,
13288                 const char *uri, enum xmittype reliable, int ignore)
13289 {
13290    const char *response;
13291    char *reqheader, *respheader;
13292    const char *authtoken;
13293    char a1_hash[256];
13294    char resp_hash[256]="";
13295    char *c;
13296    int  wrongnonce = FALSE;
13297    int  good_response;
13298    const char *usednonce = p->randdata;
13299    struct ast_str *buf;
13300    int res;
13301 
13302    /* table of recognised keywords, and their value in the digest */
13303    enum keys { K_RESP, K_URI, K_USER, K_NONCE, K_LAST };
13304    struct x {
13305       const char *key;
13306       const char *s;
13307    } *i, keys[] = {
13308       [K_RESP] = { "response=", "" },
13309       [K_URI] = { "uri=", "" },
13310       [K_USER] = { "username=", "" },
13311       [K_NONCE] = { "nonce=", "" },
13312       [K_LAST] = { NULL, NULL}
13313    };
13314 
13315    /* Always OK if no secret */
13316    if (ast_strlen_zero(secret) && ast_strlen_zero(md5secret))
13317       return AUTH_SUCCESSFUL;
13318 
13319    /* Always auth with WWW-auth since we're NOT a proxy */
13320    /* Using proxy-auth in a B2BUA may block proxy authorization in the same transaction */
13321    response = "401 Unauthorized";
13322 
13323    /*
13324     * Note the apparent swap of arguments below, compared to other
13325     * usages of auth_headers().
13326     */
13327    auth_headers(WWW_AUTH, &respheader, &reqheader);
13328 
13329    authtoken =  get_header(req, reqheader);  
13330    if (ignore && !ast_strlen_zero(p->randdata) && ast_strlen_zero(authtoken)) {
13331       /* This is a retransmitted invite/register/etc, don't reconstruct authentication
13332          information */
13333       if (!reliable) {
13334          /* Resend message if this was NOT a reliable delivery.   Otherwise the
13335             retransmission should get it */
13336          transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, 0);
13337          /* Schedule auto destroy in 32 seconds (according to RFC 3261) */
13338          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13339       }
13340       return AUTH_CHALLENGE_SENT;
13341    } else if (ast_strlen_zero(p->randdata) || ast_strlen_zero(authtoken)) {
13342       /* We have no auth, so issue challenge and request authentication */
13343       set_nonce_randdata(p, 1); /* Create nonce for challenge */
13344       transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, 0);
13345       /* Schedule auto destroy in 32 seconds */
13346       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13347       return AUTH_CHALLENGE_SENT;
13348    }
13349 
13350    /* --- We have auth, so check it */
13351 
13352    /* Whoever came up with the authentication section of SIP can suck my %&#$&* for not putting
13353       an example in the spec of just what it is you're doing a hash on. */
13354 
13355    if (!(buf = ast_str_thread_get(&check_auth_buf, CHECK_AUTH_BUF_INITLEN))) {
13356       return AUTH_SECRET_FAILED; /*! XXX \todo need a better return code here */
13357    }
13358 
13359    /* Make a copy of the response and parse it */
13360    res = ast_str_set(&buf, 0, "%s", authtoken);
13361 
13362    if (res == AST_DYNSTR_BUILD_FAILED) {
13363       return AUTH_SECRET_FAILED; /*! XXX \todo need a better return code here */
13364    }
13365 
13366    c = buf->str;
13367 
13368    while(c && *(c = ast_skip_blanks(c)) ) { /* lookup for keys */
13369       for (i = keys; i->key != NULL; i++) {
13370          const char *separator = ",";  /* default */
13371 
13372          if (strncasecmp(c, i->key, strlen(i->key)) != 0) {
13373             continue;
13374          }
13375          /* Found. Skip keyword, take text in quotes or up to the separator. */
13376          c += strlen(i->key);
13377          if (*c == '"') { /* in quotes. Skip first and look for last */
13378             c++;
13379             separator = "\"";
13380          }
13381          i->s = c;
13382          strsep(&c, separator);
13383          break;
13384       }
13385       if (i->key == NULL) { /* not found, jump after space or comma */
13386          strsep(&c, " ,");
13387       }
13388    }
13389 
13390    /* Verify that digest username matches  the username we auth as */
13391    if (strcmp(username, keys[K_USER].s)) {
13392       ast_log(LOG_WARNING, "username mismatch, have <%s>, digest has <%s>\n",
13393          username, keys[K_USER].s);
13394       /* Oops, we're trying something here */
13395       return AUTH_USERNAME_MISMATCH;
13396    }
13397 
13398    /* Verify nonce from request matches our nonce, and the nonce has not already been responded to.
13399     * If this check fails, send 401 with new nonce */
13400    if (strcasecmp(p->randdata, keys[K_NONCE].s) || p->stalenonce) { /* XXX it was 'n'casecmp ? */
13401       wrongnonce = TRUE;
13402       usednonce = keys[K_NONCE].s;
13403    } else {
13404       p->stalenonce = 1; /* now, since the nonce has a response, mark it as stale so it can't be sent or responded to again */
13405    }
13406 
13407    if (!ast_strlen_zero(md5secret)) {
13408       ast_copy_string(a1_hash, md5secret, sizeof(a1_hash));
13409    } else {
13410       char a1[256];
13411 
13412       snprintf(a1, sizeof(a1), "%s:%s:%s", username, p->realm, secret);
13413       ast_md5_hash(a1_hash, a1);
13414    }
13415 
13416    /* compute the expected response to compare with what we received */
13417    {
13418       char a2[256];
13419       char a2_hash[256];
13420       char resp[256];
13421 
13422       snprintf(a2, sizeof(a2), "%s:%s", sip_methods[sipmethod].text,
13423             S_OR(keys[K_URI].s, uri));
13424       ast_md5_hash(a2_hash, a2);
13425       snprintf(resp, sizeof(resp), "%s:%s:%s", a1_hash, usednonce, a2_hash);
13426       ast_md5_hash(resp_hash, resp);
13427    }
13428 
13429    good_response = keys[K_RESP].s &&
13430          !strncasecmp(keys[K_RESP].s, resp_hash, strlen(resp_hash));
13431    if (wrongnonce) {
13432       if (good_response) {
13433          if (sipdebug)
13434             ast_log(LOG_NOTICE, "Correct auth, but based on stale nonce received from '%s'\n", get_header(req, "From"));
13435          /* We got working auth token, based on stale nonce . */
13436          set_nonce_randdata(p, 0);
13437          transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, TRUE);
13438       } else {
13439          /* Everything was wrong, so give the device one more try with a new challenge */
13440          if (!req->ignore) {
13441             if (sipdebug) {
13442                ast_log(LOG_NOTICE, "Bad authentication received from '%s'\n", get_header(req, "To"));
13443             }
13444             set_nonce_randdata(p, 1);
13445          } else {
13446             if (sipdebug) {
13447                ast_log(LOG_NOTICE, "Duplicate authentication received from '%s'\n", get_header(req, "To"));
13448             }
13449          }
13450          transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, FALSE);
13451       }
13452 
13453       /* Schedule auto destroy in 32 seconds */
13454       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13455       return AUTH_CHALLENGE_SENT;
13456    }
13457    if (good_response) {
13458       append_history(p, "AuthOK", "Auth challenge successful for %s", username);
13459       return AUTH_SUCCESSFUL;
13460    }
13461 
13462    /* Ok, we have a bad username/secret pair */
13463    /* Tell the UAS not to re-send this authentication data, because
13464       it will continue to fail
13465    */
13466 
13467    return AUTH_SECRET_FAILED;
13468 }
13469 
13470 /*! \brief Change onhold state of a peer using a pvt structure */
13471 static void sip_peer_hold(struct sip_pvt *p, int hold)
13472 {
13473    if (!p->relatedpeer) {
13474       return;
13475    }
13476 
13477    /* If they put someone on hold, increment the value... otherwise decrement it */
13478    ast_atomic_fetchadd_int(&p->relatedpeer->onHold, (hold ? +1 : -1));
13479 
13480    /* Request device state update */
13481    ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", p->relatedpeer->name);
13482    
13483    return;
13484 }
13485 
13486 /*! \brief Receive MWI events that we have subscribed to */
13487 static void mwi_event_cb(const struct ast_event *event, void *userdata)
13488 {
13489    struct sip_peer *peer = userdata;
13490 
13491    ao2_lock(peer);
13492    sip_send_mwi_to_peer(peer, event, 0);
13493    ao2_unlock(peer);
13494 }
13495 
13496 static void network_change_event_subscribe(void)
13497 {
13498    if (!network_change_event_subscription) {
13499       network_change_event_subscription = ast_event_subscribe(AST_EVENT_NETWORK_CHANGE,
13500          network_change_event_cb,
13501          "SIP Network Change ",
13502          NULL, AST_EVENT_IE_END);
13503    }
13504 }
13505 
13506 static void network_change_event_unsubscribe(void)
13507 {
13508    if (network_change_event_subscription) {
13509       network_change_event_subscription = ast_event_unsubscribe(network_change_event_subscription);
13510    }
13511 }
13512 
13513 static int network_change_event_sched_cb(const void *data)
13514 {
13515    network_change_event_sched_id = -1;
13516    sip_send_all_registers();
13517    sip_send_all_mwi_subscriptions();
13518    return 0;
13519 }
13520 
13521 static void network_change_event_cb(const struct ast_event *event, void *userdata)
13522 {
13523    ast_debug(1, "SIP, got a network change event, renewing all SIP registrations.\n");
13524    if (network_change_event_sched_id == -1) {
13525       network_change_event_sched_id = ast_sched_add(sched, 1000, network_change_event_sched_cb, NULL);
13526    }
13527 }
13528 
13529 /*! \brief Callback for the devicestate notification (SUBSCRIBE) support subsystem
13530 \note If you add an "hint" priority to the extension in the dial plan,
13531    you will get notifications on device state changes */
13532 static int cb_extensionstate(char *context, char* exten, int state, void *data)
13533 {
13534    struct sip_pvt *p = data;
13535 
13536    sip_pvt_lock(p);
13537 
13538    switch(state) {
13539    case AST_EXTENSION_DEACTIVATED:  /* Retry after a while */
13540    case AST_EXTENSION_REMOVED:   /* Extension is gone */
13541       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);  /* Delete subscription in 32 secs */
13542       ast_verb(2, "Extension state: Watcher for hint %s %s. Notify User %s\n", exten, state == AST_EXTENSION_DEACTIVATED ? "deactivated" : "removed", p->username);
13543       p->stateid = -1;
13544       p->subscribed = NONE;
13545       append_history(p, "Subscribestatus", "%s", state == AST_EXTENSION_REMOVED ? "HintRemoved" : "Deactivated");
13546       break;
13547    default: /* Tell user */
13548       p->laststate = state;
13549       break;
13550    }
13551    if (p->subscribed != NONE) {  /* Only send state NOTIFY if we know the format */
13552       if (!p->pendinginvite) {
13553          transmit_state_notify(p, state, 1, FALSE);
13554       } else {
13555          /* We already have a NOTIFY sent that is not answered. Queue the state up.
13556             if many state changes happen meanwhile, we will only send a notification of the last one */
13557          ast_set_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE);
13558       }
13559    }
13560    ast_verb(2, "Extension Changed %s[%s] new state %s for Notify User %s %s\n", exten, context, ast_extension_state2str(state), p->username,
13561          ast_test_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE) ? "(queued)" : "");
13562 
13563    sip_pvt_unlock(p);
13564 
13565    return 0;
13566 }
13567 
13568 /*! \brief Send a fake 401 Unauthorized response when the administrator
13569   wants to hide the names of local devices  from fishers
13570  */
13571 static void transmit_fake_auth_response(struct sip_pvt *p, int sipmethod, struct sip_request *req, enum xmittype reliable)
13572 {
13573    /* We have to emulate EXACTLY what we'd get with a good peer
13574     * and a bad password, or else we leak information. */
13575    const char *response = "407 Proxy Authentication Required";
13576    const char *reqheader = "Proxy-Authorization";
13577    const char *respheader = "Proxy-Authenticate";
13578    const char *authtoken;
13579    struct ast_str *buf;
13580    char *c;
13581 
13582    /* table of recognised keywords, and their value in the digest */
13583    enum keys { K_NONCE, K_LAST };
13584    struct x {
13585       const char *key;
13586       const char *s;
13587    } *i, keys[] = {
13588       [K_NONCE] = { "nonce=", "" },
13589       [K_LAST] = { NULL, NULL}
13590    };
13591 
13592    if (sipmethod == SIP_REGISTER || sipmethod == SIP_SUBSCRIBE) {
13593       response = "401 Unauthorized";
13594       reqheader = "Authorization";
13595       respheader = "WWW-Authenticate";
13596    }
13597    authtoken = get_header(req, reqheader);
13598    if (req->ignore && !ast_strlen_zero(p->randdata) && ast_strlen_zero(authtoken)) {
13599       /* This is a retransmitted invite/register/etc, don't reconstruct authentication
13600        * information */
13601       transmit_response_with_auth(p, response, req, p->randdata, 0, respheader, 0);
13602       /* Schedule auto destroy in 32 seconds (according to RFC 3261) */
13603       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13604       return;
13605    } else if (ast_strlen_zero(p->randdata) || ast_strlen_zero(authtoken)) {
13606       /* We have no auth, so issue challenge and request authentication */
13607       set_nonce_randdata(p, 1);
13608       transmit_response_with_auth(p, response, req, p->randdata, 0, respheader, 0);
13609       /* Schedule auto destroy in 32 seconds */
13610       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13611       return;
13612    }
13613 
13614    if (!(buf = ast_str_thread_get(&check_auth_buf, CHECK_AUTH_BUF_INITLEN))) {
13615       transmit_response(p, "403 Forbidden (Bad auth)", &p->initreq);
13616       return;
13617    }
13618 
13619    /* Make a copy of the response and parse it */
13620    if (ast_str_set(&buf, 0, "%s", authtoken) == AST_DYNSTR_BUILD_FAILED) {
13621       transmit_response(p, "403 Forbidden (Bad auth)", &p->initreq);
13622       return;
13623    }
13624 
13625    c = buf->str;
13626 
13627    while (c && *(c = ast_skip_blanks(c))) { /* lookup for keys */
13628       for (i = keys; i->key != NULL; i++) {
13629          const char *separator = ",";  /* default */
13630 
13631          if (strncasecmp(c, i->key, strlen(i->key)) != 0) {
13632             continue;
13633          }
13634          /* Found. Skip keyword, take text in quotes or up to the separator. */
13635          c += strlen(i->key);
13636          if (*c == '"') { /* in quotes. Skip first and look for last */
13637             c++;
13638             separator = "\"";
13639          }
13640          i->s = c;
13641          strsep(&c, separator);
13642          break;
13643       }
13644       if (i->key == NULL) { /* not found, jump after space or comma */
13645          strsep(&c, " ,");
13646       }
13647    }
13648 
13649    /* Verify nonce from request matches our nonce.  If not, send 401 with new nonce */
13650    if (strcasecmp(p->randdata, keys[K_NONCE].s)) {
13651       if (!req->ignore) {
13652          set_nonce_randdata(p, 1);
13653       }
13654       transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, FALSE);
13655 
13656       /* Schedule auto destroy in 32 seconds */
13657       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13658    } else {
13659       transmit_response(p, "403 Forbidden (Bad auth)", &p->initreq);
13660    }
13661 }
13662 
13663 /*!
13664  * Terminate the uri at the first ';' or space.
13665  * Technically we should ignore escaped space per RFC3261 (19.1.1 etc)
13666  * but don't do it for the time being. Remember the uri format is:
13667  * (User-parameters was added after RFC 3261)
13668  *\verbatim
13669  *
13670  * sip:user:password;user-parameters@host:port;uri-parameters?headers
13671  * sips:user:password;user-parameters@host:port;uri-parameters?headers
13672  *
13673  *\endverbatim
13674  * \todo As this function does not support user-parameters, it's considered broken
13675  * and needs fixing.
13676  */
13677 static char *terminate_uri(char *uri)
13678 {
13679    char *t = uri;
13680    while (*t && *t > ' ' && *t != ';') {
13681       t++;
13682    }
13683    *t = '\0';
13684    return uri;
13685 }
13686 
13687 /*! \brief Verify registration of user
13688    - Registration is done in several steps, first a REGISTER without auth
13689      to get a challenge (nonce) then a second one with auth
13690    - Registration requests are only matched with peers that are marked as "dynamic"
13691  */
13692 static enum check_auth_result register_verify(struct sip_pvt *p, struct ast_sockaddr *addr,
13693                      struct sip_request *req, const char *uri)
13694 {
13695    enum check_auth_result res = AUTH_NOT_FOUND;
13696    struct sip_peer *peer;
13697    char tmp[256];
13698    char *name = NULL, *c, *domain = NULL, *dummy = NULL;
13699    char *uri2 = ast_strdupa(uri);
13700 
13701    terminate_uri(uri2);
13702 
13703    ast_copy_string(tmp, get_header(req, "To"), sizeof(tmp));
13704 
13705    c = get_in_brackets(tmp);
13706    c = remove_uri_parameters(c);
13707 
13708    if (parse_uri(c, "sip:,sips:", &name, &dummy, &domain, NULL)) {
13709       ast_log(LOG_NOTICE, "Invalid to address: '%s' from %s (missing sip:) trying to use anyway...\n", c, ast_sockaddr_stringify_addr(addr));
13710       return -1;
13711    }
13712 
13713    SIP_PEDANTIC_DECODE(name);
13714    SIP_PEDANTIC_DECODE(domain);
13715 
13716    /*! \todo XXX here too we interpret a missing @domain as a name-only
13717     * URI, whereas the RFC says this is a domain-only uri.
13718     */
13719    if (!ast_strlen_zero(domain) && !AST_LIST_EMPTY(&domain_list)) {
13720       if (!check_sip_domain(domain, NULL, 0)) {
13721          transmit_response(p, "404 Not found (unknown domain)", &p->initreq);
13722          return AUTH_UNKNOWN_DOMAIN;
13723       }
13724    }
13725 
13726    ast_string_field_set(p, exten, name);
13727    build_contact(p);
13728    if (req->ignore) {
13729       /* Expires is a special case, where we only want to load the peer if this isn't a deregistration attempt */
13730       const char *expires = get_header(req, "Expires");
13731       int expire = atoi(expires);
13732 
13733       if (ast_strlen_zero(expires)) { /* No expires header; look in Contact */
13734          if ((expires = strcasestr(get_header(req, "Contact"), ";expires="))) {
13735             expire = atoi(expires + 9);
13736          }
13737       }
13738       if (!ast_strlen_zero(expires) && expire == 0) {
13739          transmit_response_with_date(p, "200 OK", req);
13740          return 0;
13741       }
13742    }
13743    peer = find_peer(name, NULL, TRUE, FINDPEERS, FALSE, 0);
13744 
13745    if (!(peer && ast_apply_ha(peer->ha, addr))) {
13746       /* Peer fails ACL check */
13747       if (peer) {
13748          unref_peer(peer, "register_verify: unref_peer: from find_peer operation");
13749          peer = NULL;
13750          res = AUTH_ACL_FAILED;
13751       } else {
13752          res = AUTH_NOT_FOUND;
13753       }
13754    }
13755 
13756    if (peer) {
13757       ao2_lock(peer);
13758       if (!peer->host_dynamic) {
13759          ast_log(LOG_ERROR, "Peer '%s' is trying to register, but not configured as host=dynamic\n", peer->name);
13760          res = AUTH_PEER_NOT_DYNAMIC;
13761       } else {
13762          ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_NAT_FORCE_RPORT);
13763          if (ast_test_flag(&p->flags[1], SIP_PAGE2_REGISTERTRYING))
13764             transmit_response(p, "100 Trying", req);
13765          if (!(res = check_auth(p, req, peer->name, peer->secret, peer->md5secret, SIP_REGISTER, uri2, XMIT_UNRELIABLE, req->ignore))) {
13766             if (sip_cancel_destroy(p))
13767                ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
13768 
13769             if (check_request_transport(peer, req)) {
13770                ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
13771                transmit_response_with_date(p, "403 Forbidden", req);
13772                res = AUTH_BAD_TRANSPORT;
13773             } else {
13774 
13775                /* We have a successful registration attempt with proper authentication,
13776                   now, update the peer */
13777                switch (parse_register_contact(p, peer, req)) {
13778                case PARSE_REGISTER_DENIED:
13779                   ast_log(LOG_WARNING, "Registration denied because of contact ACL\n");
13780                   transmit_response_with_date(p, "603 Denied", req);
13781                   peer->lastmsgssent = -1;
13782                   res = 0;
13783                   break;
13784                case PARSE_REGISTER_FAILED:
13785                   ast_log(LOG_WARNING, "Failed to parse contact info\n");
13786                   transmit_response_with_date(p, "400 Bad Request", req);
13787                   peer->lastmsgssent = -1;
13788                   res = 0;
13789                   break;
13790                case PARSE_REGISTER_QUERY:
13791                   ast_string_field_set(p, fullcontact, peer->fullcontact);
13792                   transmit_response_with_date(p, "200 OK", req);
13793                   peer->lastmsgssent = -1;
13794                   res = 0;
13795                   break;
13796                case PARSE_REGISTER_UPDATE:
13797                   ast_string_field_set(p, fullcontact, peer->fullcontact);
13798                   update_peer(peer, p->expiry);
13799                   /* Say OK and ask subsystem to retransmit msg counter */
13800                   transmit_response_with_date(p, "200 OK", req);
13801                   if (!ast_test_flag((&peer->flags[1]), SIP_PAGE2_SUBSCRIBEMWIONLY))
13802                      peer->lastmsgssent = -1;
13803                   res = 0;
13804                   break;
13805                }
13806             }
13807 
13808          }
13809       }
13810       ao2_unlock(peer);
13811    }
13812    if (!peer && sip_cfg.autocreatepeer) {
13813       /* Create peer if we have autocreate mode enabled */
13814       peer = temp_peer(name);
13815       if (peer) {
13816          ao2_t_link(peers, peer, "link peer into peer table");
13817          if (!ast_sockaddr_isnull(&peer->addr)) {
13818             ao2_t_link(peers_by_ip, peer, "link peer into peers-by-ip table");
13819          }
13820          ao2_lock(peer);
13821          if (sip_cancel_destroy(p))
13822             ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
13823          switch (parse_register_contact(p, peer, req)) {
13824          case PARSE_REGISTER_DENIED:
13825             ast_log(LOG_WARNING, "Registration denied because of contact ACL\n");
13826             transmit_response_with_date(p, "403 Forbidden (ACL)", req);
13827             peer->lastmsgssent = -1;
13828             res = 0;
13829             break;
13830          case PARSE_REGISTER_FAILED:
13831             ast_log(LOG_WARNING, "Failed to parse contact info\n");
13832             transmit_response_with_date(p, "400 Bad Request", req);
13833             peer->lastmsgssent = -1;
13834             res = 0;
13835             break;
13836          case PARSE_REGISTER_QUERY:
13837             ast_string_field_set(p, fullcontact, peer->fullcontact);
13838             transmit_response_with_date(p, "200 OK", req);
13839             peer->lastmsgssent = -1;
13840             res = 0;
13841             break;
13842          case PARSE_REGISTER_UPDATE:
13843             ast_string_field_set(p, fullcontact, peer->fullcontact);
13844             /* Say OK and ask subsystem to retransmit msg counter */
13845             transmit_response_with_date(p, "200 OK", req);
13846             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));
13847             peer->lastmsgssent = -1;
13848             res = 0;
13849             break;
13850          }
13851          ao2_unlock(peer);
13852       }
13853    }
13854    if (!peer && sip_cfg.alwaysauthreject) {
13855       /* If we found a peer, we transmit a 100 Trying.  Therefore, if we're
13856        * trying to avoid leaking information, we MUST also transmit the same
13857        * response when we DON'T find a peer. */
13858       transmit_response(p, "100 Trying", req);
13859       /* Insert a fake delay between the 100 and the subsequent failure. */
13860       sched_yield();
13861    }
13862    if (!res) {
13863       ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", peer->name);
13864    }
13865    if (res < 0) {
13866       switch (res) {
13867       case AUTH_SECRET_FAILED:
13868          /* Wrong password in authentication. Go away, don't try again until you fixed it */
13869          transmit_response(p, "403 Forbidden (Bad auth)", &p->initreq);
13870          if (global_authfailureevents) {
13871             const char *peer_addr = ast_strdupa(ast_sockaddr_stringify_addr(addr));
13872             const char *peer_port = ast_strdupa(ast_sockaddr_stringify_port(addr));
13873             manager_event(EVENT_FLAG_SYSTEM, "PeerStatus",
13874                      "ChannelType: SIP\r\n"
13875                      "Peer: SIP/%s\r\n"
13876                      "PeerStatus: Rejected\r\n"
13877                      "Cause: AUTH_SECRET_FAILED\r\n"
13878                      "Address: %s\r\n"
13879                      "Port: %s\r\n",
13880                      name, peer_addr, peer_port);
13881          }
13882          break;
13883       case AUTH_USERNAME_MISMATCH:
13884          /* Username and digest username does not match.
13885             Asterisk uses the From: username for authentication. We need the
13886             devices to use the same authentication user name until we support
13887             proper authentication by digest auth name */
13888       case AUTH_NOT_FOUND:
13889       case AUTH_PEER_NOT_DYNAMIC:
13890       case AUTH_ACL_FAILED:
13891          if (sip_cfg.alwaysauthreject) {
13892             transmit_fake_auth_response(p, SIP_REGISTER, &p->initreq, XMIT_UNRELIABLE);
13893             if (global_authfailureevents) {
13894                const char *peer_addr = ast_strdupa(ast_sockaddr_stringify_addr(addr));
13895                const char *peer_port = ast_strdupa(ast_sockaddr_stringify_port(addr));
13896                manager_event(EVENT_FLAG_SYSTEM, "PeerStatus",
13897                         "ChannelType: SIP\r\n"
13898                         "Peer: SIP/%s\r\n"
13899                         "PeerStatus: Rejected\r\n"
13900                         "Cause: %s\r\n"
13901                         "Address: %s\r\n"
13902                         "Port: %s\r\n",
13903                         name,
13904                         res == AUTH_PEER_NOT_DYNAMIC ? "AUTH_PEER_NOT_DYNAMIC" : "URI_NOT_FOUND",
13905                         peer_addr, peer_port);
13906             }
13907          } else {
13908             /* URI not found */
13909             if (res == AUTH_PEER_NOT_DYNAMIC) {
13910                transmit_response(p, "403 Forbidden", &p->initreq);
13911                if (global_authfailureevents) {
13912                   const char *peer_addr = ast_strdupa(ast_sockaddr_stringify_addr(addr));
13913                   const char *peer_port = ast_strdupa(ast_sockaddr_stringify_port(addr));
13914                   manager_event(EVENT_FLAG_SYSTEM, "PeerStatus",
13915                      "ChannelType: SIP\r\n"
13916                      "Peer: SIP/%s\r\n"
13917                      "PeerStatus: Rejected\r\n"
13918                      "Cause: AUTH_PEER_NOT_DYNAMIC\r\n"
13919                      "Address: %s\r\n"
13920                      "Port: %s\r\n",
13921                      name, peer_addr, peer_port);
13922                }
13923             } else {
13924                transmit_response(p, "404 Not found", &p->initreq);
13925                if (global_authfailureevents) {
13926                   const char *peer_addr = ast_strdupa(ast_sockaddr_stringify_addr(addr));
13927                   const char *peer_port = ast_strdupa(ast_sockaddr_stringify_port(addr));
13928                   manager_event(EVENT_FLAG_SYSTEM, "PeerStatus",
13929                      "ChannelType: SIP\r\n"
13930                      "Peer: SIP/%s\r\n"
13931                      "PeerStatus: Rejected\r\n"
13932                      "Cause: %s\r\n"
13933                      "Address: %s\r\n"
13934                      "Port: %s\r\n",
13935                      name,
13936                      (res == AUTH_USERNAME_MISMATCH) ? "AUTH_USERNAME_MISMATCH" : "URI_NOT_FOUND",
13937                      peer_addr, peer_port);
13938                }
13939             }
13940          }
13941          break;
13942       case AUTH_BAD_TRANSPORT:
13943       default:
13944          break;
13945       }
13946    }
13947    if (peer) {
13948       unref_peer(peer, "register_verify: unref_peer: tossing stack peer pointer at end of func");
13949    }
13950 
13951    return res;
13952 }
13953 
13954 /*! \brief Translate referring cause */
13955 static void sip_set_redirstr(struct sip_pvt *p, char *reason) {
13956 
13957    if (!strcmp(reason, "unknown")) {
13958       ast_string_field_set(p, redircause, "UNKNOWN");
13959    } else if (!strcmp(reason, "user-busy")) {
13960       ast_string_field_set(p, redircause, "BUSY");
13961    } else if (!strcmp(reason, "no-answer")) {
13962       ast_string_field_set(p, redircause, "NOANSWER");
13963    } else if (!strcmp(reason, "unavailable")) {
13964       ast_string_field_set(p, redircause, "UNREACHABLE");
13965    } else if (!strcmp(reason, "unconditional")) {
13966       ast_string_field_set(p, redircause, "UNCONDITIONAL");
13967    } else if (!strcmp(reason, "time-of-day")) {
13968       ast_string_field_set(p, redircause, "UNKNOWN");
13969    } else if (!strcmp(reason, "do-not-disturb")) {
13970       ast_string_field_set(p, redircause, "UNKNOWN");
13971    } else if (!strcmp(reason, "deflection")) {
13972       ast_string_field_set(p, redircause, "UNKNOWN");
13973    } else if (!strcmp(reason, "follow-me")) {
13974       ast_string_field_set(p, redircause, "UNKNOWN");
13975    } else if (!strcmp(reason, "out-of-service")) {
13976       ast_string_field_set(p, redircause, "UNREACHABLE");
13977    } else if (!strcmp(reason, "away")) {
13978       ast_string_field_set(p, redircause, "UNREACHABLE");
13979    } else {
13980       ast_string_field_set(p, redircause, "UNKNOWN");
13981    }
13982 }
13983 
13984 /*! \brief Parse the parts of the P-Asserted-Identity header
13985  * on an incoming packet. Returns 1 if a valid header is found
13986  * and it is different from the current caller id.
13987  */
13988 static int get_pai(struct sip_pvt *p, struct sip_request *req)
13989 {
13990    char pai[256];
13991    char privacy[64];
13992    char *cid_num = "";
13993    char *cid_name = "";
13994    int callingpres = AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
13995    char *start = NULL, *end = NULL, *uri = NULL;
13996 
13997    ast_copy_string(pai, get_header(req, "P-Asserted-Identity"), sizeof(pai));
13998 
13999    if (ast_strlen_zero(pai)) {
14000       return 0;
14001    }
14002 
14003    start = pai;
14004    if (*start == '"') {
14005       *start++ = '\0';
14006       end = strchr(start, '"');
14007       if (!end) {
14008          return 0;
14009       }
14010       *end++ = '\0';
14011       cid_name = start;
14012       start = ast_skip_blanks(end);
14013    }
14014 
14015    if (*start != '<')
14016       return 0;
14017    /* At this point, 'start' points to the URI in brackets.
14018     * We need a copy so that our comparison to the anonymous
14019     * URI is valid.
14020     */
14021    uri = ast_strdupa(start);
14022    *start++ = '\0';
14023    end = strchr(start, '@');
14024    if (!end) {
14025       return 0;
14026    }
14027    *end++ = '\0';
14028    if (!strncasecmp(uri, "sip:anonymous@anonymous.invalid", 31)) {
14029       callingpres = AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED;
14030       /*XXX Assume no change in cid_num. Perhaps it should be
14031        * blanked?
14032        */
14033       cid_num = (char *)p->cid_num;
14034    } else if (!strncasecmp(start, "sip:", 4)) {
14035       cid_num = start + 4;
14036       if (global_shrinkcallerid && ast_is_shrinkable_phonenumber(cid_num))
14037          ast_shrink_phone_number(cid_num);
14038       start = end;
14039 
14040       end = strchr(start, '>');
14041       if (!end) {
14042          return 0;
14043       }
14044       *end = '\0';
14045    } else {
14046       return 0;
14047    }
14048 
14049    ast_copy_string(privacy, get_header(req, "Privacy"), sizeof(privacy));
14050    if (!ast_strlen_zero(privacy) && strncmp(privacy, "id", 2)) {
14051       callingpres = AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED;
14052    }
14053 
14054    /* Only return true if the supplied caller id is different */
14055    if (!strcasecmp(p->cid_num, cid_num) && !strcasecmp(p->cid_name, cid_name) && p->callingpres == callingpres) {
14056       return 0;
14057    }
14058 
14059    ast_string_field_set(p, cid_num, cid_num);
14060    ast_string_field_set(p, cid_name, cid_name);
14061    p->callingpres = callingpres;
14062 
14063    if (p->owner) {
14064       ast_set_callerid(p->owner, cid_num, cid_name, NULL);
14065       p->owner->caller.id.name.presentation = callingpres;
14066       p->owner->caller.id.number.presentation = callingpres;
14067    }
14068 
14069    return 1;
14070 }
14071 
14072 /*! \brief Get name, number and presentation from remote party id header,
14073  *  returns true if a valid header was found and it was different from the
14074  *  current caller id.
14075  */
14076 static int get_rpid(struct sip_pvt *p, struct sip_request *oreq)
14077 {
14078    char tmp[256];
14079    struct sip_request *req;
14080    char *cid_num = "";
14081    char *cid_name = "";
14082    int callingpres = AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
14083    char *privacy = "";
14084    char *screen = "";
14085    char *start, *end;
14086 
14087    if (!ast_test_flag(&p->flags[0], SIP_TRUSTRPID))
14088       return 0;
14089    req = oreq;
14090    if (!req)
14091       req = &p->initreq;
14092    ast_copy_string(tmp, get_header(req, "Remote-Party-ID"), sizeof(tmp));
14093    if (ast_strlen_zero(tmp)) {
14094       return get_pai(p, req);
14095    }
14096 
14097    start = tmp;
14098    if (*start == '"') {
14099       *start++ = '\0';
14100       end = strchr(start, '"');
14101       if (!end)
14102          return 0;
14103       *end++ = '\0';
14104       cid_name = start;
14105       start = ast_skip_blanks(end);
14106    }
14107 
14108    if (*start != '<')
14109       return 0;
14110    *start++ = '\0';
14111    end = strchr(start, '@');
14112    if (!end)
14113       return 0;
14114    *end++ = '\0';
14115    if (strncasecmp(start, "sip:", 4))
14116       return 0;
14117    cid_num = start + 4;
14118    if (global_shrinkcallerid && ast_is_shrinkable_phonenumber(cid_num))
14119       ast_shrink_phone_number(cid_num);
14120    start = end;
14121 
14122    end = strchr(start, '>');
14123    if (!end)
14124       return 0;
14125    *end++ = '\0';
14126    if (*end) {
14127       start = end;
14128       if (*start != ';')
14129          return 0;
14130       *start++ = '\0';
14131       while (!ast_strlen_zero(start)) {
14132          end = strchr(start, ';');
14133          if (end)
14134             *end++ = '\0';
14135          if (!strncasecmp(start, "privacy=", 8))
14136             privacy = start + 8;
14137          else if (!strncasecmp(start, "screen=", 7))
14138             screen = start + 7;
14139          start = end;
14140       }
14141 
14142       if (!strcasecmp(privacy, "full")) {
14143          if (!strcasecmp(screen, "yes"))
14144             callingpres = AST_PRES_PROHIB_USER_NUMBER_PASSED_SCREEN;
14145          else if (!strcasecmp(screen, "no"))
14146             callingpres = AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED;
14147       } else {
14148          if (!strcasecmp(screen, "yes"))
14149             callingpres = AST_PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN;
14150          else if (!strcasecmp(screen, "no"))
14151             callingpres = AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
14152       }
14153    }
14154 
14155    /* Only return true if the supplied caller id is different */
14156    if (!strcasecmp(p->cid_num, cid_num) && !strcasecmp(p->cid_name, cid_name) && p->callingpres == callingpres)
14157       return 0;
14158 
14159    ast_string_field_set(p, cid_num, cid_num);
14160    ast_string_field_set(p, cid_name, cid_name);
14161    p->callingpres = callingpres;
14162 
14163    if (p->owner) {
14164       ast_set_callerid(p->owner, cid_num, cid_name, NULL);
14165       p->owner->caller.id.name.presentation = callingpres;
14166       p->owner->caller.id.number.presentation = callingpres;
14167    }
14168 
14169    return 1;
14170 }
14171 
14172 /*! \brief Get referring dnis */
14173 static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq, char **name, char **number, int *reason)
14174 {
14175    char tmp[256], *exten, *rexten, *rdomain, *rname = NULL;
14176    char *params, *reason_param = NULL;
14177    struct sip_request *req;
14178 
14179    req = oreq ? oreq : &p->initreq;
14180 
14181    ast_copy_string(tmp, get_header(req, "Diversion"), sizeof(tmp));
14182    if (ast_strlen_zero(tmp))
14183       return -1;
14184 
14185    if ((params = strchr(tmp, '>'))) {
14186       params = strchr(params, ';');
14187    }
14188 
14189    exten = get_in_brackets(tmp);
14190    if (!strncasecmp(exten, "sip:", 4)) {
14191       exten += 4;
14192    } else if (!strncasecmp(exten, "sips:", 5)) {
14193       exten += 5;
14194    } else {
14195       ast_log(LOG_WARNING, "Huh?  Not an RDNIS SIP header (%s)?\n", exten);
14196       return -1;
14197    }
14198 
14199    /* Get diversion-reason param if present */
14200    if (params) {
14201       *params = '\0';   /* Cut off parameters  */
14202       params++;
14203       while (*params == ';' || *params == ' ')
14204          params++;
14205       /* Check if we have a reason parameter */
14206       if ((reason_param = strcasestr(params, "reason="))) {
14207          char *end;
14208          reason_param+=7;
14209          if ((end = strchr(reason_param, ';'))) {
14210             *end = '\0';
14211          }
14212          /* Remove enclosing double-quotes */
14213          if (*reason_param == '"')
14214             ast_strip_quoted(reason_param, "\"", "\"");
14215          if (!ast_strlen_zero(reason_param)) {
14216             sip_set_redirstr(p, reason_param);
14217             if (p->owner) {
14218                pbx_builtin_setvar_helper(p->owner, "__PRIREDIRECTREASON", p->redircause);
14219                pbx_builtin_setvar_helper(p->owner, "__SIPREDIRECTREASON", reason_param);
14220             }
14221          }
14222       }
14223    }
14224 
14225    rdomain = exten;
14226    rexten = strsep(&rdomain, "@");  /* trim anything after @ */
14227    if (p->owner)
14228       pbx_builtin_setvar_helper(p->owner, "__SIPRDNISDOMAIN", rdomain);
14229 
14230    if (sip_debug_test_pvt(p))
14231       ast_verbose("RDNIS for this call is %s (reason %s)\n", exten, reason ? reason_param : "");
14232 
14233    /*ast_string_field_set(p, rdnis, rexten);*/
14234 
14235    if (*tmp == '\"') {
14236       char *end_quote;
14237       rname = tmp + 1;
14238       end_quote = strchr(rname, '\"');
14239       *end_quote = '\0';
14240    }
14241 
14242    if (number) {
14243       *number = ast_strdup(rexten);
14244    }
14245 
14246    if (name && rname) {
14247       *name = ast_strdup(rname);
14248    }
14249 
14250    if (reason && !ast_strlen_zero(reason_param)) {
14251       *reason = sip_reason_str_to_code(reason_param);
14252    }
14253 
14254    return 0;
14255 }
14256 
14257 /*! \brief Find out who the call is for.
14258    We use the request uri as a destination.
14259    This code assumes authentication has been done, so that the
14260    device (peer/user) context is already set.
14261    \return 0 on success (found a matching extension), non-zero on failure
14262 
14263   \note If the incoming uri is a SIPS: uri, we are required to carry this across
14264    the dialplan, so that the outbound call also is a sips: call or encrypted
14265    IAX2 call. If that's not available, the call should FAIL.
14266 */
14267 static enum sip_get_dest_result get_destination(struct sip_pvt *p, struct sip_request *oreq, int *cc_recall_core_id)
14268 {
14269    char tmp[256] = "", *uri, *domain, *dummy = NULL;
14270    char tmpf[256] = "", *from = NULL;
14271    struct sip_request *req;
14272    char *decoded_uri;
14273 
14274    req = oreq;
14275    if (!req) {
14276       req = &p->initreq;
14277    }
14278 
14279    /* Find the request URI */
14280    if (req->rlPart2)
14281       ast_copy_string(tmp, REQ_OFFSET_TO_STR(req, rlPart2), sizeof(tmp));
14282    
14283    uri = ast_strdupa(get_in_brackets(tmp));
14284 
14285    if (parse_uri(uri, "sip:,sips:", &uri, &dummy, &domain, NULL)) {
14286       ast_log(LOG_WARNING, "Not a SIP header (%s)?\n", uri);
14287       return SIP_GET_DEST_INVALID_URI;
14288    }
14289 
14290    SIP_PEDANTIC_DECODE(domain);
14291    SIP_PEDANTIC_DECODE(uri);
14292 
14293    ast_string_field_set(p, domain, domain);
14294 
14295    /* Now find the From: caller ID and name */
14296    /* XXX Why is this done in get_destination? Isn't it already done?
14297       Needs to be checked
14298         */
14299    ast_copy_string(tmpf, get_header(req, "From"), sizeof(tmpf));
14300    if (!ast_strlen_zero(tmpf)) {
14301       from = get_in_brackets(tmpf);
14302       if (parse_uri(from, "sip:,sips:", &from, NULL, &domain, NULL)) {
14303          ast_log(LOG_WARNING, "Not a SIP header (%s)?\n", from);
14304          return SIP_GET_DEST_INVALID_URI;
14305       }
14306 
14307       SIP_PEDANTIC_DECODE(from);
14308       SIP_PEDANTIC_DECODE(domain);
14309 
14310       ast_string_field_set(p, fromdomain, domain);
14311    }
14312 
14313    if (!AST_LIST_EMPTY(&domain_list)) {
14314       char domain_context[AST_MAX_EXTENSION];
14315 
14316       domain_context[0] = '\0';
14317       if (!check_sip_domain(p->domain, domain_context, sizeof(domain_context))) {
14318          if (!sip_cfg.allow_external_domains && (req->method == SIP_INVITE || req->method == SIP_REFER)) {
14319             ast_debug(1, "Got SIP %s to non-local domain '%s'; refusing request.\n", sip_methods[req->method].text, p->domain);
14320             return SIP_GET_DEST_REFUSED;
14321          }
14322       }
14323       /* If we don't have a peer (i.e. we're a guest call),
14324        * overwrite the original context */
14325       if (!ast_test_flag(&p->flags[1], SIP_PAGE2_HAVEPEERCONTEXT) && !ast_strlen_zero(domain_context)) {
14326          ast_string_field_set(p, context, domain_context);
14327       }
14328    }
14329 
14330    /* If the request coming in is a subscription and subscribecontext has been specified use it */
14331    if (req->method == SIP_SUBSCRIBE && !ast_strlen_zero(p->subscribecontext)) {
14332       ast_string_field_set(p, context, p->subscribecontext);
14333    }
14334 
14335    if (sip_debug_test_pvt(p)) {
14336       ast_verbose("Looking for %s in %s (domain %s)\n", uri, p->context, p->domain);
14337    }
14338 
14339    /* Since extensions.conf can have unescaped characters, try matching a
14340     * decoded uri in addition to the non-decoded uri. */
14341    decoded_uri = ast_strdupa(uri);
14342    ast_uri_decode(decoded_uri);
14343 
14344    /* If this is a subscription we actually just need to see if a hint exists for the extension */
14345    if (req->method == SIP_SUBSCRIBE) {
14346       char hint[AST_MAX_EXTENSION];
14347       int which = 0;
14348       if (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, p->context, uri) ||
14349           (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, p->context, decoded_uri) && (which = 1))) {
14350          if (!oreq) {
14351             ast_string_field_set(p, exten, which ? decoded_uri : uri);
14352          }
14353          return SIP_GET_DEST_EXTEN_FOUND;
14354       } else {
14355          return SIP_GET_DEST_EXTEN_NOT_FOUND;
14356       }
14357    } else {
14358       struct ast_cc_agent *agent;
14359       int which = 0;
14360       /* Check the dialplan for the username part of the request URI,
14361          the domain will be stored in the SIPDOMAIN variable
14362          Return 0 if we have a matching extension */
14363       if (ast_exists_extension(NULL, p->context, uri, 1, S_OR(p->cid_num, from)) ||
14364           (ast_exists_extension(NULL, p->context, decoded_uri, 1, S_OR(p->cid_num, from)) && (which = 1)) ||
14365           !strcmp(decoded_uri, ast_pickup_ext())) {
14366          if (!oreq) {
14367             ast_string_field_set(p, exten, which ? decoded_uri : uri);
14368          }
14369          return SIP_GET_DEST_EXTEN_FOUND;
14370       } else if ((agent = find_sip_cc_agent_by_notify_uri(tmp))) {
14371          struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
14372          /* This is a CC recall. We can set p's extension to the exten from
14373           * the original INVITE
14374           */
14375          ast_string_field_set(p, exten, agent_pvt->original_exten);
14376          /* And we need to let the CC core know that the caller is attempting
14377           * his recall
14378           */
14379          ast_cc_agent_recalling(agent->core_id, "SIP caller %s is attempting recall",
14380                agent->device_name);
14381          if (cc_recall_core_id) {
14382             *cc_recall_core_id = agent->core_id;
14383          }
14384          ao2_ref(agent, -1);
14385          return SIP_GET_DEST_EXTEN_FOUND;
14386       }
14387    }
14388 
14389    /* Return 1 for pickup extension or overlap dialling support (if we support it) */
14390    if((ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP) &&
14391        ast_canmatch_extension(NULL, p->context, decoded_uri, 1, S_OR(p->cid_num, from))) ||
14392        !strncmp(decoded_uri, ast_pickup_ext(), strlen(decoded_uri))) {
14393       return SIP_GET_DEST_PICKUP_EXTEN_FOUND;
14394    }
14395 
14396    return SIP_GET_DEST_EXTEN_NOT_FOUND;
14397 }
14398 
14399 /*! \brief Lock dialog lock and find matching pvt lock
14400    \return a reference, remember to release it when done
14401 */
14402 static struct sip_pvt *get_sip_pvt_byid_locked(const char *callid, const char *totag, const char *fromtag)
14403 {
14404    struct sip_pvt *sip_pvt_ptr;
14405    struct sip_pvt tmp_dialog = {
14406       .callid = callid,
14407    };
14408 
14409    if (totag) {
14410       ast_debug(4, "Looking for callid %s (fromtag %s totag %s)\n", callid, fromtag ? fromtag : "<no fromtag>", totag ? totag : "<no totag>");
14411    }
14412 
14413    /* Search dialogs and find the match */
14414    
14415    sip_pvt_ptr = ao2_t_find(dialogs, &tmp_dialog, OBJ_POINTER, "ao2_find of dialog in dialogs table");
14416    if (sip_pvt_ptr) {
14417       /* Go ahead and lock it (and its owner) before returning */
14418       sip_pvt_lock(sip_pvt_ptr);
14419       if (sip_cfg.pedanticsipchecking) {
14420          unsigned char frommismatch = 0, tomismatch = 0;
14421 
14422          if (ast_strlen_zero(fromtag)) {
14423             sip_pvt_unlock(sip_pvt_ptr);
14424             ast_debug(4, "Matched %s call for callid=%s - no from tag specified, pedantic check fails\n",
14425                  sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid);
14426             return NULL;
14427          }
14428 
14429          if (ast_strlen_zero(totag)) {
14430             sip_pvt_unlock(sip_pvt_ptr);
14431             ast_debug(4, "Matched %s call for callid=%s - no to tag specified, pedantic check fails\n",
14432                  sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid);
14433             return NULL;
14434          }
14435          /* RFC 3891
14436           * > 3.  User Agent Server Behavior: Receiving a Replaces Header
14437           * > The Replaces header contains information used to match an existing
14438           * > SIP dialog (call-id, to-tag, and from-tag).  Upon receiving an INVITE
14439           * > with a Replaces header, the User Agent (UA) attempts to match this
14440           * > information with a confirmed or early dialog.  The User Agent Server
14441           * > (UAS) matches the to-tag and from-tag parameters as if they were tags
14442           * > present in an incoming request.  In other words, the to-tag parameter
14443           * > is compared to the local tag, and the from-tag parameter is compared
14444           * > to the remote tag.
14445           *
14446           * Thus, the totag is always compared to the local tag, regardless if
14447           * this our call is an incoming or outgoing call.
14448           */
14449          frommismatch = !!strcmp(fromtag, sip_pvt_ptr->theirtag);
14450          tomismatch = !!strcmp(totag, sip_pvt_ptr->tag);
14451 
14452          if (frommismatch || tomismatch) {
14453             sip_pvt_unlock(sip_pvt_ptr);
14454             if (frommismatch) {
14455                ast_debug(4, "Matched %s call for callid=%s - pedantic from tag check fails; their tag is %s our tag is %s\n",
14456                     sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid,
14457                     fromtag, sip_pvt_ptr->theirtag);
14458             }
14459             if (tomismatch) {
14460                ast_debug(4, "Matched %s call for callid=%s - pedantic to tag check fails; their tag is %s our tag is %s\n",
14461                     sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid,
14462                     totag, sip_pvt_ptr->tag);
14463             }
14464             return NULL;
14465          }
14466       }
14467       
14468       if (totag)
14469          ast_debug(4, "Matched %s call - their tag is %s Our tag is %s\n",
14470                  sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING",
14471                  sip_pvt_ptr->theirtag, sip_pvt_ptr->tag);
14472 
14473       /* deadlock avoidance... */
14474       while (sip_pvt_ptr->owner && ast_channel_trylock(sip_pvt_ptr->owner)) {
14475          sip_pvt_unlock(sip_pvt_ptr);
14476          usleep(1);
14477          sip_pvt_lock(sip_pvt_ptr);
14478       }
14479    }
14480    
14481    return sip_pvt_ptr;
14482 }
14483 
14484 /*! \brief Call transfer support (the REFER method)
14485  *    Extracts Refer headers into pvt dialog structure
14486  *
14487  * \note If we get a SIPS uri in the refer-to header, we're required to set up a secure signalling path
14488  * to that extension. As a minimum, this needs to be added to a channel variable, if not a channel
14489  * flag.
14490  */
14491 static int get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req)
14492 {
14493 
14494    const char *p_referred_by = NULL;
14495    char *h_refer_to = NULL;
14496    char *h_referred_by = NULL;
14497    char *refer_to;
14498    const char *p_refer_to;
14499    char *referred_by_uri = NULL;
14500    char *ptr;
14501    struct sip_request *req = NULL;
14502    const char *transfer_context = NULL;
14503    struct sip_refer *referdata;
14504 
14505 
14506    req = outgoing_req;
14507    referdata = transferer->refer;
14508 
14509    if (!req) {
14510       req = &transferer->initreq;
14511    }
14512 
14513    p_refer_to = get_header(req, "Refer-To");
14514    if (ast_strlen_zero(p_refer_to)) {
14515       ast_log(LOG_WARNING, "Refer-To Header missing. Skipping transfer.\n");
14516       return -2;  /* Syntax error */
14517    }
14518    h_refer_to = ast_strdupa(p_refer_to);
14519    refer_to = get_in_brackets(h_refer_to);
14520    if (!strncasecmp(refer_to, "sip:", 4)) {
14521       refer_to += 4;       /* Skip sip: */
14522    } else if (!strncasecmp(refer_to, "sips:", 5)) {
14523       refer_to += 5;
14524    } else {
14525       ast_log(LOG_WARNING, "Can't transfer to non-sip: URI.  (Refer-to: %s)?\n", refer_to);
14526       return -3;
14527    }
14528 
14529    /* Get referred by header if it exists */
14530    p_referred_by = get_header(req, "Referred-By");
14531 
14532    /* Give useful transfer information to the dialplan */
14533    if (transferer->owner) {
14534       struct ast_channel *peer = ast_bridged_channel(transferer->owner);
14535       if (peer) {
14536          pbx_builtin_setvar_helper(peer, "SIPREFERRINGCONTEXT", transferer->context);
14537          pbx_builtin_setvar_helper(peer, "SIPREFERREDBYHDR", p_referred_by);
14538       }
14539    }
14540 
14541    if (!ast_strlen_zero(p_referred_by)) {
14542       char *lessthan;
14543       h_referred_by = ast_strdupa(p_referred_by);
14544 
14545       /* Store referrer's caller ID name */
14546       ast_copy_string(referdata->referred_by_name, h_referred_by, sizeof(referdata->referred_by_name));
14547       if ((lessthan = strchr(referdata->referred_by_name, '<'))) {
14548          *(lessthan - 1) = '\0'; /* Space */
14549       }
14550 
14551       referred_by_uri = get_in_brackets(h_referred_by);
14552 
14553       if (!strncasecmp(referred_by_uri, "sip:", 4)) {
14554          referred_by_uri += 4;      /* Skip sip: */
14555       } else if (!strncasecmp(referred_by_uri, "sips:", 5)) {
14556          referred_by_uri += 5;      /* Skip sips: */
14557       } else {
14558          ast_log(LOG_WARNING, "Huh?  Not a sip: header (Referred-by: %s). Skipping.\n", referred_by_uri);
14559          referred_by_uri = NULL;
14560       }
14561    }
14562 
14563    /* Check for arguments in the refer_to header */
14564    if ((ptr = strcasestr(refer_to, "replaces="))) {
14565       char *to = NULL, *from = NULL;
14566       
14567       /* This is an attended transfer */
14568       referdata->attendedtransfer = 1;
14569       ast_copy_string(referdata->replaces_callid, ptr+9, sizeof(referdata->replaces_callid));
14570       ast_uri_decode(referdata->replaces_callid);
14571       if ((ptr = strchr(referdata->replaces_callid, ';')))  /* Find options */ {
14572          *ptr++ = '\0';
14573       }
14574       
14575       if (ptr) {
14576          /* Find the different tags before we destroy the string */
14577          to = strcasestr(ptr, "to-tag=");
14578          from = strcasestr(ptr, "from-tag=");
14579       }
14580       
14581       /* Grab the to header */
14582       if (to) {
14583          ptr = to + 7;
14584          if ((to = strchr(ptr, '&'))) {
14585             *to = '\0';
14586          }
14587          if ((to = strchr(ptr, ';'))) {
14588             *to = '\0';
14589          }
14590          ast_copy_string(referdata->replaces_callid_totag, ptr, sizeof(referdata->replaces_callid_totag));
14591       }
14592       
14593       if (from) {
14594          ptr = from + 9;
14595          if ((to = strchr(ptr, '&'))) {
14596             *to = '\0';
14597          }
14598          if ((to = strchr(ptr, ';'))) {
14599             *to = '\0';
14600          }
14601          ast_copy_string(referdata->replaces_callid_fromtag, ptr, sizeof(referdata->replaces_callid_fromtag));
14602       }
14603       
14604       if (!sip_cfg.pedanticsipchecking) {
14605          ast_debug(2, "Attended transfer: Will use Replace-Call-ID : %s (No check of from/to tags)\n", referdata->replaces_callid );
14606       } else {
14607          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>" );
14608       }
14609    }
14610    
14611    if ((ptr = strchr(refer_to, '@'))) {   /* Separate domain */
14612       char *urioption = NULL, *domain;
14613       int bracket = 0;
14614       *ptr++ = '\0';
14615 
14616       if ((urioption = strchr(ptr, ';'))) { /* Separate urioptions */
14617          *urioption++ = '\0';
14618       }
14619 
14620       domain = ptr;
14621 
14622       /* Remove :port */
14623       for (; *ptr != '\0'; ++ptr) {
14624          if (*ptr == ':' && bracket == 0) {
14625             *ptr = '\0';
14626             break;
14627          } else if (*ptr == '[') {
14628             ++bracket;
14629          } else if (*ptr == ']') {
14630             --bracket;
14631          }
14632       }
14633 
14634       SIP_PEDANTIC_DECODE(domain);
14635       SIP_PEDANTIC_DECODE(urioption);
14636 
14637       /* Save the domain for the dial plan */
14638       ast_copy_string(referdata->refer_to_domain, domain, sizeof(referdata->refer_to_domain));
14639       if (urioption) {
14640          ast_copy_string(referdata->refer_to_urioption, urioption, sizeof(referdata->refer_to_urioption));
14641       }
14642    }
14643 
14644    if ((ptr = strchr(refer_to, ';')))  /* Remove options */
14645       *ptr = '\0';
14646 
14647    SIP_PEDANTIC_DECODE(refer_to);
14648    ast_copy_string(referdata->refer_to, refer_to, sizeof(referdata->refer_to));
14649    
14650    if (referred_by_uri) {
14651       if ((ptr = strchr(referred_by_uri, ';')))    /* Remove options */
14652          *ptr = '\0';
14653       SIP_PEDANTIC_DECODE(referred_by_uri);
14654       ast_copy_string(referdata->referred_by, referred_by_uri, sizeof(referdata->referred_by));
14655    } else {
14656       referdata->referred_by[0] = '\0';
14657    }
14658 
14659    /* Determine transfer context */
14660    if (transferer->owner)  /* Mimic behaviour in res_features.c */
14661       transfer_context = pbx_builtin_getvar_helper(transferer->owner, "TRANSFER_CONTEXT");
14662 
14663    /* By default, use the context in the channel sending the REFER */
14664    if (ast_strlen_zero(transfer_context)) {
14665       transfer_context = S_OR(transferer->owner->macrocontext,
14666                S_OR(transferer->context, sip_cfg.default_context));
14667    }
14668 
14669    ast_copy_string(referdata->refer_to_context, transfer_context, sizeof(referdata->refer_to_context));
14670    
14671    /* Either an existing extension or the parking extension */
14672    if (referdata->attendedtransfer || ast_exists_extension(NULL, transfer_context, refer_to, 1, NULL) ) {
14673       if (sip_debug_test_pvt(transferer)) {
14674          ast_verbose("SIP transfer to extension %s@%s by %s\n", refer_to, transfer_context, referred_by_uri);
14675       }
14676       /* We are ready to transfer to the extension */
14677       return 0;
14678    }
14679    if (sip_debug_test_pvt(transferer))
14680       ast_verbose("Failed SIP Transfer to non-existing extension %s in context %s\n n", refer_to, transfer_context);
14681 
14682    /* Failure, we can't find this extension */
14683    return -1;
14684 }
14685 
14686 
14687 /*! \brief Call transfer support (old way, deprecated by the IETF)
14688  * \note does not account for SIPS: uri requirements, nor check transport
14689  */
14690 static int get_also_info(struct sip_pvt *p, struct sip_request *oreq)
14691 {
14692    char tmp[256] = "", *c, *a;
14693    struct sip_request *req = oreq ? oreq : &p->initreq;
14694    struct sip_refer *referdata = NULL;
14695    const char *transfer_context = NULL;
14696    
14697    if (!p->refer && !sip_refer_allocate(p))
14698       return -1;
14699 
14700    referdata = p->refer;
14701 
14702    ast_copy_string(tmp, get_header(req, "Also"), sizeof(tmp));
14703    c = get_in_brackets(tmp);
14704 
14705    if (parse_uri(c, "sip:,sips:", &c, NULL, &a, NULL)) {
14706       ast_log(LOG_WARNING, "Huh?  Not a SIP header in Also: transfer (%s)?\n", c);
14707       return -1;
14708    }
14709    
14710    SIP_PEDANTIC_DECODE(c);
14711    SIP_PEDANTIC_DECODE(a);
14712 
14713    if (!ast_strlen_zero(a)) {
14714       ast_copy_string(referdata->refer_to_domain, a, sizeof(referdata->refer_to_domain));
14715    }
14716 
14717    if (sip_debug_test_pvt(p))
14718       ast_verbose("Looking for %s in %s\n", c, p->context);
14719 
14720    if (p->owner)  /* Mimic behaviour in res_features.c */
14721       transfer_context = pbx_builtin_getvar_helper(p->owner, "TRANSFER_CONTEXT");
14722 
14723    /* By default, use the context in the channel sending the REFER */
14724    if (ast_strlen_zero(transfer_context)) {
14725       transfer_context = S_OR(p->owner->macrocontext,
14726                S_OR(p->context, sip_cfg.default_context));
14727    }
14728    if (ast_exists_extension(NULL, transfer_context, c, 1, NULL)) {
14729       /* This is a blind transfer */
14730       ast_debug(1, "SIP Bye-also transfer to Extension %s@%s \n", c, transfer_context);
14731       ast_copy_string(referdata->refer_to, c, sizeof(referdata->refer_to));
14732       ast_copy_string(referdata->referred_by, "", sizeof(referdata->referred_by));
14733       ast_copy_string(referdata->refer_contact, "", sizeof(referdata->refer_contact));
14734       referdata->refer_call = dialog_unref(referdata->refer_call, "unreffing referdata->refer_call");
14735       /* Set new context */
14736       ast_string_field_set(p, context, transfer_context);
14737       return 0;
14738    } else if (ast_canmatch_extension(NULL, p->context, c, 1, NULL)) {
14739       return 1;
14740    }
14741 
14742    return -1;
14743 }
14744 
14745 /*! \brief check received= and rport= in a SIP response.
14746  * If we get a response with received= and/or rport= in the Via:
14747  * line, use them as 'p->ourip' (see RFC 3581 for rport,
14748  * and RFC 3261 for received).
14749  * Using these two fields SIP can produce the correct
14750  * address and port in the SIP headers without the need for STUN.
14751  * The address part is also reused for the media sessions.
14752  * Note that ast_sip_ouraddrfor() still rewrites p->ourip
14753  * if you specify externaddr/seternaddr/.
14754  */
14755 static attribute_unused void check_via_response(struct sip_pvt *p, struct sip_request *req)
14756 {
14757    char via[256];
14758    char *cur, *opts;
14759 
14760    ast_copy_string(via, get_header(req, "Via"), sizeof(via));
14761 
14762    /* Work on the leftmost value of the topmost Via header */
14763    opts = strchr(via, ',');
14764    if (opts)
14765       *opts = '\0';
14766 
14767    /* parse all relevant options */
14768    opts = strchr(via, ';');
14769    if (!opts)
14770       return;  /* no options to parse */
14771    *opts++ = '\0';
14772    while ( (cur = strsep(&opts, ";")) ) {
14773       if (!strncmp(cur, "rport=", 6)) {
14774          int port = strtol(cur+6, NULL, 10);
14775          /* XXX add error checking */
14776          ast_sockaddr_set_port(&p->ourip, port);
14777       } else if (!strncmp(cur, "received=", 9)) {
14778          if (ast_parse_arg(cur + 9, PARSE_ADDR, &p->ourip))
14779             ;  /* XXX add error checking */
14780       }
14781    }
14782 }
14783 
14784 /*! \brief check Via: header for hostname, port and rport request/answer */
14785 static void check_via(struct sip_pvt *p, struct sip_request *req)
14786 {
14787    char via[512];
14788    char *c, *maddr;
14789    struct ast_sockaddr tmp;
14790    uint16_t port;
14791 
14792    ast_copy_string(via, get_header(req, "Via"), sizeof(via));
14793 
14794    /* Work on the leftmost value of the topmost Via header */
14795    c = strchr(via, ',');
14796    if (c)
14797       *c = '\0';
14798 
14799    /* Check for rport */
14800    c = strstr(via, ";rport");
14801    if (c && (c[6] != '=')) { /* rport query, not answer */
14802       ast_set_flag(&p->flags[1], SIP_PAGE2_RPORT_PRESENT);
14803       ast_set_flag(&p->flags[0], SIP_NAT_RPORT_PRESENT);
14804    }
14805 
14806    /* Check for maddr */
14807    maddr = strstr(via, "maddr=");
14808    if (maddr) {
14809       maddr += 6;
14810       c = maddr + strspn(maddr, "abcdefghijklmnopqrstuvwxyz"
14811                       "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-.:[]");
14812       *c = '\0';
14813    }
14814 
14815    c = strchr(via, ';');
14816    if (c)
14817       *c = '\0';
14818 
14819    c = strchr(via, ' ');
14820    if (c) {
14821       *c = '\0';
14822       c = ast_skip_blanks(c+1);
14823       if (strcasecmp(via, "SIP/2.0/UDP") && strcasecmp(via, "SIP/2.0/TCP") && strcasecmp(via, "SIP/2.0/TLS")) {
14824          ast_log(LOG_WARNING, "Don't know how to respond via '%s'\n", via);
14825          return;
14826       }
14827 
14828       if (maddr && ast_sockaddr_resolve_first(&p->sa, maddr, 0)) {
14829          p->sa = p->recv;
14830       }
14831 
14832       ast_sockaddr_resolve_first(&tmp, c, 0);
14833       port = ast_sockaddr_port(&tmp);
14834       ast_sockaddr_set_port(&p->sa,
14835                   port != 0 ? port : STANDARD_SIP_PORT);
14836 
14837       if (sip_debug_test_pvt(p)) {
14838          ast_verbose("Sending to %s (%s)\n",
14839                 ast_sockaddr_stringify(sip_real_dst(p)),
14840                 sip_nat_mode(p));
14841       }
14842    }
14843 }
14844 
14845 /*! \brief Validate device authentication */
14846 static enum check_auth_result check_peer_ok(struct sip_pvt *p, char *of,
14847    struct sip_request *req, int sipmethod, struct ast_sockaddr *addr,
14848    struct sip_peer **authpeer,
14849    enum xmittype reliable, char *calleridname, char *uri2)
14850 {
14851    enum check_auth_result res;
14852    int debug = sip_debug_test_addr(addr);
14853    struct sip_peer *peer;
14854 
14855    if (sipmethod == SIP_SUBSCRIBE) {
14856       /* For subscribes, match on device name only; for other methods,
14857       * match on IP address-port of the incoming request.
14858       */
14859       peer = find_peer(of, NULL, TRUE, FINDALLDEVICES, FALSE, 0);
14860    } else {
14861       /* First find devices based on username (avoid all type=peer's) */
14862       peer = find_peer(of, NULL, TRUE, FINDUSERS, FALSE, 0);
14863 
14864       /* Then find devices based on IP */
14865       if (!peer) {
14866          peer = find_peer(NULL, &p->recv, TRUE, FINDPEERS, FALSE, p->socket.type);
14867       }
14868    }
14869 
14870    if (!peer) {
14871       if (debug) {
14872          ast_verbose("No matching peer for '%s' from '%s'\n",
14873             of, ast_sockaddr_stringify(&p->recv));
14874       }
14875       return AUTH_DONT_KNOW;
14876    }
14877 
14878    if (!ast_apply_ha(peer->ha, addr)) {
14879       ast_debug(2, "Found peer '%s' for '%s', but fails host access\n", peer->name, of);
14880       unref_peer(peer, "unref_peer: check_peer_ok: from find_peer call, early return of AUTH_ACL_FAILED");
14881       return AUTH_ACL_FAILED;
14882    }
14883    if (debug)
14884       ast_verbose("Found peer '%s' for '%s' from %s\n",
14885          peer->name, of, ast_sockaddr_stringify(&p->recv));
14886 
14887    /* XXX what about p->prefs = peer->prefs; ? */
14888    /* Set Frame packetization */
14889    if (p->rtp) {
14890       ast_rtp_codecs_packetization_set(ast_rtp_instance_get_codecs(p->rtp), p->rtp, &peer->prefs);
14891       p->autoframing = peer->autoframing;
14892    }
14893 
14894    /* Take the peer */
14895    ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
14896    ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
14897    ast_copy_flags(&p->flags[2], &peer->flags[2], SIP_PAGE3_FLAGS_TO_COPY);
14898 
14899    if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) && p->udptl) {
14900       p->t38_maxdatagram = peer->t38_maxdatagram;
14901       set_t38_capabilities(p);
14902    }
14903 
14904    /* Copy SIP extensions profile to peer */
14905    /* XXX is this correct before a successful auth ? */
14906    if (p->sipoptions)
14907       peer->sipoptions = p->sipoptions;
14908 
14909    do_setnat(p);
14910 
14911    ast_string_field_set(p, peersecret, peer->secret);
14912    ast_string_field_set(p, peermd5secret, peer->md5secret);
14913    ast_string_field_set(p, subscribecontext, peer->subscribecontext);
14914    ast_string_field_set(p, mohinterpret, peer->mohinterpret);
14915    ast_string_field_set(p, mohsuggest, peer->mohsuggest);
14916    if (!ast_strlen_zero(peer->parkinglot)) {
14917       ast_string_field_set(p, parkinglot, peer->parkinglot);
14918    }
14919    ast_string_field_set(p, engine, peer->engine);
14920    p->disallowed_methods = peer->disallowed_methods;
14921    set_pvt_allowed_methods(p, req);
14922    ast_cc_copy_config_params(p->cc_params, peer->cc_params);
14923    if (peer->callingpres)  /* Peer calling pres setting will override RPID */
14924       p->callingpres = peer->callingpres;
14925    if (peer->maxms && peer->lastms)
14926       p->timer_t1 = peer->lastms < global_t1min ? global_t1min : peer->lastms;
14927    else
14928       p->timer_t1 = peer->timer_t1;
14929 
14930    /* Set timer B to control transaction timeouts */
14931    if (peer->timer_b)
14932       p->timer_b = peer->timer_b;
14933    else
14934       p->timer_b = 64 * p->timer_t1;
14935 
14936    if (ast_test_flag(&peer->flags[0], SIP_INSECURE_INVITE)) {
14937       /* Pretend there is no required authentication */
14938       ast_string_field_set(p, peersecret, NULL);
14939       ast_string_field_set(p, peermd5secret, NULL);
14940    }
14941    if (!(res = check_auth(p, req, peer->name, p->peersecret, p->peermd5secret, sipmethod, uri2, reliable, req->ignore))) {
14942       ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
14943       ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
14944       ast_copy_flags(&p->flags[2], &peer->flags[2], SIP_PAGE3_FLAGS_TO_COPY);
14945       /* If we have a call limit, set flag */
14946       if (peer->call_limit)
14947          ast_set_flag(&p->flags[0], SIP_CALL_LIMIT);
14948       ast_string_field_set(p, peername, peer->name);
14949       ast_string_field_set(p, authname, peer->name);
14950 
14951       if (sipmethod == SIP_INVITE) {
14952          /* copy channel vars */
14953          p->chanvars = copy_vars(peer->chanvars);
14954       }
14955 
14956       if (authpeer) {
14957          ao2_t_ref(peer, 1, "copy pointer into (*authpeer)");
14958          (*authpeer) = peer;  /* Add a ref to the object here, to keep it in memory a bit longer if it is realtime */
14959       }
14960 
14961       if (!ast_strlen_zero(peer->username)) {
14962          ast_string_field_set(p, username, peer->username);
14963          /* Use the default username for authentication on outbound calls */
14964          /* XXX this takes the name from the caller... can we override ? */
14965          ast_string_field_set(p, authname, peer->username);
14966       }
14967       if (!get_rpid(p, req)) {
14968          if (!ast_strlen_zero(peer->cid_num)) {
14969             char *tmp = ast_strdupa(peer->cid_num);
14970             if (global_shrinkcallerid && ast_is_shrinkable_phonenumber(tmp))
14971                ast_shrink_phone_number(tmp);
14972             ast_string_field_set(p, cid_num, tmp);
14973          }
14974          if (!ast_strlen_zero(peer->cid_name))
14975             ast_string_field_set(p, cid_name, peer->cid_name);
14976          if (!ast_strlen_zero(peer->cid_tag))
14977             ast_string_field_set(p, cid_tag, peer->cid_tag);
14978          if (peer->callingpres)
14979             p->callingpres = peer->callingpres;
14980       }
14981       ast_string_field_set(p, fullcontact, peer->fullcontact);
14982       if (!ast_strlen_zero(peer->context))
14983          ast_string_field_set(p, context, peer->context);
14984       ast_string_field_set(p, peersecret, peer->secret);
14985       ast_string_field_set(p, peermd5secret, peer->md5secret);
14986       ast_string_field_set(p, language, peer->language);
14987       ast_string_field_set(p, accountcode, peer->accountcode);
14988       p->amaflags = peer->amaflags;
14989       p->callgroup = peer->callgroup;
14990       p->pickupgroup = peer->pickupgroup;
14991       p->capability = peer->capability;
14992       p->prefs = peer->prefs;
14993       p->jointcapability = peer->capability;
14994       if (peer->maxforwards > 0) {
14995          p->maxforwards = peer->maxforwards;
14996       }
14997       if (p->peercapability)
14998          p->jointcapability &= p->peercapability;
14999       p->maxcallbitrate = peer->maxcallbitrate;
15000       if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
15001           (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
15002          p->noncodeccapability |= AST_RTP_DTMF;
15003       else
15004          p->noncodeccapability &= ~AST_RTP_DTMF;
15005       p->jointnoncodeccapability = p->noncodeccapability;
15006       if (!dialog_initialize_rtp(p)) {
15007          if (p->rtp) {
15008             ast_rtp_codecs_packetization_set(ast_rtp_instance_get_codecs(p->rtp), p->rtp, &peer->prefs);
15009             p->autoframing = peer->autoframing;
15010          }
15011       } else {
15012          res = AUTH_RTP_FAILED;
15013       }
15014    }
15015    unref_peer(peer, "check_peer_ok: unref_peer: tossing temp ptr to peer from find_peer");
15016    return res;
15017 }
15018 
15019 
15020 /*! \brief  Check if matching user or peer is defined
15021    Match user on From: user name and peer on IP/port
15022    This is used on first invite (not re-invites) and subscribe requests
15023     \return 0 on success, non-zero on failure
15024 */
15025 static enum check_auth_result check_user_full(struct sip_pvt *p, struct sip_request *req,
15026                      int sipmethod, const char *uri, enum xmittype reliable,
15027                      struct ast_sockaddr *addr, struct sip_peer **authpeer)
15028 {
15029    char from[256] = { 0, };
15030    char *dummy = NULL;  /* dummy return value for parse_uri */
15031    char *domain = NULL; /* dummy return value for parse_uri */
15032    char *of;
15033    enum check_auth_result res = AUTH_DONT_KNOW;
15034    char calleridname[50];
15035    char *uri2 = ast_strdupa(uri);
15036 
15037    terminate_uri(uri2); /* trim extra stuff */
15038 
15039    ast_copy_string(from, get_header(req, "From"), sizeof(from));
15040    /* XXX here tries to map the username for invite things */
15041    memset(calleridname, 0, sizeof(calleridname));
15042 
15043    /* strip the display-name portion off the beginning of the FROM header. */
15044    if (!(of = (char *) get_calleridname(from, calleridname, sizeof(calleridname)))) {
15045       ast_log(LOG_ERROR, "FROM header can not be parsed \n");
15046       return res;
15047    }
15048 
15049    if (calleridname[0])
15050       ast_string_field_set(p, cid_name, calleridname);
15051 
15052    if (ast_strlen_zero(p->exten)) {
15053       char *t = uri2;
15054       if (!strncasecmp(t, "sip:", 4))
15055          t+= 4;
15056       else if (!strncasecmp(t, "sips:", 5))
15057          t += 5;
15058       ast_string_field_set(p, exten, t);
15059       t = strchr(p->exten, '@');
15060       if (t)
15061          *t = '\0';
15062 
15063       if (ast_strlen_zero(p->our_contact))
15064          build_contact(p);
15065    }
15066 
15067    of = get_in_brackets(of);
15068 
15069    /* save the URI part of the From header */
15070    ast_string_field_set(p, from, of);
15071 
15072    /* ignore all fields but name */
15073    if (parse_uri(of, "sip:,sips:", &of, &dummy, &domain, NULL)) {
15074       ast_log(LOG_NOTICE, "From address missing 'sip:', using it anyway\n");
15075    }
15076 
15077    SIP_PEDANTIC_DECODE(of);
15078    SIP_PEDANTIC_DECODE(domain);
15079 
15080    if (ast_strlen_zero(of)) {
15081       /* XXX note: the original code considered a missing @host
15082        * as a username-only URI. The SIP RFC (19.1.1) says that
15083        * this is wrong, and it should be considered as a domain-only URI.
15084        * For backward compatibility, we keep this block, but it is
15085        * really a mistake and should go away.
15086        */
15087       of = domain;
15088    } else {
15089       char *tmp = ast_strdupa(of);
15090       /* We need to be able to handle auth-headers looking like
15091          <sip:8164444422;phone-context=+1@1.2.3.4:5060;user=phone;tag=SDadkoa01-gK0c3bdb43>
15092       */
15093       tmp = strsep(&tmp, ";");
15094       if (global_shrinkcallerid && ast_is_shrinkable_phonenumber(tmp))
15095          ast_shrink_phone_number(tmp);
15096       ast_string_field_set(p, cid_num, tmp);
15097    }
15098 
15099    if (global_match_auth_username) {
15100       /*
15101        * XXX This is experimental code to grab the search key from the
15102        * Auth header's username instead of the 'From' name, if available.
15103        * Do not enable this block unless you understand the side effects (if any!)
15104        * Note, the search for "username" should be done in a more robust way.
15105        * Note2, at the moment we check both fields, though maybe we should
15106        * pick one or another depending on the request ? XXX
15107        */
15108       const char *hdr = get_header(req, "Authorization");
15109       if (ast_strlen_zero(hdr))
15110          hdr = get_header(req, "Proxy-Authorization");
15111 
15112       if ( !ast_strlen_zero(hdr) && (hdr = strstr(hdr, "username=\"")) ) {
15113          ast_copy_string(from, hdr + strlen("username=\""), sizeof(from));
15114          of = from;
15115          of = strsep(&of, "\"");
15116       }
15117    }
15118 
15119    res = check_peer_ok(p, of, req, sipmethod, addr,
15120          authpeer, reliable, calleridname, uri2);
15121    if (res != AUTH_DONT_KNOW)
15122       return res;
15123 
15124    /* Finally, apply the guest policy */
15125    if (sip_cfg.allowguest) {
15126       get_rpid(p, req);
15127       if (!dialog_initialize_rtp(p)) {
15128          res = AUTH_SUCCESSFUL;
15129       } else {
15130          res = AUTH_RTP_FAILED;
15131       }
15132    } else if (sip_cfg.alwaysauthreject)
15133       res = AUTH_FAKE_AUTH; /* reject with fake authorization request */
15134    else
15135       res = AUTH_SECRET_FAILED; /* we don't want any guests, authentication will fail */
15136 
15137 
15138    if (ast_test_flag(&p->flags[1], SIP_PAGE2_RPORT_PRESENT)) {
15139       ast_set_flag(&p->flags[0], SIP_NAT_RPORT_PRESENT);
15140    }
15141 
15142    return res;
15143 }
15144 
15145 /*! \brief  Find user
15146    If we get a match, this will add a reference pointer to the user object in ASTOBJ, that needs to be unreferenced
15147 */
15148 static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, const char *uri, enum xmittype reliable, struct ast_sockaddr *addr)
15149 {
15150    return check_user_full(p, req, sipmethod, uri, reliable, addr, NULL);
15151 }
15152 
15153 /*! \brief  Get text out of a SIP MESSAGE packet */
15154 static int get_msg_text(char *buf, int len, struct sip_request *req, int addnewline)
15155 {
15156    int x;
15157    int y;
15158 
15159    buf[0] = '\0';
15160    /*XXX isn't strlen(buf) going to always be 0? */
15161    y = len - strlen(buf) - 5;
15162    if (y < 0)
15163       y = 0;
15164    for (x = 0; x < req->lines; x++) {
15165       const char *line = REQ_OFFSET_TO_STR(req, line[x]);
15166       strncat(buf, line, y); /* safe */
15167       y -= strlen(line) + 1;
15168       if (y < 0)
15169          y = 0;
15170       if (y != 0 && addnewline)
15171          strcat(buf, "\n"); /* safe */
15172    }
15173    return 0;
15174 }
15175 
15176 
15177 /*! \brief  Receive SIP MESSAGE method messages
15178 \note We only handle messages within current calls currently
15179    Reference: RFC 3428 */
15180 static void receive_message(struct sip_pvt *p, struct sip_request *req)
15181 {
15182    char buf[1400];   
15183    struct ast_frame f;
15184    const char *content_type = get_header(req, "Content-Type");
15185 
15186    if (strncmp(content_type, "text/plain", strlen("text/plain"))) { /* No text/plain attachment */
15187       transmit_response(p, "415 Unsupported Media Type", req); /* Good enough, or? */
15188       if (!p->owner)
15189          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
15190       return;
15191    }
15192 
15193    if (get_msg_text(buf, sizeof(buf), req, FALSE)) {
15194       ast_log(LOG_WARNING, "Unable to retrieve text from %s\n", p->callid);
15195       transmit_response(p, "202 Accepted", req);
15196       if (!p->owner)
15197          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
15198       return;
15199    }
15200 
15201    if (p->owner) {
15202       if (sip_debug_test_pvt(p))
15203          ast_verbose("SIP Text message received: '%s'\n", buf);
15204       memset(&f, 0, sizeof(f));
15205       f.frametype = AST_FRAME_TEXT;
15206       f.subclass.integer = 0;
15207       f.offset = 0;
15208       f.data.ptr = buf;
15209       f.datalen = strlen(buf);
15210       ast_queue_frame(p->owner, &f);
15211       transmit_response(p, "202 Accepted", req); /* We respond 202 accepted, since we relay the message */
15212       return;
15213    }
15214 
15215    /* Message outside of a call, we do not support that */
15216    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);
15217    transmit_response(p, "405 Method Not Allowed", req);
15218    sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
15219    return;
15220 }
15221 
15222 /*! \brief  CLI Command to show calls within limits set by call_limit */
15223 static char *sip_show_inuse(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15224 {
15225 #define FORMAT "%-25.25s %-15.15s %-15.15s \n"
15226 #define FORMAT2 "%-25.25s %-15.15s %-15.15s \n"
15227    char ilimits[40];
15228    char iused[40];
15229    int showall = FALSE;
15230    struct ao2_iterator i;
15231    struct sip_peer *peer;
15232    
15233    switch (cmd) {
15234    case CLI_INIT:
15235       e->command = "sip show inuse";
15236       e->usage =
15237          "Usage: sip show inuse [all]\n"
15238          "       List all SIP devices usage counters and limits.\n"
15239          "       Add option \"all\" to show all devices, not only those with a limit.\n";
15240       return NULL;
15241    case CLI_GENERATE:
15242       return NULL;
15243    }
15244 
15245    if (a->argc < 3)
15246       return CLI_SHOWUSAGE;
15247 
15248    if (a->argc == 4 && !strcmp(a->argv[3], "all"))
15249       showall = TRUE;
15250    
15251    ast_cli(a->fd, FORMAT, "* Peer name", "In use", "Limit");
15252 
15253    i = ao2_iterator_init(peers, 0);
15254    while ((peer = ao2_t_iterator_next(&i, "iterate thru peer table"))) {
15255       ao2_lock(peer);
15256       if (peer->call_limit)
15257          snprintf(ilimits, sizeof(ilimits), "%d", peer->call_limit);
15258       else
15259          ast_copy_string(ilimits, "N/A", sizeof(ilimits));
15260       snprintf(iused, sizeof(iused), "%d/%d/%d", peer->inUse, peer->inRinging, peer->onHold);
15261       if (showall || peer->call_limit)
15262          ast_cli(a->fd, FORMAT2, peer->name, iused, ilimits);
15263       ao2_unlock(peer);
15264       unref_peer(peer, "toss iterator pointer");
15265    }
15266    ao2_iterator_destroy(&i);
15267 
15268    return CLI_SUCCESS;
15269 #undef FORMAT
15270 #undef FORMAT2
15271 }
15272 
15273 
15274 /*! \brief Convert transfer mode to text string */
15275 static char *transfermode2str(enum transfermodes mode)
15276 {
15277    if (mode == TRANSFER_OPENFORALL)
15278       return "open";
15279    else if (mode == TRANSFER_CLOSED)
15280       return "closed";
15281    return "strict";
15282 }
15283 
15284 /*! \brief  Report Peer status in character string
15285  *  \return 0 if peer is unreachable, 1 if peer is online, -1 if unmonitored
15286  */
15287 
15288 
15289 /* Session-Timer Modes */
15290 static const struct _map_x_s stmodes[] = {
15291         { SESSION_TIMER_MODE_ACCEPT,    "Accept"},
15292         { SESSION_TIMER_MODE_ORIGINATE, "Originate"},
15293         { SESSION_TIMER_MODE_REFUSE,    "Refuse"},
15294         { -1,                           NULL},
15295 };
15296 
15297 static const char *stmode2str(enum st_mode m)
15298 {
15299    return map_x_s(stmodes, m, "Unknown");
15300 }
15301 
15302 static enum st_mode str2stmode(const char *s)
15303 {
15304    return map_s_x(stmodes, s, -1);
15305 }
15306 
15307 /* Session-Timer Refreshers */
15308 static const struct _map_x_s strefreshers[] = {
15309         { SESSION_TIMER_REFRESHER_AUTO,     "auto"},
15310         { SESSION_TIMER_REFRESHER_UAC,      "uac"},
15311         { SESSION_TIMER_REFRESHER_UAS,      "uas"},
15312         { -1,                               NULL},
15313 };
15314 
15315 static const char *strefresher2str(enum st_refresher r)
15316 {
15317    return map_x_s(strefreshers, r, "Unknown");
15318 }
15319 
15320 static enum st_refresher str2strefresher(const char *s)
15321 {
15322    return map_s_x(strefreshers, s, -1);
15323 }
15324 
15325 
15326 static int peer_status(struct sip_peer *peer, char *status, int statuslen)
15327 {
15328    int res = 0;
15329    if (peer->maxms) {
15330       if (peer->lastms < 0) {
15331          ast_copy_string(status, "UNREACHABLE", statuslen);
15332       } else if (peer->lastms > peer->maxms) {
15333          snprintf(status, statuslen, "LAGGED (%d ms)", peer->lastms);
15334          res = 1;
15335       } else if (peer->lastms) {
15336          snprintf(status, statuslen, "OK (%d ms)", peer->lastms);
15337          res = 1;
15338       } else {
15339          ast_copy_string(status, "UNKNOWN", statuslen);
15340       }
15341    } else {
15342       ast_copy_string(status, "Unmonitored", statuslen);
15343       /* Checking if port is 0 */
15344       res = -1;
15345    }
15346    return res;
15347 }
15348 
15349 /*! \brief  Show active TCP connections */
15350 static char *sip_show_tcp(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15351 {
15352    struct sip_threadinfo *th;
15353    struct ao2_iterator i;
15354 
15355 #define FORMAT2 "%-47.47s %9.9s %6.6s\n"
15356 #define FORMAT  "%-47.47s %-9.9s %-6.6s\n"
15357 
15358    switch (cmd) {
15359    case CLI_INIT:
15360       e->command = "sip show tcp";
15361       e->usage =
15362          "Usage: sip show tcp\n"
15363          "       Lists all active TCP/TLS sessions.\n";
15364       return NULL;
15365    case CLI_GENERATE:
15366       return NULL;
15367    }
15368 
15369    if (a->argc != 3)
15370       return CLI_SHOWUSAGE;
15371 
15372    ast_cli(a->fd, FORMAT2, "Address", "Transport", "Type");
15373 
15374    i = ao2_iterator_init(threadt, 0);
15375    while ((th = ao2_t_iterator_next(&i, "iterate through tcp threads for 'sip show tcp'"))) {
15376       ast_cli(a->fd, FORMAT,
15377          ast_sockaddr_stringify(&th->tcptls_session->remote_address),
15378          get_transport(th->type),
15379          (th->tcptls_session->client ? "Client" : "Server"));
15380       ao2_t_ref(th, -1, "decrement ref from iterator");
15381    }
15382    ao2_iterator_destroy(&i);
15383 
15384    return CLI_SUCCESS;
15385 #undef FORMAT
15386 #undef FORMAT2
15387 }
15388 
15389 /*! \brief  CLI Command 'SIP Show Users' */
15390 static char *sip_show_users(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15391 {
15392    regex_t regexbuf;
15393    int havepattern = FALSE;
15394    struct ao2_iterator user_iter;
15395    struct sip_peer *user;
15396 
15397 #define FORMAT  "%-25.25s  %-15.15s  %-15.15s  %-15.15s  %-5.5s%-10.10s\n"
15398 
15399    switch (cmd) {
15400    case CLI_INIT:
15401       e->command = "sip show users";
15402       e->usage =
15403          "Usage: sip show users [like <pattern>]\n"
15404          "       Lists all known SIP users.\n"
15405          "       Optional regular expression pattern is used to filter the user list.\n";
15406       return NULL;
15407    case CLI_GENERATE:
15408       return NULL;
15409    }
15410 
15411    switch (a->argc) {
15412    case 5:
15413       if (!strcasecmp(a->argv[3], "like")) {
15414          if (regcomp(&regexbuf, a->argv[4], REG_EXTENDED | REG_NOSUB))
15415             return CLI_SHOWUSAGE;
15416          havepattern = TRUE;
15417       } else
15418          return CLI_SHOWUSAGE;
15419    case 3:
15420       break;
15421    default:
15422       return CLI_SHOWUSAGE;
15423    }
15424 
15425    ast_cli(a->fd, FORMAT, "Username", "Secret", "Accountcode", "Def.Context", "ACL", "ForcerPort");
15426 
15427    user_iter = ao2_iterator_init(peers, 0);
15428    while ((user = ao2_iterator_next(&user_iter))) {
15429       ao2_lock(user);
15430       if (!(user->type & SIP_TYPE_USER)) {
15431          ao2_unlock(user);
15432          unref_peer(user, "sip show users");
15433          continue;
15434       }
15435 
15436       if (havepattern && regexec(&regexbuf, user->name, 0, NULL, 0)) {
15437          ao2_unlock(user);
15438          unref_peer(user, "sip show users");
15439          continue;
15440       }
15441 
15442       ast_cli(a->fd, FORMAT, user->name,
15443          user->secret,
15444          user->accountcode,
15445          user->context,
15446          AST_CLI_YESNO(user->ha != NULL),
15447          AST_CLI_YESNO(ast_test_flag(&user->flags[0], SIP_NAT_FORCE_RPORT)));
15448       ao2_unlock(user);
15449       unref_peer(user, "sip show users");
15450    }
15451    ao2_iterator_destroy(&user_iter);
15452 
15453    if (havepattern)
15454       regfree(&regexbuf);
15455 
15456    return CLI_SUCCESS;
15457 #undef FORMAT
15458 }
15459 
15460 /*! \brief Show SIP registrations in the manager API */
15461 static int manager_show_registry(struct mansession *s, const struct message *m)
15462 {
15463    const char *id = astman_get_header(m, "ActionID");
15464    char idtext[256] = "";
15465    int total = 0;
15466 
15467    if (!ast_strlen_zero(id))
15468       snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
15469 
15470    astman_send_listack(s, m, "Registrations will follow", "start");
15471 
15472    ASTOBJ_CONTAINER_TRAVERSE(&regl, 1, do {
15473       ASTOBJ_RDLOCK(iterator);
15474       astman_append(s,
15475          "Event: RegistryEntry\r\n"
15476          "%s"
15477          "Host: %s\r\n"
15478          "Port: %d\r\n"
15479          "Username: %s\r\n"
15480          "Domain: %s\r\n"
15481          "DomainPort: %d\r\n"
15482          "Refresh: %d\r\n"
15483          "State: %s\r\n"
15484          "RegistrationTime: %ld\r\n"
15485          "\r\n",
15486          idtext,
15487          iterator->hostname,
15488          iterator->portno ? iterator->portno : STANDARD_SIP_PORT,
15489          iterator->username,
15490          S_OR(iterator->regdomain,iterator->hostname),
15491          iterator->regdomainport ? iterator->regdomainport : STANDARD_SIP_PORT,
15492          iterator->refresh,
15493          regstate2str(iterator->regstate),
15494          (long) iterator->regtime.tv_sec);
15495       ASTOBJ_UNLOCK(iterator);
15496       total++;
15497    } while(0));
15498 
15499    astman_append(s,
15500       "Event: RegistrationsComplete\r\n"
15501       "EventList: Complete\r\n"
15502       "ListItems: %d\r\n"
15503       "%s"
15504       "\r\n", total, idtext);
15505    
15506    return 0;
15507 }
15508 
15509 /*! \brief  Show SIP peers in the manager API */
15510 /*    Inspired from chan_iax2 */
15511 static int manager_sip_show_peers(struct mansession *s, const struct message *m)
15512 {
15513    const char *id = astman_get_header(m, "ActionID");
15514    const char *a[] = {"sip", "show", "peers"};
15515    char idtext[256] = "";
15516    int total = 0;
15517 
15518    if (!ast_strlen_zero(id))
15519       snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
15520 
15521    astman_send_listack(s, m, "Peer status list will follow", "start");
15522    /* List the peers in separate manager events */
15523    _sip_show_peers(-1, &total, s, m, 3, a);
15524    /* Send final confirmation */
15525    astman_append(s,
15526    "Event: PeerlistComplete\r\n"
15527    "EventList: Complete\r\n"
15528    "ListItems: %d\r\n"
15529    "%s"
15530    "\r\n", total, idtext);
15531    return 0;
15532 }
15533 
15534 /*! \brief  CLI Show Peers command */
15535 static char *sip_show_peers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15536 {
15537    switch (cmd) {
15538    case CLI_INIT:
15539       e->command = "sip show peers";
15540       e->usage =
15541          "Usage: sip show peers [like <pattern>]\n"
15542          "       Lists all known SIP peers.\n"
15543          "       Optional regular expression pattern is used to filter the peer list.\n";
15544       return NULL;
15545    case CLI_GENERATE:
15546       return NULL;
15547    }
15548 
15549    return _sip_show_peers(a->fd, NULL, NULL, NULL, a->argc, (const char **) a->argv);
15550 }
15551 
15552 int peercomparefunc(const void *a, const void *b);
15553 
15554 int peercomparefunc(const void *a, const void *b)
15555 {
15556    struct sip_peer **ap = (struct sip_peer **)a;
15557    struct sip_peer **bp = (struct sip_peer **)b;
15558    return strcmp((*ap)->name, (*bp)->name);
15559 }
15560 
15561 
15562 /*! \brief Execute sip show peers command */
15563 static char *_sip_show_peers(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char *argv[])
15564 {
15565    regex_t regexbuf;
15566    int havepattern = FALSE;
15567    struct sip_peer *peer;
15568    struct ao2_iterator i;
15569    
15570 /* the last argument is left-aligned, so we don't need a size anyways */
15571 #define FORMAT2 "%-25.25s  %-39.39s %-3.3s %-10.10s %-3.3s %-8s %-10s %s\n"
15572 #define FORMAT  "%-25.25s  %-39.39s %-3.3s %-3.3s %-3.3s %-8d %-10s %s\n"
15573 
15574    char name[256];
15575    int total_peers = 0;
15576    int peers_mon_online = 0;
15577    int peers_mon_offline = 0;
15578    int peers_unmon_offline = 0;
15579    int peers_unmon_online = 0;
15580    const char *id;
15581    char idtext[256] = "";
15582    int realtimepeers;
15583    int objcount = ao2_container_count(peers);
15584    struct sip_peer **peerarray;
15585    int k;
15586    
15587    
15588    realtimepeers = ast_check_realtime("sippeers");
15589    peerarray = ast_calloc(sizeof(struct sip_peer *), objcount);
15590 
15591    if (s) { /* Manager - get ActionID */
15592       id = astman_get_header(m, "ActionID");
15593       if (!ast_strlen_zero(id))
15594          snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
15595    }
15596 
15597    switch (argc) {
15598    case 5:
15599       if (!strcasecmp(argv[3], "like")) {
15600          if (regcomp(&regexbuf, argv[4], REG_EXTENDED | REG_NOSUB))
15601             return CLI_SHOWUSAGE;
15602          havepattern = TRUE;
15603       } else
15604          return CLI_SHOWUSAGE;
15605    case 3:
15606       break;
15607    default:
15608       return CLI_SHOWUSAGE;
15609    }
15610 
15611    if (!s) /* Normal list */
15612       ast_cli(fd, FORMAT2, "Name/username", "Host", "Dyn", "Forcerport", "ACL", "Port", "Status", (realtimepeers ? "Realtime" : ""));
15613    
15614 
15615    i = ao2_iterator_init(peers, 0);
15616    while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {  
15617       ao2_lock(peer);
15618 
15619       if (!(peer->type & SIP_TYPE_PEER)) {
15620          ao2_unlock(peer);
15621          unref_peer(peer, "unref peer because it's actually a user");
15622          continue;
15623       }
15624 
15625       if (havepattern && regexec(&regexbuf, peer->name, 0, NULL, 0)) {
15626          objcount--;
15627          ao2_unlock(peer);
15628          unref_peer(peer, "toss iterator peer ptr before continue");
15629          continue;
15630       }
15631 
15632       peerarray[total_peers++] = peer;
15633       ao2_unlock(peer);
15634    }
15635    ao2_iterator_destroy(&i);
15636    
15637    qsort(peerarray, total_peers, sizeof(struct sip_peer *), peercomparefunc);
15638 
15639    for(k=0; k < total_peers; k++) {
15640       char status[20] = "";
15641       char srch[2000];
15642       char pstatus;
15643       peer = peerarray[k];
15644       
15645       ao2_lock(peer);
15646       if (havepattern && regexec(&regexbuf, peer->name, 0, NULL, 0)) {
15647          ao2_unlock(peer);
15648          unref_peer(peer, "toss iterator peer ptr before continue");
15649          continue;
15650       }
15651 
15652       if (!ast_strlen_zero(peer->username) && !s)
15653          snprintf(name, sizeof(name), "%s/%s", peer->name, peer->username);
15654       else
15655          ast_copy_string(name, peer->name, sizeof(name));
15656       
15657       pstatus = peer_status(peer, status, sizeof(status));
15658       if (pstatus == 1)
15659          peers_mon_online++;
15660       else if (pstatus == 0)
15661          peers_mon_offline++;
15662       else {
15663          if (ast_sockaddr_isnull(&peer->addr) ||
15664              !ast_sockaddr_port(&peer->addr)) {
15665             peers_unmon_offline++;
15666          } else {
15667             peers_unmon_online++;
15668          }
15669       }
15670 
15671       snprintf(srch, sizeof(srch), FORMAT, name,
15672          ast_sockaddr_isnull(&peer->addr) ? "(Unspecified)" : ast_sockaddr_stringify_addr(&peer->addr),
15673          peer->host_dynamic ? " D " : "   ",    /* Dynamic or not? */
15674          ast_test_flag(&peer->flags[0], SIP_NAT_FORCE_RPORT) ? " N " : "   ", /* NAT=yes? */
15675          peer->ha ? " A " : "   ",  /* permit/deny */
15676          ast_sockaddr_isnull(&peer->addr) ? 0 : ast_sockaddr_port(&peer->addr), status,
15677          realtimepeers ? (peer->is_realtime ? "Cached RT":"") : "");
15678 
15679       if (!s)  {/* Normal CLI list */
15680          ast_cli(fd, FORMAT, name,
15681          ast_sockaddr_isnull(&peer->addr) ? "(Unspecified)" : ast_sockaddr_stringify_addr(&peer->addr),
15682          peer->host_dynamic ? " D " : "   ",    /* Dynamic or not? */
15683          ast_test_flag(&peer->flags[0], SIP_NAT_FORCE_RPORT) ? " N " : "   ", /* NAT=yes? */
15684          peer->ha ? " A " : "   ",       /* permit/deny */
15685          ast_sockaddr_isnull(&peer->addr) ? 0 : ast_sockaddr_port(&peer->addr), status,
15686          realtimepeers ? (peer->is_realtime ? "Cached RT":"") : "");
15687       } else { /* Manager format */
15688          /* The names here need to be the same as other channels */
15689          astman_append(s,
15690          "Event: PeerEntry\r\n%s"
15691          "Channeltype: SIP\r\n"
15692          "ObjectName: %s\r\n"
15693          "ChanObjectType: peer\r\n" /* "peer" or "user" */
15694          "IPaddress: %s\r\n"
15695          "IPport: %d\r\n"
15696          "Dynamic: %s\r\n"
15697          "Forcerport: %s\r\n"
15698          "VideoSupport: %s\r\n"
15699          "TextSupport: %s\r\n"
15700          "ACL: %s\r\n"
15701          "Status: %s\r\n"
15702          "RealtimeDevice: %s\r\n\r\n",
15703          idtext,
15704          peer->name,
15705          ast_sockaddr_isnull(&peer->addr) ? "-none-" : ast_sockaddr_stringify(&peer->addr),
15706          ast_sockaddr_isnull(&peer->addr) ? 0 : ast_sockaddr_port(&peer->addr),
15707          peer->host_dynamic ? "yes" : "no",  /* Dynamic or not? */
15708          ast_test_flag(&peer->flags[0], SIP_NAT_FORCE_RPORT) ? "yes" : "no",  /* NAT=yes? */
15709          ast_test_flag(&peer->flags[1], SIP_PAGE2_VIDEOSUPPORT) ? "yes" : "no",  /* VIDEOSUPPORT=yes? */
15710          ast_test_flag(&peer->flags[1], SIP_PAGE2_TEXTSUPPORT) ? "yes" : "no",   /* TEXTSUPPORT=yes? */
15711          peer->ha ? "yes" : "no",       /* permit/deny */
15712          status,
15713          realtimepeers ? (peer->is_realtime ? "yes":"no") : "no");
15714       }
15715       ao2_unlock(peer);
15716       unref_peer(peer, "toss iterator peer ptr");
15717    }
15718    
15719    if (!s)
15720       ast_cli(fd, "%d sip peers [Monitored: %d online, %d offline Unmonitored: %d online, %d offline]\n",
15721               total_peers, peers_mon_online, peers_mon_offline, peers_unmon_online, peers_unmon_offline);
15722 
15723    if (havepattern)
15724       regfree(&regexbuf);
15725 
15726    if (total)
15727       *total = total_peers;
15728    
15729    ast_free(peerarray);
15730    
15731    return CLI_SUCCESS;
15732 #undef FORMAT
15733 #undef FORMAT2
15734 }
15735 
15736 static int peer_dump_func(void *userobj, void *arg, int flags)
15737 {
15738    struct sip_peer *peer = userobj;
15739    int refc = ao2_t_ref(userobj, 0, "");
15740    struct ast_cli_args *a = (struct ast_cli_args *) arg;
15741    
15742    ast_cli(a->fd, "name: %s\ntype: peer\nobjflags: %d\nrefcount: %d\n\n",
15743       peer->name, 0, refc);
15744    return 0;
15745 }
15746 
15747 static int dialog_dump_func(void *userobj, void *arg, int flags)
15748 {
15749    struct sip_pvt *pvt = userobj;
15750    int refc = ao2_t_ref(userobj, 0, "");
15751    struct ast_cli_args *a = (struct ast_cli_args *) arg;
15752    
15753    ast_cli(a->fd, "name: %s\ntype: dialog\nobjflags: %d\nrefcount: %d\n\n",
15754       pvt->callid, 0, refc);
15755    return 0;
15756 }
15757 
15758 
15759 /*! \brief List all allocated SIP Objects (realtime or static) */
15760 static char *sip_show_objects(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15761 {
15762    char tmp[256];
15763    
15764    switch (cmd) {
15765    case CLI_INIT:
15766       e->command = "sip show objects";
15767       e->usage =
15768          "Usage: sip show objects\n"
15769          "       Lists status of known SIP objects\n";
15770       return NULL;
15771    case CLI_GENERATE:
15772       return NULL;
15773    }  
15774 
15775    if (a->argc != 3)
15776       return CLI_SHOWUSAGE;
15777    ast_cli(a->fd, "-= Peer objects: %d static, %d realtime, %d autocreate =-\n\n", speerobjs, rpeerobjs, apeerobjs);
15778    ao2_t_callback(peers, OBJ_NODATA, peer_dump_func, a, "initiate ao2_callback to dump peers");
15779    ast_cli(a->fd, "-= Registry objects: %d =-\n\n", regobjs);
15780    ASTOBJ_CONTAINER_DUMP(a->fd, tmp, sizeof(tmp), &regl);
15781    ast_cli(a->fd, "-= Dialog objects:\n\n");
15782    ao2_t_callback(dialogs, OBJ_NODATA, dialog_dump_func, a, "initiate ao2_callback to dump dialogs");
15783    return CLI_SUCCESS;
15784 }
15785 /*! \brief Print call group and pickup group */
15786 static void print_group(int fd, ast_group_t group, int crlf)
15787 {
15788    char buf[256];
15789    ast_cli(fd, crlf ? "%s\r\n" : "%s\n", ast_print_group(buf, sizeof(buf), group) );
15790 }
15791 
15792 /*! \brief mapping between dtmf flags and strings */
15793 static const struct _map_x_s dtmfstr[] = {
15794    { SIP_DTMF_RFC2833,     "rfc2833" },
15795    { SIP_DTMF_INFO,        "info" },
15796    { SIP_DTMF_SHORTINFO,   "shortinfo" },
15797    { SIP_DTMF_INBAND,      "inband" },
15798    { SIP_DTMF_AUTO,        "auto" },
15799    { -1,                   NULL }, /* terminator */
15800 };
15801 
15802 /*! \brief Convert DTMF mode to printable string */
15803 static const char *dtmfmode2str(int mode)
15804 {
15805    return map_x_s(dtmfstr, mode, "<error>");
15806 }
15807 
15808 /*! \brief maps a string to dtmfmode, returns -1 on error */
15809 static int str2dtmfmode(const char *str)
15810 {
15811    return map_s_x(dtmfstr, str, -1);
15812 }
15813 
15814 static const struct _map_x_s insecurestr[] = {
15815    { SIP_INSECURE_PORT,    "port" },
15816    { SIP_INSECURE_INVITE,  "invite" },
15817    { SIP_INSECURE_PORT | SIP_INSECURE_INVITE, "port,invite" },
15818    { 0,                    "no" },
15819    { -1,                   NULL }, /* terminator */
15820 };
15821 
15822 /*! \brief Convert Insecure setting to printable string */
15823 static const char *insecure2str(int mode)
15824 {
15825    return map_x_s(insecurestr, mode, "<error>");
15826 }
15827 
15828 /*! \brief Destroy disused contexts between reloads
15829    Only used in reload_config so the code for regcontext doesn't get ugly
15830 */
15831 static void cleanup_stale_contexts(char *new, char *old)
15832 {
15833    char *oldcontext, *newcontext, *stalecontext, *stringp, newlist[AST_MAX_CONTEXT];
15834 
15835    while ((oldcontext = strsep(&old, "&"))) {
15836       stalecontext = '\0';
15837       ast_copy_string(newlist, new, sizeof(newlist));
15838       stringp = newlist;
15839       while ((newcontext = strsep(&stringp, "&"))) {
15840          if (!strcmp(newcontext, oldcontext)) {
15841             /* This is not the context you're looking for */
15842             stalecontext = '\0';
15843             break;
15844          } else if (strcmp(newcontext, oldcontext)) {
15845             stalecontext = oldcontext;
15846          }
15847          
15848       }
15849       if (stalecontext)
15850          ast_context_destroy(ast_context_find(stalecontext), "SIP");
15851    }
15852 }
15853 
15854 /*!
15855  * \brief Match dialogs that need to be destroyed
15856  *
15857  * \details This is used with ao2_callback to unlink/delete all dialogs that
15858  * are marked needdestroy. It will return CMP_MATCH for candidates, and they
15859  * will be unlinked.
15860  *
15861  * \todo Re-work this to improve efficiency.  Currently, this function is called
15862  * on _every_ dialog after processing _every_ incoming SIP/UDP packet, or
15863  * potentially even more often when the scheduler has entries to run.
15864  */
15865 
15866 static int dialog_needdestroy(void *dialogobj, void *arg, int flags)
15867 {
15868    struct sip_pvt *dialog = dialogobj;
15869    time_t *t = arg;
15870 
15871    if (sip_pvt_trylock(dialog)) {
15872       /* Don't block the monitor thread.  This function is called often enough
15873        * that we can wait for the next time around. */
15874       return 0;
15875    }
15876 
15877    /* We absolutely cannot destroy the rtp struct while a bridge is active or we WILL crash */
15878    if (dialog->rtp && ast_rtp_instance_get_bridged(dialog->rtp)) {
15879       ast_debug(2, "Bridge still active.  Delaying destroy of SIP dialog '%s' Method: %s\n", dialog->callid, sip_methods[dialog->method].text);
15880       sip_pvt_unlock(dialog);
15881       return 0;
15882    }
15883 
15884    if (dialog->vrtp && ast_rtp_instance_get_bridged(dialog->vrtp)) {
15885       ast_debug(2, "Bridge still active.  Delaying destroy of SIP dialog '%s' Method: %s\n", dialog->callid, sip_methods[dialog->method].text);
15886       sip_pvt_unlock(dialog);
15887       return 0;
15888    }
15889 
15890    /* Check RTP timeouts and kill calls if we have a timeout set and do not get RTP */
15891    check_rtp_timeout(dialog, *t);
15892 
15893    /* If we have sessions that needs to be destroyed, do it now */
15894    /* Check if we have outstanding requests not responsed to or an active call
15895       - if that's the case, wait with destruction */
15896    if (dialog->needdestroy && !dialog->packets && !dialog->owner) {
15897       /* We absolutely cannot destroy the rtp struct while a bridge is active or we WILL crash */
15898       if (dialog->rtp && ast_rtp_instance_get_bridged(dialog->rtp)) {
15899          ast_debug(2, "Bridge still active.  Delaying destruction of SIP dialog '%s' Method: %s\n", dialog->callid, sip_methods[dialog->method].text);
15900          sip_pvt_unlock(dialog);
15901          return 0;
15902       }
15903       
15904       if (dialog->vrtp && ast_rtp_instance_get_bridged(dialog->vrtp)) {
15905          ast_debug(2, "Bridge still active.  Delaying destroy of SIP dialog '%s' Method: %s\n", dialog->callid, sip_methods[dialog->method].text);
15906          sip_pvt_unlock(dialog);
15907          return 0;
15908       }
15909 
15910       sip_pvt_unlock(dialog);
15911       /* no, the unlink should handle this: dialog_unref(dialog, "needdestroy: one more refcount decrement to allow dialog to be destroyed"); */
15912       /* the CMP_MATCH will unlink this dialog from the dialog hash table */
15913       dialog_unlink_all(dialog, TRUE, FALSE);
15914       return 0; /* the unlink_all should unlink this from the table, so.... no need to return a match */
15915    }
15916 
15917    sip_pvt_unlock(dialog);
15918 
15919    return 0;
15920 }
15921 
15922 /*! \brief Remove temporary realtime objects from memory (CLI) */
15923 /*! \todo XXXX Propably needs an overhaul after removal of the devices */
15924 static char *sip_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15925 {
15926    struct sip_peer *peer, *pi;
15927    int prunepeer = FALSE;
15928    int multi = FALSE;
15929    const char *name = NULL;
15930    regex_t regexbuf;
15931    struct ao2_iterator i;
15932    static const char * const choices[] = { "all", "like", NULL };
15933    char *cmplt;
15934    
15935    if (cmd == CLI_INIT) {
15936       e->command = "sip prune realtime [peer|all]";
15937       e->usage =
15938          "Usage: sip prune realtime [peer [<name>|all|like <pattern>]|all]\n"
15939          "       Prunes object(s) from the cache.\n"
15940          "       Optional regular expression pattern is used to filter the objects.\n";
15941       return NULL;
15942    } else if (cmd == CLI_GENERATE) {
15943       if (a->pos == 4 && !strcasecmp(a->argv[3], "peer")) {
15944          cmplt = ast_cli_complete(a->word, choices, a->n);
15945          if (!cmplt)
15946             cmplt = complete_sip_peer(a->word, a->n - sizeof(choices), SIP_PAGE2_RTCACHEFRIENDS);
15947          return cmplt;
15948       }
15949       if (a->pos == 5 && !strcasecmp(a->argv[4], "like"))
15950          return complete_sip_peer(a->word, a->n, SIP_PAGE2_RTCACHEFRIENDS);
15951       return NULL;
15952    }
15953    switch (a->argc) {
15954    case 4:
15955       name = a->argv[3];
15956       /* we accept a name in position 3, but keywords are not good. */
15957       if (!strcasecmp(name, "peer") || !strcasecmp(name, "like"))
15958          return CLI_SHOWUSAGE;
15959       prunepeer = TRUE;
15960       if (!strcasecmp(name, "all")) {
15961          multi = TRUE;
15962          name = NULL;
15963       }
15964       /* else a single name, already set */
15965       break;
15966    case 5:
15967       /* sip prune realtime {peer|like} name */
15968       name = a->argv[4];
15969       if (!strcasecmp(a->argv[3], "peer"))
15970          prunepeer = TRUE;
15971       else if (!strcasecmp(a->argv[3], "like")) {
15972          prunepeer = TRUE;
15973          multi = TRUE;
15974       } else
15975          return CLI_SHOWUSAGE;
15976       if (!strcasecmp(name, "like"))
15977          return CLI_SHOWUSAGE;
15978       if (!multi && !strcasecmp(name, "all")) {
15979          multi = TRUE;
15980          name = NULL;
15981       }
15982       break;
15983    case 6:
15984       name = a->argv[5];
15985       multi = TRUE;
15986       /* sip prune realtime {peer} like name */
15987       if (strcasecmp(a->argv[4], "like"))
15988          return CLI_SHOWUSAGE;
15989       if (!strcasecmp(a->argv[3], "peer")) {
15990          prunepeer = TRUE;
15991       } else
15992          return CLI_SHOWUSAGE;
15993       break;
15994    default:
15995       return CLI_SHOWUSAGE;
15996    }
15997 
15998    if (multi && name) {
15999       if (regcomp(&regexbuf, name, REG_EXTENDED | REG_NOSUB))
16000          return CLI_SHOWUSAGE;
16001    }
16002 
16003    if (multi) {
16004       if (prunepeer) {
16005          int pruned = 0;
16006          
16007          i = ao2_iterator_init(peers, 0);
16008          while ((pi = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
16009             ao2_lock(pi);
16010             if (name && regexec(&regexbuf, pi->name, 0, NULL, 0)) {
16011                unref_peer(pi, "toss iterator peer ptr before continue");
16012                ao2_unlock(pi);
16013                continue;
16014             };
16015             if (ast_test_flag(&pi->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
16016                pi->the_mark = 1;
16017                pruned++;
16018             }
16019             ao2_unlock(pi);
16020             unref_peer(pi, "toss iterator peer ptr");
16021          }
16022          ao2_iterator_destroy(&i);
16023          if (pruned) {
16024             unlink_marked_peers_from_tables();
16025             ast_cli(a->fd, "%d peers pruned.\n", pruned);
16026          } else
16027             ast_cli(a->fd, "No peers found to prune.\n");
16028       }
16029    } else {
16030       if (prunepeer) {
16031          struct sip_peer tmp;
16032          ast_copy_string(tmp.name, name, sizeof(tmp.name));
16033          if ((peer = ao2_t_find(peers, &tmp, OBJ_POINTER | OBJ_UNLINK, "finding to unlink from peers"))) {
16034             if (!ast_sockaddr_isnull(&peer->addr)) {
16035                ao2_t_unlink(peers_by_ip, peer, "unlinking peer from peers_by_ip also");
16036             }
16037             if (!ast_test_flag(&peer->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
16038                ast_cli(a->fd, "Peer '%s' is not a Realtime peer, cannot be pruned.\n", name);
16039                /* put it back! */
16040                ao2_t_link(peers, peer, "link peer into peer table");
16041                if (!ast_sockaddr_isnull(&peer->addr)) {
16042                   ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
16043                }
16044             } else
16045                ast_cli(a->fd, "Peer '%s' pruned.\n", name);
16046             unref_peer(peer, "sip_prune_realtime: unref_peer: tossing temp peer ptr");
16047          } else
16048             ast_cli(a->fd, "Peer '%s' not found.\n", name);
16049       }
16050    }
16051 
16052    return CLI_SUCCESS;
16053 }
16054 
16055 /*! \brief Print codec list from preference to CLI/manager */
16056 static void print_codec_to_cli(int fd, struct ast_codec_pref *pref)
16057 {
16058    int x;
16059    format_t codec;
16060 
16061    for(x = 0; x < 64 ; x++) {
16062       codec = ast_codec_pref_index(pref, x);
16063       if (!codec)
16064          break;
16065       ast_cli(fd, "%s", ast_getformatname(codec));
16066       ast_cli(fd, ":%d", pref->framing[x]);
16067       if (x < 31 && ast_codec_pref_index(pref, x + 1))
16068          ast_cli(fd, ",");
16069    }
16070    if (!x)
16071       ast_cli(fd, "none");
16072 }
16073 
16074 /*! \brief Print domain mode to cli */
16075 static const char *domain_mode_to_text(const enum domain_mode mode)
16076 {
16077    switch (mode) {
16078    case SIP_DOMAIN_AUTO:
16079       return "[Automatic]";
16080    case SIP_DOMAIN_CONFIG:
16081       return "[Configured]";
16082    }
16083 
16084    return "";
16085 }
16086 
16087 /*! \brief CLI command to list local domains */
16088 static char *sip_show_domains(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16089 {
16090    struct domain *d;
16091 #define FORMAT "%-40.40s %-20.20s %-16.16s\n"
16092 
16093    switch (cmd) {
16094    case CLI_INIT:
16095       e->command = "sip show domains";
16096       e->usage =
16097          "Usage: sip show domains\n"
16098          "       Lists all configured SIP local domains.\n"
16099          "       Asterisk only responds to SIP messages to local domains.\n";
16100       return NULL;
16101    case CLI_GENERATE:
16102       return NULL;
16103    }
16104 
16105    if (AST_LIST_EMPTY(&domain_list)) {
16106       ast_cli(a->fd, "SIP Domain support not enabled.\n\n");
16107       return CLI_SUCCESS;
16108    } else {
16109       ast_cli(a->fd, FORMAT, "Our local SIP domains:", "Context", "Set by");
16110       AST_LIST_LOCK(&domain_list);
16111       AST_LIST_TRAVERSE(&domain_list, d, list)
16112          ast_cli(a->fd, FORMAT, d->domain, S_OR(d->context, "(default)"),
16113             domain_mode_to_text(d->mode));
16114       AST_LIST_UNLOCK(&domain_list);
16115       ast_cli(a->fd, "\n");
16116       return CLI_SUCCESS;
16117    }
16118 }
16119 #undef FORMAT
16120 
16121 /*! \brief Show SIP peers in the manager API  */
16122 static int manager_sip_show_peer(struct mansession *s, const struct message *m)
16123 {
16124    const char *a[4];
16125    const char *peer;
16126 
16127    peer = astman_get_header(m, "Peer");
16128    if (ast_strlen_zero(peer)) {
16129       astman_send_error(s, m, "Peer: <name> missing.");
16130       return 0;
16131    }
16132    a[0] = "sip";
16133    a[1] = "show";
16134    a[2] = "peer";
16135    a[3] = peer;
16136 
16137    _sip_show_peer(1, -1, s, m, 4, a);
16138    astman_append(s, "\r\n\r\n" );
16139    return 0;
16140 }
16141 
16142 /*! \brief Show one peer in detail */
16143 static char *sip_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16144 {
16145    switch (cmd) {
16146    case CLI_INIT:
16147       e->command = "sip show peer";
16148       e->usage =
16149          "Usage: sip show peer <name> [load]\n"
16150          "       Shows all details on one SIP peer and the current status.\n"
16151          "       Option \"load\" forces lookup of peer in realtime storage.\n";
16152       return NULL;
16153    case CLI_GENERATE:
16154       return complete_sip_show_peer(a->line, a->word, a->pos, a->n);
16155    }
16156    return _sip_show_peer(0, a->fd, NULL, NULL, a->argc, (const char **) a->argv);
16157 }
16158 
16159 /*! \brief Send qualify message to peer from cli or manager. Mostly for debugging. */
16160 static char *_sip_qualify_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[])
16161 {
16162    struct sip_peer *peer;
16163    int load_realtime;
16164 
16165    if (argc < 4)
16166       return CLI_SHOWUSAGE;
16167 
16168    load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? TRUE : FALSE;
16169    if ((peer = find_peer(argv[3], NULL, load_realtime, FINDPEERS, FALSE, 0))) {
16170       sip_poke_peer(peer, 1);
16171       unref_peer(peer, "qualify: done with peer");
16172    } else if (type == 0) {
16173       ast_cli(fd, "Peer '%s' not found\n", argv[3]);
16174    } else {
16175       astman_send_error(s, m, "Peer not found");
16176    }
16177    return CLI_SUCCESS;
16178 }
16179 
16180 /*! \brief Qualify SIP peers in the manager API  */
16181 static int manager_sip_qualify_peer(struct mansession *s, const struct message *m)
16182 {
16183    const char *a[4];
16184    const char *peer;
16185 
16186    peer = astman_get_header(m, "Peer");
16187    if (ast_strlen_zero(peer)) {
16188       astman_send_error(s, m, "Peer: <name> missing.");
16189       return 0;
16190    }
16191    a[0] = "sip";
16192    a[1] = "qualify";
16193    a[2] = "peer";
16194    a[3] = peer;
16195 
16196    _sip_qualify_peer(1, -1, s, m, 4, a);
16197    astman_append(s, "\r\n\r\n" );
16198    return 0;
16199 }
16200 
16201 /*! \brief Send an OPTIONS packet to a SIP peer */
16202 static char *sip_qualify_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16203 {
16204    switch (cmd) {
16205    case CLI_INIT:
16206       e->command = "sip qualify peer";
16207       e->usage =
16208          "Usage: sip qualify peer <name> [load]\n"
16209          "       Requests a response from one SIP peer and the current status.\n"
16210          "       Option \"load\" forces lookup of peer in realtime storage.\n";
16211       return NULL;
16212    case CLI_GENERATE:
16213       return complete_sip_show_peer(a->line, a->word, a->pos, a->n);
16214    }
16215    return _sip_qualify_peer(0, a->fd, NULL, NULL, a->argc, (const char **) a->argv);
16216 }
16217 
16218 /*! \brief list peer mailboxes to CLI */
16219 static void peer_mailboxes_to_str(struct ast_str **mailbox_str, struct sip_peer *peer)
16220 {
16221    struct sip_mailbox *mailbox;
16222 
16223    AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
16224       ast_str_append(mailbox_str, 0, "%s%s%s%s",
16225          mailbox->mailbox,
16226          ast_strlen_zero(mailbox->context) ? "" : "@",
16227          S_OR(mailbox->context, ""),
16228          AST_LIST_NEXT(mailbox, entry) ? "," : "");
16229    }
16230 }
16231 
16232 static struct _map_x_s faxecmodes[] = {
16233    { SIP_PAGE2_T38SUPPORT_UDPTL,       "None"},
16234    { SIP_PAGE2_T38SUPPORT_UDPTL_FEC,      "FEC"},
16235    { SIP_PAGE2_T38SUPPORT_UDPTL_REDUNDANCY,  "Redundancy"},
16236    { -1,                NULL},
16237 };
16238 
16239 static const char *faxec2str(int faxec)
16240 {
16241    return map_x_s(faxecmodes, faxec, "Unknown");
16242 }
16243 
16244 /*! \brief Show one peer in detail (main function) */
16245 static char *_sip_show_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[])
16246 {
16247    char status[30] = "";
16248    char cbuf[256];
16249    struct sip_peer *peer;
16250    char codec_buf[512];
16251    struct ast_codec_pref *pref;
16252    struct ast_variable *v;
16253    struct sip_auth *auth;
16254    int x = 0, load_realtime;
16255    format_t codec = 0;
16256    int realtimepeers;
16257 
16258    realtimepeers = ast_check_realtime("sippeers");
16259 
16260    if (argc < 4)
16261       return CLI_SHOWUSAGE;
16262 
16263    load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? TRUE : FALSE;
16264    peer = find_peer(argv[3], NULL, load_realtime, FINDPEERS, FALSE, 0);
16265 
16266    if (s) {    /* Manager */
16267       if (peer) {
16268          const char *id = astman_get_header(m, "ActionID");
16269 
16270          astman_append(s, "Response: Success\r\n");
16271          if (!ast_strlen_zero(id))
16272             astman_append(s, "ActionID: %s\r\n", id);
16273       } else {
16274          snprintf (cbuf, sizeof(cbuf), "Peer %s not found.", argv[3]);
16275          astman_send_error(s, m, cbuf);
16276          return CLI_SUCCESS;
16277       }
16278    }
16279    if (peer && type==0 ) { /* Normal listing */
16280       struct ast_str *mailbox_str = ast_str_alloca(512);
16281       ast_cli(fd, "\n\n");
16282       ast_cli(fd, "  * Name       : %s\n", peer->name);
16283       if (realtimepeers) { /* Realtime is enabled */
16284          ast_cli(fd, "  Realtime peer: %s\n", peer->is_realtime ? "Yes, cached" : "No");
16285       }
16286       ast_cli(fd, "  Secret       : %s\n", ast_strlen_zero(peer->secret)?"<Not set>":"<Set>");
16287       ast_cli(fd, "  MD5Secret    : %s\n", ast_strlen_zero(peer->md5secret)?"<Not set>":"<Set>");
16288       ast_cli(fd, "  Remote Secret: %s\n", ast_strlen_zero(peer->remotesecret)?"<Not set>":"<Set>");
16289       for (auth = peer->auth; auth; auth = auth->next) {
16290          ast_cli(fd, "  Realm-auth   : Realm %-15.15s User %-10.20s ", auth->realm, auth->username);
16291          ast_cli(fd, "%s\n", !ast_strlen_zero(auth->secret)?"<Secret set>":(!ast_strlen_zero(auth->md5secret)?"<MD5secret set>" : "<Not set>"));
16292       }
16293       ast_cli(fd, "  Context      : %s\n", peer->context);
16294       ast_cli(fd, "  Subscr.Cont. : %s\n", S_OR(peer->subscribecontext, "<Not set>") );
16295       ast_cli(fd, "  Language     : %s\n", peer->language);
16296       if (!ast_strlen_zero(peer->accountcode))
16297          ast_cli(fd, "  Accountcode  : %s\n", peer->accountcode);
16298       ast_cli(fd, "  AMA flags    : %s\n", ast_cdr_flags2str(peer->amaflags));
16299       ast_cli(fd, "  Transfer mode: %s\n", transfermode2str(peer->allowtransfer));
16300       ast_cli(fd, "  CallingPres  : %s\n", ast_describe_caller_presentation(peer->callingpres));
16301       if (!ast_strlen_zero(peer->fromuser))
16302          ast_cli(fd, "  FromUser     : %s\n", peer->fromuser);
16303       if (!ast_strlen_zero(peer->fromdomain))
16304          ast_cli(fd, "  FromDomain   : %s Port %d\n", peer->fromdomain, (peer->fromdomainport) ? peer->fromdomainport : STANDARD_SIP_PORT);
16305       ast_cli(fd, "  Callgroup    : ");
16306       print_group(fd, peer->callgroup, 0);
16307       ast_cli(fd, "  Pickupgroup  : ");
16308       print_group(fd, peer->pickupgroup, 0);
16309       peer_mailboxes_to_str(&mailbox_str, peer);
16310       ast_cli(fd, "  MOH Suggest  : %s\n", peer->mohsuggest);
16311       ast_cli(fd, "  Mailbox      : %s\n", mailbox_str->str);
16312       ast_cli(fd, "  VM Extension : %s\n", peer->vmexten);
16313       ast_cli(fd, "  LastMsgsSent : %d/%d\n", (peer->lastmsgssent & 0x7fff0000) >> 16, peer->lastmsgssent & 0xffff);
16314       ast_cli(fd, "  Call limit   : %d\n", peer->call_limit);
16315       ast_cli(fd, "  Max forwards : %d\n", peer->maxforwards);
16316       if (peer->busy_level)
16317          ast_cli(fd, "  Busy level   : %d\n", peer->busy_level);
16318       ast_cli(fd, "  Dynamic      : %s\n", AST_CLI_YESNO(peer->host_dynamic));
16319       ast_cli(fd, "  Callerid     : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, "<unspecified>"));
16320       ast_cli(fd, "  MaxCallBR    : %d kbps\n", peer->maxcallbitrate);
16321       ast_cli(fd, "  Expire       : %ld\n", ast_sched_when(sched, peer->expire));
16322       ast_cli(fd, "  Insecure     : %s\n", insecure2str(ast_test_flag(&peer->flags[0], SIP_INSECURE)));
16323       ast_cli(fd, "  Force rport  : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[0], SIP_NAT_FORCE_RPORT)));
16324       ast_cli(fd, "  ACL          : %s\n", AST_CLI_YESNO(peer->ha != NULL));
16325       ast_cli(fd, "  DirectMedACL : %s\n", AST_CLI_YESNO(peer->directmediaha != NULL));
16326       ast_cli(fd, "  T.38 support : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)));
16327       ast_cli(fd, "  T.38 EC mode : %s\n", faxec2str(ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)));
16328       ast_cli(fd, "  T.38 MaxDtgrm: %d\n", peer->t38_maxdatagram);
16329       ast_cli(fd, "  DirectMedia  : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[0], SIP_DIRECT_MEDIA)));
16330       ast_cli(fd, "  PromiscRedir : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[0], SIP_PROMISCREDIR)));
16331       ast_cli(fd, "  User=Phone   : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[0], SIP_USEREQPHONE)));
16332       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)));
16333       ast_cli(fd, "  Text Support : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[1], SIP_PAGE2_TEXTSUPPORT)));
16334       ast_cli(fd, "  Ign SDP ver  : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[1], SIP_PAGE2_IGNORESDPVERSION)));
16335       ast_cli(fd, "  Trust RPID   : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[0], SIP_TRUSTRPID)));
16336       ast_cli(fd, "  Send RPID    : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[0], SIP_SENDRPID)));
16337       ast_cli(fd, "  Subscriptions: %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)));
16338       ast_cli(fd, "  Overlap dial : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWOVERLAP)));
16339       if (peer->outboundproxy)
16340          ast_cli(fd, "  Outb. proxy  : %s %s\n", ast_strlen_zero(peer->outboundproxy->name) ? "<not set>" : peer->outboundproxy->name,
16341                      peer->outboundproxy->force ? "(forced)" : "");
16342 
16343       /* - is enumerated */
16344       ast_cli(fd, "  DTMFmode     : %s\n", dtmfmode2str(ast_test_flag(&peer->flags[0], SIP_DTMF)));
16345       ast_cli(fd, "  Timer T1     : %d\n", peer->timer_t1);
16346       ast_cli(fd, "  Timer B      : %d\n", peer->timer_b);
16347       ast_cli(fd, "  ToHost       : %s\n", peer->tohost);
16348       ast_cli(fd, "  Addr->IP     : %s\n", ast_sockaddr_stringify(&peer->addr));
16349       ast_cli(fd, "  Defaddr->IP  : %s\n", ast_sockaddr_stringify(&peer->defaddr));
16350       ast_cli(fd, "  Prim.Transp. : %s\n", get_transport(peer->socket.type));
16351       ast_cli(fd, "  Allowed.Trsp : %s\n", get_transport_list(peer->transports));
16352       if (!ast_strlen_zero(sip_cfg.regcontext))
16353          ast_cli(fd, "  Reg. exten   : %s\n", peer->regexten);
16354       ast_cli(fd, "  Def. Username: %s\n", peer->username);
16355       ast_cli(fd, "  SIP Options  : ");
16356       if (peer->sipoptions) {
16357          int lastoption = -1;
16358          for (x = 0 ; x < ARRAY_LEN(sip_options); x++) {
16359             if (sip_options[x].id != lastoption) {
16360                if (peer->sipoptions & sip_options[x].id)
16361                   ast_cli(fd, "%s ", sip_options[x].text);
16362                lastoption = x;
16363             }
16364          }
16365       } else
16366          ast_cli(fd, "(none)");
16367 
16368       ast_cli(fd, "\n");
16369       ast_cli(fd, "  Codecs       : ");
16370       ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
16371       ast_cli(fd, "%s\n", codec_buf);
16372       ast_cli(fd, "  Codec Order  : (");
16373       print_codec_to_cli(fd, &peer->prefs);
16374       ast_cli(fd, ")\n");
16375 
16376       ast_cli(fd, "  Auto-Framing :  %s \n", AST_CLI_YESNO(peer->autoframing));
16377       ast_cli(fd, "  100 on REG   : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[1], SIP_PAGE2_REGISTERTRYING)));
16378       ast_cli(fd, "  Status       : ");
16379       peer_status(peer, status, sizeof(status));
16380       ast_cli(fd, "%s\n", status);
16381       ast_cli(fd, "  Useragent    : %s\n", peer->useragent);
16382       ast_cli(fd, "  Reg. Contact : %s\n", peer->fullcontact);
16383       ast_cli(fd, "  Qualify Freq : %d ms\n", peer->qualifyfreq);
16384       if (peer->chanvars) {
16385          ast_cli(fd, "  Variables    :\n");
16386          for (v = peer->chanvars ; v ; v = v->next)
16387             ast_cli(fd, "                 %s = %s\n", v->name, v->value);
16388       }
16389 
16390       ast_cli(fd, "  Sess-Timers  : %s\n", stmode2str(peer->stimer.st_mode_oper));
16391       ast_cli(fd, "  Sess-Refresh : %s\n", strefresher2str(peer->stimer.st_ref));
16392       ast_cli(fd, "  Sess-Expires : %d secs\n", peer->stimer.st_max_se);
16393       ast_cli(fd, "  Min-Sess     : %d secs\n", peer->stimer.st_min_se);
16394       ast_cli(fd, "  RTP Engine   : %s\n", peer->engine);
16395       ast_cli(fd, "  Parkinglot   : %s\n", peer->parkinglot);
16396       ast_cli(fd, "  Use Reason   : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[1], SIP_PAGE2_Q850_REASON)));
16397       ast_cli(fd, "\n");
16398       peer = unref_peer(peer, "sip_show_peer: unref_peer: done with peer ptr");
16399    } else  if (peer && type == 1) { /* manager listing */
16400       char buffer[256];
16401       struct ast_str *mailbox_str = ast_str_alloca(512);
16402       astman_append(s, "Channeltype: SIP\r\n");
16403       astman_append(s, "ObjectName: %s\r\n", peer->name);
16404       astman_append(s, "ChanObjectType: peer\r\n");
16405       astman_append(s, "SecretExist: %s\r\n", ast_strlen_zero(peer->secret)?"N":"Y");
16406       astman_append(s, "RemoteSecretExist: %s\r\n", ast_strlen_zero(peer->remotesecret)?"N":"Y");
16407       astman_append(s, "MD5SecretExist: %s\r\n", ast_strlen_zero(peer->md5secret)?"N":"Y");
16408       astman_append(s, "Context: %s\r\n", peer->context);
16409       astman_append(s, "Language: %s\r\n", peer->language);
16410       if (!ast_strlen_zero(peer->accountcode))
16411          astman_append(s, "Accountcode: %s\r\n", peer->accountcode);
16412       astman_append(s, "AMAflags: %s\r\n", ast_cdr_flags2str(peer->amaflags));
16413       astman_append(s, "CID-CallingPres: %s\r\n", ast_describe_caller_presentation(peer->callingpres));
16414       if (!ast_strlen_zero(peer->fromuser))
16415          astman_append(s, "SIP-FromUser: %s\r\n", peer->fromuser);
16416       if (!ast_strlen_zero(peer->fromdomain))
16417          astman_append(s, "SIP-FromDomain: %s\r\nSip-FromDomain-Port: %d\r\n", peer->fromdomain, (peer->fromdomainport) ? peer->fromdomainport : STANDARD_SIP_PORT);
16418       astman_append(s, "Callgroup: ");
16419       astman_append(s, "%s\r\n", ast_print_group(buffer, sizeof(buffer), peer->callgroup));
16420       astman_append(s, "Pickupgroup: ");
16421       astman_append(s, "%s\r\n", ast_print_group(buffer, sizeof(buffer), peer->pickupgroup));
16422       astman_append(s, "MOHSuggest: %s\r\n", peer->mohsuggest);
16423       peer_mailboxes_to_str(&mailbox_str, peer);
16424       astman_append(s, "VoiceMailbox: %s\r\n", mailbox_str->str);
16425       astman_append(s, "TransferMode: %s\r\n", transfermode2str(peer->allowtransfer));
16426       astman_append(s, "Maxforwards: %d\r\n", peer->maxforwards);
16427       astman_append(s, "LastMsgsSent: %d\r\n", peer->lastmsgssent);
16428       astman_append(s, "Maxforwards: %d\r\n", peer->maxforwards);
16429       astman_append(s, "Call-limit: %d\r\n", peer->call_limit);
16430       astman_append(s, "Busy-level: %d\r\n", peer->busy_level);
16431       astman_append(s, "MaxCallBR: %d kbps\r\n", peer->maxcallbitrate);
16432       astman_append(s, "Dynamic: %s\r\n", peer->host_dynamic?"Y":"N");
16433       astman_append(s, "Callerid: %s\r\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, ""));
16434       astman_append(s, "RegExpire: %ld seconds\r\n", ast_sched_when(sched, peer->expire));
16435       astman_append(s, "SIP-AuthInsecure: %s\r\n", insecure2str(ast_test_flag(&peer->flags[0], SIP_INSECURE)));
16436       astman_append(s, "SIP-Forcerport: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_NAT_FORCE_RPORT)?"Y":"N"));
16437       astman_append(s, "ACL: %s\r\n", (peer->ha?"Y":"N"));
16438       astman_append(s, "SIP-CanReinvite: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_DIRECT_MEDIA)?"Y":"N"));
16439       astman_append(s, "SIP-DirectMedia: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_DIRECT_MEDIA)?"Y":"N"));
16440       astman_append(s, "SIP-PromiscRedir: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_PROMISCREDIR)?"Y":"N"));
16441       astman_append(s, "SIP-UserPhone: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_USEREQPHONE)?"Y":"N"));
16442       astman_append(s, "SIP-VideoSupport: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_VIDEOSUPPORT)?"Y":"N"));
16443       astman_append(s, "SIP-TextSupport: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_TEXTSUPPORT)?"Y":"N"));
16444       astman_append(s, "SIP-T.38Support: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)?"Y":"N"));
16445       astman_append(s, "SIP-T.38EC: %s\r\n", faxec2str(ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)));
16446       astman_append(s, "SIP-T.38MaxDtgrm: %d\r\n", peer->t38_maxdatagram);
16447       astman_append(s, "SIP-Sess-Timers: %s\r\n", stmode2str(peer->stimer.st_mode_oper));
16448       astman_append(s, "SIP-Sess-Refresh: %s\r\n", strefresher2str(peer->stimer.st_ref));
16449       astman_append(s, "SIP-Sess-Expires: %d\r\n", peer->stimer.st_max_se);
16450       astman_append(s, "SIP-Sess-Min: %d\r\n", peer->stimer.st_min_se);
16451       astman_append(s, "SIP-RTP-Engine: %s\r\n", peer->engine);
16452 
16453       /* - is enumerated */
16454       astman_append(s, "SIP-DTMFmode: %s\r\n", dtmfmode2str(ast_test_flag(&peer->flags[0], SIP_DTMF)));
16455       astman_append(s, "ToHost: %s\r\n", peer->tohost);
16456       astman_append(s, "Address-IP: %s\r\nAddress-Port: %d\r\n", ast_sockaddr_stringify_addr(&peer->addr), ast_sockaddr_port(&peer->addr));
16457       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));
16458       astman_append(s, "Default-Username: %s\r\n", peer->username);
16459       if (!ast_strlen_zero(sip_cfg.regcontext))
16460          astman_append(s, "RegExtension: %s\r\n", peer->regexten);
16461       astman_append(s, "Codecs: ");
16462       ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
16463       astman_append(s, "%s\r\n", codec_buf);
16464       astman_append(s, "CodecOrder: ");
16465       pref = &peer->prefs;
16466       for(x = 0; x < 64 ; x++) {
16467          codec = ast_codec_pref_index(pref, x);
16468          if (!codec)
16469             break;
16470          astman_append(s, "%s", ast_getformatname(codec));
16471          if (x < 63 && ast_codec_pref_index(pref, x+1))
16472             astman_append(s, ",");
16473       }
16474 
16475       astman_append(s, "\r\n");
16476       astman_append(s, "Status: ");
16477       peer_status(peer, status, sizeof(status));
16478       astman_append(s, "%s\r\n", status);
16479       astman_append(s, "SIP-Useragent: %s\r\n", peer->useragent);
16480       astman_append(s, "Reg-Contact: %s\r\n", peer->fullcontact);
16481       astman_append(s, "QualifyFreq: %d ms\r\n", peer->qualifyfreq);
16482       astman_append(s, "Parkinglot: %s\r\n", peer->parkinglot);
16483       if (peer->chanvars) {
16484          for (v = peer->chanvars ; v ; v = v->next) {
16485             astman_append(s, "ChanVariable: %s=%s\r\n", v->name, v->value);
16486          }
16487       }
16488       astman_append(s, "SIP-Use-Reason-Header : %s\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_Q850_REASON)) ? "Y" : "N");
16489 
16490       peer = unref_peer(peer, "sip_show_peer: unref_peer: done with peer");
16491 
16492    } else {
16493       ast_cli(fd, "Peer %s not found.\n", argv[3]);
16494       ast_cli(fd, "\n");
16495    }
16496 
16497    return CLI_SUCCESS;
16498 }
16499 
16500 /*! \brief Do completion on user name */
16501 static char *complete_sip_user(const char *word, int state)
16502 {
16503    char *result = NULL;
16504    int wordlen = strlen(word);
16505    int which = 0;
16506    struct ao2_iterator user_iter;
16507    struct sip_peer *user;
16508 
16509    user_iter = ao2_iterator_init(peers, 0);
16510    while ((user = ao2_iterator_next(&user_iter))) {
16511       ao2_lock(user);
16512       if (!(user->type & SIP_TYPE_USER)) {
16513          ao2_unlock(user);
16514          unref_peer(user, "complete sip user");
16515          continue;
16516       }
16517       /* locking of the object is not required because only the name and flags are being compared */
16518       if (!strncasecmp(word, user->name, wordlen) && ++which > state) {
16519          result = ast_strdup(user->name);
16520       }
16521       ao2_unlock(user);
16522       unref_peer(user, "complete sip user");
16523    }
16524    ao2_iterator_destroy(&user_iter);
16525    return result;
16526 }
16527 /*! \brief Support routine for 'sip show user' CLI */
16528 static char *complete_sip_show_user(const char *line, const char *word, int pos, int state)
16529 {
16530    if (pos == 3)
16531       return complete_sip_user(word, state);
16532 
16533    return NULL;
16534 }
16535 
16536 /*! \brief Show one user in detail */
16537 static char *sip_show_user(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16538 {
16539    char cbuf[256];
16540    struct sip_peer *user;
16541    struct ast_variable *v;
16542    int load_realtime;
16543 
16544    switch (cmd) {
16545    case CLI_INIT:
16546       e->command = "sip show user";
16547       e->usage =
16548          "Usage: sip show user <name> [load]\n"
16549          "       Shows all details on one SIP user and the current status.\n"
16550          "       Option \"load\" forces lookup of peer in realtime storage.\n";
16551       return NULL;
16552    case CLI_GENERATE:
16553       return complete_sip_show_user(a->line, a->word, a->pos, a->n);
16554    }
16555 
16556    if (a->argc < 4)
16557       return CLI_SHOWUSAGE;
16558 
16559    /* Load from realtime storage? */
16560    load_realtime = (a->argc == 5 && !strcmp(a->argv[4], "load")) ? TRUE : FALSE;
16561 
16562    if ((user = find_peer(a->argv[3], NULL, load_realtime, FINDUSERS, FALSE, 0))) {
16563       ao2_lock(user);
16564       ast_cli(a->fd, "\n\n");
16565       ast_cli(a->fd, "  * Name       : %s\n", user->name);
16566       ast_cli(a->fd, "  Secret       : %s\n", ast_strlen_zero(user->secret)?"<Not set>":"<Set>");
16567       ast_cli(a->fd, "  MD5Secret    : %s\n", ast_strlen_zero(user->md5secret)?"<Not set>":"<Set>");
16568       ast_cli(a->fd, "  Context      : %s\n", user->context);
16569       ast_cli(a->fd, "  Language     : %s\n", user->language);
16570       if (!ast_strlen_zero(user->accountcode))
16571          ast_cli(a->fd, "  Accountcode  : %s\n", user->accountcode);
16572       ast_cli(a->fd, "  AMA flags    : %s\n", ast_cdr_flags2str(user->amaflags));
16573       ast_cli(a->fd, "  Transfer mode: %s\n", transfermode2str(user->allowtransfer));
16574       ast_cli(a->fd, "  MaxCallBR    : %d kbps\n", user->maxcallbitrate);
16575       ast_cli(a->fd, "  CallingPres  : %s\n", ast_describe_caller_presentation(user->callingpres));
16576       ast_cli(a->fd, "  Call limit   : %d\n", user->call_limit);
16577       ast_cli(a->fd, "  Callgroup    : ");
16578       print_group(a->fd, user->callgroup, 0);
16579       ast_cli(a->fd, "  Pickupgroup  : ");
16580       print_group(a->fd, user->pickupgroup, 0);
16581       ast_cli(a->fd, "  Callerid     : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), user->cid_name, user->cid_num, "<unspecified>"));
16582       ast_cli(a->fd, "  ACL          : %s\n", AST_CLI_YESNO(user->ha != NULL));
16583       ast_cli(a->fd, "  Sess-Timers  : %s\n", stmode2str(user->stimer.st_mode_oper));
16584       ast_cli(a->fd, "  Sess-Refresh : %s\n", strefresher2str(user->stimer.st_ref));
16585       ast_cli(a->fd, "  Sess-Expires : %d secs\n", user->stimer.st_max_se);
16586       ast_cli(a->fd, "  Sess-Min-SE  : %d secs\n", user->stimer.st_min_se);
16587       ast_cli(a->fd, "  RTP Engine   : %s\n", user->engine);
16588 
16589       ast_cli(a->fd, "  Codec Order  : (");
16590       print_codec_to_cli(a->fd, &user->prefs);
16591       ast_cli(a->fd, ")\n");
16592 
16593       ast_cli(a->fd, "  Auto-Framing:  %s \n", AST_CLI_YESNO(user->autoframing));
16594       if (user->chanvars) {
16595          ast_cli(a->fd, "  Variables    :\n");
16596          for (v = user->chanvars ; v ; v = v->next)
16597             ast_cli(a->fd, "                 %s = %s\n", v->name, v->value);
16598       }
16599 
16600       ast_cli(a->fd, "\n");
16601 
16602       ao2_unlock(user);
16603       unref_peer(user, "sip show user");
16604    } else {
16605       ast_cli(a->fd, "User %s not found.\n", a->argv[3]);
16606       ast_cli(a->fd, "\n");
16607    }
16608 
16609    return CLI_SUCCESS;
16610 }
16611 
16612 
16613 static char *sip_show_sched(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16614 {
16615    struct ast_str *cbuf;
16616    struct ast_cb_names cbnames = {9, { "retrans_pkt",
16617                                         "__sip_autodestruct",
16618                                         "expire_register",
16619                                         "auto_congest",
16620                                         "sip_reg_timeout",
16621                                         "sip_poke_peer_s",
16622                                         "sip_poke_noanswer",
16623                                         "sip_reregister",
16624                                         "sip_reinvite_retry"},
16625                            { retrans_pkt,
16626                                      __sip_autodestruct,
16627                                      expire_register,
16628                                      auto_congest,
16629                                      sip_reg_timeout,
16630                                      sip_poke_peer_s,
16631                                      sip_poke_noanswer,
16632                                      sip_reregister,
16633                                      sip_reinvite_retry}};
16634    
16635    switch (cmd) {
16636    case CLI_INIT:
16637       e->command = "sip show sched";
16638       e->usage =
16639          "Usage: sip show sched\n"
16640          "       Shows stats on what's in the sched queue at the moment\n";
16641       return NULL;
16642    case CLI_GENERATE:
16643       return NULL;
16644    }
16645 
16646    cbuf = ast_str_alloca(2048);
16647 
16648    ast_cli(a->fd, "\n");
16649    ast_sched_report(sched, &cbuf, &cbnames);
16650    ast_cli(a->fd, "%s", cbuf->str);
16651 
16652    return CLI_SUCCESS;
16653 }
16654 
16655 /*! \brief  Show SIP Registry (registrations with other SIP proxies */
16656 static char *sip_show_registry(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16657 {
16658 #define FORMAT2 "%-39.39s %-6.6s %-12.12s  %8.8s %-20.20s %-25.25s\n"
16659 #define FORMAT  "%-39.39s %-6.6s %-12.12s  %8d %-20.20s %-25.25s\n"
16660    char host[80];
16661    char user[80];
16662    char tmpdat[256];
16663    struct ast_tm tm;
16664    int counter = 0;
16665 
16666    switch (cmd) {
16667    case CLI_INIT:
16668       e->command = "sip show registry";
16669       e->usage =
16670          "Usage: sip show registry\n"
16671          "       Lists all registration requests and status.\n";
16672       return NULL;
16673    case CLI_GENERATE:
16674       return NULL;
16675    }
16676 
16677    if (a->argc != 3)
16678       return CLI_SHOWUSAGE;
16679    ast_cli(a->fd, FORMAT2, "Host", "dnsmgr", "Username", "Refresh", "State", "Reg.Time");
16680    
16681    ASTOBJ_CONTAINER_TRAVERSE(&regl, 1, do {
16682       ASTOBJ_RDLOCK(iterator);
16683       snprintf(host, sizeof(host), "%s:%d", iterator->hostname, iterator->portno ? iterator->portno : STANDARD_SIP_PORT);
16684       snprintf(user, sizeof(user), "%s", iterator->username);
16685       if (!ast_strlen_zero(iterator->regdomain)) {
16686          snprintf(tmpdat, sizeof(tmpdat), "%s", user);
16687          snprintf(user, sizeof(user), "%s@%s", tmpdat, iterator->regdomain);}
16688       if (iterator->regdomainport) {
16689          snprintf(tmpdat, sizeof(tmpdat), "%s", user);
16690          snprintf(user, sizeof(user), "%s:%d", tmpdat, iterator->regdomainport);}
16691       if (iterator->regtime.tv_sec) {
16692          ast_localtime(&iterator->regtime, &tm, NULL);
16693          ast_strftime(tmpdat, sizeof(tmpdat), "%a, %d %b %Y %T", &tm);
16694       } else
16695          tmpdat[0] = '\0';
16696       ast_cli(a->fd, FORMAT, host, (iterator->dnsmgr) ? "Y" : "N", user, iterator->refresh, regstate2str(iterator->regstate), tmpdat);
16697       ASTOBJ_UNLOCK(iterator);
16698       counter++;
16699    } while(0));
16700    ast_cli(a->fd, "%d SIP registrations.\n", counter);
16701    return CLI_SUCCESS;
16702 #undef FORMAT
16703 #undef FORMAT2
16704 }
16705 
16706 /*! \brief Unregister (force expiration) a SIP peer in the registry via CLI
16707    \note This function does not tell the SIP device what's going on,
16708    so use it with great care.
16709 */
16710 static char *sip_unregister(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16711 {
16712    struct sip_peer *peer;
16713    int load_realtime = 0;
16714 
16715    switch (cmd) {
16716    case CLI_INIT:
16717       e->command = "sip unregister";
16718       e->usage =
16719          "Usage: sip unregister <peer>\n"
16720          "       Unregister (force expiration) a SIP peer from the registry\n";
16721       return NULL;
16722    case CLI_GENERATE:
16723       return complete_sip_unregister(a->line, a->word, a->pos, a->n);
16724    }
16725    
16726    if (a->argc != 3)
16727       return CLI_SHOWUSAGE;
16728    
16729    if ((peer = find_peer(a->argv[2], NULL, load_realtime, FINDPEERS, TRUE, 0))) {
16730       if (peer->expire > 0) {
16731          AST_SCHED_DEL_UNREF(sched, peer->expire,
16732             unref_peer(peer, "remove register expire ref"));
16733          expire_register(ref_peer(peer, "ref for expire_register"));
16734          ast_cli(a->fd, "Unregistered peer \'%s\'\n\n", a->argv[2]);
16735       } else {
16736          ast_cli(a->fd, "Peer %s not registered\n", a->argv[2]);
16737       }
16738       unref_peer(peer, "sip_unregister: unref_peer via sip_unregister: done with peer from find_peer call");
16739    } else {
16740       ast_cli(a->fd, "Peer unknown: \'%s\'. Not unregistered.\n", a->argv[2]);
16741    }
16742    
16743    return CLI_SUCCESS;
16744 }
16745 
16746 /*! \brief Callback for show_chanstats */
16747 static int show_chanstats_cb(void *__cur, void *__arg, int flags)
16748 {
16749 #define FORMAT2 "%-15.15s  %-11.11s  %-8.8s %-10.10s  %-10.10s (     %%) %-6.6s %-10.10s  %-10.10s (     %%) %-6.6s\n"
16750 #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"
16751    struct sip_pvt *cur = __cur;
16752    struct ast_rtp_instance_stats stats;
16753    char durbuf[10];
16754    int duration;
16755    int durh, durm, durs;
16756    struct ast_channel *c = cur->owner;
16757    struct __show_chan_arg *arg = __arg;
16758    int fd = arg->fd;
16759 
16760 
16761    if (cur->subscribed != NONE) /* Subscriptions */
16762       return 0;   /* don't care, we scan all channels */
16763 
16764    if (!cur->rtp) {
16765       if (sipdebug) {
16766          ast_cli(fd, "%-15.15s  %-11.11s (inv state: %s) -- %s\n",
16767             ast_sockaddr_stringify_addr(&cur->sa), cur->callid,
16768             invitestate2string[cur->invitestate].desc,
16769             "-- No RTP active");
16770       }
16771       return 0;   /* don't care, we scan all channels */
16772    }
16773 
16774    ast_rtp_instance_get_stats(cur->rtp, &stats, AST_RTP_INSTANCE_STAT_ALL);
16775 
16776    if (c && c->cdr && !ast_tvzero(c->cdr->start)) {
16777       duration = (int)(ast_tvdiff_ms(ast_tvnow(), c->cdr->start) / 1000);
16778       durh = duration / 3600;
16779       durm = (duration % 3600) / 60;
16780       durs = duration % 60;
16781       snprintf(durbuf, sizeof(durbuf), "%02d:%02d:%02d", durh, durm, durs);
16782    } else {
16783       durbuf[0] = '\0';
16784    }
16785 
16786    ast_cli(fd, FORMAT,
16787       ast_sockaddr_stringify_addr(&cur->sa),
16788       cur->callid,
16789       durbuf,
16790       stats.rxcount > (unsigned int) 100000 ? (unsigned int) (stats.rxcount)/(unsigned int) 1000 : stats.rxcount,
16791       stats.rxcount > (unsigned int) 100000 ? "K":" ",
16792       stats.rxploss,
16793       (stats.rxcount + stats.rxploss) > 0 ? (double) stats.rxploss / (stats.rxcount + stats.rxploss) * 100 : 0,
16794       stats.rxjitter,
16795       stats.txcount > (unsigned int) 100000 ? (unsigned int) (stats.txcount)/(unsigned int) 1000 : stats.txcount,
16796       stats.txcount > (unsigned int) 100000 ? "K":" ",
16797       stats.txploss,
16798       stats.txcount > 0 ? (double) stats.txploss / stats.txcount * 100 : 0,
16799       stats.txjitter
16800    );
16801    arg->numchans++;
16802 
16803    return 0;   /* don't care, we scan all channels */
16804 }
16805 
16806 /*! \brief SIP show channelstats CLI (main function) */
16807 static char *sip_show_channelstats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16808 {
16809    struct __show_chan_arg arg = { .fd = a->fd, .numchans = 0 };
16810 
16811    switch (cmd) {
16812    case CLI_INIT:
16813       e->command = "sip show channelstats";
16814       e->usage =
16815          "Usage: sip show channelstats\n"
16816          "       Lists all currently active SIP channel's RTCP statistics.\n"
16817          "       Note that calls in the much optimized RTP P2P bridge mode will not show any packets here.";
16818       return NULL;
16819    case CLI_GENERATE:
16820       return NULL;
16821    }
16822 
16823    if (a->argc != 3)
16824       return CLI_SHOWUSAGE;
16825 
16826    ast_cli(a->fd, FORMAT2, "Peer", "Call ID", "Duration", "Recv: Pack", "Lost", "Jitter", "Send: Pack", "Lost", "Jitter");
16827    /* iterate on the container and invoke the callback on each item */
16828    ao2_t_callback(dialogs, OBJ_NODATA, show_chanstats_cb, &arg, "callback to sip show chanstats");
16829    ast_cli(a->fd, "%d active SIP channel%s\n", arg.numchans, (arg.numchans != 1) ? "s" : "");
16830    return CLI_SUCCESS;
16831 }
16832 #undef FORMAT
16833 #undef FORMAT2
16834 
16835 /*! \brief List global settings for the SIP channel */
16836 static char *sip_show_settings(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16837 {
16838    int realtimepeers;
16839    int realtimeregs;
16840    char codec_buf[SIPBUFSIZE];
16841    const char *msg;  /* temporary msg pointer */
16842 
16843    switch (cmd) {
16844    case CLI_INIT:
16845       e->command = "sip show settings";
16846       e->usage =
16847          "Usage: sip show settings\n"
16848          "       Provides detailed list of the configuration of the SIP channel.\n";
16849       return NULL;
16850    case CLI_GENERATE:
16851       return NULL;
16852    }
16853 
16854 
16855    realtimepeers = ast_check_realtime("sippeers");
16856    realtimeregs = ast_check_realtime("sipregs");
16857 
16858    if (a->argc != 3)
16859       return CLI_SHOWUSAGE;
16860    ast_cli(a->fd, "\n\nGlobal Settings:\n");
16861    ast_cli(a->fd, "----------------\n");
16862    ast_cli(a->fd, "  UDP Bindaddress:        %s\n", ast_sockaddr_stringify(&bindaddr));
16863    if (ast_sockaddr_is_ipv6(&bindaddr) && ast_sockaddr_is_any(&bindaddr)) {
16864       ast_cli(a->fd, "  ** Additional Info:\n");
16865       ast_cli(a->fd, "     [::] may include IPv4 in addition to IPv6, if such a feature is enabled in the OS.\n");
16866    }
16867    ast_cli(a->fd, "  TCP SIP Bindaddress:    %s\n",
16868       sip_cfg.tcp_enabled != FALSE ?
16869             ast_sockaddr_stringify(&sip_tcp_desc.local_address) :
16870             "Disabled");
16871    ast_cli(a->fd, "  TLS SIP Bindaddress:    %s\n",
16872       default_tls_cfg.enabled != FALSE ?
16873             ast_sockaddr_stringify(&sip_tls_desc.local_address) :
16874             "Disabled");
16875    ast_cli(a->fd, "  Videosupport:           %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_VIDEOSUPPORT)));
16876    ast_cli(a->fd, "  Textsupport:            %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_TEXTSUPPORT)));
16877    ast_cli(a->fd, "  Ignore SDP sess. ver.:  %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_IGNORESDPVERSION)));
16878    ast_cli(a->fd, "  AutoCreate Peer:        %s\n", AST_CLI_YESNO(sip_cfg.autocreatepeer));
16879    ast_cli(a->fd, "  Match Auth Username:    %s\n", AST_CLI_YESNO(global_match_auth_username));
16880    ast_cli(a->fd, "  Allow unknown access:   %s\n", AST_CLI_YESNO(sip_cfg.allowguest));
16881    ast_cli(a->fd, "  Allow subscriptions:    %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)));
16882    ast_cli(a->fd, "  Allow overlap dialing:  %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP)));
16883    ast_cli(a->fd, "  Allow promsic. redir:   %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[0], SIP_PROMISCREDIR)));
16884    ast_cli(a->fd, "  Enable call counters:   %s\n", AST_CLI_YESNO(global_callcounter));
16885    ast_cli(a->fd, "  SIP domain support:     %s\n", AST_CLI_YESNO(!AST_LIST_EMPTY(&domain_list)));
16886    ast_cli(a->fd, "  Realm. auth:            %s\n", AST_CLI_YESNO(authl != NULL));
16887    ast_cli(a->fd, "  Our auth realm          %s\n", sip_cfg.realm);
16888    ast_cli(a->fd, "  Use domains as realms:  %s\n", AST_CLI_YESNO(sip_cfg.domainsasrealm));
16889    ast_cli(a->fd, "  Call to non-local dom.: %s\n", AST_CLI_YESNO(sip_cfg.allow_external_domains));
16890    ast_cli(a->fd, "  URI user is phone no:   %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[0], SIP_USEREQPHONE)));
16891    ast_cli(a->fd, "  Always auth rejects:    %s\n", AST_CLI_YESNO(sip_cfg.alwaysauthreject));
16892    ast_cli(a->fd, "  Direct RTP setup:       %s\n", AST_CLI_YESNO(sip_cfg.directrtpsetup));
16893    ast_cli(a->fd, "  User Agent:             %s\n", global_useragent);
16894    ast_cli(a->fd, "  SDP Session Name:       %s\n", ast_strlen_zero(global_sdpsession) ? "-" : global_sdpsession);
16895    ast_cli(a->fd, "  SDP Owner Name:         %s\n", ast_strlen_zero(global_sdpowner) ? "-" : global_sdpowner);
16896    ast_cli(a->fd, "  Reg. context:           %s\n", S_OR(sip_cfg.regcontext, "(not set)"));
16897    ast_cli(a->fd, "  Regexten on Qualify:    %s\n", AST_CLI_YESNO(sip_cfg.regextenonqualify));
16898    ast_cli(a->fd, "  Caller ID:              %s\n", default_callerid);
16899    if ((default_fromdomainport) && (default_fromdomainport != STANDARD_SIP_PORT)) {
16900       ast_cli(a->fd, "  From: Domain:           %s:%d\n", default_fromdomain, default_fromdomainport);
16901    } else {
16902       ast_cli(a->fd, "  From: Domain:           %s\n", default_fromdomain);
16903    }
16904    ast_cli(a->fd, "  Record SIP history:     %s\n", AST_CLI_ONOFF(recordhistory));
16905    ast_cli(a->fd, "  Call Events:            %s\n", AST_CLI_ONOFF(sip_cfg.callevents));
16906    ast_cli(a->fd, "  Auth. Failure Events:   %s\n", AST_CLI_ONOFF(global_authfailureevents));
16907 
16908    ast_cli(a->fd, "  T.38 support:           %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_T38SUPPORT)));
16909    ast_cli(a->fd, "  T.38 EC mode:           %s\n", faxec2str(ast_test_flag(&global_flags[1], SIP_PAGE2_T38SUPPORT)));
16910    ast_cli(a->fd, "  T.38 MaxDtgrm:          %d\n", global_t38_maxdatagram);
16911    if (!realtimepeers && !realtimeregs)
16912       ast_cli(a->fd, "  SIP realtime:           Disabled\n" );
16913    else
16914       ast_cli(a->fd, "  SIP realtime:           Enabled\n" );
16915    ast_cli(a->fd, "  Qualify Freq :          %d ms\n", global_qualifyfreq);
16916    ast_cli(a->fd, "  Q.850 Reason header:    %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_Q850_REASON)));
16917    ast_cli(a->fd, "\nNetwork QoS Settings:\n");
16918    ast_cli(a->fd, "---------------------------\n");
16919    ast_cli(a->fd, "  IP ToS SIP:             %s\n", ast_tos2str(global_tos_sip));
16920    ast_cli(a->fd, "  IP ToS RTP audio:       %s\n", ast_tos2str(global_tos_audio));
16921    ast_cli(a->fd, "  IP ToS RTP video:       %s\n", ast_tos2str(global_tos_video));
16922    ast_cli(a->fd, "  IP ToS RTP text:        %s\n", ast_tos2str(global_tos_text));
16923    ast_cli(a->fd, "  802.1p CoS SIP:         %d\n", global_cos_sip);
16924    ast_cli(a->fd, "  802.1p CoS RTP audio:   %d\n", global_cos_audio);
16925    ast_cli(a->fd, "  802.1p CoS RTP video:   %d\n", global_cos_video);
16926    ast_cli(a->fd, "  802.1p CoS RTP text:    %d\n", global_cos_text);
16927    ast_cli(a->fd, "  Jitterbuffer enabled:   %s\n", AST_CLI_YESNO(ast_test_flag(&global_jbconf, AST_JB_ENABLED)));
16928    ast_cli(a->fd, "  Jitterbuffer forced:    %s\n", AST_CLI_YESNO(ast_test_flag(&global_jbconf, AST_JB_FORCED)));
16929    ast_cli(a->fd, "  Jitterbuffer max size:  %ld\n", global_jbconf.max_size);
16930    ast_cli(a->fd, "  Jitterbuffer resync:    %ld\n", global_jbconf.resync_threshold);
16931    ast_cli(a->fd, "  Jitterbuffer impl:      %s\n", global_jbconf.impl);
16932    ast_cli(a->fd, "  Jitterbuffer log:       %s\n", AST_CLI_YESNO(ast_test_flag(&global_jbconf, AST_JB_LOG)));
16933 
16934    ast_cli(a->fd, "\nNetwork Settings:\n");
16935    ast_cli(a->fd, "---------------------------\n");
16936    /* determine if/how SIP address can be remapped */
16937    if (localaddr == NULL)
16938       msg = "Disabled, no localnet list";
16939    else if (ast_sockaddr_isnull(&externaddr))
16940       msg = "Disabled";
16941    else if (!ast_strlen_zero(externhost))
16942       msg = "Enabled using externhost";
16943    else
16944       msg = "Enabled using externaddr";
16945    ast_cli(a->fd, "  SIP address remapping:  %s\n", msg);
16946    ast_cli(a->fd, "  Externhost:             %s\n", S_OR(externhost, "<none>"));
16947    ast_cli(a->fd, "  externaddr:               %s\n", ast_sockaddr_stringify(&externaddr));
16948    ast_cli(a->fd, "  Externrefresh:          %d\n", externrefresh);
16949    {
16950       struct ast_ha *d;
16951       const char *prefix = "Localnet:";
16952 
16953       for (d = localaddr; d ; prefix = "", d = d->next) {
16954          const char *addr = ast_strdupa(ast_sockaddr_stringify_addr(&d->addr));
16955          const char *mask = ast_strdupa(ast_sockaddr_stringify_addr(&d->netmask));
16956          ast_cli(a->fd, "  %-24s%s/%s\n", prefix, addr, mask);
16957       }
16958    }
16959    ast_cli(a->fd, "\nGlobal Signalling Settings:\n");
16960    ast_cli(a->fd, "---------------------------\n");
16961    ast_cli(a->fd, "  Codecs:                 ");
16962    ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, sip_cfg.capability);
16963    ast_cli(a->fd, "%s\n", codec_buf);
16964    ast_cli(a->fd, "  Codec Order:            ");
16965    print_codec_to_cli(a->fd, &default_prefs);
16966    ast_cli(a->fd, "\n");
16967    ast_cli(a->fd, "  Relax DTMF:             %s\n", AST_CLI_YESNO(global_relaxdtmf));
16968    ast_cli(a->fd, "  RFC2833 Compensation:   %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_RFC2833_COMPENSATE)));
16969    ast_cli(a->fd, "  Symmetric RTP:          %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_SYMMETRICRTP)));
16970    ast_cli(a->fd, "  Compact SIP headers:    %s\n", AST_CLI_YESNO(sip_cfg.compactheaders));
16971    ast_cli(a->fd, "  RTP Keepalive:          %d %s\n", global_rtpkeepalive, global_rtpkeepalive ? "" : "(Disabled)" );
16972    ast_cli(a->fd, "  RTP Timeout:            %d %s\n", global_rtptimeout, global_rtptimeout ? "" : "(Disabled)" );
16973    ast_cli(a->fd, "  RTP Hold Timeout:       %d %s\n", global_rtpholdtimeout, global_rtpholdtimeout ? "" : "(Disabled)");
16974    ast_cli(a->fd, "  MWI NOTIFY mime type:   %s\n", default_notifymime);
16975    ast_cli(a->fd, "  DNS SRV lookup:         %s\n", AST_CLI_YESNO(sip_cfg.srvlookup));
16976    ast_cli(a->fd, "  Pedantic SIP support:   %s\n", AST_CLI_YESNO(sip_cfg.pedanticsipchecking));
16977    ast_cli(a->fd, "  Reg. min duration       %d secs\n", min_expiry);
16978    ast_cli(a->fd, "  Reg. max duration:      %d secs\n", max_expiry);
16979    ast_cli(a->fd, "  Reg. default duration:  %d secs\n", default_expiry);
16980    ast_cli(a->fd, "  Outbound reg. timeout:  %d secs\n", global_reg_timeout);
16981    ast_cli(a->fd, "  Outbound reg. attempts: %d\n", global_regattempts_max);
16982    ast_cli(a->fd, "  Notify ringing state:   %s\n", AST_CLI_YESNO(sip_cfg.notifyringing));
16983    if (sip_cfg.notifyringing) {
16984       ast_cli(a->fd, "    Include CID:          %s%s\n",
16985             AST_CLI_YESNO(sip_cfg.notifycid),
16986             sip_cfg.notifycid == IGNORE_CONTEXT ? " (Ignoring context)" : "");
16987    }
16988    ast_cli(a->fd, "  Notify hold state:      %s\n", AST_CLI_YESNO(sip_cfg.notifyhold));
16989    ast_cli(a->fd, "  SIP Transfer mode:      %s\n", transfermode2str(sip_cfg.allowtransfer));
16990    ast_cli(a->fd, "  Max Call Bitrate:       %d kbps\n", default_maxcallbitrate);
16991    ast_cli(a->fd, "  Auto-Framing:           %s\n", AST_CLI_YESNO(global_autoframing));
16992    ast_cli(a->fd, "  Outb. proxy:            %s %s\n", ast_strlen_zero(sip_cfg.outboundproxy.name) ? "<not set>" : sip_cfg.outboundproxy.name,
16993                      sip_cfg.outboundproxy.force ? "(forced)" : "");
16994    ast_cli(a->fd, "  Session Timers:         %s\n", stmode2str(global_st_mode));
16995    ast_cli(a->fd, "  Session Refresher:      %s\n", strefresher2str (global_st_refresher));
16996    ast_cli(a->fd, "  Session Expires:        %d secs\n", global_max_se);
16997    ast_cli(a->fd, "  Session Min-SE:         %d secs\n", global_min_se);
16998    ast_cli(a->fd, "  Timer T1:               %d\n", global_t1);
16999    ast_cli(a->fd, "  Timer T1 minimum:       %d\n", global_t1min);
17000    ast_cli(a->fd, "  Timer B:                %d\n", global_timer_b);
17001    ast_cli(a->fd, "  No premature media:     %s\n", AST_CLI_YESNO(global_prematuremediafilter));
17002    ast_cli(a->fd, "  Max forwards:           %d\n", sip_cfg.default_max_forwards);
17003 
17004    ast_cli(a->fd, "\nDefault Settings:\n");
17005    ast_cli(a->fd, "-----------------\n");
17006    ast_cli(a->fd, "  Allowed transports:     %s\n", get_transport_list(default_transports));
17007    ast_cli(a->fd, "  Outbound transport:    %s\n", get_transport(default_primary_transport));
17008    ast_cli(a->fd, "  Context:                %s\n", sip_cfg.default_context);
17009    ast_cli(a->fd, "  Force rport:            %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[0], SIP_NAT_FORCE_RPORT)));
17010    ast_cli(a->fd, "  DTMF:                   %s\n", dtmfmode2str(ast_test_flag(&global_flags[0], SIP_DTMF)));
17011    ast_cli(a->fd, "  Qualify:                %d\n", default_qualify);
17012    ast_cli(a->fd, "  Use ClientCode:         %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[0], SIP_USECLIENTCODE)));
17013    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)));
17014    ast_cli(a->fd, "  Language:               %s\n", default_language);
17015    ast_cli(a->fd, "  MOH Interpret:          %s\n", default_mohinterpret);
17016    ast_cli(a->fd, "  MOH Suggest:            %s\n", default_mohsuggest);
17017    ast_cli(a->fd, "  Voice Mail Extension:   %s\n", default_vmexten);
17018 
17019    
17020    if (realtimepeers || realtimeregs) {
17021       ast_cli(a->fd, "\nRealtime SIP Settings:\n");
17022       ast_cli(a->fd, "----------------------\n");
17023       ast_cli(a->fd, "  Realtime Peers:         %s\n", AST_CLI_YESNO(realtimepeers));
17024       ast_cli(a->fd, "  Realtime Regs:          %s\n", AST_CLI_YESNO(realtimeregs));
17025       ast_cli(a->fd, "  Cache Friends:          %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)));
17026       ast_cli(a->fd, "  Update:                 %s\n", AST_CLI_YESNO(sip_cfg.peer_rtupdate));
17027       ast_cli(a->fd, "  Ignore Reg. Expire:     %s\n", AST_CLI_YESNO(sip_cfg.ignore_regexpire));
17028       ast_cli(a->fd, "  Save sys. name:         %s\n", AST_CLI_YESNO(sip_cfg.rtsave_sysname));
17029       ast_cli(a->fd, "  Auto Clear:             %d\n", sip_cfg.rtautoclear);
17030    }
17031    ast_cli(a->fd, "\n----\n");
17032    return CLI_SUCCESS;
17033 }
17034 
17035 static char *sip_show_mwi(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
17036 {
17037 #define FORMAT  "%-30.30s  %-12.12s  %-10.10s  %-10.10s\n"
17038    char host[80];
17039    
17040    switch (cmd) {
17041    case CLI_INIT:
17042       e->command = "sip show mwi";
17043       e->usage =
17044          "Usage: sip show mwi\n"
17045          "       Provides a list of MWI subscriptions and status.\n";
17046       return NULL;
17047    case CLI_GENERATE:
17048       return NULL;
17049    }
17050    
17051    ast_cli(a->fd, FORMAT, "Host", "Username", "Mailbox", "Subscribed");
17052    
17053    ASTOBJ_CONTAINER_TRAVERSE(&submwil, 1, do {
17054       ASTOBJ_RDLOCK(iterator);
17055       snprintf(host, sizeof(host), "%s:%d", iterator->hostname, iterator->portno ? iterator->portno : STANDARD_SIP_PORT);
17056       ast_cli(a->fd, FORMAT, host, iterator->username, iterator->mailbox, AST_CLI_YESNO(iterator->subscribed));
17057       ASTOBJ_UNLOCK(iterator);
17058    } while(0));
17059 
17060    return CLI_SUCCESS;
17061 #undef FORMAT
17062 }
17063 
17064 
17065 /*! \brief Show subscription type in string format */
17066 static const char *subscription_type2str(enum subscriptiontype subtype)
17067 {
17068    int i;
17069 
17070    for (i = 1; i < ARRAY_LEN(subscription_types); i++) {
17071       if (subscription_types[i].type == subtype) {
17072          return subscription_types[i].text;
17073       }
17074    }
17075    return subscription_types[0].text;
17076 }
17077 
17078 /*! \brief Find subscription type in array */
17079 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype)
17080 {
17081    int i;
17082 
17083    for (i = 1; i < ARRAY_LEN(subscription_types); i++) {
17084       if (subscription_types[i].type == subtype) {
17085          return &subscription_types[i];
17086       }
17087    }
17088    return &subscription_types[0];
17089 }
17090 
17091 /*
17092  * We try to structure all functions that loop on data structures as
17093  * a handler for individual entries, and a mainloop that iterates
17094  * on the main data structure. This way, moving the code to containers
17095  * that support iteration through callbacks will be a lot easier.
17096  */
17097 
17098 #define FORMAT4 "%-15.15s  %-15.15s  %-15.15s  %-15.15s  %-13.13s  %-15.15s %-10.10s %-6.6d\n"
17099 #define FORMAT3 "%-15.15s  %-15.15s  %-15.15s  %-15.15s  %-13.13s  %-15.15s %-10.10s %-6.6s\n"
17100 #define FORMAT2 "%-15.15s  %-15.15s  %-15.15s  %-15.15s  %-7.7s  %-15.15s %-10.10s %-10.10s\n"
17101 #define FORMAT  "%-15.15s  %-15.15s  %-15.15s  %-15.15s  %-3.3s %-3.3s  %-15.15s %-10.10s %-10.10s\n"
17102 
17103 /*! \brief callback for show channel|subscription */
17104 static int show_channels_cb(void *__cur, void *__arg, int flags)
17105 {
17106    struct sip_pvt *cur = __cur;
17107    struct __show_chan_arg *arg = __arg;
17108    const struct ast_sockaddr *dst = sip_real_dst(cur);
17109    
17110    /* XXX indentation preserved to reduce diff. Will be fixed later */
17111    if (cur->subscribed == NONE && !arg->subscriptions) {
17112       /* set if SIP transfer in progress */
17113       const char *referstatus = cur->refer ? referstatus2str(cur->refer->status) : "";
17114       char formatbuf[SIPBUFSIZE/2];
17115       
17116       ast_cli(arg->fd, FORMAT, ast_sockaddr_stringify_addr(dst),
17117             S_OR(cur->username, S_OR(cur->cid_num, "(None)")),
17118             cur->callid,
17119             ast_getformatname_multiple(formatbuf, sizeof(formatbuf), cur->owner ? cur->owner->nativeformats : 0),
17120             AST_CLI_YESNO(ast_test_flag(&cur->flags[1], SIP_PAGE2_CALL_ONHOLD)),
17121             cur->needdestroy ? "(d)" : "",
17122             cur->lastmsg ,
17123             referstatus,
17124             cur->relatedpeer ? cur->relatedpeer->name : "<guest>"
17125          );
17126       arg->numchans++;
17127    }
17128    if (cur->subscribed != NONE && arg->subscriptions) {
17129       struct ast_str *mailbox_str = ast_str_alloca(512);
17130       if (cur->subscribed == MWI_NOTIFICATION && cur->relatedpeer)
17131          peer_mailboxes_to_str(&mailbox_str, cur->relatedpeer);
17132       ast_cli(arg->fd, FORMAT4, ast_sockaddr_stringify_addr(dst),
17133             S_OR(cur->username, S_OR(cur->cid_num, "(None)")),
17134                cur->callid,
17135             /* the 'complete' exten/context is hidden in the refer_to field for subscriptions */
17136             cur->subscribed == MWI_NOTIFICATION ? "--" : cur->subscribeuri,
17137             cur->subscribed == MWI_NOTIFICATION ? "<none>" : ast_extension_state2str(cur->laststate),
17138             subscription_type2str(cur->subscribed),
17139             cur->subscribed == MWI_NOTIFICATION ? S_OR(mailbox_str->str, "<none>") : "<none>",
17140             cur->expiry
17141          );
17142       arg->numchans++;
17143    }
17144    return 0;   /* don't care, we scan all channels */
17145 }
17146 
17147 /*! \brief CLI for show channels or subscriptions.
17148  * This is a new-style CLI handler so a single function contains
17149  * the prototype for the function, the 'generator' to produce multiple
17150  * entries in case it is required, and the actual handler for the command.
17151  */
17152 static char *sip_show_channels(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
17153 {
17154    struct __show_chan_arg arg = { .fd = a->fd, .numchans = 0 };
17155 
17156 
17157    if (cmd == CLI_INIT) {
17158       e->command = "sip show {channels|subscriptions}";
17159       e->usage =
17160          "Usage: sip show channels\n"
17161          "       Lists all currently active SIP calls (dialogs).\n"
17162          "Usage: sip show subscriptions\n"
17163          "       Lists active SIP subscriptions.\n";
17164       return NULL;
17165    } else if (cmd == CLI_GENERATE)
17166       return NULL;
17167 
17168    if (a->argc != e->args)
17169       return CLI_SHOWUSAGE;
17170    arg.subscriptions = !strcasecmp(a->argv[e->args - 1], "subscriptions");
17171    if (!arg.subscriptions)
17172       ast_cli(arg.fd, FORMAT2, "Peer", "User/ANR", "Call ID", "Format", "Hold", "Last Message", "Expiry", "Peer");
17173    else
17174       ast_cli(arg.fd, FORMAT3, "Peer", "User", "Call ID", "Extension", "Last state", "Type", "Mailbox", "Expiry");
17175 
17176    /* iterate on the container and invoke the callback on each item */
17177    ao2_t_callback(dialogs, OBJ_NODATA, show_channels_cb, &arg, "callback to show channels");
17178    
17179    /* print summary information */
17180    ast_cli(arg.fd, "%d active SIP %s%s\n", arg.numchans,
17181       (arg.subscriptions ? "subscription" : "dialog"),
17182       ESS(arg.numchans));  /* ESS(n) returns an "s" if n>1 */
17183    return CLI_SUCCESS;
17184 #undef FORMAT
17185 #undef FORMAT2
17186 #undef FORMAT3
17187 }
17188 
17189 /*! \brief Support routine for 'sip show channel' and 'sip show history' CLI
17190  * This is in charge of generating all strings that match a prefix in the
17191  * given position. As many functions of this kind, each invokation has
17192  * O(state) time complexity so be careful in using it.
17193  */
17194 static char *complete_sipch(const char *line, const char *word, int pos, int state)
17195 {
17196    int which=0;
17197    struct sip_pvt *cur;
17198    char *c = NULL;
17199    int wordlen = strlen(word);
17200    struct ao2_iterator i;
17201 
17202    if (pos != 3) {
17203       return NULL;
17204    }
17205 
17206    i = ao2_iterator_init(dialogs, 0);
17207    while ((cur = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
17208       sip_pvt_lock(cur);
17209       if (!strncasecmp(word, cur->callid, wordlen) && ++which > state) {
17210          c = ast_strdup(cur->callid);
17211          sip_pvt_unlock(cur);
17212          dialog_unref(cur, "drop ref in iterator loop break");
17213          break;
17214       }
17215       sip_pvt_unlock(cur);
17216       dialog_unref(cur, "drop ref in iterator loop");
17217    }
17218    ao2_iterator_destroy(&i);
17219    return c;
17220 }
17221 
17222 
17223 /*! \brief Do completion on peer name */
17224 static char *complete_sip_peer(const char *word, int state, int flags2)
17225 {
17226    char *result = NULL;
17227    int wordlen = strlen(word);
17228    int which = 0;
17229    struct ao2_iterator i = ao2_iterator_init(peers, 0);
17230    struct sip_peer *peer;
17231 
17232    while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
17233       /* locking of the object is not required because only the name and flags are being compared */
17234       if (!strncasecmp(word, peer->name, wordlen) &&
17235             (!flags2 || ast_test_flag(&peer->flags[1], flags2)) &&
17236             ++which > state)
17237          result = ast_strdup(peer->name);
17238       unref_peer(peer, "toss iterator peer ptr before break");
17239       if (result) {
17240          break;
17241       }
17242    }
17243    ao2_iterator_destroy(&i);
17244    return result;
17245 }
17246 
17247 /*! \brief Do completion on registered peer name */
17248 static char *complete_sip_registered_peer(const char *word, int state, int flags2)
17249 {
17250        char *result = NULL;
17251        int wordlen = strlen(word);
17252        int which = 0;
17253        struct ao2_iterator i;
17254        struct sip_peer *peer;
17255        
17256        i = ao2_iterator_init(peers, 0);
17257        while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
17258           if (!strncasecmp(word, peer->name, wordlen) &&
17259          (!flags2 || ast_test_flag(&peer->flags[1], flags2)) &&
17260          ++which > state && peer->expire > 0)
17261              result = ast_strdup(peer->name);
17262           if (result) {
17263              unref_peer(peer, "toss iterator peer ptr before break");
17264              break;
17265           }
17266           unref_peer(peer, "toss iterator peer ptr");
17267        }
17268        ao2_iterator_destroy(&i);
17269        return result;
17270 }
17271 
17272 /*! \brief Support routine for 'sip show history' CLI */
17273 static char *complete_sip_show_history(const char *line, const char *word, int pos, int state)
17274 {
17275    if (pos == 3)
17276       return complete_sipch(line, word, pos, state);
17277 
17278    return NULL;
17279 }
17280 
17281 /*! \brief Support routine for 'sip show peer' CLI */
17282 static char *complete_sip_show_peer(const char *line, const char *word, int pos, int state)
17283 {
17284    if (pos == 3) {
17285       return complete_sip_peer(word, state, 0);
17286    }
17287 
17288    return NULL;
17289 }
17290 
17291 /*! \brief Support routine for 'sip unregister' CLI */
17292 static char *complete_sip_unregister(const char *line, const char *word, int pos, int state)
17293 {
17294        if (pos == 2)
17295                return complete_sip_registered_peer(word, state, 0);
17296 
17297        return NULL;
17298 }
17299 
17300 /*! \brief Support routine for 'sip notify' CLI */
17301 static char *complete_sipnotify(const char *line, const char *word, int pos, int state)
17302 {
17303    char *c = NULL;
17304 
17305    if (pos == 2) {
17306       int which = 0;
17307       char *cat = NULL;
17308       int wordlen = strlen(word);
17309 
17310       /* do completion for notify type */
17311 
17312       if (!notify_types)
17313          return NULL;
17314       
17315       while ( (cat = ast_category_browse(notify_types, cat)) ) {
17316          if (!strncasecmp(word, cat, wordlen) && ++which > state) {
17317             c = ast_strdup(cat);
17318             break;
17319          }
17320       }
17321       return c;
17322    }
17323 
17324    if (pos > 2)
17325       return complete_sip_peer(word, state, 0);
17326 
17327    return NULL;
17328 }
17329 
17330 /*! \brief Show details of one active dialog */
17331 static char *sip_show_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
17332 {
17333    struct sip_pvt *cur;
17334    size_t len;
17335    int found = 0;
17336    struct ao2_iterator i;
17337 
17338    switch (cmd) {
17339    case CLI_INIT:
17340       e->command = "sip show channel";
17341       e->usage =
17342          "Usage: sip show channel <call-id>\n"
17343          "       Provides detailed status on a given SIP dialog (identified by SIP call-id).\n";
17344       return NULL;
17345    case CLI_GENERATE:
17346       return complete_sipch(a->line, a->word, a->pos, a->n);
17347    }
17348 
17349    if (a->argc != 4)
17350       return CLI_SHOWUSAGE;
17351    len = strlen(a->argv[3]);
17352    
17353    i = ao2_iterator_init(dialogs, 0);
17354    while ((cur = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
17355       sip_pvt_lock(cur);
17356 
17357       if (!strncasecmp(cur->callid, a->argv[3], len)) {
17358          char formatbuf[SIPBUFSIZE/2];
17359          ast_cli(a->fd, "\n");
17360          if (cur->subscribed != NONE)
17361             ast_cli(a->fd, "  * Subscription (type: %s)\n", subscription_type2str(cur->subscribed));
17362          else
17363             ast_cli(a->fd, "  * SIP Call\n");
17364          ast_cli(a->fd, "  Curr. trans. direction:  %s\n", ast_test_flag(&cur->flags[0], SIP_OUTGOING) ? "Outgoing" : "Incoming");
17365          ast_cli(a->fd, "  Call-ID:                %s\n", cur->callid);
17366          ast_cli(a->fd, "  Owner channel ID:       %s\n", cur->owner ? cur->owner->name : "<none>");
17367          ast_cli(a->fd, "  Our Codec Capability:   %s\n", ast_getformatname_multiple(formatbuf, sizeof(formatbuf), cur->capability));
17368          ast_cli(a->fd, "  Non-Codec Capability (DTMF):   %d\n", cur->noncodeccapability);
17369          ast_cli(a->fd, "  Their Codec Capability:   %s\n", ast_getformatname_multiple(formatbuf, sizeof(formatbuf), cur->peercapability));
17370          ast_cli(a->fd, "  Joint Codec Capability:   %s\n", ast_getformatname_multiple(formatbuf, sizeof(formatbuf), cur->jointcapability));
17371          ast_cli(a->fd, "  Format:                 %s\n", ast_getformatname_multiple(formatbuf, sizeof(formatbuf), cur->owner ? cur->owner->nativeformats : 0) );
17372          ast_cli(a->fd, "  T.38 support            %s\n", AST_CLI_YESNO(cur->udptl != NULL));
17373          ast_cli(a->fd, "  Video support           %s\n", AST_CLI_YESNO(cur->vrtp != NULL));
17374          ast_cli(a->fd, "  MaxCallBR:              %d kbps\n", cur->maxcallbitrate);
17375          ast_cli(a->fd, "  Theoretical Address:    %s\n", ast_sockaddr_stringify(&cur->sa));
17376          ast_cli(a->fd, "  Received Address:       %s\n", ast_sockaddr_stringify(&cur->recv));
17377          ast_cli(a->fd, "  SIP Transfer mode:      %s\n", transfermode2str(cur->allowtransfer));
17378          ast_cli(a->fd, "  Force rport:            %s\n", AST_CLI_YESNO(ast_test_flag(&cur->flags[0], SIP_NAT_FORCE_RPORT)));
17379          if (ast_sockaddr_isnull(&cur->redirip)) {
17380             ast_cli(a->fd,
17381                "  Audio IP:               %s (local)\n",
17382                ast_sockaddr_stringify_addr(&cur->ourip));
17383          } else {
17384             ast_cli(a->fd,
17385                "  Audio IP:               %s (Outside bridge)\n",
17386                ast_sockaddr_stringify_addr(&cur->redirip));
17387          }
17388          ast_cli(a->fd, "  Our Tag:                %s\n", cur->tag);
17389          ast_cli(a->fd, "  Their Tag:              %s\n", cur->theirtag);
17390          ast_cli(a->fd, "  SIP User agent:         %s\n", cur->useragent);
17391          if (!ast_strlen_zero(cur->username))
17392             ast_cli(a->fd, "  Username:               %s\n", cur->username);
17393          if (!ast_strlen_zero(cur->peername))
17394             ast_cli(a->fd, "  Peername:               %s\n", cur->peername);
17395          if (!ast_strlen_zero(cur->uri))
17396             ast_cli(a->fd, "  Original uri:           %s\n", cur->uri);
17397          if (!ast_strlen_zero(cur->cid_num))
17398             ast_cli(a->fd, "  Caller-ID:              %s\n", cur->cid_num);
17399          ast_cli(a->fd, "  Need Destroy:           %s\n", AST_CLI_YESNO(cur->needdestroy));
17400          ast_cli(a->fd, "  Last Message:           %s\n", cur->lastmsg);
17401          ast_cli(a->fd, "  Promiscuous Redir:      %s\n", AST_CLI_YESNO(ast_test_flag(&cur->flags[0], SIP_PROMISCREDIR)));
17402          ast_cli(a->fd, "  Route:                  %s\n", cur->route ? cur->route->hop : "N/A");
17403          ast_cli(a->fd, "  DTMF Mode:              %s\n", dtmfmode2str(ast_test_flag(&cur->flags[0], SIP_DTMF)));
17404          ast_cli(a->fd, "  SIP Options:            ");
17405          if (cur->sipoptions) {
17406             int x;
17407             for (x = 0 ; x < ARRAY_LEN(sip_options); x++) {
17408                if (cur->sipoptions & sip_options[x].id)
17409                   ast_cli(a->fd, "%s ", sip_options[x].text);
17410             }
17411             ast_cli(a->fd, "\n");
17412          } else
17413             ast_cli(a->fd, "(none)\n");
17414 
17415          if (!cur->stimer)
17416             ast_cli(a->fd, "  Session-Timer:          Uninitiallized\n");
17417          else {
17418             ast_cli(a->fd, "  Session-Timer:          %s\n", cur->stimer->st_active ? "Active" : "Inactive");
17419             if (cur->stimer->st_active == TRUE) {
17420                ast_cli(a->fd, "  S-Timer Interval:       %d\n", cur->stimer->st_interval);
17421                ast_cli(a->fd, "  S-Timer Refresher:      %s\n", strefresher2str(cur->stimer->st_ref));
17422                ast_cli(a->fd, "  S-Timer Expirys:        %d\n", cur->stimer->st_expirys);
17423                ast_cli(a->fd, "  S-Timer Sched Id:       %d\n", cur->stimer->st_schedid);
17424                ast_cli(a->fd, "  S-Timer Peer Sts:       %s\n", cur->stimer->st_active_peer_ua ? "Active" : "Inactive");
17425                ast_cli(a->fd, "  S-Timer Cached Min-SE:  %d\n", cur->stimer->st_cached_min_se);
17426                ast_cli(a->fd, "  S-Timer Cached SE:      %d\n", cur->stimer->st_cached_max_se);
17427                ast_cli(a->fd, "  S-Timer Cached Ref:     %s\n", strefresher2str(cur->stimer->st_cached_ref));
17428                ast_cli(a->fd, "  S-Timer Cached Mode:    %s\n", stmode2str(cur->stimer->st_cached_mode));
17429             }
17430          }
17431 
17432          ast_cli(a->fd, "\n\n");
17433 
17434          found++;
17435       }
17436 
17437       sip_pvt_unlock(cur);
17438 
17439       ao2_t_ref(cur, -1, "toss dialog ptr set by iterator_next");
17440    }
17441    ao2_iterator_destroy(&i);
17442 
17443    if (!found)
17444       ast_cli(a->fd, "No such SIP Call ID starting with '%s'\n", a->argv[3]);
17445 
17446    return CLI_SUCCESS;
17447 }
17448 
17449 /*! \brief Show history details of one dialog */
17450 static char *sip_show_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
17451 {
17452    struct sip_pvt *cur;
17453    size_t len;
17454    int found = 0;
17455    struct ao2_iterator i;
17456 
17457    switch (cmd) {
17458    case CLI_INIT:
17459       e->command = "sip show history";
17460       e->usage =
17461          "Usage: sip show history <call-id>\n"
17462          "       Provides detailed dialog history on a given SIP call (specified by call-id).\n";
17463       return NULL;
17464    case CLI_GENERATE:
17465       return complete_sip_show_history(a->line, a->word, a->pos, a->n);
17466    }
17467 
17468    if (a->argc != 4)
17469       return CLI_SHOWUSAGE;
17470 
17471    if (!recordhistory)
17472       ast_cli(a->fd, "\n***Note: History recording is currently DISABLED.  Use 'sip set history on' to ENABLE.\n");
17473 
17474    len = strlen(a->argv[3]);
17475 
17476    i = ao2_iterator_init(dialogs, 0);
17477    while ((cur = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
17478       sip_pvt_lock(cur);
17479       if (!strncasecmp(cur->callid, a->argv[3], len)) {
17480          struct sip_history *hist;
17481          int x = 0;
17482 
17483          ast_cli(a->fd, "\n");
17484          if (cur->subscribed != NONE)
17485             ast_cli(a->fd, "  * Subscription\n");
17486          else
17487             ast_cli(a->fd, "  * SIP Call\n");
17488          if (cur->history)
17489             AST_LIST_TRAVERSE(cur->history, hist, list)
17490                ast_cli(a->fd, "%d. %s\n", ++x, hist->event);
17491          if (x == 0)
17492             ast_cli(a->fd, "Call '%s' has no history\n", cur->callid);
17493          found++;
17494       }
17495       sip_pvt_unlock(cur);
17496       ao2_t_ref(cur, -1, "toss dialog ptr from iterator_next");
17497    }
17498    ao2_iterator_destroy(&i);
17499 
17500    if (!found)
17501       ast_cli(a->fd, "No such SIP Call ID starting with '%s'\n", a->argv[3]);
17502 
17503    return CLI_SUCCESS;
17504 }
17505 
17506 /*! \brief Dump SIP history to debug log file at end of lifespan for SIP dialog */
17507 static void sip_dump_history(struct sip_pvt *dialog)
17508 {
17509    int x = 0;
17510    struct sip_history *hist;
17511    static int errmsg = 0;
17512 
17513    if (!dialog)
17514       return;
17515 
17516    if (!option_debug && !sipdebug) {
17517       if (!errmsg) {
17518          ast_log(LOG_NOTICE, "You must have debugging enabled (SIP or Asterisk) in order to dump SIP history.\n");
17519          errmsg = 1;
17520       }
17521       return;
17522    }
17523 
17524    ast_debug(1, "\n---------- SIP HISTORY for '%s' \n", dialog->callid);
17525    if (dialog->subscribed)
17526       ast_debug(1, "  * Subscription\n");
17527    else
17528       ast_debug(1, "  * SIP Call\n");
17529    if (dialog->history)
17530       AST_LIST_TRAVERSE(dialog->history, hist, list)
17531          ast_debug(1, "  %-3.3d. %s\n", ++x, hist->event);
17532    if (!x)
17533       ast_debug(1, "Call '%s' has no history\n", dialog->callid);
17534    ast_debug(1, "\n---------- END SIP HISTORY for '%s' \n", dialog->callid);
17535 }
17536 
17537 
17538 /*! \brief  Receive SIP INFO Message */
17539 static void handle_request_info(struct sip_pvt *p, struct sip_request *req)
17540 {
17541    char buf[1024];
17542    unsigned int event;
17543    const char *c = get_header(req, "Content-Type");
17544 
17545    /* Need to check the media/type */
17546    if (!strcasecmp(c, "application/dtmf-relay") ||
17547        !strcasecmp(c, "application/vnd.nortelnetworks.digits")) {
17548       unsigned int duration = 0;
17549 
17550       if (!p->owner) {  /* not a PBX call */
17551          transmit_response(p, "481 Call leg/transaction does not exist", req);
17552          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
17553          return;
17554       }
17555 
17556       /* Try getting the "signal=" part */
17557       if (ast_strlen_zero(c = get_body(req, "Signal", '=')) && ast_strlen_zero(c = get_body(req, "d", '='))) {
17558          ast_log(LOG_WARNING, "Unable to retrieve DTMF signal from INFO message from %s\n", p->callid);
17559          transmit_response(p, "200 OK", req); /* Should return error */
17560          return;
17561       } else {
17562          ast_copy_string(buf, c, sizeof(buf));
17563       }
17564 
17565       if (!ast_strlen_zero((c = get_body(req, "Duration", '='))))
17566          duration = atoi(c);
17567       if (!duration)
17568          duration = 100; /* 100 ms */
17569 
17570 
17571       if (ast_strlen_zero(buf)) {
17572          transmit_response(p, "200 OK", req);
17573          return;
17574       }
17575 
17576       if (buf[0] == '*')
17577          event = 10;
17578       else if (buf[0] == '#')
17579          event = 11;
17580       else if ((buf[0] >= 'A') && (buf[0] <= 'D'))
17581          event = 12 + buf[0] - 'A';
17582       else if (buf[0] == '!')
17583          event = 16;
17584       else
17585          event = atoi(buf);
17586       if (event == 16) {
17587          /* send a FLASH event */
17588          struct ast_frame f = { AST_FRAME_CONTROL, { AST_CONTROL_FLASH, } };
17589          ast_queue_frame(p->owner, &f);
17590          if (sipdebug)
17591             ast_verbose("* DTMF-relay event received: FLASH\n");
17592       } else {
17593          /* send a DTMF event */
17594          struct ast_frame f = { AST_FRAME_DTMF, };
17595          if (event < 10) {
17596             f.subclass.integer = '0' + event;
17597          } else if (event == 10) {
17598             f.subclass.integer = '*';
17599          } else if (event == 11) {
17600             f.subclass.integer = '#';
17601          } else if (event < 16) {
17602             f.subclass.integer = 'A' + (event - 12);
17603          }
17604          f.len = duration;
17605          ast_queue_frame(p->owner, &f);
17606          if (sipdebug)
17607             ast_verbose("* DTMF-relay event received: %c\n", (int) f.subclass.integer);
17608       }
17609       transmit_response(p, "200 OK", req);
17610       return;
17611    } else if (!strcasecmp(c, "application/dtmf")) {
17612       /*! \todo Note: Doesn't read the duration of the DTMF. Should be fixed. */
17613       unsigned int duration = 0;
17614 
17615       if (!p->owner) {  /* not a PBX call */
17616          transmit_response(p, "481 Call leg/transaction does not exist", req);
17617          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
17618          return;
17619       }
17620 
17621       get_msg_text(buf, sizeof(buf), req, TRUE);
17622       duration = 100; /* 100 ms */
17623 
17624       if (ast_strlen_zero(buf)) {
17625          transmit_response(p, "200 OK", req);
17626          return;
17627       }
17628       event = atoi(buf);
17629       if (event == 16) {
17630          /* send a FLASH event */
17631          struct ast_frame f = { AST_FRAME_CONTROL, { AST_CONTROL_FLASH }, };
17632          ast_queue_frame(p->owner, &f);
17633          if (sipdebug)
17634             ast_verbose("* DTMF-relay event received: FLASH\n");
17635       } else {
17636          /* send a DTMF event */
17637          struct ast_frame f = { AST_FRAME_DTMF, };
17638          if (event < 10) {
17639             f.subclass.integer = '0' + event;
17640          } else if (event == 10) {
17641             f.subclass.integer = '*';
17642          } else if (event == 11) {
17643             f.subclass.integer = '#';
17644          } else if (event < 16) {
17645             f.subclass.integer = 'A' + (event - 12);
17646          }
17647          f.len = duration;
17648          ast_queue_frame(p->owner, &f);
17649          if (sipdebug)
17650             ast_verbose("* DTMF-relay event received: %c\n", (int) f.subclass.integer);
17651       }
17652       transmit_response(p, "200 OK", req);
17653       return;
17654 
17655    } else if (!strcasecmp(c, "application/media_control+xml")) {
17656       /* Eh, we'll just assume it's a fast picture update for now */
17657       if (p->owner)
17658          ast_queue_control(p->owner, AST_CONTROL_VIDUPDATE);
17659       transmit_response(p, "200 OK", req);
17660       return;
17661    } else if (!ast_strlen_zero(c = get_header(req, "X-ClientCode"))) {
17662       /* Client code (from SNOM phone) */
17663       if (ast_test_flag(&p->flags[0], SIP_USECLIENTCODE)) {
17664          if (p->owner && p->owner->cdr)
17665             ast_cdr_setuserfield(p->owner, c);
17666          if (p->owner && ast_bridged_channel(p->owner) && ast_bridged_channel(p->owner)->cdr)
17667             ast_cdr_setuserfield(ast_bridged_channel(p->owner), c);
17668          transmit_response(p, "200 OK", req);
17669       } else {
17670          transmit_response(p, "403 Forbidden", req);
17671       }
17672       return;
17673    } else if (!ast_strlen_zero(c = get_header(req, "Record"))) {
17674       /* INFO messages generated by some phones to start/stop recording
17675          on phone calls.
17676          OEJ: I think this should be something that is enabled/disabled
17677          per device. I don't want incoming callers to record calls in my
17678          pbx.
17679       */
17680       /* first, get the feature string, if it exists */
17681       struct ast_call_feature *feat;
17682       int j;
17683       struct ast_frame f = { AST_FRAME_DTMF, };
17684 
17685       ast_rdlock_call_features();
17686       feat = ast_find_call_feature("automon");
17687       if (!feat || ast_strlen_zero(feat->exten)) {
17688          ast_log(LOG_WARNING, "Recording requested, but no One Touch Monitor registered. (See features.conf)\n");
17689          /* 403 means that we don't support this feature, so don't request it again */
17690          transmit_response(p, "403 Forbidden", req);
17691          ast_unlock_call_features();
17692          return;
17693       }
17694       /* Send the feature code to the PBX as DTMF, just like the handset had sent it */
17695       f.len = 100;
17696       for (j=0; j < strlen(feat->exten); j++) {
17697          f.subclass.integer = feat->exten[j];
17698          ast_queue_frame(p->owner, &f);
17699          if (sipdebug)
17700             ast_verbose("* DTMF-relay event faked: %c\n", f.subclass.integer);
17701       }
17702       ast_unlock_call_features();
17703 
17704       ast_debug(1, "Got a Request to Record the channel, state %s\n", c);
17705       transmit_response(p, "200 OK", req);
17706       return;
17707    } else if (ast_strlen_zero(c = get_header(req, "Content-Length")) || !strcasecmp(c, "0")) {
17708       /* This is probably just a packet making sure the signalling is still up, just send back a 200 OK */
17709       transmit_response(p, "200 OK", req);
17710       return;
17711    }
17712 
17713    /* Other type of INFO message, not really understood by Asterisk */
17714    /* if (get_msg_text(buf, sizeof(buf), req)) { */
17715 
17716    ast_log(LOG_WARNING, "Unable to parse INFO message from %s. Content %s\n", p->callid, buf);
17717    transmit_response(p, "415 Unsupported media type", req);
17718    return;
17719 }
17720 
17721 /*! \brief Enable SIP Debugging for a single IP */
17722 static char *sip_do_debug_ip(int fd, const char *arg)
17723 {
17724    if (ast_sockaddr_resolve_first(&debugaddr, arg, 0)) {
17725       return CLI_SHOWUSAGE;
17726    }
17727 
17728    ast_cli(fd, "SIP Debugging Enabled for IP: %s\n", ast_sockaddr_stringify_addr(&debugaddr));
17729    sipdebug |= sip_debug_console;
17730 
17731    return CLI_SUCCESS;
17732 }
17733 
17734 /*! \brief  Turn on SIP debugging for a given peer */
17735 static char *sip_do_debug_peer(int fd, const char *arg)
17736 {
17737    struct sip_peer *peer = find_peer(arg, NULL, TRUE, FINDPEERS, FALSE, 0);
17738    if (!peer)
17739       ast_cli(fd, "No such peer '%s'\n", arg);
17740    else if (ast_sockaddr_isnull(&peer->addr))
17741       ast_cli(fd, "Unable to get IP address of peer '%s'\n", arg);
17742    else {
17743       ast_sockaddr_copy(&debugaddr, &peer->addr);
17744       ast_cli(fd, "SIP Debugging Enabled for IP: %s\n", ast_sockaddr_stringify_addr(&debugaddr));
17745       sipdebug |= sip_debug_console;
17746    }
17747    if (peer)
17748       unref_peer(peer, "sip_do_debug_peer: unref_peer, from find_peer call");
17749    return CLI_SUCCESS;
17750 }
17751 
17752 /*! \brief Turn on SIP debugging (CLI command) */
17753 static char *sip_do_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
17754 {
17755    int oldsipdebug = sipdebug & sip_debug_console;
17756    const char *what;
17757 
17758    if (cmd == CLI_INIT) {
17759       e->command = "sip set debug {on|off|ip|peer}";
17760       e->usage =
17761          "Usage: sip set debug {off|on|ip addr[:port]|peer peername}\n"
17762          "       Globally disables dumping of SIP packets,\n"
17763          "       or enables it either globally or for a (single)\n"
17764          "       IP address or registered peer.\n";
17765       return NULL;
17766    } else if (cmd == CLI_GENERATE) {
17767       if (a->pos == 4 && !strcasecmp(a->argv[3], "peer"))
17768          return complete_sip_peer(a->word, a->n, 0);
17769       return NULL;
17770         }
17771 
17772    what = a->argv[e->args-1];      /* guaranteed to exist */
17773    if (a->argc == e->args) {       /* on/off */
17774       if (!strcasecmp(what, "on")) {
17775          sipdebug |= sip_debug_console;
17776          sipdebug_text = 1;   /*! \note this can be a special debug command - "sip debug text" or something */
17777          memset(&debugaddr, 0, sizeof(debugaddr));
17778          ast_cli(a->fd, "SIP Debugging %senabled\n", oldsipdebug ? "re-" : "");
17779          return CLI_SUCCESS;
17780       } else if (!strcasecmp(what, "off")) {
17781          sipdebug &= ~sip_debug_console;
17782          sipdebug_text = 0;
17783          ast_cli(a->fd, "SIP Debugging Disabled\n");
17784          return CLI_SUCCESS;
17785       }
17786    } else if (a->argc == e->args +1) {/* ip/peer */
17787       if (!strcasecmp(what, "ip"))
17788          return sip_do_debug_ip(a->fd, a->argv[e->args]);
17789       else if (!strcasecmp(what, "peer"))
17790          return sip_do_debug_peer(a->fd, a->argv[e->args]);
17791    }
17792    return CLI_SHOWUSAGE;   /* default, failure */
17793 }
17794 
17795 /*! \brief Cli command to send SIP notify to peer */
17796 static char *sip_cli_notify(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
17797 {
17798    struct ast_variable *varlist;
17799    int i;
17800 
17801    switch (cmd) {
17802    case CLI_INIT:
17803       e->command = "sip notify";
17804       e->usage =
17805          "Usage: sip notify <type> <peer> [<peer>...]\n"
17806          "       Send a NOTIFY message to a SIP peer or peers\n"
17807          "       Message types are defined in sip_notify.conf\n";
17808       return NULL;
17809    case CLI_GENERATE:
17810       return complete_sipnotify(a->line, a->word, a->pos, a->n);
17811    }
17812 
17813    if (a->argc < 4)
17814       return CLI_SHOWUSAGE;
17815 
17816    if (!notify_types) {
17817       ast_cli(a->fd, "No %s file found, or no types listed there\n", notify_config);
17818       return CLI_FAILURE;
17819    }
17820 
17821    varlist = ast_variable_browse(notify_types, a->argv[2]);
17822 
17823    if (!varlist) {
17824       ast_cli(a->fd, "Unable to find notify type '%s'\n", a->argv[2]);
17825       return CLI_FAILURE;
17826    }
17827 
17828    for (i = 3; i < a->argc; i++) {
17829       struct sip_pvt *p;
17830       char buf[512];
17831       struct ast_variable *header, *var;
17832 
17833       if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY, NULL))) {
17834          ast_log(LOG_WARNING, "Unable to build sip pvt data for notify (memory/socket error)\n");
17835          return CLI_FAILURE;
17836       }
17837 
17838       if (create_addr(p, a->argv[i], NULL, 1, NULL)) {
17839          /* Maybe they're not registered, etc. */
17840          dialog_unlink_all(p, TRUE, TRUE);
17841          dialog_unref(p, "unref dialog inside for loop" );
17842          /* sip_destroy(p); */
17843          ast_cli(a->fd, "Could not create address for '%s'\n", a->argv[i]);
17844          continue;
17845       }
17846 
17847       /* Notify is outgoing call */
17848       ast_set_flag(&p->flags[0], SIP_OUTGOING);
17849       sip_notify_allocate(p);
17850       p->notify->headers = header = ast_variable_new("Subscription-State", "terminated", "");
17851 
17852       for (var = varlist; var; var = var->next) {
17853          ast_copy_string(buf, var->value, sizeof(buf));
17854          ast_unescape_semicolon(buf);
17855 
17856          if (!strcasecmp(var->name, "Content")) {
17857             if (ast_str_strlen(p->notify->content))
17858                ast_str_append(&p->notify->content, 0, "\r\n");
17859             ast_str_append(&p->notify->content, 0, "%s", buf);
17860          } else if (!strcasecmp(var->name, "Content-Length")) {
17861             ast_log(LOG_WARNING, "it is not necessary to specify Content-Length in sip_notify.conf, ignoring");
17862          } else {
17863             header->next = ast_variable_new(var->name, buf, "");
17864             header = header->next;
17865          }
17866       }
17867 
17868       /* Recalculate our side, and recalculate Call ID */
17869       ast_cli(a->fd, "Sending NOTIFY of type '%s' to '%s'\n", a->argv[2], a->argv[i]);
17870       dialog_ref(p, "bump the count of p, which transmit_sip_request will decrement.");
17871       sip_scheddestroy(p, SIP_TRANS_TIMEOUT);
17872       transmit_invite(p, SIP_NOTIFY, 0, 2, NULL);
17873    }
17874 
17875    return CLI_SUCCESS;
17876 }
17877 
17878 /*! \brief Enable/Disable SIP History logging (CLI) */
17879 static char *sip_set_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
17880 {
17881    switch (cmd) {
17882    case CLI_INIT:
17883       e->command = "sip set history {on|off}";
17884       e->usage =
17885          "Usage: sip set history {on|off}\n"
17886          "       Enables/Disables recording of SIP dialog history for debugging purposes.\n"
17887          "       Use 'sip show history' to view the history of a call number.\n";
17888       return NULL;
17889    case CLI_GENERATE:
17890       return NULL;
17891    }
17892 
17893    if (a->argc != e->args)
17894       return CLI_SHOWUSAGE;
17895 
17896    if (!strncasecmp(a->argv[e->args - 1], "on", 2)) {
17897       recordhistory = TRUE;
17898       ast_cli(a->fd, "SIP History Recording Enabled (use 'sip show history')\n");
17899    } else if (!strncasecmp(a->argv[e->args - 1], "off", 3)) {
17900       recordhistory = FALSE;
17901       ast_cli(a->fd, "SIP History Recording Disabled\n");
17902    } else {
17903       return CLI_SHOWUSAGE;
17904    }
17905    return CLI_SUCCESS;
17906 }
17907 
17908 /*! \brief Authenticate for outbound registration */
17909 static int do_register_auth(struct sip_pvt *p, struct sip_request *req, enum sip_auth_type code)
17910 {
17911    char *header, *respheader;
17912    char digest[1024];
17913 
17914    p->authtries++;
17915    auth_headers(code, &header, &respheader);
17916    memset(digest, 0, sizeof(digest));
17917    if (reply_digest(p, req, header, SIP_REGISTER, digest, sizeof(digest))) {
17918       /* There's nothing to use for authentication */
17919       /* No digest challenge in request */
17920       if (sip_debug_test_pvt(p) && p->registry)
17921          ast_verbose("No authentication challenge, sending blank registration to domain/host name %s\n", p->registry->hostname);
17922          /* No old challenge */
17923       return -1;
17924    }
17925    if (p->do_history)
17926       append_history(p, "RegistryAuth", "Try: %d", p->authtries);
17927    if (sip_debug_test_pvt(p) && p->registry)
17928       ast_verbose("Responding to challenge, registration to domain/host name %s\n", p->registry->hostname);
17929    return transmit_register(p->registry, SIP_REGISTER, digest, respheader);
17930 }
17931 
17932 /*! \brief Add authentication on outbound SIP packet */
17933 static int do_proxy_auth(struct sip_pvt *p, struct sip_request *req, enum sip_auth_type code, int sipmethod, int init)
17934 {
17935    char *header, *respheader;
17936    char digest[1024];
17937 
17938    if (!p->options && !(p->options = ast_calloc(1, sizeof(*p->options))))
17939       return -2;
17940 
17941    p->authtries++;
17942    auth_headers(code, &header, &respheader);
17943    ast_debug(2, "Auth attempt %d on %s\n", p->authtries, sip_methods[sipmethod].text);
17944    memset(digest, 0, sizeof(digest));
17945    if (reply_digest(p, req, header, sipmethod, digest, sizeof(digest) )) {
17946       /* No way to authenticate */
17947       return -1;
17948    }
17949    /* Now we have a reply digest */
17950    p->options->auth = digest;
17951    p->options->authheader = respheader;
17952    return transmit_invite(p, sipmethod, sipmethod == SIP_INVITE, init, NULL);
17953 }
17954 
17955 /*! \brief  reply to authentication for outbound registrations
17956 \return  Returns -1 if we have no auth
17957 \note This is used for register= servers in sip.conf, SIP proxies we register
17958    with  for receiving calls from.  */
17959 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod,  char *digest, int digest_len)
17960 {
17961    char tmp[512];
17962    char *c;
17963    char oldnonce[256];
17964 
17965    /* table of recognised keywords, and places where they should be copied */
17966    const struct x {
17967       const char *key;
17968       const ast_string_field *field;
17969    } *i, keys[] = {
17970       { "realm=", &p->realm },
17971       { "nonce=", &p->nonce },
17972       { "opaque=", &p->opaque },
17973       { "qop=", &p->qop },
17974       { "domain=", &p->domain },
17975       { NULL, 0 },
17976    };
17977 
17978    ast_copy_string(tmp, get_header(req, header), sizeof(tmp));
17979    if (ast_strlen_zero(tmp))
17980       return -1;
17981    if (strncasecmp(tmp, "Digest ", strlen("Digest "))) {
17982       ast_log(LOG_WARNING, "missing Digest.\n");
17983       return -1;
17984    }
17985    c = tmp + strlen("Digest ");
17986    ast_copy_string(oldnonce, p->nonce, sizeof(oldnonce));
17987    while (c && *(c = ast_skip_blanks(c))) {  /* lookup for keys */
17988       for (i = keys; i->key != NULL; i++) {
17989          char *src, *separator;
17990          if (strncasecmp(c, i->key, strlen(i->key)) != 0)
17991             continue;
17992          /* Found. Skip keyword, take text in quotes or up to the separator. */
17993          c += strlen(i->key);
17994          if (*c == '"') {
17995             src = ++c;
17996             separator = "\"";
17997          } else {
17998             src = c;
17999             separator = ",";
18000          }
18001          strsep(&c, separator); /* clear separator and move ptr */
18002          ast_string_field_ptr_set(p, i->field, src);
18003          break;
18004       }
18005       if (i->key == NULL) /* not found, try ',' */
18006          strsep(&c, ",");
18007    }
18008    /* Reset nonce count */
18009    if (strcmp(p->nonce, oldnonce))
18010       p->noncecount = 0;
18011 
18012    /* Save auth data for following registrations */
18013    if (p->registry) {
18014       struct sip_registry *r = p->registry;
18015 
18016       if (strcmp(r->nonce, p->nonce)) {
18017          ast_string_field_set(r, realm, p->realm);
18018          ast_string_field_set(r, nonce, p->nonce);
18019          ast_string_field_set(r, authdomain, p->domain);
18020          ast_string_field_set(r, opaque, p->opaque);
18021          ast_string_field_set(r, qop, p->qop);
18022          r->noncecount = 0;
18023       }
18024    }
18025    return build_reply_digest(p, sipmethod, digest, digest_len);
18026 }
18027 
18028 /*! \brief  Build reply digest
18029 \return  Returns -1 if we have no auth
18030 \note Build digest challenge for authentication of registrations and calls
18031    Also used for authentication of BYE
18032 */
18033 static int build_reply_digest(struct sip_pvt *p, int method, char* digest, int digest_len)
18034 {
18035    char a1[256];
18036    char a2[256];
18037    char a1_hash[256];
18038    char a2_hash[256];
18039    char resp[256];
18040    char resp_hash[256];
18041    char uri[256];
18042    char opaque[256] = "";
18043    char cnonce[80];
18044    const char *username;
18045    const char *secret;
18046    const char *md5secret;
18047    struct sip_auth *auth = NULL; /* Realm authentication */
18048 
18049    if (!ast_strlen_zero(p->domain))
18050       ast_copy_string(uri, p->domain, sizeof(uri));
18051    else if (!ast_strlen_zero(p->uri))
18052       ast_copy_string(uri, p->uri, sizeof(uri));
18053    else
18054       snprintf(uri, sizeof(uri), "sip:%s@%s", p->username, ast_sockaddr_stringify_host(&p->sa));
18055 
18056    snprintf(cnonce, sizeof(cnonce), "%08lx", ast_random());
18057 
18058    /* Check if we have separate auth credentials */
18059    if(!(auth = find_realm_authentication(p->peerauth, p->realm))) /* Start with peer list */
18060       auth = find_realm_authentication(authl, p->realm); /* If not, global list */
18061 
18062    if (auth) {
18063       ast_debug(3, "use realm [%s] from peer [%s][%s]\n", auth->username, p->peername, p->username);
18064       username = auth->username;
18065       secret = auth->secret;
18066       md5secret = auth->md5secret;
18067       if (sipdebug)
18068          ast_debug(1, "Using realm %s authentication for call %s\n", p->realm, p->callid);
18069    } else {
18070       /* No authentication, use peer or register= config */
18071       username = p->authname;
18072       secret =  p->peersecret;
18073       md5secret = p->peermd5secret;
18074    }
18075    if (ast_strlen_zero(username))   /* We have no authentication */
18076       return -1;
18077 
18078    /* Calculate SIP digest response */
18079    snprintf(a1, sizeof(a1), "%s:%s:%s", username, p->realm, secret);
18080    snprintf(a2, sizeof(a2), "%s:%s", sip_methods[method].text, uri);
18081    if (!ast_strlen_zero(md5secret))
18082       ast_copy_string(a1_hash, md5secret, sizeof(a1_hash));
18083    else
18084       ast_md5_hash(a1_hash, a1);
18085    ast_md5_hash(a2_hash, a2);
18086 
18087    p->noncecount++;
18088    if (!ast_strlen_zero(p->qop))
18089       snprintf(resp, sizeof(resp), "%s:%s:%08x:%s:%s:%s", a1_hash, p->nonce, p->noncecount, cnonce, "auth", a2_hash);
18090    else
18091       snprintf(resp, sizeof(resp), "%s:%s:%s", a1_hash, p->nonce, a2_hash);
18092    ast_md5_hash(resp_hash, resp);
18093 
18094    /* only include the opaque string if it's set */
18095    if (!ast_strlen_zero(p->opaque)) {
18096      snprintf(opaque, sizeof(opaque), ", opaque=\"%s\"", p->opaque);
18097    }
18098 
18099    /* XXX We hard code our qop to "auth" for now.  XXX */
18100    if (!ast_strlen_zero(p->qop))
18101       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);
18102    else
18103       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);
18104 
18105    append_history(p, "AuthResp", "Auth response sent for %s in realm %s - nc %d", username, p->realm, p->noncecount);
18106 
18107    return 0;
18108 }
18109    
18110 /*! \brief Read SIP header (dialplan function) */
18111 static int func_header_read(struct ast_channel *chan, const char *function, char *data, char *buf, size_t len)
18112 {
18113    struct sip_pvt *p;
18114    const char *content = NULL;
18115    AST_DECLARE_APP_ARGS(args,
18116       AST_APP_ARG(header);
18117       AST_APP_ARG(number);
18118    );
18119    int i, number, start = 0;
18120 
18121    if (ast_strlen_zero(data)) {
18122       ast_log(LOG_WARNING, "This function requires a header name.\n");
18123       return -1;
18124    }
18125 
18126    ast_channel_lock(chan);
18127    if (!IS_SIP_TECH(chan->tech)) {
18128       ast_log(LOG_WARNING, "This function can only be used on SIP channels.\n");
18129       ast_channel_unlock(chan);
18130       return -1;
18131    }
18132 
18133    AST_STANDARD_APP_ARGS(args, data);
18134    if (!args.number) {
18135       number = 1;
18136    } else {
18137       sscanf(args.number, "%30d", &number);
18138       if (number < 1)
18139          number = 1;
18140    }
18141 
18142    p = chan->tech_pvt;
18143 
18144    /* If there is no private structure, this channel is no longer alive */
18145    if (!p) {
18146       ast_channel_unlock(chan);
18147       return -1;
18148    }
18149 
18150    for (i = 0; i < number; i++)
18151       content = __get_header(&p->initreq, args.header, &start);
18152 
18153    if (ast_strlen_zero(content)) {
18154       ast_channel_unlock(chan);
18155       return -1;
18156    }
18157 
18158    ast_copy_string(buf, content, len);
18159    ast_channel_unlock(chan);
18160 
18161    return 0;
18162 }
18163 
18164 static struct ast_custom_function sip_header_function = {
18165    .name = "SIP_HEADER",
18166    .read = func_header_read,
18167 };
18168 
18169 /*! \brief  Dial plan function to check if domain is local */
18170 static int func_check_sipdomain(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
18171 {
18172    if (ast_strlen_zero(data)) {
18173       ast_log(LOG_WARNING, "CHECKSIPDOMAIN requires an argument - A domain name\n");
18174       return -1;
18175    }
18176    if (check_sip_domain(data, NULL, 0))
18177       ast_copy_string(buf, data, len);
18178    else
18179       buf[0] = '\0';
18180    return 0;
18181 }
18182 
18183 static struct ast_custom_function checksipdomain_function = {
18184    .name = "CHECKSIPDOMAIN",
18185    .read = func_check_sipdomain,
18186 };
18187 
18188 /*! \brief  ${SIPPEER()} Dialplan function - reads peer data */
18189 static int function_sippeer(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
18190 {
18191    struct sip_peer *peer;
18192    char *colname;
18193 
18194    if ((colname = strchr(data, ':'))) {   /*! \todo Will be deprecated after 1.4 */
18195       static int deprecation_warning = 0;
18196       *colname++ = '\0';
18197       if (deprecation_warning++ % 10 == 0)
18198          ast_log(LOG_WARNING, "SIPPEER(): usage of ':' to separate arguments is deprecated.  Please use ',' instead.\n");
18199    } else if ((colname = strchr(data, ',')))
18200       *colname++ = '\0';
18201    else
18202       colname = "ip";
18203 
18204    if (!(peer = find_peer(data, NULL, TRUE, FINDPEERS, FALSE, 0)))
18205       return -1;
18206 
18207    if (!strcasecmp(colname, "ip")) {
18208       ast_copy_string(buf, ast_sockaddr_stringify_addr(&peer->addr), len);
18209    } else  if (!strcasecmp(colname, "port")) {
18210       snprintf(buf, len, "%d", ast_sockaddr_port(&peer->addr));
18211    } else  if (!strcasecmp(colname, "status")) {
18212       peer_status(peer, buf, len);
18213    } else  if (!strcasecmp(colname, "language")) {
18214       ast_copy_string(buf, peer->language, len);
18215    } else  if (!strcasecmp(colname, "regexten")) {
18216       ast_copy_string(buf, peer->regexten, len);
18217    } else  if (!strcasecmp(colname, "limit")) {
18218       snprintf(buf, len, "%d", peer->call_limit);
18219    } else  if (!strcasecmp(colname, "busylevel")) {
18220       snprintf(buf, len, "%d", peer->busy_level);
18221    } else  if (!strcasecmp(colname, "curcalls")) {
18222       snprintf(buf, len, "%d", peer->inUse);
18223    } else if (!strcasecmp(colname, "maxforwards")) {
18224       snprintf(buf, len, "%d", peer->maxforwards);
18225    } else  if (!strcasecmp(colname, "accountcode")) {
18226       ast_copy_string(buf, peer->accountcode, len);
18227    } else  if (!strcasecmp(colname, "callgroup")) {
18228       ast_print_group(buf, len, peer->callgroup);
18229    } else  if (!strcasecmp(colname, "pickupgroup")) {
18230       ast_print_group(buf, len, peer->pickupgroup);
18231    } else  if (!strcasecmp(colname, "useragent")) {
18232       ast_copy_string(buf, peer->useragent, len);
18233    } else  if (!strcasecmp(colname, "mailbox")) {
18234       struct ast_str *mailbox_str = ast_str_alloca(512);
18235       peer_mailboxes_to_str(&mailbox_str, peer);
18236       ast_copy_string(buf, mailbox_str->str, len);
18237    } else  if (!strcasecmp(colname, "context")) {
18238       ast_copy_string(buf, peer->context, len);
18239    } else  if (!strcasecmp(colname, "expire")) {
18240       snprintf(buf, len, "%d", peer->expire);
18241    } else  if (!strcasecmp(colname, "dynamic")) {
18242       ast_copy_string(buf, peer->host_dynamic ? "yes" : "no", len);
18243    } else  if (!strcasecmp(colname, "callerid_name")) {
18244       ast_copy_string(buf, peer->cid_name, len);
18245    } else  if (!strcasecmp(colname, "callerid_num")) {
18246       ast_copy_string(buf, peer->cid_num, len);
18247    } else  if (!strcasecmp(colname, "codecs")) {
18248       ast_getformatname_multiple(buf, len -1, peer->capability);
18249    } else if (!strcasecmp(colname, "encryption")) {
18250       snprintf(buf, len, "%d", ast_test_flag(&peer->flags[1], SIP_PAGE2_USE_SRTP));
18251    } else  if (!strncasecmp(colname, "chanvar[", 8)) {
18252       char *chanvar=colname + 8;
18253       struct ast_variable *v;
18254    
18255       chanvar = strsep(&chanvar, "]");
18256       for (v = peer->chanvars ; v ; v = v->next) {
18257          if (!strcasecmp(v->name, chanvar)) {
18258             ast_copy_string(buf, v->value, len);
18259          }
18260       }
18261    } else  if (!strncasecmp(colname, "codec[", 6)) {
18262       char *codecnum;
18263       format_t codec = 0;
18264       
18265       codecnum = colname + 6; /* move past the '[' */
18266       codecnum = strsep(&codecnum, "]"); /* trim trailing ']' if any */
18267       if((codec = ast_codec_pref_index(&peer->prefs, atoi(codecnum)))) {
18268          ast_copy_string(buf, ast_getformatname(codec), len);
18269       } else {
18270          buf[0] = '\0';
18271       }
18272    } else {
18273       buf[0] = '\0';
18274    }
18275 
18276    unref_peer(peer, "unref_peer from function_sippeer, just before return");
18277 
18278    return 0;
18279 }
18280 
18281 /*! \brief Structure to declare a dialplan function: SIPPEER */
18282 static struct ast_custom_function sippeer_function = {
18283    .name = "SIPPEER",
18284    .read = function_sippeer,
18285 };
18286 
18287 /*! \brief ${SIPCHANINFO()} Dialplan function - reads sip channel data */
18288 static int function_sipchaninfo_read(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
18289 {
18290    struct sip_pvt *p;
18291    static int deprecated = 0;
18292 
18293    *buf = 0;
18294    
18295    if (!data) {
18296       ast_log(LOG_WARNING, "This function requires a parameter name.\n");
18297       return -1;
18298    }
18299 
18300    ast_channel_lock(chan);
18301    if (!IS_SIP_TECH(chan->tech)) {
18302       ast_log(LOG_WARNING, "This function can only be used on SIP channels.\n");
18303       ast_channel_unlock(chan);
18304       return -1;
18305    }
18306 
18307    if (deprecated++ % 20 == 0) {
18308       /* Deprecated in 1.6.1 */
18309       ast_log(LOG_WARNING, "SIPCHANINFO() is deprecated.  Please transition to using CHANNEL().\n");
18310    }
18311 
18312    p = chan->tech_pvt;
18313 
18314    /* If there is no private structure, this channel is no longer alive */
18315    if (!p) {
18316       ast_channel_unlock(chan);
18317       return -1;
18318    }
18319 
18320    if (!strcasecmp(data, "peerip")) {
18321       ast_copy_string(buf, ast_sockaddr_stringify_addr(&p->sa), len);
18322    } else  if (!strcasecmp(data, "recvip")) {
18323       ast_copy_string(buf, ast_sockaddr_stringify_addr(&p->recv), len);
18324    } else  if (!strcasecmp(data, "from")) {
18325       ast_copy_string(buf, p->from, len);
18326    } else  if (!strcasecmp(data, "uri")) {
18327       ast_copy_string(buf, p->uri, len);
18328    } else  if (!strcasecmp(data, "useragent")) {
18329       ast_copy_string(buf, p->useragent, len);
18330    } else  if (!strcasecmp(data, "peername")) {
18331       ast_copy_string(buf, p->peername, len);
18332    } else if (!strcasecmp(data, "t38passthrough")) {
18333       if (p->t38.state == T38_DISABLED) {
18334          ast_copy_string(buf, "0", len);
18335       } else { /* T38 is offered or enabled in this call */
18336          ast_copy_string(buf, "1", len);
18337       }
18338    } else {
18339       ast_channel_unlock(chan);
18340       return -1;
18341    }
18342    ast_channel_unlock(chan);
18343 
18344    return 0;
18345 }
18346 
18347 /*! \brief Structure to declare a dialplan function: SIPCHANINFO */
18348 static struct ast_custom_function sipchaninfo_function = {
18349    .name = "SIPCHANINFO",
18350    .read = function_sipchaninfo_read,
18351 };
18352 
18353 /*! \brief update redirecting information for a channel based on headers
18354  *
18355  */
18356 static void change_redirecting_information(struct sip_pvt *p, struct sip_request *req,
18357    struct ast_party_redirecting *redirecting,
18358    struct ast_set_party_redirecting *update_redirecting, int set_call_forward)
18359 {
18360    char *redirecting_from_name = NULL;
18361    char *redirecting_from_number = NULL;
18362    char *redirecting_to_name = NULL;
18363    char *redirecting_to_number = NULL;
18364    int reason = AST_REDIRECTING_REASON_UNCONDITIONAL;
18365    int is_response = req->method == SIP_RESPONSE;
18366    int res = 0;
18367 
18368    res = get_rdnis(p, req, &redirecting_from_name, &redirecting_from_number, &reason);
18369    if (res == -1) {
18370       if (is_response) {
18371          get_name_and_number(get_header(req, "TO"), &redirecting_from_name, &redirecting_from_number);
18372       } else {
18373          return;
18374       }
18375    }
18376 
18377    /* At this point, all redirecting "from" info should be filled in appropriately
18378     * on to the "to" info
18379     */
18380 
18381    if (is_response) {
18382       parse_moved_contact(p, req, &redirecting_to_name, &redirecting_to_number, set_call_forward);
18383    } else {
18384       get_name_and_number(get_header(req, "TO"), &redirecting_to_name, &redirecting_to_number);
18385    }
18386 
18387    if (!ast_strlen_zero(redirecting_from_number)) {
18388       ast_debug(3, "Got redirecting from number %s\n", redirecting_from_number);
18389       update_redirecting->from.number = 1;
18390       redirecting->from.number.valid = 1;
18391       ast_free(redirecting->from.number.str);
18392       redirecting->from.number.str = redirecting_from_number;
18393    }
18394    if (!ast_strlen_zero(redirecting_from_name)) {
18395       ast_debug(3, "Got redirecting from name %s\n", redirecting_from_name);
18396       update_redirecting->from.name = 1;
18397       redirecting->from.name.valid = 1;
18398       ast_free(redirecting->from.name.str);
18399       redirecting->from.name.str = redirecting_from_name;
18400    }
18401    if (!ast_strlen_zero(p->cid_tag)) {
18402       ast_free(redirecting->from.tag);
18403       redirecting->from.tag = ast_strdup(p->cid_tag);
18404       ast_free(redirecting->to.tag);
18405       redirecting->to.tag = ast_strdup(p->cid_tag);
18406    }
18407    if (!ast_strlen_zero(redirecting_to_number)) {
18408       ast_debug(3, "Got redirecting to number %s\n", redirecting_to_number);
18409       update_redirecting->to.number = 1;
18410       redirecting->to.number.valid = 1;
18411       ast_free(redirecting->to.number.str);
18412       redirecting->to.number.str = redirecting_to_number;
18413    }
18414    if (!ast_strlen_zero(redirecting_to_name)) {
18415       ast_debug(3, "Got redirecting to name %s\n", redirecting_from_number);
18416       update_redirecting->to.name = 1;
18417       redirecting->to.name.valid = 1;
18418       ast_free(redirecting->to.name.str);
18419       redirecting->to.name.str = redirecting_to_name;
18420    }
18421    redirecting->reason = reason;
18422 }
18423 
18424 /*! \brief Parse 302 Moved temporalily response
18425    \todo XXX Doesn't redirect over TLS on sips: uri's.
18426       If we get a redirect to a SIPS: uri, this needs to be going back to the
18427       dialplan (this is a request for a secure signalling path).
18428       Note that transport=tls is deprecated, but we need to support it on incoming requests.
18429 */
18430 static void parse_moved_contact(struct sip_pvt *p, struct sip_request *req, char **name, char **number, int set_call_forward)
18431 {
18432    char contact[SIPBUFSIZE];
18433    char *contact_name = NULL;
18434    char *contact_number = NULL;
18435    char *separator, *trans;
18436    char *domain;
18437    enum sip_transport transport = SIP_TRANSPORT_UDP;
18438 
18439    ast_copy_string(contact, get_header(req, "Contact"), sizeof(contact));
18440    if ((separator = strchr(contact, ',')))
18441       *separator = '\0';
18442 
18443    contact_number = get_in_brackets(contact);
18444    if ((trans = strcasestr(contact_number, ";transport="))) {
18445       trans += 11;
18446 
18447       if ((separator = strchr(trans, ';')))
18448          *separator = '\0';
18449 
18450       if (!strncasecmp(trans, "tcp", 3))
18451          transport = SIP_TRANSPORT_TCP;
18452       else if (!strncasecmp(trans, "tls", 3))
18453          transport = SIP_TRANSPORT_TLS;
18454       else {
18455          if (strncasecmp(trans, "udp", 3))
18456             ast_debug(1, "received contact with an invalid transport, '%s'\n", contact_number);
18457          /* This will assume UDP for all unknown transports */
18458          transport = SIP_TRANSPORT_UDP;
18459       }
18460    }
18461    contact_number = remove_uri_parameters(contact_number);
18462 
18463    if (p->socket.tcptls_session) {
18464       ao2_ref(p->socket.tcptls_session, -1);
18465       p->socket.tcptls_session = NULL;
18466    }
18467 
18468    set_socket_transport(&p->socket, transport);
18469 
18470    if (set_call_forward && ast_test_flag(&p->flags[0], SIP_PROMISCREDIR)) {
18471       char *host = NULL;
18472       if (!strncasecmp(contact_number, "sip:", 4))
18473          contact_number += 4;
18474       else if (!strncasecmp(contact_number, "sips:", 5))
18475          contact_number += 5;
18476       separator = strchr(contact_number, '/');
18477       if (separator)
18478          *separator = '\0';
18479       if ((host = strchr(contact_number, '@'))) {
18480          *host++ = '\0';
18481          ast_debug(2, "Found promiscuous redirection to 'SIP/%s::::%s@%s'\n", contact_number, get_transport(transport), host);
18482          if (p->owner)
18483             ast_string_field_build(p->owner, call_forward, "SIP/%s::::%s@%s", contact_number, get_transport(transport), host);
18484       } else {
18485          ast_debug(2, "Found promiscuous redirection to 'SIP/::::%s@%s'\n", get_transport(transport), contact_number);
18486          if (p->owner)
18487             ast_string_field_build(p->owner, call_forward, "SIP/::::%s@%s", get_transport(transport), contact_number);
18488       }
18489    } else {
18490       separator = strchr(contact, '@');
18491       if (separator) {
18492          *separator++ = '\0';
18493          domain = separator;
18494       } else {
18495          /* No username part */
18496          domain = contact;
18497       }
18498       separator = strchr(contact, '/');   /* WHEN do we hae a forward slash in the URI? */
18499       if (separator)
18500          *separator = '\0';
18501 
18502       if (!strncasecmp(contact_number, "sip:", 4))
18503          contact_number += 4;
18504       else if (!strncasecmp(contact_number, "sips:", 5))
18505          contact_number += 5;
18506       separator = strchr(contact_number, ';');  /* And username ; parameters? */
18507       if (separator)
18508          *separator = '\0';
18509       ast_uri_decode(contact_number);
18510       if (set_call_forward) {
18511          ast_debug(2, "Received 302 Redirect to extension '%s' (domain %s)\n", contact_number, domain);
18512          if (p->owner) {
18513             pbx_builtin_setvar_helper(p->owner, "SIPDOMAIN", domain);
18514             ast_string_field_set(p->owner, call_forward, contact_number);
18515          }
18516       }
18517    }
18518 
18519    /* We've gotten the number for the contact, now get the name */
18520 
18521    if (*contact == '\"') {
18522       contact_name = contact + 1;
18523       if (!(separator = (char *)find_closing_quote(contact_name, NULL))) {
18524          ast_log(LOG_NOTICE, "No closing quote on name in Contact header? %s\n", contact);
18525       }
18526       *separator = '\0';
18527    }
18528 
18529    if (name && !ast_strlen_zero(contact_name)) {
18530       *name = ast_strdup(contact_name);
18531    }
18532    if (number) {
18533       *number = ast_strdup(contact_number);
18534    }
18535 }
18536 
18537 /*! \brief Check pending actions on SIP call 
18538  *
18539  * \note both sip_pvt and sip_pvt's owner channel (if present)
18540  *  must be locked for this function.
18541  */
18542 static void check_pendings(struct sip_pvt *p)
18543 {
18544    if (ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
18545       /* if we can't BYE, then this is really a pending CANCEL */
18546       if (p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA) {
18547          p->invitestate = INV_CANCELLED;
18548          transmit_request(p, SIP_CANCEL, p->lastinvite, XMIT_RELIABLE, FALSE);
18549          /* Actually don't destroy us yet, wait for the 487 on our original
18550             INVITE, but do set an autodestruct just in case we never get it. */
18551       } else {
18552          /* We have a pending outbound invite, don't send something
18553             new in-transaction */
18554          if (p->pendinginvite)
18555             return;
18556 
18557          if (p->owner) {
18558             ast_softhangup_nolock(p->owner, AST_SOFTHANGUP_DEV);
18559          }
18560          /* Perhaps there is an SD change INVITE outstanding */
18561          transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, TRUE);
18562       }
18563       ast_clear_flag(&p->flags[0], SIP_PENDINGBYE);   
18564       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
18565    } else if (ast_test_flag(&p->flags[0], SIP_NEEDREINVITE)) {
18566       /* if we can't REINVITE, hold it for later */
18567       if (p->pendinginvite || p->invitestate == INV_CALLING || p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA || p->waitid > 0) {
18568          ast_debug(2, "NOT Sending pending reinvite (yet) on '%s'\n", p->callid);
18569       } else {
18570          ast_debug(2, "Sending pending reinvite on '%s'\n", p->callid);
18571          /* Didn't get to reinvite yet, so do it now */
18572          transmit_reinvite_with_sdp(p, (p->t38.state == T38_LOCAL_REINVITE ? TRUE : FALSE), FALSE);
18573          ast_clear_flag(&p->flags[0], SIP_NEEDREINVITE); 
18574       }
18575    }
18576 }
18577 
18578 /*! \brief Reset the NEEDREINVITE flag after waiting when we get 491 on a Re-invite
18579    to avoid race conditions between asterisk servers.
18580    Called from the scheduler.
18581 */
18582 static int sip_reinvite_retry(const void *data)
18583 {
18584    struct sip_pvt *p = (struct sip_pvt *) data;
18585    struct ast_channel *owner;
18586 
18587    sip_pvt_lock(p); /* called from schedule thread which requires a lock */
18588    while ((owner = p->owner) && ast_channel_trylock(owner)) {
18589       sip_pvt_unlock(p);
18590       usleep(1);
18591       sip_pvt_lock(p);
18592    }
18593    ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
18594    p->waitid = -1;
18595    check_pendings(p);
18596    sip_pvt_unlock(p);
18597    if (owner) {
18598       ast_channel_unlock(owner);
18599    }
18600    dialog_unref(p, "unref the dialog ptr from sip_reinvite_retry, because it held a dialog ptr");
18601    return 0;
18602 }
18603 
18604 /*!
18605  * \brief Handle authentication challenge for SIP UPDATE
18606  *
18607  * This function is only called upon the receipt of a 401/407 response to an UPDATE.
18608  */
18609 static void handle_response_update(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno)
18610 {
18611    if (p->options) {
18612       p->options->auth_type = (resp == 401 ? WWW_AUTH : PROXY_AUTH);
18613    }
18614    if ((p->authtries == MAX_AUTHTRIES) || do_proxy_auth(p, req, resp, SIP_UPDATE, 1)) {
18615       ast_log(LOG_NOTICE, "Failed to authenticate on UPDATE to '%s'\n", get_header(&p->initreq, "From"));
18616    }
18617 }
18618 
18619 static void cc_handle_publish_error(struct sip_pvt *pvt, const int resp, struct sip_request *req, struct sip_epa_entry *epa_entry)
18620 {
18621    struct cc_epa_entry *cc_entry = epa_entry->instance_data;
18622    struct sip_monitor_instance *monitor_instance = ao2_callback(sip_monitor_instances, 0,
18623          find_sip_monitor_instance_by_suspension_entry, epa_entry);
18624    const char *min_expires;
18625 
18626    if (!monitor_instance) {
18627       ast_log(LOG_WARNING, "Can't find monitor_instance corresponding to epa_entry %p.\n", epa_entry);
18628       return;
18629    }
18630 
18631    if (resp != 423) {
18632       ast_cc_monitor_failed(cc_entry->core_id, monitor_instance->device_name,
18633             "Received error response to our PUBLISH");
18634       ao2_ref(monitor_instance, -1);
18635       return;
18636    }
18637 
18638    /* Allrighty, the other end doesn't like our Expires value. They think it's
18639     * too small, so let's see if they've provided a more sensible value. If they
18640     * haven't, then we'll just double our Expires value and see if they like that
18641     * instead.
18642     *
18643     * XXX Ideally this logic could be placed into its own function so that SUBSCRIBE,
18644     * PUBLISH, and REGISTER could all benefit from the same shared code.
18645     */
18646    min_expires = get_header(req, "Min-Expires");
18647    if (ast_strlen_zero(min_expires)) {
18648       pvt->expiry *= 2;
18649       if (pvt->expiry < 0) {
18650          /* You dork! You overflowed! */
18651          ast_cc_monitor_failed(cc_entry->core_id, monitor_instance->device_name,
18652                "PUBLISH expiry overflowed");
18653          ao2_ref(monitor_instance, -1);
18654          return;
18655       }
18656    } else if (sscanf(min_expires, "%d", &pvt->expiry) != 1) {
18657       ast_cc_monitor_failed(cc_entry->core_id, monitor_instance->device_name,
18658             "Min-Expires has non-numeric value");
18659       ao2_ref(monitor_instance, -1);
18660       return;
18661    }
18662    /* At this point, we have most certainly changed pvt->expiry, so try transmitting
18663     * again
18664     */
18665    transmit_invite(pvt, SIP_PUBLISH, FALSE, 0, NULL);
18666    ao2_ref(monitor_instance, -1);
18667 }
18668 
18669 static void handle_response_publish(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno)
18670 {
18671    struct sip_epa_entry *epa_entry = p->epa_entry;
18672    const char *etag = get_header(req, "Sip-ETag");
18673 
18674    ast_assert(epa_entry != NULL);
18675 
18676    if (resp == 401 || resp == 407) {
18677       ast_string_field_set(p, theirtag, NULL);
18678       if (p->options) {
18679          p->options->auth_type = (resp == 401 ? WWW_AUTH : PROXY_AUTH);
18680       }
18681       if ((p->authtries == MAX_AUTHTRIES) || do_proxy_auth(p, req, resp, SIP_PUBLISH, 0)) {
18682          ast_log(LOG_NOTICE, "Failed to authenticate on PUBLISH to '%s'\n", get_header(&p->initreq, "From"));
18683          pvt_set_needdestroy(p, "Failed to authenticate on PUBLISH");
18684          sip_alreadygone(p);
18685       }
18686       return;
18687    }
18688 
18689    if (resp == 501 || resp == 405) {
18690       mark_method_unallowed(&p->allowed_methods, SIP_PUBLISH);
18691    }
18692 
18693    if (resp == 200) {
18694       p->authtries = 0;
18695       /* If I've read section 6, item 6 of RFC 3903 correctly,
18696        * an ESC will only generate a new etag when it sends a 200 OK
18697        */
18698       if (!ast_strlen_zero(etag)) {
18699          ast_copy_string(epa_entry->entity_tag, etag, sizeof(epa_entry->entity_tag));
18700       }
18701       /* The nominal case. Everything went well. Everybody is happy.
18702        * Each EPA will have a specific action to take as a result of this
18703        * development, so ... callbacks!
18704        */
18705       if (epa_entry->static_data->handle_ok) {
18706          epa_entry->static_data->handle_ok(p, req, epa_entry);
18707       }
18708    } else {
18709       /* Rather than try to make individual callbacks for each error
18710        * type, there is just a single error callback. The callback
18711        * can distinguish between error messages and do what it needs to
18712        */
18713       if (epa_entry->static_data->handle_error) {
18714          epa_entry->static_data->handle_error(p, resp, req, epa_entry);
18715       }
18716    }
18717 }
18718 
18719 /*! \brief Handle SIP response to INVITE dialogue */
18720 static void handle_response_invite(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno)
18721 {
18722    int outgoing = ast_test_flag(&p->flags[0], SIP_OUTGOING);
18723    int res = 0;
18724    int xmitres = 0;
18725    int reinvite = (p->owner && p->owner->_state == AST_STATE_UP);
18726    char *p_hdrval;
18727    int rtn;
18728    struct ast_party_connected_line connected;
18729    struct ast_set_party_connected_line update_connected;
18730 
18731    if (reinvite)
18732       ast_debug(4, "SIP response %d to RE-invite on %s call %s\n", resp, outgoing ? "outgoing" : "incoming", p->callid);
18733    else
18734       ast_debug(4, "SIP response %d to standard invite\n", resp);
18735 
18736    if (p->alreadygone) { /* This call is already gone */
18737       ast_debug(1, "Got response on call that is already terminated: %s (ignoring)\n", p->callid);
18738       return;
18739    }
18740 
18741    /* Acknowledge sequence number - This only happens on INVITE from SIP-call */
18742    /* Don't auto congest anymore since we've gotten something useful back */
18743    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"));
18744 
18745    /* RFC3261 says we must treat every 1xx response (but not 100)
18746       that we don't recognize as if it was 183.
18747    */
18748    if (resp > 100 && resp < 200 && resp!=101 && resp != 180 && resp != 181 && resp != 182 && resp != 183)
18749       resp = 183;
18750 
18751    /* Any response between 100 and 199 is PROCEEDING */
18752    if (resp >= 100 && resp < 200 && p->invitestate == INV_CALLING)
18753       p->invitestate = INV_PROCEEDING;
18754 
18755    /* Final response, not 200 ? */
18756    if (resp >= 300 && (p->invitestate == INV_CALLING || p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA ))
18757       p->invitestate = INV_COMPLETED;
18758    
18759    /* Final response, clear out pending invite */
18760    if ((resp == 200 || resp >= 300) && p->pendinginvite && seqno == p->pendinginvite)
18761       p->pendinginvite = 0;
18762 
18763    /* If this is a response to our initial INVITE, we need to set what we can use
18764     * for this peer.
18765     */
18766    if (!reinvite) {
18767       set_pvt_allowed_methods(p, req);
18768    }     
18769 
18770    switch (resp) {
18771    case 100:   /* Trying */
18772    case 101:   /* Dialog establishment */
18773       if (!req->ignore && p->invitestate != INV_CANCELLED && sip_cancel_destroy(p))
18774          ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
18775       check_pendings(p);
18776       break;
18777 
18778    case 180:   /* 180 Ringing */
18779    case 182:       /* 182 Queued */
18780       if (!req->ignore && p->invitestate != INV_CANCELLED && sip_cancel_destroy(p))
18781          ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
18782       if (!req->ignore && p->owner) {
18783          if (get_rpid(p, req)) {
18784             ast_party_connected_line_init(&connected);
18785             memset(&update_connected, 0, sizeof(update_connected));
18786             if (p->cid_num) {
18787                update_connected.id.number = 1;
18788                connected.id.number.valid = 1;
18789                connected.id.number.str = (char *) p->cid_num;
18790                connected.id.number.presentation = p->callingpres;
18791             }
18792             if (p->cid_name) {
18793                update_connected.id.name = 1;
18794                connected.id.name.valid = 1;
18795                connected.id.name.str = (char *) p->cid_name;
18796                connected.id.name.presentation = p->callingpres;
18797             }
18798             connected.id.tag = (char *) p->cid_tag;
18799             connected.source = AST_CONNECTED_LINE_UPDATE_SOURCE_ANSWER;
18800             ast_channel_queue_connected_line_update(p->owner, &connected,
18801                &update_connected);
18802          }
18803          sip_handle_cc(p, req, AST_CC_CCNR);
18804          ast_queue_control(p->owner, AST_CONTROL_RINGING);
18805          if (p->owner->_state != AST_STATE_UP) {
18806             ast_setstate(p->owner, AST_STATE_RINGING);
18807          }
18808       }
18809       if (find_sdp(req)) {
18810          if (p->invitestate != INV_CANCELLED)
18811             p->invitestate = INV_EARLY_MEDIA;
18812          res = process_sdp(p, req, SDP_T38_NONE);
18813          if (!req->ignore && p->owner) {
18814             /* Queue a progress frame only if we have SDP in 180 or 182 */
18815             ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
18816          }
18817          ast_rtp_instance_activate(p->rtp);
18818       }
18819       check_pendings(p);
18820       break;
18821 
18822    case 181:   /* Call Is Being Forwarded */
18823       if (!req->ignore && (p->invitestate != INV_CANCELLED) && sip_cancel_destroy(p))
18824          ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
18825       if (!req->ignore && p->owner) {
18826          struct ast_party_redirecting redirecting;
18827          struct ast_set_party_redirecting update_redirecting;
18828 
18829          ast_party_redirecting_init(&redirecting);
18830          memset(&update_redirecting, 0, sizeof(update_redirecting));
18831          change_redirecting_information(p, req, &redirecting, &update_redirecting,
18832             FALSE);
18833          ast_channel_queue_redirecting_update(p->owner, &redirecting,
18834             &update_redirecting);
18835          ast_party_redirecting_free(&redirecting);
18836          sip_handle_cc(p, req, AST_CC_CCNR);
18837       }
18838       check_pendings(p);
18839       break;
18840 
18841    case 183:   /* Session progress */
18842       if (!req->ignore && (p->invitestate != INV_CANCELLED) && sip_cancel_destroy(p))
18843          ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
18844       if (!req->ignore && p->owner) {
18845          if (get_rpid(p, req)) {
18846             /* Queue a connected line update */
18847             ast_party_connected_line_init(&connected);
18848             memset(&update_connected, 0, sizeof(update_connected));
18849             if (p->cid_num) {
18850                update_connected.id.number = 1;
18851                connected.id.number.valid = 1;
18852                connected.id.number.str = (char *) p->cid_num;
18853                connected.id.number.presentation = p->callingpres;
18854             }
18855             if (p->cid_name) {
18856                update_connected.id.name = 1;
18857                connected.id.name.valid = 1;
18858                connected.id.name.str = (char *) p->cid_name;
18859                connected.id.name.presentation = p->callingpres;
18860             }
18861             connected.id.tag = (char *) p->cid_tag;
18862             connected.source = AST_CONNECTED_LINE_UPDATE_SOURCE_ANSWER;
18863             ast_channel_queue_connected_line_update(p->owner, &connected,
18864                &update_connected);
18865          }
18866          sip_handle_cc(p, req, AST_CC_CCNR);
18867       }
18868       if (find_sdp(req)) {
18869          if (p->invitestate != INV_CANCELLED)
18870             p->invitestate = INV_EARLY_MEDIA;
18871          res = process_sdp(p, req, SDP_T38_NONE);
18872          if (!req->ignore && p->owner) {
18873             /* Queue a progress frame */
18874             ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
18875          }
18876          ast_rtp_instance_activate(p->rtp);
18877       } else {
18878          /* Alcatel PBXs are known to send 183s with no SDP after sending
18879           * a 100 Trying response. We're just going to treat this sort of thing
18880           * the same as we would treat a 180 Ringing
18881           */
18882          if (!req->ignore && p->owner) {
18883             ast_queue_control(p->owner, AST_CONTROL_RINGING);
18884          }
18885       }
18886       check_pendings(p);
18887       break;
18888 
18889    case 200:   /* 200 OK on invite - someone's answering our call */
18890       if (!req->ignore && (p->invitestate != INV_CANCELLED) && sip_cancel_destroy(p))
18891          ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
18892       p->authtries = 0;
18893       if (find_sdp(req)) {
18894          if ((res = process_sdp(p, req, SDP_T38_ACCEPT)) && !req->ignore)
18895             if (!reinvite)
18896                /* This 200 OK's SDP is not acceptable, so we need to ack, then hangup */
18897                /* For re-invites, we try to recover */
18898                ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
18899          ast_rtp_instance_activate(p->rtp);
18900       }
18901 
18902       if (!req->ignore && p->owner && (get_rpid(p, req) || !reinvite)) {
18903          /* Queue a connected line update */
18904          ast_party_connected_line_init(&connected);
18905          memset(&update_connected, 0, sizeof(update_connected));
18906          if (p->cid_num) {
18907             update_connected.id.number = 1;
18908             connected.id.number.valid = 1;
18909             connected.id.number.str = (char *) p->cid_num;
18910             connected.id.number.presentation = p->callingpres;
18911          }
18912          if (p->cid_name) {
18913             update_connected.id.name = 1;
18914             connected.id.name.valid = 1;
18915             connected.id.name.str = (char *) p->cid_name;
18916             connected.id.name.presentation = p->callingpres;
18917          }
18918          connected.id.tag = (char *) p->cid_tag;
18919          connected.source = AST_CONNECTED_LINE_UPDATE_SOURCE_ANSWER;
18920          ast_channel_queue_connected_line_update(p->owner, &connected,
18921             &update_connected);
18922       }
18923 
18924       /* Parse contact header for continued conversation */
18925       /* When we get 200 OK, we know which device (and IP) to contact for this call */
18926       /* This is important when we have a SIP proxy between us and the phone */
18927       if (outgoing) {
18928          update_call_counter(p, DEC_CALL_RINGING);
18929          parse_ok_contact(p, req);
18930          /* Save Record-Route for any later requests we make on this dialogue */
18931          if (!reinvite)
18932             build_route(p, req, 1);
18933 
18934          if(set_address_from_contact(p)) {
18935             /* Bad contact - we don't know how to reach this device */
18936             /* We need to ACK, but then send a bye */
18937             if (!p->route && !req->ignore)
18938                ast_set_flag(&p->flags[0], SIP_PENDINGBYE);  
18939          }
18940 
18941       }
18942 
18943       if (!req->ignore && p->owner) {
18944          if (!reinvite) {
18945             ast_queue_control(p->owner, AST_CONTROL_ANSWER);
18946             if (sip_cfg.callevents)
18947                manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
18948                   "Channel: %s\r\nChanneltype: %s\r\nUniqueid: %s\r\nSIPcallid: %s\r\nSIPfullcontact: %s\r\nPeername: %s\r\n",
18949                   p->owner->name, "SIP", p->owner->uniqueid, p->callid, p->fullcontact, p->peername);
18950          } else { /* RE-invite */
18951             ast_queue_frame(p->owner, &ast_null_frame);
18952          }
18953       } else {
18954           /* It's possible we're getting an 200 OK after we've tried to disconnect
18955               by sending CANCEL */
18956          /* First send ACK, then send bye */
18957          if (!req->ignore)
18958             ast_set_flag(&p->flags[0], SIP_PENDINGBYE);  
18959       }
18960 
18961       /* Check for Session-Timers related headers */
18962       if (st_get_mode(p) != SESSION_TIMER_MODE_REFUSE && p->outgoing_call == TRUE && !reinvite) {
18963          p_hdrval = (char*)get_header(req, "Session-Expires");
18964          if (!ast_strlen_zero(p_hdrval)) {
18965             /* UAS supports Session-Timers */
18966             enum st_refresher tmp_st_ref = SESSION_TIMER_REFRESHER_AUTO;
18967             int tmp_st_interval = 0;
18968             rtn = parse_session_expires(p_hdrval, &tmp_st_interval, &tmp_st_ref);
18969             if (rtn != 0) {
18970                ast_set_flag(&p->flags[0], SIP_PENDINGBYE);  
18971             }
18972             if (tmp_st_ref == SESSION_TIMER_REFRESHER_UAC ||
18973                tmp_st_ref == SESSION_TIMER_REFRESHER_UAS) {
18974                p->stimer->st_ref = tmp_st_ref;
18975             }
18976             if (tmp_st_interval) {
18977                p->stimer->st_interval = tmp_st_interval;
18978             }
18979             p->stimer->st_active = TRUE;
18980             p->stimer->st_active_peer_ua = TRUE;
18981             start_session_timer(p);
18982          } else {
18983             /* UAS doesn't support Session-Timers */
18984             if (st_get_mode(p) == SESSION_TIMER_MODE_ORIGINATE) {
18985                p->stimer->st_ref = SESSION_TIMER_REFRESHER_UAC;
18986                p->stimer->st_active_peer_ua = FALSE;
18987                start_session_timer(p);
18988             }
18989          }
18990       }
18991 
18992 
18993       /* If I understand this right, the branch is different for a non-200 ACK only */
18994       p->invitestate = INV_TERMINATED;
18995       ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
18996       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, TRUE);
18997       check_pendings(p);
18998       break;
18999 
19000    case 407: /* Proxy authentication */
19001    case 401: /* Www auth */
19002       /* First we ACK */
19003       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
19004       if (p->options)
19005          p->options->auth_type = resp;
19006 
19007       /* Then we AUTH */
19008       ast_string_field_set(p, theirtag, NULL);  /* forget their old tag, so we don't match tags when getting response */
19009       if (!req->ignore) {
19010          if (p->authtries < MAX_AUTHTRIES)
19011             p->invitestate = INV_CALLING;
19012          if (p->authtries == MAX_AUTHTRIES || do_proxy_auth(p, req, resp, SIP_INVITE, 1)) {
19013             ast_log(LOG_NOTICE, "Failed to authenticate on INVITE to '%s'\n", get_header(&p->initreq, "From"));
19014             pvt_set_needdestroy(p, "failed to authenticate on INVITE");
19015             sip_alreadygone(p);
19016             if (p->owner)
19017                ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
19018          }
19019       }
19020       break;
19021 
19022    case 403: /* Forbidden */
19023       /* First we ACK */
19024       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
19025       ast_log(LOG_WARNING, "Received response: \"Forbidden\" from '%s'\n", get_header(&p->initreq, "From"));
19026       if (!req->ignore && p->owner) {
19027          ast_set_hangupsource(p->owner, p->owner->name, 0);
19028          ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
19029       }
19030       pvt_set_needdestroy(p, "received 403 response");
19031       sip_alreadygone(p);
19032       break;
19033 
19034    case 404: /* Not found */
19035       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
19036       if (p->owner && !req->ignore) {
19037          ast_set_hangupsource(p->owner, p->owner->name, 0);
19038          ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
19039       }
19040       sip_alreadygone(p);
19041       break;
19042 
19043    case 408: /* Request timeout */
19044    case 481: /* Call leg does not exist */
19045       /* Could be REFER caused INVITE with replaces */
19046       ast_log(LOG_WARNING, "Re-invite to non-existing call leg on other UA. SIP dialog '%s'. Giving up.\n", p->callid);
19047       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
19048       if (p->owner)
19049          ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
19050       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19051       break;
19052 
19053    case 422: /* Session-Timers: Session interval too small */
19054       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
19055       ast_string_field_set(p, theirtag, NULL);
19056       proc_422_rsp(p, req);
19057       break;
19058 
19059    case 428: /* Use identity header - rfc 4474 - not supported by Asterisk yet */
19060       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
19061       append_history(p, "Identity", "SIP identity is required. Not supported by Asterisk.");
19062       ast_log(LOG_WARNING, "SIP identity required by proxy. SIP dialog '%s'. Giving up.\n", p->callid);
19063       if (p->owner)
19064          ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
19065       break;
19066 
19067       
19068 
19069    case 487: /* Cancelled transaction */
19070       /* We have sent CANCEL on an outbound INVITE
19071          This transaction is already scheduled to be killed by sip_hangup().
19072       */
19073       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
19074       if (p->owner && !req->ignore) {
19075          ast_queue_hangup_with_cause(p->owner, AST_CAUSE_NORMAL_CLEARING);
19076          append_history(p, "Hangup", "Got 487 on CANCEL request from us. Queued AST hangup request");
19077       } else if (!req->ignore) {
19078          update_call_counter(p, DEC_CALL_LIMIT);
19079          append_history(p, "Hangup", "Got 487 on CANCEL request from us on call without owner. Killing this dialog.");
19080          pvt_set_needdestroy(p, "received 487 response");
19081          sip_alreadygone(p);
19082       }
19083       break;
19084    case 415: /* Unsupported media type */
19085    case 488: /* Not acceptable here */
19086    case 606: /* Not Acceptable */
19087       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
19088       if (p->udptl && p->t38.state == T38_LOCAL_REINVITE) {
19089          change_t38_state(p, T38_DISABLED);
19090          /* Try to reset RTP timers */
19091          //ast_rtp_set_rtptimers_onhold(p->rtp);
19092 
19093          /* Trigger a reinvite back to audio */
19094          transmit_reinvite_with_sdp(p, FALSE, FALSE);
19095       } else {
19096          /* We can't set up this call, so give up */
19097          if (p->owner && !req->ignore)
19098             ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
19099          pvt_set_needdestroy(p, "received 488 response");
19100          /* If there's no dialog to end, then mark p as already gone */
19101          if (!reinvite)
19102             sip_alreadygone(p);
19103       }
19104       break;
19105    case 491: /* Pending */
19106       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
19107       if (p->owner && !req->ignore) {
19108          if (p->owner->_state != AST_STATE_UP) {
19109             ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
19110             pvt_set_needdestroy(p, "received 491 response");
19111          } else {
19112             /* This is a re-invite that failed. */
19113             /* Reset the flag after a while
19114              */
19115             int wait;
19116             /* RFC 3261, if owner of call, wait between 2.1 to 4 seconds,
19117              * if not owner of call, wait 0 to 2 seconds */
19118             if (p->outgoing_call) {
19119                wait = 2100 + ast_random() % 2000;
19120             } else {
19121                wait = ast_random() % 2000;
19122             }
19123             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."));
19124             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);
19125             ast_debug(2, "Reinvite race. Waiting %d secs before retry\n", wait);
19126          }
19127       }
19128       break;
19129 
19130    case 405: /* Not allowed */
19131    case 501: /* Not implemented */
19132       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
19133       if (p->owner)
19134          ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
19135       break;
19136    }
19137    if (xmitres == XMIT_ERROR)
19138       ast_log(LOG_WARNING, "Could not transmit message in dialog %s\n", p->callid);
19139 }
19140 
19141 /* \brief Handle SIP response in NOTIFY transaction
19142        We've sent a NOTIFY, now handle responses to it
19143   */
19144 static void handle_response_notify(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno)
19145 {
19146    switch (resp) {
19147    case 200:   /* Notify accepted */
19148       /* They got the notify, this is the end */
19149       if (p->owner) {
19150          if (!p->refer) {
19151             ast_log(LOG_WARNING, "Notify answer on an owned channel? - %s\n", p->owner->name);
19152             ast_queue_hangup_with_cause(p->owner, AST_CAUSE_NORMAL_UNSPECIFIED);
19153          } else {
19154             ast_debug(4, "Got OK on REFER Notify message\n");
19155          }
19156       } else {
19157          if (p->subscribed == NONE) {
19158             ast_debug(4, "Got 200 accepted on NOTIFY\n");
19159             pvt_set_needdestroy(p, "received 200 response");
19160          }
19161          if (ast_test_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE)) {
19162             /* Ready to send the next state we have on queue */
19163             ast_clear_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE);
19164             cb_extensionstate((char *)p->context, (char *)p->exten, p->laststate, (void *) p);
19165          }
19166       }
19167       break;
19168    case 401:   /* Not www-authorized on SIP method */
19169    case 407:   /* Proxy auth */
19170       if (!p->notify) {
19171          break; /* Only device notify can use NOTIFY auth */
19172       }
19173       ast_string_field_set(p, theirtag, NULL);
19174       if (ast_strlen_zero(p->authname)) {
19175          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));
19176          pvt_set_needdestroy(p, "unable to authenticate NOTIFY");
19177       }
19178       if (p->authtries > 1 || do_proxy_auth(p, req, resp, SIP_NOTIFY, 0)) {
19179          ast_log(LOG_NOTICE, "Failed to authenticate on NOTIFY to '%s'\n", get_header(&p->initreq, "From"));
19180          pvt_set_needdestroy(p, "failed to authenticate NOTIFY");
19181       }
19182       break;
19183    }
19184 }
19185 
19186 /* \brief Handle SIP response in SUBSCRIBE transaction */
19187 static void handle_response_subscribe(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno)
19188 {
19189    if (!p->mwi) {
19190       return;
19191    }
19192 
19193    switch (resp) {
19194    case 200: /* Subscription accepted */
19195       ast_debug(3, "Got 200 OK on subscription for MWI\n");
19196       set_pvt_allowed_methods(p, req);
19197       if (p->options) {
19198          ast_free(p->options);
19199          p->options = NULL;
19200       }
19201       p->mwi->subscribed = 1;
19202       if ((p->mwi->resub = ast_sched_add(sched, mwi_expiry * 1000, sip_subscribe_mwi_do, ASTOBJ_REF(p->mwi))) < 0) {
19203          ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
19204       }
19205       break;
19206    case 401:
19207    case 407:
19208       ast_string_field_set(p, theirtag, NULL);
19209       if (p->authtries > 1 || do_proxy_auth(p, req, resp, SIP_SUBSCRIBE, 0)) {
19210          ast_log(LOG_NOTICE, "Failed to authenticate on SUBSCRIBE to '%s'\n", get_header(&p->initreq, "From"));
19211          p->mwi->call = NULL;
19212          ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
19213          pvt_set_needdestroy(p, "failed to authenticate SUBSCRIBE");
19214       }
19215       break;
19216    case 403:
19217       transmit_response_with_date(p, "200 OK", req);
19218       ast_log(LOG_WARNING, "Authentication failed while trying to subscribe for MWI.\n");
19219       p->mwi->call = NULL;
19220       ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
19221       pvt_set_needdestroy(p, "received 403 response");
19222       sip_alreadygone(p);
19223       break;
19224    case 404:
19225       ast_log(LOG_WARNING, "Subscription failed for MWI. The remote side said that a mailbox may not have been configured.\n");
19226       p->mwi->call = NULL;
19227       ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
19228       pvt_set_needdestroy(p, "received 404 response");
19229       break;
19230    case 481:
19231       ast_log(LOG_WARNING, "Subscription failed for MWI. The remote side said that our dialog did not exist.\n");
19232       p->mwi->call = NULL;
19233       ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
19234       pvt_set_needdestroy(p, "received 481 response");
19235       break;
19236    case 500:
19237    case 501:
19238       ast_log(LOG_WARNING, "Subscription failed for MWI. The remote side may have suffered a heart attack.\n");
19239       p->mwi->call = NULL;
19240       ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
19241       pvt_set_needdestroy(p, "received 500/501 response");
19242       break;
19243    }
19244 }
19245 
19246 /* \brief Handle SIP response in REFER transaction
19247    We've sent a REFER, now handle responses to it
19248   */
19249 static void handle_response_refer(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno)
19250 {
19251    enum ast_control_transfer message = AST_TRANSFER_FAILED;
19252 
19253    /* If no refer structure exists, then do nothing */
19254    if (!p->refer)
19255       return;
19256 
19257    switch (resp) {
19258    case 202:   /* Transfer accepted */
19259       /* We need  to do something here */
19260       /* The transferee is now sending INVITE to target */
19261       p->refer->status = REFER_ACCEPTED;
19262       /* Now wait for next message */
19263       ast_debug(3, "Got 202 accepted on transfer\n");
19264       /* We should hang along, waiting for NOTIFY's here */
19265       break;
19266 
19267    case 401:   /* Not www-authorized on SIP method */
19268    case 407:   /* Proxy auth */
19269       if (ast_strlen_zero(p->authname)) {
19270          ast_log(LOG_WARNING, "Asked to authenticate REFER to %s but we have no matching peer or realm auth!\n",
19271             ast_sockaddr_stringify(&p->recv));
19272          if (p->owner) {
19273             ast_queue_control_data(p->owner, AST_CONTROL_TRANSFER, &message, sizeof(message));
19274          }
19275          pvt_set_needdestroy(p, "unable to authenticate REFER");
19276       }
19277       if (p->authtries > 1 || do_proxy_auth(p, req, resp, SIP_REFER, 0)) {
19278          ast_log(LOG_NOTICE, "Failed to authenticate on REFER to '%s'\n", get_header(&p->initreq, "From"));
19279          p->refer->status = REFER_NOAUTH;
19280          if (p->owner) {
19281             ast_queue_control_data(p->owner, AST_CONTROL_TRANSFER, &message, sizeof(message));
19282          }
19283          pvt_set_needdestroy(p, "failed to authenticate REFER");
19284       }
19285       break;
19286    
19287    case 405:   /* Method not allowed */
19288       /* Return to the current call onhold */
19289       /* Status flag needed to be reset */
19290       ast_log(LOG_NOTICE, "SIP transfer to %s failed, REFER not allowed. \n", p->refer->refer_to);
19291       pvt_set_needdestroy(p, "received 405 response");
19292       p->refer->status = REFER_FAILED;
19293       if (p->owner) {
19294          ast_queue_control_data(p->owner, AST_CONTROL_TRANSFER, &message, sizeof(message));
19295       }
19296       break;
19297 
19298    case 481: /* Call leg does not exist */
19299 
19300       /* A transfer with Replaces did not work */
19301       /* OEJ: We should Set flag, cancel the REFER, go back
19302       to original call - but right now we can't */
19303       ast_log(LOG_WARNING, "Remote host can't match REFER request to call '%s'. Giving up.\n", p->callid);
19304       if (p->owner)
19305          ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
19306       pvt_set_needdestroy(p, "received 481 response");
19307       break;
19308 
19309    case 500:   /* Server error */
19310    case 501:   /* Method not implemented */
19311       /* Return to the current call onhold */
19312       /* Status flag needed to be reset */
19313       ast_log(LOG_NOTICE, "SIP transfer to %s failed, call miserably fails. \n", p->refer->refer_to);
19314       pvt_set_needdestroy(p, "received 500/501 response");
19315       p->refer->status = REFER_FAILED;
19316       if (p->owner) {
19317          ast_queue_control_data(p->owner, AST_CONTROL_TRANSFER, &message, sizeof(message));
19318       }
19319       break;
19320    case 603:   /* Transfer declined */
19321       ast_log(LOG_NOTICE, "SIP transfer to %s declined, call miserably fails. \n", p->refer->refer_to);
19322       p->refer->status = REFER_FAILED;
19323       pvt_set_needdestroy(p, "received 603 response");
19324       if (p->owner) {
19325          ast_queue_control_data(p->owner, AST_CONTROL_TRANSFER, &message, sizeof(message));
19326       }
19327       break;
19328    default:
19329       /* We should treat unrecognized 9xx as 900.  400 is actually
19330          specified as a possible response, but any 4-6xx is 
19331          theoretically possible. */
19332 
19333       if (resp < 299) { /* 1xx cases don't get here */
19334          ast_log(LOG_WARNING, "SIP transfer to %s had unxpected 2xx response (%d), confusion is possible. \n", p->refer->refer_to, resp);
19335       } else {
19336          ast_log(LOG_WARNING, "SIP transfer to %s with response (%d). \n", p->refer->refer_to, resp);
19337       }
19338 
19339       p->refer->status = REFER_FAILED;
19340       pvt_set_needdestroy(p, "received failure response");
19341       if (p->owner) {
19342          ast_queue_control_data(p->owner, AST_CONTROL_TRANSFER, &message, sizeof(message));
19343       }
19344       break;
19345    }
19346 }
19347 
19348 /*! \brief Handle responses on REGISTER to services */
19349 static int handle_response_register(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno)
19350 {
19351    int expires, expires_ms;
19352    struct sip_registry *r;
19353    r=p->registry;
19354    
19355    switch (resp) {
19356    case 401:   /* Unauthorized */
19357       if (p->authtries == MAX_AUTHTRIES || do_register_auth(p, req, resp)) {
19358          ast_log(LOG_NOTICE, "Failed to authenticate on REGISTER to '%s@%s' (Tries %d)\n", p->registry->username, p->registry->hostname, p->authtries);
19359          pvt_set_needdestroy(p, "failed to authenticate REGISTER");
19360       }
19361       break;
19362    case 403:   /* Forbidden */
19363       ast_log(LOG_WARNING, "Forbidden - wrong password on authentication for REGISTER for '%s' to '%s'\n", p->registry->username, p->registry->hostname);
19364       AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 403"));
19365       r->regstate = REG_STATE_NOAUTH;
19366       pvt_set_needdestroy(p, "received 403 response");
19367       break;
19368    case 404:   /* Not found */
19369       ast_log(LOG_WARNING, "Got 404 Not found on SIP register to service %s@%s, giving up\n", p->registry->username, p->registry->hostname);
19370       pvt_set_needdestroy(p, "received 404 response");
19371       if (r->call)
19372          r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 404");
19373       r->regstate = REG_STATE_REJECTED;
19374       AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 404"));
19375       break;
19376    case 407:   /* Proxy auth */
19377       if (p->authtries == MAX_AUTHTRIES || do_register_auth(p, req, resp)) {
19378          ast_log(LOG_NOTICE, "Failed to authenticate on REGISTER to '%s' (tries '%d')\n", get_header(&p->initreq, "From"), p->authtries);
19379          pvt_set_needdestroy(p, "failed to authenticate REGISTER");
19380       }
19381       break;
19382    case 408:   /* Request timeout */
19383       /* Got a timeout response, so reset the counter of failed responses */
19384       if (r) {
19385          r->regattempts = 0;
19386       } else {
19387          ast_log(LOG_WARNING, "Got a 408 response to our REGISTER on call %s after we had destroyed the registry object\n", p->callid);
19388       }
19389       break;
19390    case 423:   /* Interval too brief */
19391       r->expiry = atoi(get_header(req, "Min-Expires"));
19392       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);
19393       AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 423"));
19394       if (r->call) {
19395          r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 423");
19396          pvt_set_needdestroy(p, "received 423 response");
19397       }
19398       if (r->expiry > max_expiry) {
19399          ast_log(LOG_WARNING, "Required expiration time from %s@%s is too high, giving up\n", p->registry->username, p->registry->hostname);
19400          r->expiry = r->configured_expiry;
19401          r->regstate = REG_STATE_REJECTED;
19402       } else {
19403          r->regstate = REG_STATE_UNREGISTERED;
19404          transmit_register(r, SIP_REGISTER, NULL, NULL);
19405       }
19406       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));
19407       break;
19408    case 479:   /* SER: Not able to process the URI - address is wrong in register*/
19409       ast_log(LOG_WARNING, "Got error 479 on register to %s@%s, giving up (check config)\n", p->registry->username, p->registry->hostname);
19410       pvt_set_needdestroy(p, "received 479 response");
19411       if (r->call)
19412          r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 479");
19413       r->regstate = REG_STATE_REJECTED;
19414       AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 479"));
19415       break;
19416    case 200:   /* 200 OK */
19417       if (!r) {
19418          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));
19419          pvt_set_needdestroy(p, "received erroneous 200 response");
19420          return 0;
19421       }
19422       
19423       r->regstate = REG_STATE_REGISTERED;
19424       r->regtime = ast_tvnow();     /* Reset time of last successful registration */
19425       manager_event(EVENT_FLAG_SYSTEM, "Registry", "ChannelType: SIP\r\nDomain: %s\r\nStatus: %s\r\n", r->hostname, regstate2str(r->regstate));
19426       r->regattempts = 0;
19427       ast_debug(1, "Registration successful\n");
19428       if (r->timeout > -1) {
19429          ast_debug(1, "Cancelling timeout %d\n", r->timeout);
19430       }
19431       AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 200"));
19432       if (r->call)
19433          r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 200");
19434       p->registry = registry_unref(p->registry, "unref registry entry p->registry");
19435       /* Let this one hang around until we have all the responses */
19436       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19437       /* p->needdestroy = 1; */
19438       
19439       /* set us up for re-registering
19440        * figure out how long we got registered for
19441        * according to section 6.13 of RFC, contact headers override
19442        * expires headers, so check those first */
19443       expires = 0;
19444 
19445       /* XXX todo: try to save the extra call */
19446       if (!ast_strlen_zero(get_header(req, "Contact"))) {
19447          const char *contact = NULL;
19448          const char *tmptmp = NULL;
19449          int start = 0;
19450          for(;;) {
19451             contact = __get_header(req, "Contact", &start);
19452             /* this loop ensures we get a contact header about our register request */
19453             if(!ast_strlen_zero(contact)) {
19454                if( (tmptmp=strstr(contact, p->our_contact))) {
19455                   contact=tmptmp;
19456                   break;
19457                }
19458             } else
19459                break;
19460          }
19461          tmptmp = strcasestr(contact, "expires=");
19462          if (tmptmp) {
19463             if (sscanf(tmptmp + 8, "%30d;", &expires) != 1)
19464                expires = 0;
19465          }
19466          
19467       }
19468       if (!expires)
19469          expires=atoi(get_header(req, "expires"));
19470       if (!expires)
19471          expires=default_expiry;
19472       
19473       expires_ms = expires * 1000;
19474       if (expires <= EXPIRY_GUARD_LIMIT)
19475          expires_ms -= MAX((expires_ms * EXPIRY_GUARD_PCT), EXPIRY_GUARD_MIN);
19476       else
19477          expires_ms -= EXPIRY_GUARD_SECS * 1000;
19478       if (sipdebug)
19479          ast_log(LOG_NOTICE, "Outbound Registration: Expiry for %s is %d sec (Scheduling reregistration in %d s)\n", r->hostname, expires, expires_ms/1000);
19480       
19481       r->refresh= (int) expires_ms / 1000;
19482       
19483       /* Schedule re-registration before we expire */
19484       AST_SCHED_REPLACE_UNREF(r->expire, sched, expires_ms, sip_reregister, r,
19485                         registry_unref(_data,"unref in REPLACE del fail"),
19486                         registry_unref(r,"unref in REPLACE add fail"),
19487                         registry_addref(r,"The Addition side of REPLACE"));
19488    }
19489    return 1;
19490 }
19491 
19492 /*! \brief Handle qualification responses (OPTIONS) */
19493 static void handle_response_peerpoke(struct sip_pvt *p, int resp, struct sip_request *req)
19494 {
19495    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! */
19496    int statechanged, is_reachable, was_reachable;
19497    int pingtime = ast_tvdiff_ms(ast_tvnow(), peer->ps);
19498 
19499    /*
19500     * Compute the response time to a ping (goes in peer->lastms.)
19501     * -1 means did not respond, 0 means unknown,
19502     * 1..maxms is a valid response, >maxms means late response.
19503     */
19504    if (pingtime < 1) /* zero = unknown, so round up to 1 */
19505       pingtime = 1;
19506 
19507    /* Now determine new state and whether it has changed.
19508     * Use some helper variables to simplify the writing
19509     * of the expressions.
19510     */
19511    was_reachable = peer->lastms > 0 && peer->lastms <= peer->maxms;
19512    is_reachable = pingtime <= peer->maxms;
19513    statechanged = peer->lastms == 0 /* yes, unknown before */
19514       || was_reachable != is_reachable;
19515 
19516    peer->lastms = pingtime;
19517    peer->call = dialog_unref(peer->call, "unref dialog peer->call");
19518    if (statechanged) {
19519       const char *s = is_reachable ? "Reachable" : "Lagged";
19520       char str_lastms[20];
19521       snprintf(str_lastms, sizeof(str_lastms), "%d", pingtime);
19522 
19523       ast_log(LOG_NOTICE, "Peer '%s' is now %s. (%dms / %dms)\n",
19524          peer->name, s, pingtime, peer->maxms);
19525       ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", peer->name);
19526       if (sip_cfg.peer_rtupdate) {
19527          ast_update_realtime(ast_check_realtime("sipregs") ? "sipregs" : "sippeers", "name", peer->name, "lastms", str_lastms, SENTINEL);
19528       }
19529       manager_event(EVENT_FLAG_SYSTEM, "PeerStatus",
19530          "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: %s\r\nTime: %d\r\n",
19531          peer->name, s, pingtime);
19532       if (is_reachable && sip_cfg.regextenonqualify)
19533          register_peer_exten(peer, TRUE);
19534    }
19535 
19536    pvt_set_needdestroy(p, "got OPTIONS response");
19537 
19538    /* Try again eventually */
19539    AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched,
19540          is_reachable ? peer->qualifyfreq : DEFAULT_FREQ_NOTOK,
19541          sip_poke_peer_s, peer,
19542          unref_peer(_data, "removing poke peer ref"),
19543          unref_peer(peer, "removing poke peer ref"),
19544          ref_peer(peer, "adding poke peer ref"));
19545 }
19546 
19547 /*! \brief Immediately stop RTP, VRTP and UDPTL as applicable */
19548 static void stop_media_flows(struct sip_pvt *p)
19549 {
19550    /* Immediately stop RTP, VRTP and UDPTL as applicable */
19551    if (p->rtp)
19552       ast_rtp_instance_stop(p->rtp);
19553    if (p->vrtp)
19554       ast_rtp_instance_stop(p->vrtp);
19555    if (p->trtp)
19556       ast_rtp_instance_stop(p->trtp);
19557    if (p->udptl)
19558       ast_udptl_stop(p->udptl);
19559 }
19560 
19561 /*! \brief Handle SIP response in dialogue
19562    \note only called by handle_incoming */
19563 static void handle_response(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno)
19564 {
19565    struct ast_channel *owner;
19566    int sipmethod;
19567    int res = 1;
19568    const char *c = get_header(req, "Cseq");
19569    /* 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 */
19570    char *c_copy = ast_strdupa(c);
19571    /* Skip the Cseq and its subsequent spaces */
19572    const char *msg = ast_skip_blanks(ast_skip_nonblanks(c_copy));
19573 
19574    if (!msg)
19575       msg = "";
19576 
19577    sipmethod = find_sip_method(msg);
19578 
19579    owner = p->owner;
19580    if (owner) {
19581       const char *rp = NULL, *rh = NULL;
19582 
19583       owner->hangupcause = 0;
19584       if (ast_test_flag(&p->flags[1], SIP_PAGE2_Q850_REASON) && (rh = get_header(req, "Reason"))) {
19585          rh = ast_skip_blanks(rh);
19586          if (!strncasecmp(rh, "Q.850", 5)) {
19587             rp = strstr(rh, "cause=");
19588             if (rp && sscanf(rp + 6, "%30d", &owner->hangupcause) == 1) {
19589                owner->hangupcause &= 0x7f;
19590                if (req->debug)
19591                   ast_verbose("Using Reason header for cause code: %d\n", owner->hangupcause);
19592             }
19593          }
19594       }
19595 
19596       if (!owner->hangupcause)
19597          owner->hangupcause = hangup_sip2cause(resp);
19598    }
19599 
19600    if (p->socket.type == SIP_TRANSPORT_UDP) {
19601       int ack_res = FALSE;
19602 
19603       /* Acknowledge whatever it is destined for */
19604       if ((resp >= 100) && (resp <= 199)) {
19605          /* NON-INVITE messages do not ack a 1XX response. RFC 3261 section 17.1.2.2 */
19606          if (sipmethod == SIP_INVITE) {
19607             ack_res = __sip_semi_ack(p, seqno, 0, sipmethod);
19608          }
19609       } else {
19610          ack_res = __sip_ack(p, seqno, 0, sipmethod);
19611       }
19612 
19613       if (ack_res == FALSE) {
19614          /* RFC 3261 13.2.2.4 and 17.1.1.2 - We must re-send ACKs to re-transmitted final responses */
19615          if (sipmethod == SIP_INVITE && resp >= 200) {
19616             transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, resp < 300 ? TRUE: FALSE);
19617          }
19618 
19619          append_history(p, "Ignore", "Ignoring this retransmit\n");
19620          return;
19621       }
19622    }
19623 
19624    /* If this is a NOTIFY for a subscription clear the flag that indicates that we have a NOTIFY pending */
19625    if (!p->owner && sipmethod == SIP_NOTIFY && p->pendinginvite)
19626       p->pendinginvite = 0;
19627 
19628    /* Get their tag if we haven't already */
19629    if (ast_strlen_zero(p->theirtag) || (resp >= 200)) {
19630       char tag[128];
19631 
19632       gettag(req, "To", tag, sizeof(tag));
19633       ast_string_field_set(p, theirtag, tag);
19634    }
19635    /* This needs to be configurable on a channel/peer level,
19636       not mandatory for all communication. Sadly enough, NAT implementations
19637       are not so stable so we can always rely on these headers.
19638       Temporarily disabled, while waiting for fix.
19639       Fix assigned to Rizzo :-)
19640    */
19641    /* check_via_response(p, req); */
19642 
19643    /* RFC 3261 Section 15 specifies that if we receive a 408 or 481
19644     * in response to a BYE, then we should end the current dialog
19645     * and session.  It is known that at least one phone manufacturer
19646     * potentially will send a 404 in response to a BYE, so we'll be
19647     * liberal in what we accept and end the dialog and session if we
19648     * receive any of those responses to a BYE.
19649     */
19650    if ((resp == 404 || resp == 408 || resp == 481) && sipmethod == SIP_BYE) {
19651       pvt_set_needdestroy(p, "received 4XX response to a BYE");
19652       return;
19653    }
19654 
19655    if (p->relatedpeer && p->method == SIP_OPTIONS) {
19656       /* We don't really care what the response is, just that it replied back.
19657          Well, as long as it's not a 100 response...  since we might
19658          need to hang around for something more "definitive" */
19659       if (resp != 100)
19660          handle_response_peerpoke(p, resp, req);
19661    } else if (sipmethod == SIP_REFER && resp >= 200) {
19662       handle_response_refer(p, resp, rest, req, seqno);
19663    } else if (sipmethod == SIP_PUBLISH) {
19664       /* SIP PUBLISH transcends this morass of doodoo and instead
19665        * we just always call the response handler. Good gravy!
19666        */
19667       handle_response_publish(p, resp, rest, req, seqno);
19668    } else if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
19669       switch(resp) {
19670       case 100:   /* 100 Trying */
19671       case 101:   /* 101 Dialog establishment */
19672       case 183:   /* 183 Session Progress */
19673       case 180:   /* 180 Ringing */
19674       case 182:   /* 182 Queued */
19675       case 181:   /* 181 Call Is Being Forwarded */
19676          if (sipmethod == SIP_INVITE)
19677             handle_response_invite(p, resp, rest, req, seqno);
19678          break;
19679       case 200:   /* 200 OK */
19680          p->authtries = 0; /* Reset authentication counter */
19681          if (sipmethod == SIP_MESSAGE || sipmethod == SIP_INFO) {
19682             /* We successfully transmitted a message
19683                or a video update request in INFO */
19684             /* Nothing happens here - the message is inside a dialog */
19685          } else if (sipmethod == SIP_INVITE) {
19686             handle_response_invite(p, resp, rest, req, seqno);
19687          } else if (sipmethod == SIP_NOTIFY) {
19688             handle_response_notify(p, resp, rest, req, seqno);
19689          } else if (sipmethod == SIP_REGISTER) {
19690             res = handle_response_register(p, resp, rest, req, seqno);
19691          } else if (sipmethod == SIP_SUBSCRIBE) {
19692             ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
19693             handle_response_subscribe(p, resp, rest, req, seqno);
19694          } else if (sipmethod == SIP_BYE) {     /* Ok, we're ready to go */
19695             pvt_set_needdestroy(p, "received 200 response");
19696             ast_clear_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
19697          }
19698          break;
19699       case 401: /* Not www-authorized on SIP method */
19700       case 407: /* Proxy auth required */
19701          if (sipmethod == SIP_INVITE)
19702             handle_response_invite(p, resp, rest, req, seqno);
19703          else if (sipmethod == SIP_NOTIFY)
19704             handle_response_notify(p, resp, rest, req, seqno);
19705          else if (sipmethod == SIP_SUBSCRIBE)
19706             handle_response_subscribe(p, resp, rest, req, seqno);
19707          else if (p->registry && sipmethod == SIP_REGISTER)
19708             res = handle_response_register(p, resp, rest, req, seqno);
19709          else if (sipmethod == SIP_UPDATE) {
19710             handle_response_update(p, resp, rest, req, seqno);
19711          } else if (sipmethod == SIP_BYE) {
19712             if (p->options)
19713                p->options->auth_type = resp;
19714             if (ast_strlen_zero(p->authname)) {
19715                ast_log(LOG_WARNING, "Asked to authenticate %s, to %s but we have no matching peer!\n",
19716                      msg, ast_sockaddr_stringify(&p->recv));
19717                pvt_set_needdestroy(p, "unable to authenticate BYE");
19718             } else if ((p->authtries == MAX_AUTHTRIES) || do_proxy_auth(p, req, resp,  sipmethod, 0)) {
19719                ast_log(LOG_NOTICE, "Failed to authenticate on %s to '%s'\n", msg, get_header(&p->initreq, "From"));
19720                pvt_set_needdestroy(p, "failed to authenticate BYE");
19721             }
19722          } else {
19723             ast_log(LOG_WARNING, "Got authentication request (%d) on %s to '%s'\n", resp, sip_methods[sipmethod].text, get_header(req, "To"));
19724             pvt_set_needdestroy(p, "received 407 response");
19725          }
19726          break;
19727       case 403: /* Forbidden - we failed authentication */
19728          if (sipmethod == SIP_INVITE)
19729             handle_response_invite(p, resp, rest, req, seqno);
19730          else if (sipmethod == SIP_SUBSCRIBE)
19731             handle_response_subscribe(p, resp, rest, req, seqno);
19732          else if (p->registry && sipmethod == SIP_REGISTER)
19733             res = handle_response_register(p, resp, rest, req, seqno);
19734          else {
19735             ast_log(LOG_WARNING, "Forbidden - maybe wrong password on authentication for %s\n", msg);
19736             pvt_set_needdestroy(p, "received 403 response");
19737          }
19738          break;
19739       case 404: /* Not found */
19740          if (p->registry && sipmethod == SIP_REGISTER)
19741             res = handle_response_register(p, resp, rest, req, seqno);
19742          else if (sipmethod == SIP_INVITE)
19743             handle_response_invite(p, resp, rest, req, seqno);
19744          else if (sipmethod == SIP_SUBSCRIBE)
19745             handle_response_subscribe(p, resp, rest, req, seqno);
19746          else if (owner)
19747             ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
19748          break;
19749       case 423: /* Interval too brief */
19750          if (sipmethod == SIP_REGISTER)
19751             res = handle_response_register(p, resp, rest, req, seqno);
19752          break;
19753       case 408: /* Request timeout - terminate dialog */
19754          if (sipmethod == SIP_INVITE)
19755             handle_response_invite(p, resp, rest, req, seqno);
19756          else if (sipmethod == SIP_REGISTER)
19757             res = handle_response_register(p, resp, rest, req, seqno);
19758          else if (sipmethod == SIP_BYE) {
19759             pvt_set_needdestroy(p, "received 408 response");
19760             ast_debug(4, "Got timeout on bye. Thanks for the answer. Now, kill this call\n");
19761          } else {
19762             if (owner)
19763                ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
19764             pvt_set_needdestroy(p, "received 408 response");
19765          }
19766          break;
19767 
19768       case 422: /* Session-Timers: Session Interval Too Small */
19769          if (sipmethod == SIP_INVITE) {
19770             handle_response_invite(p, resp, rest, req, seqno);
19771          }
19772          break;
19773 
19774       case 481: /* Call leg does not exist */
19775          if (sipmethod == SIP_INVITE) {
19776             handle_response_invite(p, resp, rest, req, seqno);
19777          } else if (sipmethod == SIP_SUBSCRIBE) {
19778             handle_response_subscribe(p, resp, rest, req, seqno);
19779          } else if (sipmethod == SIP_NOTIFY) {
19780             pvt_set_needdestroy(p, "received 481 response");
19781          } else if (sipmethod == SIP_BYE) {
19782             /* The other side has no transaction to bye,
19783             just assume it's all right then */
19784             ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
19785          } else if (sipmethod == SIP_CANCEL) {
19786             /* The other side has no transaction to cancel,
19787             just assume it's all right then */
19788             ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
19789          } else {
19790             ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
19791             /* Guessing that this is not an important request */
19792          }
19793          break;
19794       case 487:
19795          if (sipmethod == SIP_INVITE)
19796             handle_response_invite(p, resp, rest, req, seqno);
19797          break;
19798       case 415: /* Unsupported media type */
19799       case 488: /* Not acceptable here - codec error */
19800       case 606: /* Not Acceptable */
19801          if (sipmethod == SIP_INVITE)
19802             handle_response_invite(p, resp, rest, req, seqno);
19803          break;
19804       case 491: /* Pending */
19805          if (sipmethod == SIP_INVITE)
19806             handle_response_invite(p, resp, rest, req, seqno);
19807          else {
19808             ast_debug(1, "Got 491 on %s, unsupported. Call ID %s\n", sip_methods[sipmethod].text, p->callid);
19809             pvt_set_needdestroy(p, "received 491 response");
19810          }
19811          break;
19812       case 405:
19813       case 501: /* Not Implemented */
19814          mark_method_unallowed(&p->allowed_methods, sipmethod);
19815          if (p->relatedpeer) {
19816             mark_method_allowed(&p->relatedpeer->disallowed_methods, sipmethod);
19817          }
19818          if (sipmethod == SIP_INVITE)
19819             handle_response_invite(p, resp, rest, req, seqno);
19820          else
19821             ast_log(LOG_WARNING, "Host '%s' does not implement '%s'\n", ast_sockaddr_stringify(&p->sa), msg);
19822          break;
19823          /* Fallthrough */
19824       default:
19825          if ((resp >= 300) && (resp < 700)) {
19826             /* Fatal response */
19827             if ((resp != 487))
19828                ast_verb(3, "Got SIP response %d \"%s\" back from %s\n", resp, rest, ast_sockaddr_stringify(&p->sa));
19829    
19830             if (sipmethod == SIP_INVITE)
19831                stop_media_flows(p); /* Immediately stop RTP, VRTP and UDPTL as applicable */
19832 
19833             /* XXX Locking issues?? XXX */
19834             switch(resp) {
19835             case 300: /* Multiple Choices */
19836             case 301: /* Moved permanently */
19837             case 302: /* Moved temporarily */
19838             case 305: /* Use Proxy */
19839             if (p->owner) {
19840                struct ast_party_redirecting redirecting;
19841                struct ast_set_party_redirecting update_redirecting;
19842 
19843                ast_party_redirecting_init(&redirecting);
19844                change_redirecting_information(p, req, &redirecting,
19845                   &update_redirecting, TRUE);
19846                ast_channel_set_redirecting(p->owner, &redirecting,
19847                   &update_redirecting);
19848                ast_party_redirecting_free(&redirecting);
19849             }
19850                /* Fall through */
19851             case 486: /* Busy here */
19852             case 600: /* Busy everywhere */
19853             case 603: /* Decline */
19854                if (p->owner) {
19855                   sip_handle_cc(p, req, AST_CC_CCBS);
19856                   ast_queue_control(p->owner, AST_CONTROL_BUSY);
19857                }
19858                break;
19859             case 482: /* Loop Detected */
19860             case 480: /* Temporarily Unavailable */
19861             case 404: /* Not Found */
19862             case 410: /* Gone */
19863             case 400: /* Bad Request */
19864             case 500: /* Server error */
19865                if (sipmethod == SIP_SUBSCRIBE) {
19866                   handle_response_subscribe(p, resp, rest, req, seqno);
19867                   break;
19868                }
19869                /* Fall through */
19870             case 502: /* Bad gateway */
19871             case 503: /* Service Unavailable */
19872             case 504: /* Server Timeout */
19873                if (owner)
19874                   ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
19875                break;
19876             default:
19877                /* Send hangup */ 
19878                if (owner && sipmethod != SIP_MESSAGE && sipmethod != SIP_INFO && sipmethod != SIP_BYE)
19879                   ast_queue_hangup_with_cause(p->owner, AST_CAUSE_PROTOCOL_ERROR);
19880                break;
19881             }
19882             /* ACK on invite */
19883             if (sipmethod == SIP_INVITE)
19884                transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
19885             if (sipmethod != SIP_MESSAGE && sipmethod != SIP_INFO)
19886                sip_alreadygone(p);
19887             if (!p->owner) {
19888                pvt_set_needdestroy(p, "transaction completed");
19889             }
19890          } else if ((resp >= 100) && (resp < 200)) {
19891             if (sipmethod == SIP_INVITE) {
19892                if (!req->ignore && sip_cancel_destroy(p))
19893                   ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
19894                if (find_sdp(req))
19895                   process_sdp(p, req, SDP_T38_NONE);
19896                if (p->owner) {
19897                   /* Queue a progress frame */
19898                   ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
19899                }
19900             }
19901          } else
19902             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));
19903       }
19904    } else { 
19905       /* Responses to OUTGOING SIP requests on INCOMING calls
19906          get handled here. As well as out-of-call message responses */
19907       if (req->debug)
19908          ast_verbose("SIP Response message for INCOMING dialog %s arrived\n", msg);
19909 
19910       if (sipmethod == SIP_INVITE && resp == 200) {
19911          /* Tags in early session is replaced by the tag in 200 OK, which is
19912          the final reply to our INVITE */
19913          char tag[128];
19914 
19915          gettag(req, "To", tag, sizeof(tag));
19916          ast_string_field_set(p, theirtag, tag);
19917       }
19918 
19919       if (sipmethod == SIP_SUBSCRIBE && resp >= 400) {
19920          struct sip_monitor_instance *monitor_instance = ao2_callback(sip_monitor_instances,
19921                0, find_sip_monitor_instance_by_subscription_pvt, p);
19922          if (monitor_instance) {
19923             ast_cc_monitor_failed(monitor_instance->core_id, monitor_instance->device_name,
19924                   "Received error response to our SUBSCRIBE");
19925             return;
19926          }
19927       }
19928 
19929       switch(resp) {
19930       case 200:
19931          if (sipmethod == SIP_INVITE) {
19932             handle_response_invite(p, resp, rest, req, seqno);
19933          } else if (sipmethod == SIP_CANCEL) {
19934             ast_debug(1, "Got 200 OK on CANCEL\n");
19935 
19936             /* Wait for 487, then destroy */
19937          } else if (sipmethod == SIP_NOTIFY) {
19938             /* They got the notify, this is the end */
19939             if (p->owner) {
19940                if (p->refer) {
19941                   ast_debug(1, "Got 200 OK on NOTIFY for transfer\n");
19942                } else
19943                   ast_log(LOG_WARNING, "Notify answer on an owned channel?\n");
19944                /* ast_queue_hangup(p->owner); Disabled */
19945             } else {
19946                if (!p->subscribed && !p->refer) {
19947                   pvt_set_needdestroy(p, "transaction completed");
19948                }
19949                if (ast_test_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE)) {
19950                   /* Ready to send the next state we have on queue */
19951                   ast_clear_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE);
19952                   cb_extensionstate((char *)p->context, (char *)p->exten, p->laststate, (void *) p);
19953                }
19954             }
19955          } else if (sipmethod == SIP_BYE) {
19956             pvt_set_needdestroy(p, "transaction completed");
19957          } else if (sipmethod == SIP_MESSAGE || sipmethod == SIP_INFO) {
19958             /* We successfully transmitted a message or
19959                a video update request in INFO */
19960             ;
19961          }
19962          break;
19963       case 401:   /* www-auth */
19964       case 407:
19965          if (sipmethod == SIP_INVITE)
19966             handle_response_invite(p, resp, rest, req, seqno);
19967          else if (sipmethod == SIP_BYE) {
19968             if (p->authtries == MAX_AUTHTRIES || do_proxy_auth(p, req, resp, sipmethod, 0)) {
19969                ast_log(LOG_NOTICE, "Failed to authenticate on %s to '%s'\n", msg, get_header(&p->initreq, "From"));
19970                pvt_set_needdestroy(p, "failed to authenticate BYE");
19971             }
19972          }
19973          break;
19974       case 481:   /* Call leg does not exist */
19975          if (sipmethod == SIP_INVITE) {
19976             /* Re-invite failed */
19977             handle_response_invite(p, resp, rest, req, seqno);
19978          } else if (sipmethod == SIP_BYE) {
19979             pvt_set_needdestroy(p, "received 481 response");
19980          } else if (sipmethod == SIP_NOTIFY) {
19981             pvt_set_needdestroy(p, "received 481 response");
19982          } else if (sipdebug) {
19983             ast_debug(1, "Remote host can't match request %s to call '%s'. Giving up\n", sip_methods[sipmethod].text, p->callid);
19984          }
19985          break;
19986       case 501: /* Not Implemented */
19987          if (sipmethod == SIP_INVITE)
19988             handle_response_invite(p, resp, rest, req, seqno);
19989          break;
19990       default: /* Errors without handlers */
19991          if ((resp >= 100) && (resp < 200)) {
19992             if (sipmethod == SIP_INVITE) {   /* re-invite */
19993                if (!req->ignore && sip_cancel_destroy(p))
19994                   ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
19995             }
19996          }
19997          if ((resp >= 300) && (resp < 700)) {
19998             if ((resp != 487))
19999                ast_verb(3, "Incoming call: Got SIP response %d \"%s\" back from %s\n", resp, rest, ast_sockaddr_stringify(&p->sa));
20000             switch(resp) {
20001             case 415: /* Unsupported media type */
20002             case 488: /* Not acceptable here - codec error */
20003             case 603: /* Decline */
20004             case 500: /* Server error */
20005             case 502: /* Bad gateway */
20006             case 503: /* Service Unavailable */
20007             case 504: /* Server timeout */
20008 
20009                /* re-invite failed */
20010                if (sipmethod == SIP_INVITE && sip_cancel_destroy(p))
20011                   ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
20012                break;
20013             }
20014          }
20015          break;
20016       }
20017    }
20018 }
20019 
20020 
20021 /*! \brief Park SIP call support function
20022    Starts in a new thread, then parks the call
20023    XXX Should we add a wait period after streaming audio and before hangup?? Sometimes the
20024       audio can't be heard before hangup
20025 */
20026 static void *sip_park_thread(void *stuff)
20027 {
20028    struct ast_channel *transferee, *transferer; /* Chan1: The transferee, Chan2: The transferer */
20029    struct sip_dual *d;
20030    struct sip_request req = {0,};
20031    int ext;
20032    int res;
20033 
20034    d = stuff;
20035    transferee = d->chan1;
20036    transferer = d->chan2;
20037    copy_request(&req, &d->req);
20038 
20039    if (!transferee || !transferer) {
20040       ast_log(LOG_ERROR, "Missing channels for parking! Transferer %s Transferee %s\n", transferer ? "<available>" : "<missing>", transferee ? "<available>" : "<missing>" );
20041       deinit_req(&d->req);
20042       free(d);
20043       return NULL;
20044    }
20045    ast_debug(4, "SIP Park: Transferer channel %s, Transferee %s\n", transferer->name, transferee->name);
20046 
20047    if (ast_do_masquerade(transferee)) {
20048       ast_log(LOG_WARNING, "Masquerade failed.\n");
20049       transmit_response(transferer->tech_pvt, "503 Internal error", &req);
20050       deinit_req(&d->req);
20051       free(d);
20052       return NULL;
20053    }
20054 
20055    res = ast_park_call(transferee, transferer, 0, d->parkexten, &ext);
20056    
20057 
20058 #ifdef WHEN_WE_KNOW_THAT_THE_CLIENT_SUPPORTS_MESSAGE
20059    if (!res) {
20060       transmit_message_with_text(transferer->tech_pvt, "Unable to park call.\n");
20061    } else {
20062       /* Then tell the transferer what happened */
20063       sprintf(buf, "Call parked on extension '%d'", ext);
20064       transmit_message_with_text(transferer->tech_pvt, buf);
20065    }
20066 #endif
20067 
20068    /* Any way back to the current call??? */
20069    /* Transmit response to the REFER request */
20070    transmit_response(transferer->tech_pvt, "202 Accepted", &req);
20071    if (!res)   {
20072       /* Transfer succeeded */
20073       append_history(transferer->tech_pvt, "SIPpark", "Parked call on %d", ext);
20074       transmit_notify_with_sipfrag(transferer->tech_pvt, d->seqno, "200 OK", TRUE);
20075       transferer->hangupcause = AST_CAUSE_NORMAL_CLEARING;
20076       ast_hangup(transferer); /* This will cause a BYE */
20077       ast_debug(1, "SIP Call parked on extension '%d'\n", ext);
20078    } else {
20079       transmit_notify_with_sipfrag(transferer->tech_pvt, d->seqno, "503 Service Unavailable", TRUE);
20080       append_history(transferer->tech_pvt, "SIPpark", "Parking failed\n");
20081       ast_debug(1, "SIP Call parked failed \n");
20082       /* Do not hangup call */
20083    }
20084    deinit_req(&d->req);
20085    free(d);
20086    return NULL;
20087 }
20088 
20089 /*! \brief Park a call using the subsystem in res_features.c
20090    This is executed in a separate thread
20091 */
20092 static int sip_park(struct ast_channel *chan1, struct ast_channel *chan2, struct sip_request *req, int seqno, char *parkexten)
20093 {
20094    struct sip_dual *d;
20095    struct ast_channel *transferee, *transferer;
20096       /* Chan2m: The transferer, chan1m: The transferee */
20097    pthread_t th;
20098 
20099    transferee = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, chan1->accountcode, chan1->exten, chan1->context, chan1->linkedid, chan1->amaflags, "Parking/%s", chan1->name);
20100    transferer = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, chan2->accountcode, chan2->exten, chan2->context, chan2->linkedid, chan2->amaflags, "SIPPeer/%s", chan2->name);
20101    if ((!transferer) || (!transferee)) {
20102       if (transferee) {
20103          transferee->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
20104          ast_hangup(transferee);
20105       }
20106       if (transferer) {
20107          transferer->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
20108          ast_hangup(transferer);
20109       }
20110       return -1;
20111    }
20112 
20113    /* Make formats okay */
20114    transferee->readformat = chan1->readformat;
20115    transferee->writeformat = chan1->writeformat;
20116 
20117    /* Prepare for taking over the channel */
20118    ast_channel_masquerade(transferee, chan1);
20119 
20120    /* Setup the extensions and such */
20121    ast_copy_string(transferee->context, chan1->context, sizeof(transferee->context));
20122    ast_copy_string(transferee->exten, chan1->exten, sizeof(transferee->exten));
20123    transferee->priority = chan1->priority;
20124       
20125    /* We make a clone of the peer channel too, so we can play
20126       back the announcement */
20127 
20128    /* Make formats okay */
20129    transferer->readformat = chan2->readformat;
20130    transferer->writeformat = chan2->writeformat;
20131    if (!ast_strlen_zero(chan2->parkinglot))
20132       ast_string_field_set(transferer, parkinglot, chan2->parkinglot);
20133 
20134    /* Prepare for taking over the channel.  Go ahead and grab this channel
20135     * lock here to avoid a deadlock with callbacks into the channel driver
20136     * that hold the channel lock and want the pvt lock.  */
20137    while (ast_channel_trylock(chan2)) {
20138       struct sip_pvt *pvt = chan2->tech_pvt;
20139       sip_pvt_unlock(pvt);
20140       usleep(1);
20141       sip_pvt_lock(pvt);
20142    }
20143    ast_channel_masquerade(transferer, chan2);
20144    ast_channel_unlock(chan2);
20145 
20146    /* Setup the extensions and such */
20147    ast_copy_string(transferer->context, chan2->context, sizeof(transferer->context));
20148    ast_copy_string(transferer->exten, chan2->exten, sizeof(transferer->exten));
20149    transferer->priority = chan2->priority;
20150 
20151    if (ast_do_masquerade(transferer)) {
20152       ast_log(LOG_WARNING, "Masquerade failed :(\n");
20153       transferer->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
20154       ast_hangup(transferer);
20155       return -1;
20156    }
20157    if (!transferer || !transferee) {
20158       if (!transferer) {
20159          ast_debug(1, "No transferer channel, giving up parking\n");
20160       }
20161       if (!transferee) {
20162          ast_debug(1, "No transferee channel, giving up parking\n");
20163       }
20164       return -1;
20165    }
20166    if ((d = ast_calloc(1, sizeof(*d)))) {
20167 
20168       /* Save original request for followup */
20169       copy_request(&d->req, req);
20170       d->chan1 = transferee;  /* Transferee */
20171       d->chan2 = transferer;  /* Transferer */
20172       d->seqno = seqno;
20173       d->parkexten = parkexten;
20174       if (ast_pthread_create_detached_background(&th, NULL, sip_park_thread, d) < 0) {
20175          /* Could not start thread */
20176          deinit_req(&d->req);
20177          ast_free(d);   /* We don't need it anymore. If thread is created, d will be free'd
20178                   by sip_park_thread() */
20179          return 0;
20180       }
20181    }
20182    return -1;
20183 }
20184 
20185 /*! \brief Turn off generator data
20186    XXX Does this function belong in the SIP channel?
20187 */
20188 static void ast_quiet_chan(struct ast_channel *chan)
20189 {
20190    if (chan && chan->_state == AST_STATE_UP) {
20191       if (ast_test_flag(chan, AST_FLAG_MOH))
20192          ast_moh_stop(chan);
20193       else if (chan->generatordata)
20194          ast_deactivate_generator(chan);
20195    }
20196 }
20197 
20198 /*! \brief Attempt transfer of SIP call
20199    This fix for attended transfers on a local PBX */
20200 static int attempt_transfer(struct sip_dual *transferer, struct sip_dual *target)
20201 {
20202    int res = 0;
20203    struct ast_channel *peera = NULL,   
20204       *peerb = NULL,
20205       *peerc = NULL,
20206       *peerd = NULL;
20207 
20208 
20209    /* We will try to connect the transferee with the target and hangup
20210       all channels to the transferer */   
20211    ast_debug(4, "Sip transfer:--------------------\n");
20212    if (transferer->chan1)
20213       ast_debug(4, "-- Transferer to PBX channel: %s State %s\n", transferer->chan1->name, ast_state2str(transferer->chan1->_state));
20214    else
20215       ast_debug(4, "-- No transferer first channel - odd??? \n");
20216    if (target->chan1)
20217       ast_debug(4, "-- Transferer to PBX second channel (target): %s State %s\n", target->chan1->name, ast_state2str(target->chan1->_state));
20218    else
20219       ast_debug(4, "-- No target first channel ---\n");
20220    if (transferer->chan2)
20221       ast_debug(4, "-- Bridged call to transferee: %s State %s\n", transferer->chan2->name, ast_state2str(transferer->chan2->_state));
20222    else
20223       ast_debug(4, "-- No bridged call to transferee\n");
20224    if (target->chan2)
20225       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)");
20226    else
20227       ast_debug(4, "-- No target second channel ---\n");
20228    ast_debug(4, "-- END Sip transfer:--------------------\n");
20229    if (transferer->chan2) { /* We have a bridge on the transferer's channel */
20230       peera = transferer->chan1; /* Transferer - PBX -> transferee channel * the one we hangup */
20231       peerb = target->chan1;     /* Transferer - PBX -> target channel - This will get lost in masq */
20232       peerc = transferer->chan2; /* Asterisk to Transferee */
20233       peerd = target->chan2;     /* Asterisk to Target */
20234       ast_debug(3, "SIP transfer: Four channels to handle\n");
20235    } else if (target->chan2) {   /* Transferer has no bridge (IVR), but transferee */
20236       peera = target->chan1;     /* Transferer to PBX -> target channel */
20237       peerb = transferer->chan1; /* Transferer to IVR*/
20238       peerc = target->chan2;     /* Asterisk to Target */
20239       peerd = transferer->chan2; /* Nothing */
20240       ast_debug(3, "SIP transfer: Three channels to handle\n");
20241    }
20242 
20243    if (peera && peerb && peerc && (peerb != peerc)) {
20244       ast_quiet_chan(peera);     /* Stop generators */
20245       ast_quiet_chan(peerb);  
20246       ast_quiet_chan(peerc);
20247       if (peerd)
20248          ast_quiet_chan(peerd);
20249 
20250       ast_debug(4, "SIP transfer: trying to masquerade %s into %s\n", peerc->name, peerb->name);
20251       if (ast_channel_masquerade(peerb, peerc)) {
20252          ast_log(LOG_WARNING, "Failed to masquerade %s into %s\n", peerb->name, peerc->name);
20253          res = -1;
20254       } else
20255          ast_debug(4, "SIP transfer: Succeeded to masquerade channels.\n");
20256       return res;
20257    } else {
20258       ast_log(LOG_NOTICE, "SIP Transfer attempted with no appropriate bridged calls to transfer\n");
20259       if (transferer->chan1)
20260          ast_softhangup_nolock(transferer->chan1, AST_SOFTHANGUP_DEV);
20261       if (target->chan1)
20262          ast_softhangup_nolock(target->chan1, AST_SOFTHANGUP_DEV);
20263       return -1;
20264    }
20265    return 0;
20266 }
20267 
20268 /*! \brief Get tag from packet
20269  *
20270  * \return Returns the pointer to the provided tag buffer,
20271  *         or NULL if the tag was not found.
20272  */
20273 static const char *gettag(const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize)
20274 {
20275    const char *thetag;
20276 
20277    if (!tagbuf)
20278       return NULL;
20279    tagbuf[0] = '\0';    /* reset the buffer */
20280    thetag = get_header(req, header);
20281    thetag = strcasestr(thetag, ";tag=");
20282    if (thetag) {
20283       thetag += 5;
20284       ast_copy_string(tagbuf, thetag, tagbufsize);
20285       return strsep(&tagbuf, ";");
20286    }
20287    return NULL;
20288 }
20289 
20290 static int handle_cc_notify(struct sip_pvt *pvt, struct sip_request *req)
20291 {
20292    struct sip_monitor_instance *monitor_instance = ao2_callback(sip_monitor_instances, 0,
20293          find_sip_monitor_instance_by_subscription_pvt, pvt);
20294    const char *status = get_body(req, "cc-state", ':');
20295    struct cc_epa_entry *cc_entry;
20296    char *uri;
20297 
20298    if (!monitor_instance) {
20299       transmit_response(pvt, "400 Bad Request", req);
20300       return -1;
20301    }
20302 
20303    if (ast_strlen_zero(status)) {
20304       ao2_ref(monitor_instance, -1);
20305       transmit_response(pvt, "400 Bad Request", req);
20306       return -1;
20307    }
20308 
20309    if (!strcmp(status, "queued")) {
20310       /* We've been told that we're queued. This is the endpoint's way of telling
20311        * us that it has accepted our CC request. We need to alert the core of this
20312        * development
20313        */
20314       ast_cc_monitor_request_acked(monitor_instance->core_id, "SIP endpoint %s accepted request", monitor_instance->device_name);
20315       transmit_response(pvt, "200 OK", req);
20316       ao2_ref(monitor_instance, -1);
20317       return 0;
20318    }
20319 
20320    /* It's open! Yay! */
20321    uri = get_body(req, "cc-URI", ':');
20322    if (ast_strlen_zero(uri)) {
20323       uri = get_in_brackets((char *)get_header(req, "From"));
20324    }
20325 
20326    ast_string_field_set(monitor_instance, notify_uri, uri);
20327    if (monitor_instance->suspension_entry) {
20328       cc_entry = monitor_instance->suspension_entry->instance_data;
20329       if (cc_entry->current_state == CC_CLOSED) {
20330          /* If we've created a suspension entry and the current state is closed, then that means
20331           * we got a notice from the CC core earlier to suspend monitoring, but because this particular
20332           * call leg had not yet notified us that it was ready for recall, it meant that we
20333           * could not yet send a PUBLISH. Now, however, we can.
20334           */
20335          construct_pidf_body(CC_CLOSED, monitor_instance->suspension_entry->body,
20336                sizeof(monitor_instance->suspension_entry->body), monitor_instance->peername);
20337          transmit_publish(monitor_instance->suspension_entry, SIP_PUBLISH_INITIAL, monitor_instance->notify_uri);
20338       } else {
20339          ast_cc_monitor_callee_available(monitor_instance->core_id, "SIP monitored callee has become available");
20340       }
20341    } else {
20342       ast_cc_monitor_callee_available(monitor_instance->core_id, "SIP monitored callee has become available");
20343    }
20344    ao2_ref(monitor_instance, -1);
20345    transmit_response(pvt, "200 OK", req);
20346 
20347    return 0;
20348 }
20349 
20350 /*! \brief Handle incoming notifications */
20351 static int handle_request_notify(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, int seqno, const char *e)
20352 {
20353    /* This is mostly a skeleton for future improvements */
20354    /* Mostly created to return proper answers on notifications on outbound REFER's */
20355    int res = 0;
20356    const char *event = get_header(req, "Event");
20357    char *eventid = NULL;
20358    char *sep;
20359 
20360    if( (sep = strchr(event, ';')) ) {  /* XXX bug here - overwriting string ? */
20361       *sep++ = '\0';
20362       eventid = sep;
20363    }
20364    
20365    if (sipdebug)
20366       ast_debug(2, "Got NOTIFY Event: %s\n", event);
20367 
20368    if (!strcmp(event, "refer")) {
20369       /* Save nesting depth for now, since there might be other events we will
20370          support in the future */
20371 
20372       /* Handle REFER notifications */
20373 
20374       char buf[1024];
20375       char *cmd, *code;
20376       int respcode;
20377       int success = TRUE;
20378 
20379       /* EventID for each transfer... EventID is basically the REFER cseq
20380 
20381        We are getting notifications on a call that we transfered
20382        We should hangup when we are getting a 200 OK in a sipfrag
20383        Check if we have an owner of this event */
20384       
20385       /* Check the content type */
20386       if (strncasecmp(get_header(req, "Content-Type"), "message/sipfrag", strlen("message/sipfrag"))) {
20387          /* We need a sipfrag */
20388          transmit_response(p, "400 Bad request", req);
20389          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20390          return -1;
20391       }
20392 
20393       /* Get the text of the attachment */
20394       if (get_msg_text(buf, sizeof(buf), req, TRUE)) {
20395          ast_log(LOG_WARNING, "Unable to retrieve attachment from NOTIFY %s\n", p->callid);
20396          transmit_response(p, "400 Bad request", req);
20397          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20398          return -1;
20399       }
20400 
20401       /*
20402       From the RFC...
20403       A minimal, but complete, implementation can respond with a single
20404       NOTIFY containing either the body:
20405          SIP/2.0 100 Trying
20406       
20407       if the subscription is pending, the body:
20408          SIP/2.0 200 OK
20409       if the reference was successful, the body:
20410          SIP/2.0 503 Service Unavailable
20411       if the reference failed, or the body:
20412          SIP/2.0 603 Declined
20413 
20414       if the REFER request was accepted before approval to follow the
20415       reference could be obtained and that approval was subsequently denied
20416       (see Section 2.4.7).
20417       
20418       If there are several REFERs in the same dialog, we need to
20419       match the ID of the event header...
20420       */
20421       ast_debug(3, "* SIP Transfer NOTIFY Attachment: \n---%s\n---\n", buf);
20422       cmd = ast_skip_blanks(buf);
20423       code = cmd;
20424       /* We are at SIP/2.0 */
20425       while(*code && (*code > 32)) {   /* Search white space */
20426          code++;
20427       }
20428       *code++ = '\0';
20429       code = ast_skip_blanks(code);
20430       sep = code;
20431       sep++;
20432       while(*sep && (*sep > 32)) {  /* Search white space */
20433          sep++;
20434       }
20435       *sep++ = '\0';       /* Response string */
20436       respcode = atoi(code);
20437       switch (respcode) {
20438       case 200:   /* OK: The new call is up, hangup this call */
20439          /* Hangup the call that we are replacing */
20440          break;
20441       case 301: /* Moved permenantly */
20442       case 302: /* Moved temporarily */
20443          /* Do we get the header in the packet in this case? */
20444          success = FALSE;
20445          break;
20446       case 503:   /* Service Unavailable: The new call failed */
20447       case 603:   /* Declined: Not accepted */
20448             /* Cancel transfer, continue the current call */
20449          success = FALSE;
20450          break;
20451       case 0:     /* Parse error */
20452             /* Cancel transfer, continue the current call */
20453          ast_log(LOG_NOTICE, "Error parsing sipfrag in NOTIFY in response to REFER.\n");
20454          success = FALSE;
20455          break;
20456       default:
20457          if (respcode < 200) {
20458             /* ignore provisional responses */
20459             success = -1;
20460          } else {
20461             ast_log(LOG_NOTICE, "Got unknown code '%d' in NOTIFY in response to REFER.\n", respcode);
20462             success = FALSE;
20463          }
20464          break;
20465       }
20466       if (success == FALSE) {
20467          ast_log(LOG_NOTICE, "Transfer failed. Sorry. Nothing further to do with this call\n");
20468       }
20469 
20470       if (p->owner && success != -1) {
20471          enum ast_control_transfer message = success ? AST_TRANSFER_SUCCESS : AST_TRANSFER_FAILED;
20472          ast_queue_control_data(p->owner, AST_CONTROL_TRANSFER, &message, sizeof(message));
20473       }
20474       /* Confirm that we received this packet */
20475       transmit_response(p, "200 OK", req);
20476    } else if (!strcmp(event, "message-summary")) {
20477       const char *mailbox = NULL;
20478       char *c = ast_strdupa(get_body(req, "Voice-Message", ':'));
20479 
20480       if (!p->mwi) {
20481          struct sip_peer *peer = find_peer(NULL, &p->recv, TRUE, FINDPEERS, FALSE, p->socket.type);
20482 
20483          if (peer) {
20484             mailbox = ast_strdupa(peer->unsolicited_mailbox);
20485             unref_peer(peer, "removing unsolicited mwi ref");
20486          }
20487       } else {
20488          mailbox = p->mwi->mailbox;
20489       }
20490 
20491       if (!ast_strlen_zero(mailbox) && !ast_strlen_zero(c)) {
20492          char *old = strsep(&c, " ");
20493          char *new = strsep(&old, "/");
20494          struct ast_event *event;
20495 
20496          if ((event = ast_event_new(AST_EVENT_MWI,
20497                      AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, mailbox,
20498                      AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, "SIP_Remote",
20499                      AST_EVENT_IE_NEWMSGS, AST_EVENT_IE_PLTYPE_UINT, atoi(new),
20500                      AST_EVENT_IE_OLDMSGS, AST_EVENT_IE_PLTYPE_UINT, atoi(old),
20501                      AST_EVENT_IE_END))) {
20502             ast_event_queue_and_cache(event);
20503          }
20504          transmit_response(p, "200 OK", req);
20505       } else {
20506          transmit_response(p, "489 Bad event", req);
20507          res = -1;
20508       }
20509    } else if (!strcmp(event, "keep-alive")) {
20510        /* Used by Sipura/Linksys for NAT pinhole,
20511         * just confirm that we recieved the packet. */
20512       transmit_response(p, "200 OK", req);
20513    } else if (!strcmp(event, "call-completion")) {
20514       res = handle_cc_notify(p, req);
20515    } else {
20516       /* We don't understand this event. */
20517       transmit_response(p, "489 Bad event", req);
20518       res = -1;
20519    }
20520 
20521    if (!p->lastinvite)
20522       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20523 
20524    return res;
20525 }
20526 
20527 /*! \brief Handle incoming OPTIONS request
20528    An OPTIONS request should be answered like an INVITE from the same UA, including SDP
20529 */
20530 static int handle_request_options(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, const char *e)
20531 {
20532    int res;
20533 
20534    if (p->lastinvite) {
20535       /* if this is a request in an active dialog, just confirm that the dialog exists. */
20536       transmit_response_with_allow(p, "200 OK", req, 0);
20537       return 0;
20538    }
20539 
20540    if (sip_cfg.auth_options_requests) {
20541       /* Do authentication if this OPTIONS request began the dialog */
20542       copy_request(&p->initreq, req);
20543       set_pvt_allowed_methods(p, req);
20544       res = check_user(p, req, SIP_OPTIONS, e, XMIT_UNRELIABLE, addr);
20545       if (res == AUTH_CHALLENGE_SENT) {
20546          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20547          return 0;
20548       }
20549       if (res < 0) { /* Something failed in authentication */
20550          if (res == AUTH_FAKE_AUTH) {
20551             ast_log(LOG_NOTICE, "Sending fake auth rejection for device %s\n", get_header(req, "From"));
20552             transmit_fake_auth_response(p, SIP_OPTIONS, req, XMIT_UNRELIABLE);
20553          } else {
20554             ast_log(LOG_NOTICE, "Failed to authenticate device %s\n", get_header(req, "From"));
20555             transmit_response(p, "403 Forbidden", req);
20556          }
20557          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20558          return 0;
20559       }
20560    }
20561 
20562    /* must go through authentication before getting here */
20563    res = (get_destination(p, req, NULL) == SIP_GET_DEST_EXTEN_FOUND ? 0 : -1);
20564    build_contact(p);
20565 
20566    if (ast_strlen_zero(p->context))
20567       ast_string_field_set(p, context, sip_cfg.default_context);
20568 
20569    if (ast_shutting_down())
20570       transmit_response_with_allow(p, "503 Unavailable", req, 0);
20571    else if (res < 0)
20572       transmit_response_with_allow(p, "404 Not Found", req, 0);
20573    else
20574       transmit_response_with_allow(p, "200 OK", req, 0);
20575 
20576    /* Destroy if this OPTIONS was the opening request, but not if
20577       it's in the middle of a normal call flow. */
20578    sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20579 
20580    return res;
20581 }
20582 
20583 /*! \brief Handle the transfer part of INVITE with a replaces: header,
20584     meaning a target pickup or an attended transfer.
20585     Used only once.
20586    XXX 'ignore' is unused.
20587 
20588    \note this function is called by handle_request_invite(). Four locks
20589    held at the beginning of this function, p, p->owner, p->refer->refer_call and
20590    p->refere->refer_call->owner.  only p's lock should remain at the end of this
20591    function.  p's lock as well as the channel p->owner's lock are held by
20592    handle_request_do(), we unlock p->owner before the masq.  By setting nounlock
20593    we are indicating to handle_request_do() that we have already unlocked the owner.
20594  */
20595 static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, struct ast_sockaddr *addr, int *nounlock)
20596 {
20597    int earlyreplace = 0;
20598    int oneleggedreplace = 0;     /* Call with no bridge, propably IVR or voice message */
20599    struct ast_channel *c = p->owner;   /* Our incoming call */
20600    struct ast_channel *replacecall = p->refer->refer_call->owner; /* The channel we're about to take over */
20601    struct ast_channel *targetcall;     /* The bridge to the take-over target */
20602 
20603    /* Check if we're in ring state */
20604    if (replacecall->_state == AST_STATE_RING)
20605       earlyreplace = 1;
20606 
20607    /* Check if we have a bridge */
20608    if (!(targetcall = ast_bridged_channel(replacecall))) {
20609       /* We have no bridge */
20610       if (!earlyreplace) {
20611          ast_debug(2, " Attended transfer attempted to replace call with no bridge (maybe ringing). Channel %s!\n", replacecall->name);
20612          oneleggedreplace = 1;
20613       }
20614    }
20615    if (targetcall && targetcall->_state == AST_STATE_RINGING)
20616       ast_debug(4, "SIP transfer: Target channel is in ringing state\n");
20617 
20618    if (targetcall)
20619       ast_debug(4, "SIP transfer: Invite Replace incoming channel should bridge to channel %s while hanging up channel %s\n", targetcall->name, replacecall->name);
20620    else
20621       ast_debug(4, "SIP transfer: Invite Replace incoming channel should replace and hang up channel %s (one call leg)\n", replacecall->name);
20622 
20623    if (req->ignore) {
20624       ast_log(LOG_NOTICE, "Ignoring this INVITE with replaces in a stupid way.\n");
20625       /* We should answer something here. If we are here, the
20626          call we are replacing exists, so an accepted
20627          can't harm */
20628       transmit_response_with_sdp(p, "200 OK", req, XMIT_RELIABLE, FALSE, FALSE);
20629       /* Do something more clever here */
20630       if (c) {
20631          *nounlock = 1;
20632          ast_channel_unlock(c);
20633       }
20634       ast_channel_unlock(replacecall);
20635       sip_pvt_unlock(p->refer->refer_call);
20636       return 1;
20637    }
20638    if (!c) {
20639       /* What to do if no channel ??? */
20640       ast_log(LOG_ERROR, "Unable to create new channel.  Invite/replace failed.\n");
20641       transmit_response_reliable(p, "503 Service Unavailable", req);
20642       append_history(p, "Xfer", "INVITE/Replace Failed. No new channel.");
20643       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20644       ast_channel_unlock(replacecall);
20645       sip_pvt_unlock(p->refer->refer_call);
20646       return 1;
20647    }
20648    append_history(p, "Xfer", "INVITE/Replace received");
20649    /* We have three channels to play with
20650       channel c: New incoming call
20651       targetcall: Call from PBX to target
20652       p->refer->refer_call: SIP pvt dialog from transferer to pbx.
20653       replacecall: The owner of the previous
20654       We need to masq C into refer_call to connect to
20655       targetcall;
20656       If we are talking to internal audio stream, target call is null.
20657    */
20658 
20659    /* Fake call progress */
20660    transmit_response(p, "100 Trying", req);
20661    ast_setstate(c, AST_STATE_RING);
20662 
20663    /* Masquerade the new call into the referred call to connect to target call
20664       Targetcall is not touched by the masq */
20665 
20666    /* Answer the incoming call and set channel to UP state */
20667    transmit_response_with_sdp(p, "200 OK", req, XMIT_RELIABLE, FALSE, FALSE);
20668 
20669    ast_setstate(c, AST_STATE_UP);
20670 
20671    /* Stop music on hold and other generators */
20672    ast_quiet_chan(replacecall);
20673    ast_quiet_chan(targetcall);
20674    ast_debug(4, "Invite/Replaces: preparing to masquerade %s into %s\n", c->name, replacecall->name);
20675 
20676    /* Make sure that the masq does not free our PVT for the old call */
20677    if (! earlyreplace && ! oneleggedreplace )
20678       ast_set_flag(&p->refer->refer_call->flags[0], SIP_DEFER_BYE_ON_TRANSFER);  /* Delay hangup */
20679 
20680    /* Prepare the masquerade - if this does not happen, we will be gone */
20681    if(ast_channel_masquerade(replacecall, c))
20682       ast_log(LOG_ERROR, "Failed to masquerade C into Replacecall\n");
20683    else
20684       ast_debug(4, "Invite/Replaces: Going to masquerade %s into %s\n", c->name, replacecall->name);
20685 
20686    /* C should now be in place of replacecall. all channel locks and pvt locks should be removed
20687     * before issuing the masq.  Since we are unlocking both the pvt (p) and its owner channel (c)
20688     * it is possible for channel c to be destroyed on us.  To prevent this, we must give c a reference
20689     * before any unlocking takes place and remove it only once we are completely done with it */
20690    ast_channel_ref(c);
20691    ast_channel_unlock(replacecall);
20692    ast_channel_unlock(c);
20693    sip_pvt_unlock(p->refer->refer_call);
20694    sip_pvt_unlock(p);
20695    if (ast_do_masquerade(replacecall)) {
20696       ast_log(LOG_WARNING, "Failed to perform masquerade with INVITE replaces\n");
20697    }
20698    ast_channel_lock(c);
20699    if (earlyreplace || oneleggedreplace ) {
20700       c->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
20701    }
20702    ast_setstate(c, AST_STATE_DOWN);
20703    ast_channel_unlock(c);
20704 
20705    /* The call should be down with no ast_channel, so hang it up */
20706    c->tech_pvt = dialog_unref(c->tech_pvt, "unref dialog c->tech_pvt");
20707 
20708    /* c and c's tech pvt must be unlocked at this point for ast_hangup */
20709    ast_hangup(c);
20710    /* this indicates to handle_request_do that the owner channel has already been unlocked */
20711    *nounlock = 1;
20712    /* lock PVT structure again after hangup */
20713    sip_pvt_lock(p);
20714    ast_channel_unref(c);
20715    return 0;
20716 }
20717 
20718 /*! \note No channel or pvt locks should be held while calling this function. */
20719 static int do_magic_pickup(struct ast_channel *channel, const char *extension, const char *context)
20720 {
20721    struct ast_str *str = ast_str_alloca(AST_MAX_EXTENSION + AST_MAX_CONTEXT + 2);
20722    struct ast_app *pickup = pbx_findapp("Pickup");
20723 
20724    if (!pickup) {
20725       ast_log(LOG_ERROR, "Unable to perform pickup: Application 'Pickup' not loaded (app_directed_pickup.so).\n");
20726       return -1;
20727    }
20728 
20729    ast_str_set(&str, 0, "%s@%s", extension, sip_cfg.notifycid == IGNORE_CONTEXT ? "PICKUPMARK" : context);
20730 
20731    ast_debug(2, "About to call Pickup(%s)\n", str->str);
20732 
20733    /* There is no point in capturing the return value since pickup_exec
20734       doesn't return anything meaningful unless the passed data is an empty
20735       string (which in our case it will not be) */
20736    pbx_exec(channel, pickup, str->str);
20737 
20738    return 0;
20739 }
20740 
20741 /*! \brief Called to deny a T38 reinvite if the core does not respond to our request */
20742 static int sip_t38_abort(const void *data)
20743 {
20744    struct sip_pvt *p = (struct sip_pvt *) data;
20745 
20746    sip_pvt_lock(p);
20747    /* an application may have taken ownership of the T.38 negotiation on this
20748     * channel while we were waiting to grab the lock... if it did, the scheduler
20749     * id will have been reset to -1, which is our indication that we do *not*
20750     * want to abort the negotiation process
20751     */
20752    if (p->t38id != -1) {
20753       change_t38_state(p, T38_DISABLED);
20754       transmit_response_reliable(p, "488 Not acceptable here", &p->initreq);
20755       p->t38id = -1;
20756       dialog_unref(p, "unref the dialog ptr from sip_t38_abort, because it held a dialog ptr");
20757    }
20758    sip_pvt_unlock(p);
20759    return 0;
20760 }
20761 
20762 /*!
20763  * \brief bare-bones support for SIP UPDATE
20764  *
20765  * XXX This is not even close to being RFC 3311-compliant. We don't advertise
20766  * that we support the UPDATE method, so no one should ever try sending us
20767  * an UPDATE anyway. However, Asterisk can send an UPDATE to change connected
20768  * line information, so we need to be prepared to handle this. The way we distinguish
20769  * such an UPDATE is through the X-Asterisk-rpid-update header.
20770  *
20771  * Actually updating the media session may be some future work.
20772  */
20773 static int handle_request_update(struct sip_pvt *p, struct sip_request *req)
20774 {
20775    if (ast_strlen_zero(get_header(req, "X-Asterisk-rpid-update"))) {
20776       transmit_response(p, "501 Method Not Implemented", req);
20777       return 0;
20778    }
20779    if (get_rpid(p, req)) {
20780       struct ast_party_connected_line connected;
20781       struct ast_set_party_connected_line update_connected;
20782       ast_party_connected_line_init(&connected);
20783       memset(&update_connected, 0, sizeof(update_connected));
20784       if (p->cid_num) {
20785          update_connected.id.number = 1;
20786          connected.id.number.valid = 1;
20787          connected.id.number.str = (char *) p->cid_num;
20788          connected.id.number.presentation = p->callingpres;
20789       }
20790       if (p->cid_name) {
20791          update_connected.id.name = 1;
20792          connected.id.name.valid = 1;
20793          connected.id.name.str = (char *) p->cid_name;
20794          connected.id.name.presentation = p->callingpres;
20795       }
20796       connected.id.tag = (char *) p->cid_tag;
20797       connected.source = AST_CONNECTED_LINE_UPDATE_SOURCE_TRANSFER;
20798       ast_channel_queue_connected_line_update(p->owner, &connected, &update_connected);
20799    }
20800    transmit_response(p, "200 OK", req);
20801    return 0;
20802 }
20803 
20804 /*!
20805  * \brief Handle incoming INVITE request
20806  * \note If the INVITE has a Replaces header, it is part of an
20807  * attended transfer. If so, we do not go through the dial
20808  * plan but try to find the active call and masquerade
20809  * into it
20810  */
20811 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)
20812 {
20813    int res = 1;
20814    int gotdest;
20815    const char *p_replaces;
20816    char *replace_id = NULL;
20817    int refer_locked = 0;
20818    const char *required;
20819    unsigned int required_profile = 0;
20820    struct ast_channel *c = NULL;    /* New channel */
20821    struct sip_peer *authpeer = NULL;   /* Matching Peer */
20822    int reinvite = 0;
20823    int rtn;
20824    struct ast_party_redirecting redirecting;
20825    struct ast_set_party_redirecting update_redirecting;
20826 
20827    const char *p_uac_se_hdr;       /* UAC's Session-Expires header string                      */
20828    const char *p_uac_min_se;       /* UAC's requested Min-SE interval (char string)            */
20829    int uac_max_se = -1;            /* UAC's Session-Expires in integer format                  */
20830    int uac_min_se = -1;            /* UAC's Min-SE in integer format                           */
20831    int st_active = FALSE;          /* Session-Timer on/off boolean                             */
20832    int st_interval = 0;            /* Session-Timer negotiated refresh interval                */
20833    enum st_refresher st_ref;       /* Session-Timer session refresher                          */
20834    int dlg_min_se = -1;
20835    struct {
20836       char exten[AST_MAX_EXTENSION];
20837       char context[AST_MAX_CONTEXT];
20838    } pickup = {
20839          .exten = "",
20840    };
20841    st_ref = SESSION_TIMER_REFRESHER_AUTO;
20842 
20843    /* Find out what they support */
20844    if (!p->sipoptions) {
20845       const char *supported = get_header(req, "Supported");
20846       if (!ast_strlen_zero(supported)) {
20847          p->sipoptions = parse_sip_options(supported, NULL, 0);
20848       }
20849    }
20850 
20851    /* Find out what they require */
20852    required = get_header(req, "Require");
20853    if (!ast_strlen_zero(required)) {
20854       char unsupported[256] = { 0, };
20855       required_profile = parse_sip_options(required, unsupported, ARRAY_LEN(unsupported));
20856 
20857       /* If there are any options required that we do not support,
20858        * then send a 420 with only those unsupported options listed */
20859       if (!ast_strlen_zero(unsupported)) {
20860          transmit_response_with_unsupported(p, "420 Bad extension (unsupported)", req, unsupported);
20861          ast_log(LOG_WARNING, "Received SIP INVITE with unsupported required extension: required:%s unsupported:%s\n", required, unsupported);
20862          p->invitestate = INV_COMPLETED;
20863          if (!p->lastinvite)
20864             sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20865          res = -1;
20866          goto request_invite_cleanup;
20867       }
20868    }
20869 
20870    /* The option tags may be present in Supported: or Require: headers.
20871    Include the Require: option tags for further processing as well */
20872    p->sipoptions |= required_profile;
20873    p->reqsipoptions = required_profile;
20874 
20875    /* Check if this is a loop */
20876    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) {
20877       /* This is a call to ourself.  Send ourselves an error code and stop
20878          processing immediately, as SIP really has no good mechanism for
20879          being able to call yourself */
20880       /* If pedantic is on, we need to check the tags. If they're different, this is
20881          in fact a forked call through a SIP proxy somewhere. */
20882       int different;
20883       const char *initial_rlPart2 = REQ_OFFSET_TO_STR(&p->initreq, rlPart2);
20884       const char *this_rlPart2 = REQ_OFFSET_TO_STR(req, rlPart2);
20885       if (sip_cfg.pedanticsipchecking)
20886          different = sip_uri_cmp(initial_rlPart2, this_rlPart2);
20887       else
20888          different = strcmp(initial_rlPart2, this_rlPart2);
20889       if (!different) {
20890          transmit_response(p, "482 Loop Detected", req);
20891          p->invitestate = INV_COMPLETED;
20892          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20893          res = 0;
20894          goto request_invite_cleanup;
20895       } else {
20896          /*! This is a spiral. What we need to do is to just change the outgoing INVITE
20897           * so that it now routes to the new Request URI. Since we created the INVITE ourselves
20898           * that should be all we need to do.
20899           *
20900           * \todo XXX This needs to be reviewed.  YOu don't change the request URI really, you route the packet
20901           * correctly instead...
20902           */
20903          char *uri = ast_strdupa(this_rlPart2);
20904          char *at = strchr(uri, '@');
20905          char *peerorhost;
20906          ast_debug(2, "Potential spiral detected. Original RURI was %s, new RURI is %s\n", initial_rlPart2, this_rlPart2);
20907          transmit_response(p, "100 Trying", req);
20908          if (at) {
20909             *at = '\0';
20910          }
20911          /* Parse out "sip:" */
20912          if ((peerorhost = strchr(uri, ':'))) {
20913             *peerorhost++ = '\0';
20914          }
20915          ast_string_field_set(p, theirtag, NULL);
20916          /* Treat this as if there were a call forward instead...
20917           */
20918          ast_string_field_set(p->owner, call_forward, peerorhost);
20919          ast_queue_control(p->owner, AST_CONTROL_BUSY);
20920          res = 0;
20921          goto request_invite_cleanup;
20922       }
20923    }
20924 
20925    if (!req->ignore && p->pendinginvite) {
20926       if (!ast_test_flag(&p->flags[0], SIP_OUTGOING) && (p->invitestate == INV_COMPLETED || p->invitestate == INV_TERMINATED)) {
20927          /* What do these circumstances mean? We have received an INVITE for an "incoming" dialog for which we
20928           * have sent a final response. We have not yet received an ACK, though (which is why p->pendinginvite is non-zero).
20929           * We also know that the INVITE is not a retransmission, because otherwise the "ignore" flag would be set.
20930           * This means that either we are receiving a reinvite for a terminated dialog, or we are receiving an INVITE with
20931           * credentials based on one we challenged earlier.
20932           *
20933           * The action to take in either case is to treat the INVITE as though it contains an implicit ACK for the previous
20934           * transaction. Calling __sip_ack will take care of this by clearing the p->pendinginvite and removing the response
20935           * from the previous transaction from the list of outstanding packets.
20936           */
20937          __sip_ack(p, p->pendinginvite, 1, 0);
20938       } else {
20939          /* We already have a pending invite. Sorry. You are on hold. */
20940          p->glareinvite = seqno;
20941          if (p->rtp && find_sdp(req)) {
20942             struct ast_sockaddr addr;
20943             if (get_ip_and_port_from_sdp(req, SDP_AUDIO, &addr)) {
20944                ast_log(LOG_WARNING, "Failed to set an alternate media source on glared reinvite. Audio may not work properly on this call.\n");
20945             } else {
20946                ast_rtp_instance_set_alt_remote_address(p->rtp, &addr);
20947             }
20948             if (p->vrtp) {
20949                if (get_ip_and_port_from_sdp(req, SDP_VIDEO, &addr)) {
20950                   ast_log(LOG_WARNING, "Failed to set an alternate media source on glared reinvite. Video may not work properly on this call.\n");
20951                } else {
20952                   ast_rtp_instance_set_alt_remote_address(p->vrtp, &addr);
20953                }
20954             }
20955          }
20956          transmit_response_reliable(p, "491 Request Pending", req);
20957          ast_debug(1, "Got INVITE on call where we already have pending INVITE, deferring that - %s\n", p->callid);
20958          /* Don't destroy dialog here */
20959          res = 0;
20960          goto request_invite_cleanup;
20961       }
20962    }
20963 
20964    p_replaces = get_header(req, "Replaces");
20965    if (!ast_strlen_zero(p_replaces)) {
20966       /* We have a replaces header */
20967       char *ptr;
20968       char *fromtag = NULL;
20969       char *totag = NULL;
20970       char *start, *to;
20971       int error = 0;
20972 
20973       if (p->owner) {
20974          ast_debug(3, "INVITE w Replaces on existing call? Refusing action. [%s]\n", p->callid);
20975          transmit_response_reliable(p, "400 Bad request", req);   /* The best way to not not accept the transfer */
20976          /* Do not destroy existing call */
20977          res = -1;
20978          goto request_invite_cleanup;
20979       }
20980 
20981       if (sipdebug)
20982          ast_debug(3, "INVITE part of call transfer. Replaces [%s]\n", p_replaces);
20983       /* Create a buffer we can manipulate */
20984       replace_id = ast_strdupa(p_replaces);
20985       ast_uri_decode(replace_id);
20986 
20987       if (!p->refer && !sip_refer_allocate(p)) {
20988          transmit_response_reliable(p, "500 Server Internal Error", req);
20989          append_history(p, "Xfer", "INVITE/Replace Failed. Out of memory.");
20990          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20991          p->invitestate = INV_COMPLETED;
20992          res = -1;
20993          goto request_invite_cleanup;
20994       }
20995 
20996       /*  Todo: (When we find phones that support this)
20997          if the replaces header contains ";early-only"
20998          we can only replace the call in early
20999          stage, not after it's up.
21000 
21001          If it's not in early mode, 486 Busy.
21002       */
21003 
21004       /* Skip leading whitespace */
21005       replace_id = ast_skip_blanks(replace_id);
21006 
21007       start = replace_id;
21008       while ( (ptr = strsep(&start, ";")) ) {
21009          ptr = ast_skip_blanks(ptr); /* XXX maybe unnecessary ? */
21010          if ( (to = strcasestr(ptr, "to-tag=") ) )
21011             totag = to + 7;   /* skip the keyword */
21012          else if ( (to = strcasestr(ptr, "from-tag=") ) ) {
21013             fromtag = to + 9; /* skip the keyword */
21014             fromtag = strsep(&fromtag, "&"); /* trim what ? */
21015          }
21016       }
21017 
21018       if (sipdebug)
21019          ast_debug(4, "Invite/replaces: Will use Replace-Call-ID : %s Fromtag: %s Totag: %s\n",
21020                  replace_id,
21021                  fromtag ? fromtag : "<no from tag>",
21022                  totag ? totag : "<no to tag>");
21023 
21024       /* Try to find call that we are replacing.
21025          If we have a Replaces header, we need to cancel that call if we succeed with this call.
21026          First we cheat a little and look for a magic call-id from phones that support
21027          dialog-info+xml so we can do technology independent pickup... */
21028       if (strncmp(replace_id, "pickup-", 7) == 0) {
21029          struct sip_pvt *subscription = NULL;
21030          replace_id += 7; /* Worst case we are looking at \0 */
21031 
21032          if ((subscription = get_sip_pvt_byid_locked(replace_id, totag, fromtag)) == NULL) {
21033             ast_log(LOG_NOTICE, "Unable to find subscription with call-id: %s\n", replace_id);
21034             transmit_response_reliable(p, "481 Call Leg Does Not Exist (Replaces)", req);
21035             error = 1;
21036          } else {
21037             ast_log(LOG_NOTICE, "Trying to pick up %s@%s\n", subscription->exten, subscription->context);
21038             ast_copy_string(pickup.exten, subscription->exten, sizeof(pickup.exten));
21039             ast_copy_string(pickup.context, subscription->context, sizeof(pickup.context));
21040             sip_pvt_unlock(subscription);
21041             if (subscription->owner) {
21042                ast_channel_unlock(subscription->owner);
21043             }
21044          }
21045       }
21046 
21047       /* This locks both refer_call pvt and refer_call pvt's owner!!!*/
21048       if (!error && ast_strlen_zero(pickup.exten) && (p->refer->refer_call = get_sip_pvt_byid_locked(replace_id, totag, fromtag)) == NULL) {
21049          ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-existent call id (%s)!\n", replace_id);
21050          transmit_response_reliable(p, "481 Call Leg Does Not Exist (Replaces)", req);
21051          error = 1;
21052       } else {
21053          refer_locked = 1;
21054       }
21055 
21056       /* The matched call is the call from the transferer to Asterisk .
21057          We want to bridge the bridged part of the call to the
21058          incoming invite, thus taking over the refered call */
21059 
21060       if (p->refer->refer_call == p) {
21061          ast_log(LOG_NOTICE, "INVITE with replaces into it's own call id (%s == %s)!\n", replace_id, p->callid);
21062          p->refer->refer_call = dialog_unref(p->refer->refer_call, "unref dialog p->refer->refer_call");
21063          transmit_response_reliable(p, "400 Bad request", req);   /* The best way to not not accept the transfer */
21064          error = 1;
21065       }
21066 
21067       if (!error && ast_strlen_zero(pickup.exten) && !p->refer->refer_call->owner) {
21068          /* Oops, someting wrong anyway, no owner, no call */
21069          ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-existing call id (%s)!\n", replace_id);
21070          /* Check for better return code */
21071          transmit_response_reliable(p, "481 Call Leg Does Not Exist (Replace)", req);
21072          error = 1;
21073       }
21074 
21075       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) {
21076          ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-ringing or active call id (%s)!\n", replace_id);
21077          transmit_response_reliable(p, "603 Declined (Replaces)", req);
21078          error = 1;
21079       }
21080 
21081       if (error) {   /* Give up this dialog */
21082          append_history(p, "Xfer", "INVITE/Replace Failed.");
21083          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
21084          sip_pvt_unlock(p);
21085          if (p->refer->refer_call) {
21086             sip_pvt_unlock(p->refer->refer_call);
21087             if (p->refer->refer_call->owner) {
21088                ast_channel_unlock(p->refer->refer_call->owner);
21089             }
21090          }
21091          refer_locked = 0;
21092          p->invitestate = INV_COMPLETED;
21093          res = -1;
21094          goto request_invite_cleanup;
21095       }
21096    }
21097 
21098    /* Check if this is an INVITE that sets up a new dialog or
21099       a re-invite in an existing dialog */
21100 
21101    if (!req->ignore) {
21102       int newcall = (p->initreq.headers ? TRUE : FALSE);
21103 
21104       if (sip_cancel_destroy(p))
21105          ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
21106       /* This also counts as a pending invite */
21107       p->pendinginvite = seqno;
21108       check_via(p, req);
21109 
21110       copy_request(&p->initreq, req);     /* Save this INVITE as the transaction basis */
21111       if (sipdebug)
21112          ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
21113       if (!p->owner) {  /* Not a re-invite */
21114          if (debug)
21115             ast_verbose("Using INVITE request as basis request - %s\n", p->callid);
21116          if (newcall)
21117             append_history(p, "Invite", "New call: %s", p->callid);
21118          parse_ok_contact(p, req);
21119       } else { /* Re-invite on existing call */
21120          ast_clear_flag(&p->flags[0], SIP_OUTGOING);  /* This is now an inbound dialog */
21121          if (get_rpid(p, req)) {
21122             struct ast_party_connected_line connected;
21123             struct ast_set_party_connected_line update_connected;
21124 
21125             ast_party_connected_line_init(&connected);
21126             memset(&update_connected, 0, sizeof(update_connected));
21127             if (p->cid_num) {
21128                update_connected.id.number = 1;
21129                connected.id.number.valid = 1;
21130                connected.id.number.str = (char *) p->cid_num;
21131                connected.id.number.presentation = p->callingpres;
21132             }
21133             if (p->cid_name) {
21134                update_connected.id.name = 1;
21135                connected.id.name.valid = 1;
21136                connected.id.name.str = (char *) p->cid_name;
21137                connected.id.name.presentation = p->callingpres;
21138             }
21139             connected.id.tag = (char *) p->cid_tag;
21140             connected.source = AST_CONNECTED_LINE_UPDATE_SOURCE_TRANSFER;
21141             ast_channel_queue_connected_line_update(p->owner, &connected,
21142                &update_connected);
21143          }
21144          /* Handle SDP here if we already have an owner */
21145          if (find_sdp(req)) {
21146             if (process_sdp(p, req, SDP_T38_INITIATE)) {
21147                if (!ast_strlen_zero(get_header(req, "Content-Encoding"))) {
21148                   /* Asterisk does not yet support any Content-Encoding methods.  Always
21149                    * attempt to process the sdp, but return a 415 if a Content-Encoding header
21150                    * was present after processing failed.  */
21151                   transmit_response_reliable(p, "415 Unsupported Media type", req);
21152                } else {
21153                   transmit_response_reliable(p, "488 Not acceptable here", req);
21154                }
21155                if (!p->lastinvite)
21156                   sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
21157                res = -1;
21158                goto request_invite_cleanup;
21159             }
21160             ast_queue_control(p->owner, AST_CONTROL_SRCUPDATE);
21161          } else {
21162             p->jointcapability = p->capability;
21163             ast_debug(1, "Hm....  No sdp for the moment\n");
21164          }
21165          if (p->do_history) /* This is a response, note what it was for */
21166             append_history(p, "ReInv", "Re-invite received");
21167       }
21168    } else if (debug)
21169       ast_verbose("Ignoring this INVITE request\n");
21170 
21171    if (!p->lastinvite && !req->ignore && !p->owner) {
21172       /* This is a new invite */
21173       /* Handle authentication if this is our first invite */
21174       int cc_recall_core_id = -1;
21175       set_pvt_allowed_methods(p, req);
21176       res = check_user_full(p, req, SIP_INVITE, e, XMIT_RELIABLE, addr, &authpeer);
21177       if (res == AUTH_CHALLENGE_SENT) {
21178          p->invitestate = INV_COMPLETED;     /* Needs to restart in another INVITE transaction */
21179          res = 0;
21180          goto request_invite_cleanup;
21181       }
21182       if (res < 0) { /* Something failed in authentication */
21183          if (res == AUTH_FAKE_AUTH) {
21184             ast_log(LOG_NOTICE, "Sending fake auth rejection for device %s\n", get_header(req, "From"));
21185             transmit_fake_auth_response(p, SIP_INVITE, req, XMIT_RELIABLE);
21186          } else {
21187             ast_log(LOG_NOTICE, "Failed to authenticate device %s\n", get_header(req, "From"));
21188             transmit_response_reliable(p, "403 Forbidden", req);
21189          }
21190          p->invitestate = INV_COMPLETED;
21191          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
21192          ast_string_field_set(p, theirtag, NULL);
21193          res = 0;
21194          goto request_invite_cleanup;
21195       }
21196 
21197       /* Successful authentication and peer matching so record the peer related to this pvt (for easy access to peer settings) */
21198       if (p->relatedpeer) {
21199          p->relatedpeer = unref_peer(p->relatedpeer,"unsetting the relatedpeer field in the dialog, before it is set to something else.");
21200       }
21201       if (authpeer) {
21202          p->relatedpeer = ref_peer(authpeer, "setting dialog's relatedpeer pointer");
21203       }
21204       /* If T38 is needed but not present, then make it magically appear */
21205       if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) && !p->udptl) {
21206          if ((p->udptl = ast_udptl_new_with_bindaddr(sched, io, 0, &bindaddr))) {
21207             p->t38_maxdatagram = global_t38_maxdatagram;
21208             set_t38_capabilities(p);
21209          } else {
21210             /* udptl creation failed, T38 can not be supported on this dialog */
21211             ast_debug(1, "UDPTL creation failed on dialog.\n");
21212             ast_clear_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT);
21213          }
21214       }
21215 
21216       /* We have a successful authentication, process the SDP portion if there is one */
21217       if (find_sdp(req)) {
21218          if (process_sdp(p, req, SDP_T38_INITIATE)) {
21219             /* Asterisk does not yet support any Content-Encoding methods.  Always
21220              * attempt to process the sdp, but return a 415 if a Content-Encoding header
21221              * was present after processing fails. */
21222             if (!ast_strlen_zero(get_header(req, "Content-Encoding"))) {
21223                transmit_response_reliable(p, "415 Unsupported Media type", req);
21224             } else {
21225                /* Unacceptable codecs */
21226                transmit_response_reliable(p, "488 Not acceptable here", req);
21227             }
21228             p->invitestate = INV_COMPLETED;
21229             sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
21230             ast_debug(1, "No compatible codecs for this SIP call.\n");
21231             res = -1;
21232             goto request_invite_cleanup;
21233          }
21234       } else { /* No SDP in invite, call control session */
21235          p->jointcapability = p->capability;
21236          ast_debug(2, "No SDP in Invite, third party call control\n");
21237       }
21238 
21239       /* Queue NULL frame to prod ast_rtp_bridge if appropriate */
21240       /* This seems redundant ... see !p-owner above */
21241       if (p->owner)
21242          ast_queue_frame(p->owner, &ast_null_frame);
21243 
21244 
21245       /* Initialize the context if it hasn't been already */
21246       if (ast_strlen_zero(p->context))
21247          ast_string_field_set(p, context, sip_cfg.default_context);
21248 
21249 
21250       /* Check number of concurrent calls -vs- incoming limit HERE */
21251       ast_debug(1, "Checking SIP call limits for device %s\n", p->username);
21252       if ((res = update_call_counter(p, INC_CALL_LIMIT))) {
21253          if (res < 0) {
21254             ast_log(LOG_NOTICE, "Failed to place call for device %s, too many calls\n", p->username);
21255             transmit_response_reliable(p, "480 Temporarily Unavailable (Call limit) ", req);
21256             sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
21257             p->invitestate = INV_COMPLETED;
21258          }
21259          res = 0;
21260          goto request_invite_cleanup;
21261       }
21262       gotdest = get_destination(p, NULL, &cc_recall_core_id);  /* Get destination right away */
21263       extract_uri(p, req);       /* Get the Contact URI */
21264       build_contact(p);       /* Build our contact header */
21265 
21266       if (p->rtp) {
21267          ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_DTMF, ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
21268          ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_DTMF_COMPENSATE, ast_test_flag(&p->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
21269       }
21270 
21271       if (!replace_id && (gotdest != SIP_GET_DEST_EXTEN_FOUND)) { /* No matching extension found */
21272          switch(gotdest) {
21273          case SIP_GET_DEST_INVALID_URI:
21274             transmit_response_reliable(p, "416 Unsupported URI scheme", req);
21275             break;
21276          case SIP_GET_DEST_PICKUP_EXTEN_FOUND:
21277             if (ast_test_flag(&p->flags[1], SIP_PAGE2_ALLOWOVERLAP)) {
21278                transmit_response_reliable(p, "484 Address Incomplete", req);
21279                break;
21280             }
21281          /* INTENTIONAL FALL THROUGH */
21282          case SIP_GET_DEST_EXTEN_NOT_FOUND:
21283          case SIP_GET_DEST_REFUSED:
21284          default:
21285             {
21286                char *decoded_exten = ast_strdupa(p->exten);
21287                transmit_response_reliable(p, "404 Not Found", req);
21288                ast_uri_decode(decoded_exten);
21289                ast_log(LOG_NOTICE, "Call from '%s' to extension"
21290                   " '%s' rejected because extension not found in context '%s'.\n",
21291                   S_OR(p->username, p->peername), decoded_exten, p->context);
21292             }
21293          } /* end switch */
21294 
21295          p->invitestate = INV_COMPLETED;
21296          update_call_counter(p, DEC_CALL_LIMIT);
21297          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
21298          res = 0;
21299          goto request_invite_cleanup;
21300       } else {
21301 
21302          /* If no extension was specified, use the s one */
21303          /* Basically for calling to IP/Host name only */
21304          if (ast_strlen_zero(p->exten))
21305             ast_string_field_set(p, exten, "s");
21306          /* Initialize our tag */
21307 
21308          make_our_tag(p->tag, sizeof(p->tag));
21309          /* First invitation - create the channel.  Allocation
21310           * failures are handled below. */
21311          c = sip_new(p, AST_STATE_DOWN, S_OR(p->peername, NULL), NULL);
21312          if (cc_recall_core_id != -1) {
21313             ast_setup_cc_recall_datastore(c, cc_recall_core_id);
21314             ast_cc_agent_set_interfaces_chanvar(c);
21315          }
21316          *recount = 1;
21317 
21318          /* Save Record-Route for any later requests we make on this dialogue */
21319          build_route(p, req, 0);
21320 
21321          if (c) {
21322             ast_party_redirecting_init(&redirecting);
21323             memset(&update_redirecting, 0, sizeof(update_redirecting));
21324             /* Pre-lock the call */
21325             ast_channel_lock(c);
21326             change_redirecting_information(p, req, &redirecting, &update_redirecting,
21327                FALSE); /*Will return immediately if no Diversion header is present */
21328             ast_channel_set_redirecting(c, &redirecting, &update_redirecting);
21329             ast_party_redirecting_free(&redirecting);
21330          }
21331       }
21332    } else {
21333       ast_party_redirecting_init(&redirecting);
21334       memset(&update_redirecting, 0, sizeof(update_redirecting));
21335       if (sipdebug) {
21336          if (!req->ignore)
21337             ast_debug(2, "Got a SIP re-invite for call %s\n", p->callid);
21338          else
21339             ast_debug(2, "Got a SIP re-transmit of INVITE for call %s\n", p->callid);
21340       }
21341       if (!req->ignore)
21342          reinvite = 1;
21343       c = p->owner;
21344       change_redirecting_information(p, req, &redirecting, &update_redirecting, FALSE); /*Will return immediately if no Diversion header is present */
21345       if (c) {
21346          ast_channel_set_redirecting(c, &redirecting, &update_redirecting);
21347       }
21348       ast_party_redirecting_free(&redirecting);
21349    }
21350 
21351    /* Session-Timers */
21352    if ((p->sipoptions & SIP_OPT_TIMER) && !ast_strlen_zero(get_header(req, "Session-Expires"))) {
21353       /* The UAC has requested session-timers for this session. Negotiate
21354       the session refresh interval and who will be the refresher */
21355       ast_debug(2, "Incoming INVITE with 'timer' option supported and \"Session-Expires\" header.\n");
21356 
21357       /* Allocate Session-Timers struct w/in the dialog */
21358       if (!p->stimer)
21359          sip_st_alloc(p);
21360 
21361       /* Parse the Session-Expires header */
21362       p_uac_se_hdr = get_header(req, "Session-Expires");
21363       rtn = parse_session_expires(p_uac_se_hdr, &uac_max_se, &st_ref);
21364       if (rtn != 0) {
21365          transmit_response_reliable(p, "400 Session-Expires Invalid Syntax", req);
21366          p->invitestate = INV_COMPLETED;
21367          if (!p->lastinvite) {
21368             sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
21369          }
21370          res = -1;
21371          goto request_invite_cleanup;
21372       }
21373 
21374       /* Parse the Min-SE header */
21375       p_uac_min_se = get_header(req, "Min-SE");
21376       if (!ast_strlen_zero(p_uac_min_se)) {
21377          rtn = parse_minse(p_uac_min_se, &uac_min_se);
21378          if (rtn != 0) {
21379             transmit_response_reliable(p, "400 Min-SE Invalid Syntax", req);
21380             p->invitestate = INV_COMPLETED;
21381             if (!p->lastinvite) {
21382                sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
21383             }
21384             res = -1;
21385             goto request_invite_cleanup;
21386          }
21387       }
21388 
21389       dlg_min_se = st_get_se(p, FALSE);
21390       switch (st_get_mode(p)) {
21391       case SESSION_TIMER_MODE_ACCEPT:
21392       case SESSION_TIMER_MODE_ORIGINATE:
21393          if (uac_max_se > 0 && uac_max_se < dlg_min_se) {
21394             transmit_response_with_minse(p, "422 Session Interval Too Small", req, dlg_min_se);
21395             p->invitestate = INV_COMPLETED;
21396             if (!p->lastinvite) {
21397                sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
21398             }
21399             res = -1;
21400             goto request_invite_cleanup;
21401          }
21402 
21403          p->stimer->st_active_peer_ua = TRUE;
21404          st_active = TRUE;
21405          if (st_ref == SESSION_TIMER_REFRESHER_AUTO) {
21406             st_ref = st_get_refresher(p);
21407          }
21408 
21409          if (uac_max_se > 0) {
21410             int dlg_max_se = st_get_se(p, TRUE);
21411             if (dlg_max_se >= uac_min_se) {
21412                st_interval = (uac_max_se < dlg_max_se) ? uac_max_se : dlg_max_se;
21413             } else {
21414                st_interval = uac_max_se;
21415             }
21416          } else {
21417             /* Set to default max value */
21418             st_interval = global_max_se;
21419          }
21420          break;
21421 
21422       case SESSION_TIMER_MODE_REFUSE:
21423          if (p->reqsipoptions & SIP_OPT_TIMER) {
21424             transmit_response_with_unsupported(p, "420 Option Disabled", req, required);
21425             ast_log(LOG_WARNING, "Received SIP INVITE with supported but disabled option: %s\n", required);
21426             p->invitestate = INV_COMPLETED;
21427             if (!p->lastinvite) {
21428                sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
21429             }
21430             res = -1;
21431             goto request_invite_cleanup;
21432          }
21433          break;
21434 
21435       default:
21436          ast_log(LOG_ERROR, "Internal Error %d at %s:%d\n", st_get_mode(p), __FILE__, __LINE__);
21437          break;
21438       }
21439    } else {
21440       /* The UAC did not request session-timers.  Asterisk (UAS), will now decide
21441       (based on session-timer-mode in sip.conf) whether to run session-timers for
21442       this session or not. */
21443       switch (st_get_mode(p)) {
21444       case SESSION_TIMER_MODE_ORIGINATE:
21445          st_active = TRUE;
21446          st_interval = st_get_se(p, TRUE);
21447          st_ref = SESSION_TIMER_REFRESHER_UAS;
21448          p->stimer->st_active_peer_ua = FALSE;
21449          break;
21450 
21451       default:
21452          break;
21453       }
21454    }
21455 
21456    if (reinvite == 0) {
21457       /* Session-Timers: Start session refresh timer based on negotiation/config */
21458       if (st_active == TRUE) {
21459          p->stimer->st_active   = TRUE;
21460          p->stimer->st_interval = st_interval;
21461          p->stimer->st_ref      = st_ref;
21462          start_session_timer(p);
21463       }
21464    } else {
21465       if (p->stimer->st_active == TRUE) {
21466          /* Session-Timers:  A re-invite request sent within a dialog will serve as
21467          a refresh request, no matter whether the re-invite was sent for refreshing
21468          the session or modifying it.*/
21469          ast_debug (2, "Restarting session-timers on a refresh - %s\n", p->callid);
21470 
21471          /* The UAC may be adjusting the session-timers mid-session */
21472          if (st_interval > 0) {
21473             p->stimer->st_interval = st_interval;
21474             p->stimer->st_ref      = st_ref;
21475          }
21476 
21477          restart_session_timer(p);
21478          if (p->stimer->st_expirys > 0) {
21479             p->stimer->st_expirys--;
21480          }
21481       }
21482    }
21483 
21484    if (!req->ignore && p)
21485       p->lastinvite = seqno;
21486 
21487    if (c && replace_id) {  /* Attended transfer or call pickup - we're the target */
21488       if (!ast_strlen_zero(pickup.exten)) {
21489          append_history(p, "Xfer", "INVITE/Replace received");
21490 
21491          /* Let the caller know we're giving it a shot */
21492          transmit_response(p, "100 Trying", req);
21493          p->invitestate = INV_PROCEEDING;
21494          ast_setstate(c, AST_STATE_RING);
21495 
21496          /* Do the pickup itself */
21497          ast_channel_unlock(c);
21498          *nounlock = 1;
21499 
21500          /* since p->owner (c) is unlocked, we need to go ahead and unlock pvt for both
21501           * magic pickup and ast_hangup.  Both of these functions will attempt to lock
21502           * p->owner again, which can cause a deadlock if we already hold a lock on p.
21503           * Locking order is, channel then pvt.  Dead lock avoidance must be used if
21504           * called the other way around. */
21505          sip_pvt_unlock(p);
21506          do_magic_pickup(c, pickup.exten, pickup.context);
21507          /* Now we're either masqueraded or we failed to pickup, in either case we... */
21508          ast_hangup(c);
21509          sip_pvt_lock(p); /* pvt is expected to remain locked on return, so re-lock it */
21510 
21511          res = 0;
21512          goto request_invite_cleanup;
21513       } else {
21514          /* Go and take over the target call */
21515          if (sipdebug)
21516             ast_debug(4, "Sending this call to the invite/replcaes handler %s\n", p->callid);
21517          res = handle_invite_replaces(p, req, debug, seqno, addr, nounlock);
21518          refer_locked = 0;
21519          goto request_invite_cleanup;
21520       }
21521    }
21522 
21523 
21524    if (c) { /* We have a call  -either a new call or an old one (RE-INVITE) */
21525       enum ast_channel_state c_state = c->_state;
21526 
21527       if (c_state != AST_STATE_UP && reinvite &&
21528          (p->invitestate == INV_TERMINATED || p->invitestate == INV_CONFIRMED)) {
21529          /* If these conditions are true, and the channel is still in the 'ringing'
21530           * state, then this likely means that we have a situation where the initial
21531           * INVITE transaction has completed *but* the channel's state has not yet been
21532           * changed to UP. The reason this could happen is if the reinvite is received
21533           * on the SIP socket prior to an application calling ast_read on this channel
21534           * to read the answer frame we earlier queued on it. In this case, the reinvite
21535           * is completely legitimate so we need to handle this the same as if the channel
21536           * were already UP. Thus we are purposely falling through to the AST_STATE_UP case.
21537           */
21538          c_state = AST_STATE_UP;
21539       }
21540 
21541       switch(c_state) {
21542       case AST_STATE_DOWN:
21543          ast_debug(2, "%s: New call is still down.... Trying... \n", c->name);
21544          transmit_provisional_response(p, "100 Trying", req, 0);
21545          p->invitestate = INV_PROCEEDING;
21546          ast_setstate(c, AST_STATE_RING);
21547          if (strcmp(p->exten, ast_pickup_ext())) { /* Call to extension -start pbx on this call */
21548             enum ast_pbx_result result;
21549 
21550             result = ast_pbx_start(c);
21551 
21552             switch(result) {
21553             case AST_PBX_FAILED:
21554                ast_log(LOG_WARNING, "Failed to start PBX :(\n");
21555                p->invitestate = INV_COMPLETED;
21556                transmit_response_reliable(p, "503 Unavailable", req);
21557                break;
21558             case AST_PBX_CALL_LIMIT:
21559                ast_log(LOG_WARNING, "Failed to start PBX (call limit reached) \n");
21560                p->invitestate = INV_COMPLETED;
21561                transmit_response_reliable(p, "480 Temporarily Unavailable", req);
21562                break;
21563             case AST_PBX_SUCCESS:
21564                /* nothing to do */
21565                break;
21566             }
21567 
21568             if (result) {
21569 
21570                /* Unlock locks so ast_hangup can do its magic */
21571                ast_channel_unlock(c);
21572                sip_pvt_unlock(p);
21573                ast_hangup(c);
21574                sip_pvt_lock(p);
21575                c = NULL;
21576             }
21577          } else { /* Pickup call in call group */
21578             ast_channel_unlock(c);
21579             *nounlock = 1;
21580             if (ast_pickup_call(c)) {
21581                ast_log(LOG_NOTICE, "Nothing to pick up for %s\n", p->callid);
21582                transmit_response_reliable(p, "503 Unavailable", req);
21583                sip_alreadygone(p);
21584                /* Unlock locks so ast_hangup can do its magic */
21585                sip_pvt_unlock(p);
21586                c->hangupcause = AST_CAUSE_CALL_REJECTED;
21587             } else {
21588                sip_pvt_unlock(p);
21589                c->hangupcause = AST_CAUSE_NORMAL_CLEARING;
21590             }
21591             p->invitestate = INV_COMPLETED;
21592             ast_hangup(c);
21593             sip_pvt_lock(p);
21594             c = NULL;
21595          }
21596          break;
21597       case AST_STATE_RING:
21598          transmit_provisional_response(p, "100 Trying", req, 0);
21599          p->invitestate = INV_PROCEEDING;
21600          break;
21601       case AST_STATE_RINGING:
21602          transmit_provisional_response(p, "180 Ringing", req, 0);
21603          p->invitestate = INV_PROCEEDING;
21604          break;
21605       case AST_STATE_UP:
21606          ast_debug(2, "%s: This call is UP.... \n", c->name);
21607 
21608          transmit_response(p, "100 Trying", req);
21609 
21610          if (p->t38.state == T38_PEER_REINVITE) {
21611             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."));
21612          } else if (p->t38.state == T38_ENABLED) {
21613             ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
21614             transmit_response_with_t38_sdp(p, "200 OK", req, (reinvite ? XMIT_RELIABLE : (req->ignore ?  XMIT_UNRELIABLE : XMIT_CRITICAL)));
21615          } else if (p->t38.state == T38_DISABLED) {
21616             /* If this is not a re-invite or something to ignore - it's critical */
21617             if (p->srtp && !ast_test_flag(p->srtp, SRTP_CRYPTO_OFFER_OK)) {
21618                ast_log(LOG_WARNING, "Target does not support required crypto\n");
21619                transmit_response_reliable(p, "488 Not Acceptable Here (crypto)", req);
21620             } else {
21621                ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
21622                transmit_response_with_sdp(p, "200 OK", req, (reinvite ? XMIT_RELIABLE : (req->ignore ?  XMIT_UNRELIABLE : XMIT_CRITICAL)), p->session_modify == TRUE ? FALSE : TRUE, FALSE);
21623             }
21624          }
21625 
21626          p->invitestate = INV_TERMINATED;
21627          break;
21628       default:
21629          ast_log(LOG_WARNING, "Don't know how to handle INVITE in state %d\n", c->_state);
21630          transmit_response(p, "100 Trying", req);
21631          break;
21632       }
21633    } else {
21634       if (p && (p->autokillid == -1)) {
21635          const char *msg;
21636 
21637          if (!p->jointcapability)
21638             msg = "488 Not Acceptable Here (codec error)";
21639          else {
21640             ast_log(LOG_NOTICE, "Unable to create/find SIP channel for this INVITE\n");
21641             msg = "503 Unavailable";
21642          }
21643          transmit_response_reliable(p, msg, req);
21644          p->invitestate = INV_COMPLETED;
21645          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
21646       }
21647    }
21648 
21649 request_invite_cleanup:
21650 
21651    if (refer_locked && p->refer && p->refer->refer_call) {
21652       sip_pvt_unlock(p->refer->refer_call);
21653       if (p->refer->refer_call->owner) {
21654          ast_channel_unlock(p->refer->refer_call->owner);
21655       }
21656    }
21657    if (authpeer) {
21658       authpeer = unref_peer(authpeer, "unref_peer, from handle_request_invite authpeer");
21659    }
21660 
21661    return res;
21662 }
21663 
21664 /*! \brief  Find all call legs and bridge transferee with target
21665  * called from handle_request_refer
21666  *
21667  * \note this function assumes two locks to begin with, sip_pvt transferer and current.chan1 (the pvt's owner)... 
21668  * 2 additional locks are held at the beginning of the function, targetcall_pvt, and targetcall_pvt's owner
21669  * channel (which is stored in target.chan1).  These 2 locks _MUST_ be let go by the end of the function.  Do
21670  * not be confused into thinking a pvt's owner is the same thing as the channels locked at the beginning of
21671  * this function, after the masquerade this may not be true.  Be consistent and unlock only the exact same
21672  * pointers that were locked to begin with.
21673  *
21674  * If this function is successful, only the transferer pvt lock will remain on return.  Setting nounlock indicates
21675  * to handle_request_do() that the pvt's owner it locked does not require an unlock.
21676  */
21677 static int local_attended_transfer(struct sip_pvt *transferer, struct sip_dual *current, struct sip_request *req, int seqno, int *nounlock)
21678 {
21679    struct sip_dual target;    /* Chan 1: Call from tranferer to Asterisk */
21680                /* Chan 2: Call from Asterisk to target */
21681    int res = 0;
21682    struct sip_pvt *targetcall_pvt;
21683    struct ast_party_connected_line connected_to_transferee;
21684    struct ast_party_connected_line connected_to_target;
21685    char transferer_linkedid[32];
21686    struct ast_channel *chans[2];
21687 
21688    /* Check if the call ID of the replaces header does exist locally */
21689    if (!(targetcall_pvt = get_sip_pvt_byid_locked(transferer->refer->replaces_callid, transferer->refer->replaces_callid_totag,
21690       transferer->refer->replaces_callid_fromtag))) {
21691       if (transferer->refer->localtransfer) {
21692          /* We did not find the refered call. Sorry, can't accept then */
21693          transmit_response(transferer, "202 Accepted", req);
21694          /* Let's fake a response from someone else in order
21695             to follow the standard */
21696          transmit_notify_with_sipfrag(transferer, seqno, "481 Call leg/transaction does not exist", TRUE);
21697          append_history(transferer, "Xfer", "Refer failed");
21698          ast_clear_flag(&transferer->flags[0], SIP_GOTREFER);
21699          transferer->refer->status = REFER_FAILED;
21700          return -1;
21701       }
21702       /* Fall through for remote transfers that we did not find locally */
21703       ast_debug(3, "SIP attended transfer: Not our call - generating INVITE with replaces\n");
21704       return 0;
21705    }
21706 
21707    /* Ok, we can accept this transfer */
21708    transmit_response(transferer, "202 Accepted", req);
21709    append_history(transferer, "Xfer", "Refer accepted");
21710    if (!targetcall_pvt->owner) { /* No active channel */
21711       ast_debug(4, "SIP attended transfer: Error: No owner of target call\n");
21712       /* Cancel transfer */
21713       transmit_notify_with_sipfrag(transferer, seqno, "503 Service Unavailable", TRUE);
21714       append_history(transferer, "Xfer", "Refer failed");
21715       ast_clear_flag(&transferer->flags[0], SIP_GOTREFER);
21716       transferer->refer->status = REFER_FAILED;
21717       sip_pvt_unlock(targetcall_pvt);
21718       if (targetcall_pvt)
21719          ao2_t_ref(targetcall_pvt, -1, "Drop targetcall_pvt pointer");
21720       return -1;
21721    }
21722 
21723    /* We have a channel, find the bridge */
21724    target.chan1 = targetcall_pvt->owner;           /* Transferer to Asterisk */
21725    target.chan2 = ast_bridged_channel(targetcall_pvt->owner);  /* Asterisk to target */
21726 
21727    if (!target.chan2 || !(target.chan2->_state == AST_STATE_UP || target.chan2->_state == AST_STATE_RINGING) ) {
21728       /* Wrong state of new channel */
21729       if (target.chan2)
21730          ast_debug(4, "SIP attended transfer: Error: Wrong state of target call: %s\n", ast_state2str(target.chan2->_state));
21731       else if (target.chan1->_state != AST_STATE_RING)
21732          ast_debug(4, "SIP attended transfer: Error: No target channel\n");
21733       else
21734          ast_debug(4, "SIP attended transfer: Attempting transfer in ringing state\n");
21735    }
21736 
21737    /* Transfer */
21738    if (sipdebug) {
21739       if (current->chan2)  /* We have two bridges */
21740          ast_debug(4, "SIP attended transfer: trying to bridge %s and %s\n", target.chan1->name, current->chan2->name);
21741       else        /* One bridge, propably transfer of IVR/voicemail etc */
21742          ast_debug(4, "SIP attended transfer: trying to make %s take over (masq) %s\n", target.chan1->name, current->chan1->name);
21743    }
21744 
21745    ast_set_flag(&transferer->flags[0], SIP_DEFER_BYE_ON_TRANSFER);   /* Delay hangup */
21746 
21747    ast_copy_string(transferer_linkedid, transferer->owner->linkedid, sizeof(transferer_linkedid));
21748 
21749    /* Perform the transfer */
21750    chans[0] = transferer->owner;
21751    chans[1] = target.chan1;
21752    ast_manager_event_multichan(EVENT_FLAG_CALL, "Transfer", 2, chans,
21753       "TransferMethod: SIP\r\n"
21754       "TransferType: Attended\r\n"
21755       "Channel: %s\r\n"
21756       "Uniqueid: %s\r\n"
21757       "SIP-Callid: %s\r\n"
21758       "TargetChannel: %s\r\n"
21759       "TargetUniqueid: %s\r\n",
21760       transferer->owner->name,
21761       transferer->owner->uniqueid,
21762       transferer->callid,
21763       target.chan1->name,
21764       target.chan1->uniqueid);
21765    ast_party_connected_line_init(&connected_to_transferee);
21766    ast_party_connected_line_init(&connected_to_target);
21767    /* No need to lock current->chan1 here since it was locked in sipsock_read */
21768    ast_party_connected_line_copy(&connected_to_transferee, &current->chan1->connected);
21769    /* No need to lock target.chan1 here since it was locked in get_sip_pvt_byid_locked */
21770    ast_party_connected_line_copy(&connected_to_target, &target.chan1->connected);
21771    connected_to_target.source = connected_to_transferee.source = AST_CONNECTED_LINE_UPDATE_SOURCE_TRANSFER;
21772    res = attempt_transfer(current, &target);
21773    if (res) {
21774       /* Failed transfer */
21775       transmit_notify_with_sipfrag(transferer, seqno, "486 Busy Here", TRUE);
21776       append_history(transferer, "Xfer", "Refer failed");
21777       ast_clear_flag(&transferer->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
21778       /* if transfer failed, go ahead and unlock targetcall_pvt and it's owner channel */
21779       sip_pvt_unlock(targetcall_pvt);
21780       ast_channel_unlock(target.chan1);
21781    } else {
21782       /* Transfer succeeded! */
21783       const char *xfersound = pbx_builtin_getvar_helper(target.chan1, "ATTENDED_TRANSFER_COMPLETE_SOUND");
21784 
21785       /* target.chan1 was locked in get_sip_pvt_byid_locked, do not unlock target.chan1 before this */
21786       ast_cel_report_event(target.chan1, AST_CEL_ATTENDEDTRANSFER, NULL, transferer_linkedid, target.chan2);
21787 
21788       /* Tell transferer that we're done. */
21789       transmit_notify_with_sipfrag(transferer, seqno, "200 OK", TRUE);
21790       append_history(transferer, "Xfer", "Refer succeeded");
21791       transferer->refer->status = REFER_200OK;
21792       if (target.chan2 && !ast_strlen_zero(xfersound) && ast_streamfile(target.chan2, xfersound, target.chan2->language) >= 0) {
21793          ast_waitstream(target.chan2, "");
21794       }
21795 
21796       /* By forcing the masquerade, we know that target.chan1 and target.chan2 are bridged. We then
21797        * can queue connected line updates where they need to go.
21798        *
21799        * before a masquerade, all channel and pvt locks must be unlocked.  Any recursive
21800        * channel locks held before this function invalidates channel container locking order.
21801        * Since we are unlocking both the pvt (transferer) and its owner channel (current.chan1)
21802        * it is possible for current.chan1 to be destroyed in the pbx thread.  To prevent this
21803        * we must give c a reference before any unlocking takes place.
21804        */
21805 
21806       ast_channel_ref(current->chan1);
21807       ast_channel_unlock(current->chan1); /* current.chan1 is p->owner before the masq, it was locked by socket_read()*/
21808       ast_channel_unlock(target.chan1);
21809       *nounlock = 1;  /* we just unlocked the dialog's channel and have no plans of locking it again. */
21810       sip_pvt_unlock(targetcall_pvt);
21811       sip_pvt_unlock(transferer);
21812 
21813       ast_do_masquerade(target.chan1);
21814 
21815       sip_pvt_lock(transferer); /* the transferer pvt is expected to remain locked on return */
21816 
21817       ast_indicate(target.chan1, AST_CONTROL_UNHOLD);
21818 
21819       if (target.chan2) {
21820          ast_channel_queue_connected_line_update(target.chan1, &connected_to_transferee, NULL);
21821          ast_channel_queue_connected_line_update(target.chan2, &connected_to_target, NULL);
21822       } else {
21823          /* Since target.chan1 isn't actually connected to another channel, there is no way for us
21824           * to queue a frame so that its connected line status will be updated.
21825           *
21826           * Instead, we use the somewhat hackish approach of using a special control frame type that
21827           * instructs ast_read to perform a specific action. In this case, the frame we queue tells
21828           * ast_read to call the connected line interception macro configured for target.chan1.
21829           */
21830          struct ast_control_read_action_payload *frame_payload;
21831          int payload_size;
21832          int frame_size;
21833          unsigned char connected_line_data[1024];
21834          payload_size = ast_connected_line_build_data(connected_line_data,
21835             sizeof(connected_line_data), &connected_to_target, NULL);
21836          frame_size = payload_size + sizeof(*frame_payload);
21837          if (payload_size != -1 && (frame_payload = alloca(frame_size))) {
21838             frame_payload->payload_size = payload_size;
21839             memcpy(frame_payload->payload, connected_line_data, payload_size);
21840             frame_payload->action = AST_FRAME_READ_ACTION_CONNECTED_LINE_MACRO;
21841             ast_queue_control_data(target.chan1, AST_CONTROL_READ_ACTION, frame_payload, frame_size);
21842          }
21843          /* In addition to queueing the read action frame so that target.chan1's connected line info
21844           * will be updated, we also are going to queue a plain old connected line update on target.chan1. This
21845           * way, either Dial or Queue can apply this connected line update to the outgoing ringing channel.
21846           */
21847          ast_channel_queue_connected_line_update(target.chan1, &connected_to_transferee, NULL);
21848 
21849       }
21850       ast_channel_unref(current->chan1);
21851    }
21852 
21853    /* at this point if the transfer is successful only the transferer pvt should be locked. */
21854    ast_party_connected_line_free(&connected_to_target);
21855    ast_party_connected_line_free(&connected_to_transferee);
21856    if (targetcall_pvt)
21857       ao2_t_ref(targetcall_pvt, -1, "drop targetcall_pvt");
21858    return 1;
21859 }
21860 
21861 
21862 /*! \brief Handle incoming REFER request */
21863 /*! \page SIP_REFER SIP transfer Support (REFER)
21864 
21865    REFER is used for call transfer in SIP. We get a REFER
21866    to place a new call with an INVITE somwhere and then
21867    keep the transferor up-to-date of the transfer. If the
21868    transfer fails, get back on line with the orginal call.
21869 
21870    - REFER can be sent outside or inside of a dialog.
21871      Asterisk only accepts REFER inside of a dialog.
21872 
21873    - If we get a replaces header, it is an attended transfer
21874 
21875    \par Blind transfers
21876    The transferor provides the transferee
21877    with the transfer targets contact. The signalling between
21878    transferer or transferee should not be cancelled, so the
21879    call is recoverable if the transfer target can not be reached
21880    by the transferee.
21881 
21882    In this case, Asterisk receives a TRANSFER from
21883    the transferor, thus is the transferee. We should
21884    try to set up a call to the contact provided
21885    and if that fails, re-connect the current session.
21886    If the new call is set up, we issue a hangup.
21887    In this scenario, we are following section 5.2
21888    in the SIP CC Transfer draft. (Transfer without
21889    a GRUU)
21890 
21891    \par Transfer with consultation hold
21892    In this case, the transferor
21893    talks to the transfer target before the transfer takes place.
21894    This is implemented with SIP hold and transfer.
21895    Note: The invite From: string could indicate a transfer.
21896    (Section 6. Transfer with consultation hold)
21897    The transferor places the transferee on hold, starts a call
21898    with the transfer target to alert them to the impending
21899    transfer, terminates the connection with the target, then
21900    proceeds with the transfer (as in Blind transfer above)
21901 
21902    \par Attended transfer
21903    The transferor places the transferee
21904    on hold, calls the transfer target to alert them,
21905    places the target on hold, then proceeds with the transfer
21906    using a Replaces header field in the Refer-to header. This
21907    will force the transfee to send an Invite to the target,
21908    with a replaces header that instructs the target to
21909    hangup the call between the transferor and the target.
21910    In this case, the Refer/to: uses the AOR address. (The same
21911    URI that the transferee used to establish the session with
21912    the transfer target (To: ). The Require: replaces header should
21913    be in the INVITE to avoid the wrong UA in a forked SIP proxy
21914    scenario to answer and have no call to replace with.
21915 
21916    The referred-by header is *NOT* required, but if we get it,
21917    can be copied into the INVITE to the transfer target to
21918    inform the target about the transferor
21919 
21920    "Any REFER request has to be appropriately authenticated.".
21921    
21922    We can't destroy dialogs, since we want the call to continue.
21923    
21924    */
21925 static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, int *nounlock)
21926 {
21927    struct sip_dual current;   /* Chan1: Call between asterisk and transferer */
21928                /* Chan2: Call between asterisk and transferee */
21929 
21930    int res = 0;
21931    struct ast_channel *chans[2];
21932    current.req.data = NULL;
21933 
21934    if (req->debug)
21935       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");
21936 
21937    if (!p->owner) {
21938       /* This is a REFER outside of an existing SIP dialog */
21939       /* We can't handle that, so decline it */
21940       ast_debug(3, "Call %s: Declined REFER, outside of dialog...\n", p->callid);
21941       transmit_response(p, "603 Declined (No dialog)", req);
21942       if (!req->ignore) {
21943          append_history(p, "Xfer", "Refer failed. Outside of dialog.");
21944          sip_alreadygone(p);
21945          pvt_set_needdestroy(p, "outside of dialog");
21946       }
21947       return 0;
21948    }
21949 
21950 
21951    /* Check if transfer is allowed from this device */
21952    if (p->allowtransfer == TRANSFER_CLOSED ) {
21953       /* Transfer not allowed, decline */
21954       transmit_response(p, "603 Declined (policy)", req);
21955       append_history(p, "Xfer", "Refer failed. Allowtransfer == closed.");
21956       /* Do not destroy SIP session */
21957       return 0;
21958    }
21959 
21960    if (!req->ignore && ast_test_flag(&p->flags[0], SIP_GOTREFER)) {
21961       /* Already have a pending REFER */
21962       transmit_response(p, "491 Request pending", req);
21963       append_history(p, "Xfer", "Refer failed. Request pending.");
21964       return 0;
21965    }
21966 
21967    /* Allocate memory for call transfer data */
21968    if (!p->refer && !sip_refer_allocate(p)) {
21969       transmit_response(p, "500 Internal Server Error", req);
21970       append_history(p, "Xfer", "Refer failed. Memory allocation error.");
21971       return -3;
21972    }
21973 
21974    res = get_refer_info(p, req); /* Extract headers */
21975 
21976    p->refer->status = REFER_SENT;
21977 
21978    if (res != 0) {
21979       switch (res) {
21980       case -2: /* Syntax error */
21981          transmit_response(p, "400 Bad Request (Refer-to missing)", req);
21982          append_history(p, "Xfer", "Refer failed. Refer-to missing.");
21983          if (req->debug)
21984             ast_debug(1, "SIP transfer to black hole can't be handled (no refer-to: )\n");
21985          break;
21986       case -3:
21987          transmit_response(p, "603 Declined (Non sip: uri)", req);
21988          append_history(p, "Xfer", "Refer failed. Non SIP uri");
21989          if (req->debug)
21990             ast_debug(1, "SIP transfer to non-SIP uri denied\n");
21991          break;
21992       default:
21993          /* Refer-to extension not found, fake a failed transfer */
21994          transmit_response(p, "202 Accepted", req);
21995          append_history(p, "Xfer", "Refer failed. Bad extension.");
21996          transmit_notify_with_sipfrag(p, seqno, "404 Not found", TRUE);
21997          ast_clear_flag(&p->flags[0], SIP_GOTREFER);  
21998          if (req->debug)
21999             ast_debug(1, "SIP transfer to bad extension: %s\n", p->refer->refer_to);
22000          break;
22001       }
22002       return 0;
22003    }
22004    if (ast_strlen_zero(p->context))
22005       ast_string_field_set(p, context, sip_cfg.default_context);
22006 
22007    /* If we do not support SIP domains, all transfers are local */
22008    if (sip_cfg.allow_external_domains && check_sip_domain(p->refer->refer_to_domain, NULL, 0)) {
22009       p->refer->localtransfer = 1;
22010       if (sipdebug)
22011          ast_debug(3, "This SIP transfer is local : %s\n", p->refer->refer_to_domain);
22012    } else if (AST_LIST_EMPTY(&domain_list) || check_sip_domain(p->refer->refer_to_domain, NULL, 0)) {
22013       /* This PBX doesn't bother with SIP domains or domain is local, so this transfer is local */
22014       p->refer->localtransfer = 1;
22015    } else if (sipdebug)
22016          ast_debug(3, "This SIP transfer is to a remote SIP extension (remote domain %s)\n", p->refer->refer_to_domain);
22017 
22018    /* Is this a repeat of a current request? Ignore it */
22019    /* Don't know what else to do right now. */
22020    if (req->ignore)
22021       return res;
22022 
22023    /* If this is a blind transfer, we have the following
22024    channels to work with:
22025    - chan1, chan2: The current call between transferer and transferee (2 channels)
22026    - target_channel: A new call from the transferee to the target (1 channel)
22027    We need to stay tuned to what happens in order to be able
22028    to bring back the call to the transferer */
22029 
22030    /* If this is a attended transfer, we should have all call legs within reach:
22031    - chan1, chan2: The call between the transferer and transferee (2 channels)
22032    - target_channel, targetcall_pvt: The call between the transferer and the target (2 channels)
22033    We want to bridge chan2 with targetcall_pvt!
22034    
22035    The replaces call id in the refer message points
22036    to the call leg between Asterisk and the transferer.
22037    So we need to connect the target and the transferee channel
22038    and hangup the two other channels silently
22039    
22040    If the target is non-local, the call ID could be on a remote
22041    machine and we need to send an INVITE with replaces to the
22042    target. We basically handle this as a blind transfer
22043    and let the sip_call function catch that we need replaces
22044    header in the INVITE.
22045    */
22046 
22047 
22048    /* Get the transferer's channel */
22049    chans[0] = current.chan1 = p->owner;
22050 
22051    /* Find the other part of the bridge (2) - transferee */
22052    chans[1] = current.chan2 = ast_bridged_channel(current.chan1);
22053 
22054    if (sipdebug)
22055       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>");
22056 
22057    if (!current.chan2 && !p->refer->attendedtransfer) {
22058       /* No bridged channel, propably IVR or echo or similar... */
22059       /* Guess we should masquerade or something here */
22060       /* Until we figure it out, refuse transfer of such calls */
22061       if (sipdebug)
22062          ast_debug(3, "Refused SIP transfer on non-bridged channel.\n");
22063       p->refer->status = REFER_FAILED;
22064       append_history(p, "Xfer", "Refer failed. Non-bridged channel.");
22065       transmit_response(p, "603 Declined", req);
22066       return -1;
22067    }
22068 
22069    if (current.chan2) {
22070       if (sipdebug)
22071          ast_debug(4, "Got SIP transfer, applying to bridged peer '%s'\n", current.chan2->name);
22072 
22073       ast_queue_control(current.chan1, AST_CONTROL_UNHOLD);
22074    }
22075 
22076    ast_set_flag(&p->flags[0], SIP_GOTREFER);
22077 
22078    /* Attended transfer: Find all call legs and bridge transferee with target*/
22079    if (p->refer->attendedtransfer) {
22080       if ((res = local_attended_transfer(p, &current, req, seqno, nounlock)))
22081          return res; /* We're done with the transfer */
22082       /* Fall through for remote transfers that we did not find locally */
22083       if (sipdebug)
22084          ast_debug(4, "SIP attended transfer: Still not our call - generating INVITE with replaces\n");
22085       /* Fallthrough if we can't find the call leg internally */
22086    }
22087 
22088    /* Parking a call */
22089    if (p->refer->localtransfer && ast_parking_ext_valid(p->refer->refer_to, p->owner, p->owner->context)) {
22090       /* Must release c's lock now, because it will not longer be accessible after the transfer! */
22091       *nounlock = 1;
22092       ast_channel_unlock(current.chan1);
22093       copy_request(&current.req, req);
22094       ast_clear_flag(&p->flags[0], SIP_GOTREFER);
22095       p->refer->status = REFER_200OK;
22096       append_history(p, "Xfer", "REFER to call parking.");
22097       ast_manager_event_multichan(EVENT_FLAG_CALL, "Transfer", 2, chans,
22098          "TransferMethod: SIP\r\n"
22099          "TransferType: Blind\r\n"
22100          "Channel: %s\r\n"
22101          "Uniqueid: %s\r\n"
22102          "SIP-Callid: %s\r\n"
22103          "TargetChannel: %s\r\n"
22104          "TargetUniqueid: %s\r\n"
22105          "TransferExten: %s\r\n"
22106          "Transfer2Parking: Yes\r\n",
22107          current.chan1->name,
22108          current.chan1->uniqueid,
22109          p->callid,
22110          current.chan2->name,
22111          current.chan2->uniqueid,
22112          p->refer->refer_to);
22113       if (sipdebug)
22114          ast_debug(4, "SIP transfer to parking: trying to park %s. Parked by %s\n", current.chan2->name, current.chan1->name);
22115       sip_park(current.chan2, current.chan1, req, seqno, p->refer->refer_to);
22116       return res;
22117    }
22118 
22119    /* Blind transfers and remote attended xfers */
22120    transmit_response(p, "202 Accepted", req);
22121 
22122    if (current.chan1 && current.chan2) {
22123       ast_debug(3, "chan1->name: %s\n", current.chan1->name);
22124       pbx_builtin_setvar_helper(current.chan1, "BLINDTRANSFER", current.chan2->name);
22125    }
22126    if (current.chan2) {
22127       pbx_builtin_setvar_helper(current.chan2, "BLINDTRANSFER", current.chan1->name);
22128       pbx_builtin_setvar_helper(current.chan2, "SIPDOMAIN", p->refer->refer_to_domain);
22129       pbx_builtin_setvar_helper(current.chan2, "SIPTRANSFER", "yes");
22130       /* One for the new channel */
22131       pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER", "yes");
22132       /* Attended transfer to remote host, prepare headers for the INVITE */
22133       if (p->refer->referred_by)
22134          pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER_REFERER", p->refer->referred_by);
22135    }
22136    /* Generate a Replaces string to be used in the INVITE during attended transfer */
22137    if (!ast_strlen_zero(p->refer->replaces_callid)) {
22138       char tempheader[SIPBUFSIZE];
22139       snprintf(tempheader, sizeof(tempheader), "%s%s%s%s%s", p->refer->replaces_callid,
22140             p->refer->replaces_callid_totag ? ";to-tag=" : "",
22141             p->refer->replaces_callid_totag,
22142             p->refer->replaces_callid_fromtag ? ";from-tag=" : "",
22143             p->refer->replaces_callid_fromtag);
22144       if (current.chan2)
22145          pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER_REPLACES", tempheader);
22146    }
22147    /* Must release lock now, because it will not longer
22148       be accessible after the transfer! */
22149    *nounlock = 1;
22150    /*
22151     * Increase ref count so that we can delay channel destruction until after
22152     * we get a chance to fire off some events.
22153     */
22154    ast_channel_ref(current.chan1);
22155    ast_channel_unlock(current.chan1);
22156 
22157    /* Connect the call */
22158 
22159    /* FAKE ringing if not attended transfer */
22160    if (!p->refer->attendedtransfer)
22161       transmit_notify_with_sipfrag(p, seqno, "183 Ringing", FALSE);
22162 
22163    /* For blind transfer, this will lead to a new call */
22164    /* For attended transfer to remote host, this will lead to
22165       a new SIP call with a replaces header, if the dial plan allows it
22166    */
22167    if (!current.chan2) {
22168       /* We have no bridge, so we're talking with Asterisk somehow */
22169       /* We need to masquerade this call */
22170       /* What to do to fix this situation:
22171          * Set up the new call in a new channel
22172          * Let the new channel masq into this channel
22173          Please add that code here :-)
22174       */
22175       p->refer->status = REFER_FAILED;
22176       transmit_notify_with_sipfrag(p, seqno, "503 Service Unavailable (can't handle one-legged xfers)", TRUE);
22177       ast_clear_flag(&p->flags[0], SIP_GOTREFER);  
22178       append_history(p, "Xfer", "Refer failed (only bridged calls).");
22179       ast_channel_unref(current.chan1);
22180       return -1;
22181    }
22182    ast_set_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER);   /* Delay hangup */
22183 
22184 
22185    /* For blind transfers, move the call to the new extensions. For attended transfers on multiple
22186       servers - generate an INVITE with Replaces. Either way, let the dial plan decided  */
22187    res = ast_async_goto(current.chan2, p->refer->refer_to_context, p->refer->refer_to, 1);
22188 
22189    if (!res) {
22190       ast_manager_event_multichan(EVENT_FLAG_CALL, "Transfer", 2, chans,
22191          "TransferMethod: SIP\r\n"
22192          "TransferType: Blind\r\n"
22193          "Channel: %s\r\n"
22194          "Uniqueid: %s\r\n"
22195          "SIP-Callid: %s\r\n"
22196          "TargetChannel: %s\r\n"
22197          "TargetUniqueid: %s\r\n"
22198          "TransferExten: %s\r\n"
22199          "TransferContext: %s\r\n",
22200          current.chan1->name,
22201          current.chan1->uniqueid,
22202          p->callid,
22203          current.chan2->name,
22204          current.chan2->uniqueid,
22205          p->refer->refer_to, p->refer->refer_to_context);
22206       /* Success  - we have a new channel */
22207       ast_debug(3, "%s transfer succeeded. Telling transferer.\n", p->refer->attendedtransfer? "Attended" : "Blind");
22208 
22209       while (ast_channel_trylock(current.chan1)) {
22210          sip_pvt_unlock(p);
22211          sched_yield();
22212          sip_pvt_lock(p);
22213       }
22214 
22215       /* XXX - what to we put in CEL 'extra' for attended transfers to external systems? NULL for now */
22216       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);
22217       ast_channel_unlock(current.chan1);
22218 
22219       transmit_notify_with_sipfrag(p, seqno, "200 Ok", TRUE);
22220       if (p->refer->localtransfer)
22221          p->refer->status = REFER_200OK;
22222       if (p->owner)
22223          p->owner->hangupcause = AST_CAUSE_NORMAL_CLEARING;
22224       append_history(p, "Xfer", "Refer succeeded.");
22225       ast_clear_flag(&p->flags[0], SIP_GOTREFER);  
22226       /* Do not hangup call, the other side do that when we say 200 OK */
22227       /* We could possibly implement a timer here, auto congestion */
22228       res = 0;
22229    } else {
22230       ast_clear_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER); /* Don't delay hangup */
22231       ast_debug(3, "%s transfer failed. Resuming original call.\n", p->refer->attendedtransfer? "Attended" : "Blind");
22232       append_history(p, "Xfer", "Refer failed.");
22233       /* Failure of some kind */
22234       p->refer->status = REFER_FAILED;
22235       transmit_notify_with_sipfrag(p, seqno, "503 Service Unavailable", TRUE);
22236       ast_clear_flag(&p->flags[0], SIP_GOTREFER);  
22237       res = -1;
22238    }
22239 
22240    ast_channel_unref(current.chan1);
22241 
22242    return res;
22243 }
22244 
22245 /*! \brief Handle incoming CANCEL request */
22246 static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req)
22247 {
22248 
22249    check_via(p, req);
22250    sip_alreadygone(p);
22251 
22252    if (p->owner && p->owner->_state == AST_STATE_UP) {
22253       /* This call is up, cancel is ignored, we need a bye */
22254       transmit_response(p, "200 OK", req);
22255       ast_debug(1, "Got CANCEL on an answered call. Ignoring... \n");
22256       return 0;
22257    }
22258 
22259    /* At this point, we could have cancelled the invite at the same time
22260       as the other side sends a CANCEL. Our final reply with error code
22261       might not have been received by the other side before the CANCEL
22262       was sent, so let's just give up retransmissions and waiting for
22263       ACK on our error code. The call is hanging up any way. */
22264    if (p->invitestate == INV_TERMINATED || p->invitestate == INV_COMPLETED) {
22265       __sip_pretend_ack(p);
22266    }
22267    if (p->invitestate != INV_TERMINATED)
22268       p->invitestate = INV_CANCELLED;
22269 
22270    if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD))
22271       update_call_counter(p, DEC_CALL_LIMIT);
22272 
22273    stop_media_flows(p); /* Immediately stop RTP, VRTP and UDPTL as applicable */
22274    if (p->owner) {
22275       ast_set_hangupsource(p->owner, p->owner->name, 0);
22276       ast_queue_hangup(p->owner);
22277    }
22278    else
22279       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
22280    if (p->initreq.len > 0) {
22281       struct sip_pkt *pkt, *prev_pkt;
22282       /* If the CANCEL we are receiving is a retransmission, and we already have scheduled
22283        * a reliable 487, then we don't want to schedule another one on top of the previous
22284        * one.
22285        *
22286        * As odd as this may sound, we can't rely on the previously-transmitted "reliable"
22287        * response in this situation. What if we've sent all of our reliable responses
22288        * already and now all of a sudden, we get this second CANCEL?
22289        *
22290        * The only way to do this correctly is to cancel our previously-scheduled reliably-
22291        * transmitted response and send a new one in its place.
22292        */
22293       for (pkt = p->packets, prev_pkt = NULL; pkt; prev_pkt = pkt, pkt = pkt->next) {
22294          if (pkt->seqno == p->lastinvite && pkt->response_code == 487) {
22295             AST_SCHED_DEL(sched, pkt->retransid);
22296             UNLINK(pkt, p->packets, prev_pkt);
22297             ast_free(pkt);
22298             break;
22299          }
22300       }
22301       transmit_response_reliable(p, "487 Request Terminated", &p->initreq);
22302       transmit_response(p, "200 OK", req);
22303       return 1;
22304    } else {
22305       transmit_response(p, "481 Call Leg Does Not Exist", req);
22306       return 0;
22307    }
22308 }
22309 
22310 /*! \brief Handle incoming BYE request */
22311 static int handle_request_bye(struct sip_pvt *p, struct sip_request *req)
22312 {
22313    struct ast_channel *c=NULL;
22314    int res;
22315    struct ast_channel *bridged_to;
22316    const char *required;
22317 
22318    /* If we have an INCOMING invite that we haven't answered, terminate that transaction */
22319    if (p->pendinginvite && !ast_test_flag(&p->flags[0], SIP_OUTGOING) && !req->ignore) {
22320       transmit_response_reliable(p, "487 Request Terminated", &p->initreq);
22321    }
22322 
22323    __sip_pretend_ack(p);
22324 
22325    p->invitestate = INV_TERMINATED;
22326 
22327    copy_request(&p->initreq, req);
22328    if (sipdebug)
22329       ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
22330    check_via(p, req);
22331    sip_alreadygone(p);
22332 
22333    /* Get RTCP quality before end of call */
22334    if (p->do_history || p->owner) {
22335       char quality_buf[AST_MAX_USER_FIELD], *quality;
22336       struct ast_channel *bridge = p->owner ? ast_bridged_channel(p->owner) : NULL;
22337 
22338       /* We need to get the lock on bridge because ast_rtp_instance_set_stats_vars will attempt
22339        * to lock the bridge. This may get hairy...
22340        */
22341       while (bridge && ast_channel_trylock(bridge)) {
22342          ast_channel_unlock(p->owner);
22343          do {
22344             /* Can't use DEADLOCK_AVOIDANCE since p is an ao2 object */
22345             sip_pvt_unlock(p);
22346             usleep(1);
22347             sip_pvt_lock(p);
22348          } while (p->owner && ast_channel_trylock(p->owner));
22349          bridge = p->owner ? ast_bridged_channel(p->owner) : NULL;
22350       }
22351 
22352 
22353       if (p->rtp && (quality = ast_rtp_instance_get_quality(p->rtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY, quality_buf, sizeof(quality_buf)))) {
22354          if (p->do_history) {
22355             append_history(p, "RTCPaudio", "Quality:%s", quality);
22356 
22357             if ((quality = ast_rtp_instance_get_quality(p->rtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY_JITTER, quality_buf, sizeof(quality_buf)))) {
22358                append_history(p, "RTCPaudioJitter", "Quality:%s", quality);
22359             }
22360             if ((quality = ast_rtp_instance_get_quality(p->rtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY_LOSS, quality_buf, sizeof(quality_buf)))) {
22361                append_history(p, "RTCPaudioLoss", "Quality:%s", quality);
22362             }
22363             if ((quality = ast_rtp_instance_get_quality(p->rtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY_RTT, quality_buf, sizeof(quality_buf)))) {
22364                append_history(p, "RTCPaudioRTT", "Quality:%s", quality);
22365             }
22366          }
22367 
22368          if (p->owner) {
22369             ast_rtp_instance_set_stats_vars(p->owner, p->rtp);
22370          }
22371 
22372       }
22373 
22374       if (bridge) {
22375          struct sip_pvt *q = bridge->tech_pvt;
22376 
22377          if (IS_SIP_TECH(bridge->tech) && q && q->rtp) {
22378             ast_rtp_instance_set_stats_vars(bridge, q->rtp);
22379          }
22380          ast_channel_unlock(bridge);
22381       }
22382 
22383       if (p->vrtp && (quality = ast_rtp_instance_get_quality(p->vrtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY, quality_buf, sizeof(quality_buf)))) {
22384          if (p->do_history) {
22385             append_history(p, "RTCPvideo", "Quality:%s", quality);
22386          }
22387          if (p->owner) {
22388             pbx_builtin_setvar_helper(p->owner, "RTPVIDEOQOS", quality);
22389          }
22390       }
22391       if (p->trtp && (quality = ast_rtp_instance_get_quality(p->trtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY, quality_buf, sizeof(quality_buf)))) {
22392          if (p->do_history) {
22393             append_history(p, "RTCPtext", "Quality:%s", quality);
22394          }
22395          if (p->owner) {
22396             pbx_builtin_setvar_helper(p->owner, "RTPTEXTQOS", quality);
22397          }
22398       }
22399    }
22400 
22401    stop_media_flows(p); /* Immediately stop RTP, VRTP and UDPTL as applicable */
22402    stop_session_timer(p); /* Stop Session-Timer */
22403 
22404    if (!ast_strlen_zero(get_header(req, "Also"))) {
22405       ast_log(LOG_NOTICE, "Client '%s' using deprecated BYE/Also transfer method.  Ask vendor to support REFER instead\n",
22406          ast_sockaddr_stringify(&p->recv));
22407       if (ast_strlen_zero(p->context))
22408          ast_string_field_set(p, context, sip_cfg.default_context);
22409       res = get_also_info(p, req);
22410       if (!res) {
22411          c = p->owner;
22412          if (c) {
22413             bridged_to = ast_bridged_channel(c);
22414             if (bridged_to) {
22415                /* Don't actually hangup here... */
22416                ast_queue_control(c, AST_CONTROL_UNHOLD);
22417                ast_channel_unlock(c);  /* async_goto can do a masquerade, no locks can be held during a masq */
22418                ast_async_goto(bridged_to, p->context, p->refer->refer_to, 1);
22419                ast_channel_lock(c);
22420             } else
22421                ast_queue_hangup(p->owner);
22422          }
22423       } else {
22424          ast_log(LOG_WARNING, "Invalid transfer information from '%s'\n", ast_sockaddr_stringify(&p->recv));
22425          if (p->owner)
22426             ast_queue_hangup_with_cause(p->owner, AST_CAUSE_PROTOCOL_ERROR);
22427       }
22428    } else if (p->owner) {
22429       ast_set_hangupsource(p->owner, p->owner->name, 0);
22430       ast_queue_hangup(p->owner);
22431       sip_scheddestroy_final(p, DEFAULT_TRANS_TIMEOUT);
22432       ast_debug(3, "Received bye, issuing owner hangup\n");
22433    } else {
22434       sip_scheddestroy_final(p, DEFAULT_TRANS_TIMEOUT);
22435       ast_debug(3, "Received bye, no owner, selfdestruct soon.\n");
22436    }
22437    ast_clear_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
22438 
22439    /* Find out what they require */
22440    required = get_header(req, "Require");
22441    if (!ast_strlen_zero(required)) {
22442       char unsupported[256] = { 0, };
22443       parse_sip_options(required, unsupported, ARRAY_LEN(unsupported));
22444       /* If there are any options required that we do not support,
22445        * then send a 420 with only those unsupported options listed */
22446       if (!ast_strlen_zero(unsupported)) {
22447          transmit_response_with_unsupported(p, "420 Bad extension (unsupported)", req, unsupported);
22448          ast_log(LOG_WARNING, "Received SIP BYE with unsupported required extension: required:%s unsupported:%s\n", required, unsupported);
22449       } else {
22450          transmit_response(p, "200 OK", req);
22451       }
22452    } else {
22453       transmit_response(p, "200 OK", req);
22454    }
22455 
22456    return 1;
22457 }
22458 
22459 /*! \brief Handle incoming MESSAGE request */
22460 static int handle_request_message(struct sip_pvt *p, struct sip_request *req)
22461 {
22462    if (!req->ignore) {
22463       if (req->debug)
22464          ast_verbose("Receiving message!\n");
22465       receive_message(p, req);
22466    } else
22467       transmit_response(p, "202 Accepted", req);
22468    return 1;
22469 }
22470 
22471 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)
22472 {
22473    int etag_present = !ast_strlen_zero(etag);
22474    int body_present = req->lines > 0;
22475 
22476    ast_assert(expires_int != NULL);
22477 
22478    if (ast_strlen_zero(expires)) {
22479       /* Section 6, item 4, second bullet point of RFC 3903 says to
22480        * use a locally-configured default expiration if none is provided
22481        * in the request
22482        */
22483       *expires_int = DEFAULT_PUBLISH_EXPIRES;
22484    } else if (sscanf(expires, "%30d", expires_int) != 1) {
22485       return SIP_PUBLISH_UNKNOWN;
22486    }
22487 
22488    if (*expires_int == 0) {
22489       return SIP_PUBLISH_REMOVE;
22490    } else if (!etag_present && body_present) {
22491       return SIP_PUBLISH_INITIAL;
22492    } else if (etag_present && !body_present) {
22493       return SIP_PUBLISH_REFRESH;
22494    } else if (etag_present && body_present) {
22495       return SIP_PUBLISH_MODIFY;
22496    }
22497 
22498    return SIP_PUBLISH_UNKNOWN;
22499 }
22500 
22501 #ifdef HAVE_LIBXML2
22502 static void get_pidf_body(struct sip_request *req, char *pidf_body, size_t size)
22503 {
22504    int i;
22505    struct ast_str *str = ast_str_alloca(size);
22506    for (i = 0; i < req->lines; ++i) {
22507       ast_str_append(&str, 0, "%s", REQ_OFFSET_TO_STR(req, line[i]));
22508    }
22509    ast_copy_string(pidf_body, ast_str_buffer(str), size);
22510 }
22511 
22512 static int pidf_validate_tuple(struct ast_xml_node *tuple_node)
22513 {
22514    const char *id;
22515    int status_found = FALSE;
22516    struct ast_xml_node *tuple_children;
22517    struct ast_xml_node *tuple_children_iterator;
22518    /* Tuples have to have an id attribute or they're invalid */
22519    if (!(id = ast_xml_get_attribute(tuple_node, "id"))) {
22520       ast_log(LOG_WARNING, "Tuple XML element has no attribute 'id'\n");
22521       return FALSE;
22522    }
22523    /* We don't care what it actually is, just that it's there */
22524    ast_xml_free_attr(id);
22525    /* This is a tuple. It must have a status element */
22526    if (!(tuple_children = ast_xml_node_get_children(tuple_node))) {
22527       /* The tuple has no children. It sucks */
22528       ast_log(LOG_WARNING, "Tuple XML element has no child elements\n");
22529       return FALSE;
22530    }
22531    for (tuple_children_iterator = tuple_children; tuple_children_iterator;
22532          tuple_children_iterator = ast_xml_node_get_next(tuple_children_iterator)) {
22533       /* Similar to the wording used regarding tuples, the status element should appear
22534        * first. However, we will once again relax things and accept the status at any
22535        * position. We will enforce that only a single status element can be present.
22536        */
22537       if (strcmp(ast_xml_node_get_name(tuple_children_iterator), "status")) {
22538          /* Not the status, we don't care */
22539          continue;
22540       }
22541       if (status_found == TRUE) {
22542          /* THERE CAN BE ONLY ONE!!! */
22543          ast_log(LOG_WARNING, "Multiple status elements found in tuple. Only one allowed\n");
22544          return FALSE;
22545       }
22546       status_found = TRUE;
22547    }
22548    return status_found;
22549 }
22550 
22551 
22552 static int pidf_validate_presence(struct ast_xml_doc *doc)
22553 {
22554    struct ast_xml_node *presence_node = ast_xml_get_root(doc);
22555    struct ast_xml_node *child_nodes;
22556    struct ast_xml_node *node_iterator;
22557    struct ast_xml_ns *ns;
22558    const char *entity;
22559    const char *namespace;
22560    const char presence_namespace[] = "urn:ietf:params:xml:ns:pidf";
22561 
22562    if (!presence_node) {
22563       ast_log(LOG_WARNING, "Unable to retrieve root node of the XML document\n");
22564       return FALSE;
22565    }
22566    /* Okay, we managed to open the document! YAY! Now, let's start making sure it's all PIDF-ified
22567     * correctly.
22568     */
22569    if (strcmp(ast_xml_node_get_name(presence_node), "presence")) {
22570       ast_log(LOG_WARNING, "Root node of PIDF document is not 'presence'. Invalid\n");
22571       return FALSE;
22572    }
22573 
22574    /* The presence element must have an entity attribute and an xmlns attribute. Furthermore
22575     * the xmlns attribute must be "urn:ietf:params:xml:ns:pidf"
22576     */
22577    if (!(entity = ast_xml_get_attribute(presence_node, "entity"))) {
22578       ast_log(LOG_WARNING, "Presence element of PIDF document has no 'entity' attribute\n");
22579       return FALSE;
22580    }
22581    /* We're not interested in what the entity is, just that it exists */
22582    ast_xml_free_attr(entity);
22583 
22584    if (!(ns = ast_xml_find_namespace(doc, presence_node, NULL))) {
22585       ast_log(LOG_WARNING, "Couldn't find default namespace...\n");
22586       return FALSE;
22587    }
22588 
22589    namespace = ast_xml_get_ns_href(ns);
22590    if (ast_strlen_zero(namespace) || strcmp(namespace, presence_namespace)) {
22591       ast_log(LOG_WARNING, "PIDF document has invalid namespace value %s\n", namespace);
22592       return FALSE;
22593    }
22594 
22595    if (!(child_nodes = ast_xml_node_get_children(presence_node))) {
22596       ast_log(LOG_WARNING, "PIDF document has no elements as children of 'presence'. Invalid\n");
22597       return FALSE;
22598    }
22599 
22600    /* Check for tuple elements. RFC 3863 says that PIDF documents can have any number of
22601     * tuples, including 0. The big thing here is that if there are tuple elements present,
22602     * they have to have a single status element within.
22603     *
22604     * The RFC is worded such that tuples should appear as the first elements as children of
22605     * the presence element. However, we'll be accepting of documents which may place other elements
22606     * before the tuple(s).
22607     */
22608    for (node_iterator = child_nodes; node_iterator;
22609          node_iterator = ast_xml_node_get_next(node_iterator)) {
22610       if (strcmp(ast_xml_node_get_name(node_iterator), "tuple")) {
22611          /* Not a tuple. We don't give a rat's hind quarters */
22612          continue;
22613       }
22614       if (pidf_validate_tuple(node_iterator) == FALSE) {
22615          ast_log(LOG_WARNING, "Unable to validate tuple\n");
22616          return FALSE;
22617       }
22618    }
22619 
22620    return TRUE;
22621 }
22622 
22623 /*!
22624  * \brief Makes sure that body is properly formatted PIDF
22625  *
22626  * Specifically, we check that the document has a "presence" element
22627  * at the root and that within that, there is at least one "tuple" element
22628  * that contains a "status" element.
22629  *
22630  * XXX This function currently assumes a default namespace is used. Of course
22631  * if you're not using a default namespace, you're probably a stupid jerk anyway.
22632  *
22633  * \param req The SIP request to check
22634  * \param[out] pidf_doc The validated PIDF doc.
22635  * \retval FALSE The XML was malformed or the basic PIDF structure was marred
22636  * \retval TRUE The PIDF document is of a valid format
22637  */
22638 static int sip_pidf_validate(struct sip_request *req, struct ast_xml_doc **pidf_doc)
22639 {
22640    struct ast_xml_doc *doc;
22641    int content_length;
22642    const char *content_length_str = get_header(req, "Content-Length");
22643    const char *content_type = get_header(req, "Content-Type");
22644    char pidf_body[SIPBUFSIZE];
22645    int res;
22646 
22647    if (ast_strlen_zero(content_type) || strcmp(content_type, "application/pidf+xml")) {
22648       ast_log(LOG_WARNING, "Content type is not PIDF\n");
22649       return FALSE;
22650    }
22651 
22652    if (ast_strlen_zero(content_length_str)) {
22653       ast_log(LOG_WARNING, "No content length. Can't determine bounds of PIDF document\n");
22654       return FALSE;
22655    }
22656 
22657    if (sscanf(content_length_str, "%30d", &content_length) != 1) {
22658       ast_log(LOG_WARNING, "Invalid content length provided\n");
22659       return FALSE;
22660    }
22661 
22662    if (content_length > sizeof(pidf_body)) {
22663       ast_log(LOG_WARNING, "Content length of PIDF document truncated to %d bytes\n", (int) sizeof(pidf_body));
22664       content_length = sizeof(pidf_body);
22665    }
22666 
22667    get_pidf_body(req, pidf_body, content_length);
22668 
22669    if (!(doc = ast_xml_read_memory(pidf_body, content_length))) {
22670       ast_log(LOG_WARNING, "Unable to open XML PIDF document. Is it malformed?\n");
22671       return FALSE;
22672    }
22673 
22674    res = pidf_validate_presence(doc);
22675    if (res == TRUE) {
22676       *pidf_doc = doc;
22677    } else {
22678       ast_xml_close(doc);
22679    }
22680    return res;
22681 }
22682 
22683 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)
22684 {
22685    const char *uri = REQ_OFFSET_TO_STR(req, rlPart2);
22686    struct ast_cc_agent *agent = find_sip_cc_agent_by_notify_uri(uri);
22687    struct sip_cc_agent_pvt *agent_pvt;
22688    struct ast_xml_doc *pidf_doc = NULL;
22689    const char *basic_status = NULL;
22690    struct ast_xml_node *presence_node;
22691    struct ast_xml_node *presence_children;
22692    struct ast_xml_node *tuple_node;
22693    struct ast_xml_node *tuple_children;
22694    struct ast_xml_node *status_node;
22695    struct ast_xml_node *status_children;
22696    struct ast_xml_node *basic_node;
22697    int res = 0;
22698 
22699    if (!agent) {
22700       ast_log(LOG_WARNING, "Could not find agent using uri '%s'\n", uri);
22701       transmit_response(pvt, "412 Conditional Request Failed", req);
22702       return -1;
22703    }
22704 
22705    agent_pvt = agent->private_data;
22706 
22707    if (sip_pidf_validate(req, &pidf_doc) == FALSE) {
22708       res = -1;
22709       goto cc_publish_cleanup;
22710    }
22711 
22712    /* It's important to note that the PIDF validation routine has no knowledge
22713     * of what we specifically want in this instance. A valid PIDF document could
22714     * have no tuples, or it could have tuples whose status element has no basic
22715     * element contained within. While not violating the PIDF spec, these are
22716     * insufficient for our needs in this situation
22717     */
22718    presence_node = ast_xml_get_root(pidf_doc);
22719    if (!(presence_children = ast_xml_node_get_children(presence_node))) {
22720       ast_log(LOG_WARNING, "No tuples within presence element.\n");
22721       res = -1;
22722       goto cc_publish_cleanup;
22723    }
22724 
22725    if (!(tuple_node = ast_xml_find_element(presence_children, "tuple", NULL, NULL))) {
22726       ast_log(LOG_NOTICE, "Couldn't find tuple node?\n");
22727       res = -1;
22728       goto cc_publish_cleanup;
22729    }
22730 
22731    /* We already made sure that the tuple has a status node when we validated the PIDF
22732     * document earlier. So there's no need to enclose this operation in an if statement.
22733     */
22734    tuple_children = ast_xml_node_get_children(tuple_node);
22735    status_node = ast_xml_find_element(tuple_children, "status", NULL, NULL);
22736 
22737    if (!(status_children = ast_xml_node_get_children(status_node))) {
22738       ast_log(LOG_WARNING, "No basic elements within status element.\n");
22739       res = -1;
22740       goto cc_publish_cleanup;
22741    }
22742 
22743    if (!(basic_node = ast_xml_find_element(status_children, "basic", NULL, NULL))) {
22744       ast_log(LOG_WARNING, "Couldn't find basic node?\n");
22745       res = -1;
22746       goto cc_publish_cleanup;
22747    }
22748 
22749    basic_status = ast_xml_get_text(basic_node);
22750 
22751    if (ast_strlen_zero(basic_status)) {
22752       ast_log(LOG_NOTICE, "NOthing in basic node?\n");
22753       res = -1;
22754       goto cc_publish_cleanup;
22755    }
22756 
22757    if (!strcmp(basic_status, "open")) {
22758       agent_pvt->is_available = TRUE;
22759       ast_cc_agent_caller_available(agent->core_id, "Received PUBLISH stating SIP caller %s is available",
22760             agent->device_name);
22761    } else if (!strcmp(basic_status, "closed")) {
22762       agent_pvt->is_available = FALSE;
22763       ast_cc_agent_caller_busy(agent->core_id, "Received PUBLISH stating SIP caller %s is busy",
22764             agent->device_name);
22765    } else {
22766       ast_log(LOG_NOTICE, "Invalid content in basic element: %s\n", basic_status);
22767    }
22768 
22769 cc_publish_cleanup:
22770    if (basic_status) {
22771       ast_xml_free_text(basic_status);
22772    }
22773    if (pidf_doc) {
22774       ast_xml_close(pidf_doc);
22775    }
22776    ao2_ref(agent, -1);
22777    if (res) {
22778       transmit_response(pvt, "400 Bad Request", req);
22779    }
22780    return res;
22781 }
22782 
22783 #endif /* HAVE_LIBXML2 */
22784 
22785 static int handle_sip_publish_initial(struct sip_pvt *p, struct sip_request *req, struct event_state_compositor *esc, const int expires)
22786 {
22787    struct sip_esc_entry *esc_entry = create_esc_entry(esc, req, expires);
22788    int res = 0;
22789 
22790    if (!esc_entry) {
22791       transmit_response(p, "503 Internal Server Failure", req);
22792       return -1;
22793    }
22794 
22795    if (esc->callbacks->initial_handler) {
22796       res = esc->callbacks->initial_handler(p, req, esc, esc_entry);
22797    }
22798 
22799    if (!res) {
22800       transmit_response_with_sip_etag(p, "200 OK", req, esc_entry, 0);
22801    }
22802 
22803    ao2_ref(esc_entry, -1);
22804    return res;
22805 }
22806 
22807 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)
22808 {
22809    struct sip_esc_entry *esc_entry = get_esc_entry(etag, esc);
22810    int expires_ms = expires * 1000;
22811    int res = 0;
22812 
22813    if (!esc_entry) {
22814       transmit_response(p, "412 Conditional Request Failed", req);
22815       return -1;
22816    }
22817 
22818    AST_SCHED_REPLACE_UNREF(esc_entry->sched_id, sched, expires_ms, publish_expire, esc_entry,
22819          ao2_ref(_data, -1),
22820          ao2_ref(esc_entry, -1),
22821          ao2_ref(esc_entry, +1));
22822 
22823    if (esc->callbacks->refresh_handler) {
22824       res = esc->callbacks->refresh_handler(p, req, esc, esc_entry);
22825    }
22826 
22827    if (!res) {
22828       transmit_response_with_sip_etag(p, "200 OK", req, esc_entry, 1);
22829    }
22830 
22831    ao2_ref(esc_entry, -1);
22832    return res;
22833 }
22834 
22835 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)
22836 {
22837    struct sip_esc_entry *esc_entry = get_esc_entry(etag, esc);
22838    int expires_ms = expires * 1000;
22839    int res = 0;
22840 
22841    if (!esc_entry) {
22842       transmit_response(p, "412 Conditional Request Failed", req);
22843       return -1;
22844    }
22845 
22846    AST_SCHED_REPLACE_UNREF(esc_entry->sched_id, sched, expires_ms, publish_expire, esc_entry,
22847          ao2_ref(_data, -1),
22848          ao2_ref(esc_entry, -1),
22849          ao2_ref(esc_entry, +1));
22850 
22851    if (esc->callbacks->modify_handler) {
22852       res = esc->callbacks->modify_handler(p, req, esc, esc_entry);
22853    }
22854 
22855    if (!res) {
22856       transmit_response_with_sip_etag(p, "200 OK", req, esc_entry, 1);
22857    }
22858 
22859    ao2_ref(esc_entry, -1);
22860    return res;
22861 }
22862 
22863 static int handle_sip_publish_remove(struct sip_pvt *p, struct sip_request *req, struct event_state_compositor *esc, const char * const etag)
22864 {
22865    struct sip_esc_entry *esc_entry = get_esc_entry(etag, esc);
22866    int res = 0;
22867 
22868    if (!esc_entry) {
22869       transmit_response(p, "412 Conditional Request Failed", req);
22870       return -1;
22871    }
22872 
22873    AST_SCHED_DEL(sched, esc_entry->sched_id);
22874    /* Scheduler's ref of the esc_entry */
22875    ao2_ref(esc_entry, -1);
22876 
22877    if (esc->callbacks->remove_handler) {
22878       res = esc->callbacks->remove_handler(p, req, esc, esc_entry);
22879    }
22880 
22881    if (!res) {
22882       transmit_response_with_sip_etag(p, "200 OK", req, esc_entry, 1);
22883    }
22884 
22885    /* Ref from finding the esc_entry earlier in function */
22886    ao2_unlink(esc->compositor, esc_entry);
22887    ao2_ref(esc_entry, -1);
22888    return res;
22889 }
22890 
22891 static int handle_request_publish(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, const int seqno, const char *uri)
22892 {
22893    const char *etag = get_header(req, "SIP-If-Match");
22894    const char *event = get_header(req, "Event");
22895    struct event_state_compositor *esc;
22896    enum sip_publish_type publish_type;
22897    const char *expires_str = get_header(req, "Expires");
22898    int expires_int;
22899    int auth_result;
22900    int handler_result = -1;
22901 
22902    if (ast_strlen_zero(event)) {
22903       transmit_response(p, "489 Bad Event", req);
22904       return -1;
22905    }
22906 
22907    if (!(esc = get_esc(event))) {
22908       transmit_response(p, "489 Bad Event", req);
22909       return -1;
22910    }
22911 
22912    auth_result = check_user(p, req, SIP_PUBLISH, uri, XMIT_RELIABLE, addr);
22913    if (auth_result == AUTH_CHALLENGE_SENT) {
22914       p->lastinvite = seqno;
22915       return 0;
22916    } else if (auth_result < 0) {
22917       if (auth_result == AUTH_FAKE_AUTH) {
22918          ast_log(LOG_NOTICE, "Sending fake auth rejection for device %s\n", get_header(req, "From"));
22919          transmit_fake_auth_response(p, SIP_INVITE, req, XMIT_RELIABLE);
22920       } else {
22921          ast_log(LOG_NOTICE, "Failed to authenticate device %s\n", get_header(req, "From"));
22922          transmit_response_reliable(p, "403 Forbidden", req);
22923       }
22924       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
22925       ast_string_field_set(p, theirtag, NULL);
22926       return 0;
22927    } else if (auth_result == AUTH_SUCCESSFUL && p->lastinvite) {
22928       /* We need to stop retransmitting the 401 */
22929       __sip_ack(p, p->lastinvite, 1, 0);
22930    }
22931 
22932    publish_type = determine_sip_publish_type(req, event, etag, expires_str, &expires_int);
22933 
22934    /* It is the responsibility of these handlers to formulate any response
22935     * sent for a PUBLISH
22936     */
22937    switch (publish_type) {
22938    case SIP_PUBLISH_UNKNOWN:
22939       transmit_response(p, "400 Bad Request", req);
22940       break;
22941    case SIP_PUBLISH_INITIAL:
22942       handler_result = handle_sip_publish_initial(p, req, esc, expires_int);
22943       break;
22944    case SIP_PUBLISH_REFRESH:
22945       handler_result = handle_sip_publish_refresh(p, req, esc, etag, expires_int);
22946       break;
22947    case SIP_PUBLISH_MODIFY:
22948       handler_result = handle_sip_publish_modify(p, req, esc, etag, expires_int);
22949       break;
22950    case SIP_PUBLISH_REMOVE:
22951       handler_result = handle_sip_publish_remove(p, req, esc, etag);
22952       break;
22953    default:
22954       transmit_response(p, "400 Impossible Condition", req);
22955       break;
22956    }
22957 
22958    return handler_result;
22959 }
22960 
22961 static void add_peer_mwi_subs(struct sip_peer *peer)
22962 {
22963    struct sip_mailbox *mailbox;
22964 
22965    AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
22966       mailbox->event_sub = ast_event_subscribe(AST_EVENT_MWI, mwi_event_cb, "SIP mbox event", peer,
22967          AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, mailbox->mailbox,
22968          AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, S_OR(mailbox->context, "default"),
22969          AST_EVENT_IE_END);
22970    }
22971 }
22972 
22973 static int handle_cc_subscribe(struct sip_pvt *p, struct sip_request *req)
22974 {
22975    const char *uri = REQ_OFFSET_TO_STR(req, rlPart2);
22976    char *param_separator;
22977    struct ast_cc_agent *agent;
22978    struct sip_cc_agent_pvt *agent_pvt;
22979    const char *expires_str = get_header(req, "Expires");
22980    int expires = -1; /* Just need it to be non-zero */
22981 
22982    if (!ast_strlen_zero(expires_str)) {
22983       sscanf(expires_str, "%d", &expires);
22984    }
22985 
22986    if ((param_separator = strchr(uri, ';'))) {
22987       *param_separator = '\0';
22988    }
22989 
22990    if (!(agent = find_sip_cc_agent_by_subscribe_uri(uri))) {
22991       if (!expires) {
22992          /* Typically, if a 0 Expires reaches us and we can't find
22993           * the corresponding agent, it means that the CC transaction
22994           * has completed and so the calling side is just trying to
22995           * clean up its subscription. We'll just respond with a
22996           * 200 OK and be done with it
22997           */
22998          transmit_response(p, "200 OK", req);
22999          return 0;
23000       }
23001       ast_log(LOG_WARNING, "Invalid URI '%s' in CC subscribe\n", uri);
23002       transmit_response(p, "404 Not Found", req);
23003       return -1;
23004    }
23005 
23006    agent_pvt = agent->private_data;
23007 
23008    if (!expires) {
23009       /* We got sent a SUBSCRIBE and found an agent. This means that CC
23010        * is being canceled.
23011        */
23012       ast_cc_failed(agent->core_id, "CC is being canceled by %s", agent->device_name);
23013       transmit_response(p, "200 OK", req);
23014       ao2_ref(agent, -1);
23015       return 0;
23016    }
23017 
23018    agent_pvt->subscribe_pvt = dialog_ref(p, "SIP CC agent gains reference to subscription dialog");
23019    ast_cc_agent_accept_request(agent->core_id, "SIP caller %s has requested CC via SUBSCRIBE",
23020          agent->device_name);
23021    p->subscribed = CALL_COMPLETION;
23022 
23023    /* We don't send a response here. That is done in the agent's ack callback or in the
23024     * agent destructor, should a failure occur before we have responded
23025     */
23026    ao2_ref(agent, -1);
23027    return 0;
23028 }
23029 
23030 /*! \brief  Handle incoming SUBSCRIBE request */
23031 static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, int seqno, const char *e)
23032 {
23033    int gotdest = 0;
23034    int res = 0;
23035    int firststate = AST_EXTENSION_REMOVED;
23036    struct sip_peer *authpeer = NULL;
23037    const char *eventheader = get_header(req, "Event");   /* Get Event package name */
23038    int resubscribe = (p->subscribed != NONE);
23039    char *temp, *event;
23040 
23041    if (p->initreq.headers) {  
23042       /* We already have a dialog */
23043       if (p->initreq.method != SIP_SUBSCRIBE) {
23044          /* This is a SUBSCRIBE within another SIP dialog, which we do not support */
23045          /* For transfers, this could happen, but since we haven't seen it happening, let us just refuse this */
23046          transmit_response(p, "403 Forbidden (within dialog)", req);
23047          /* Do not destroy session, since we will break the call if we do */
23048          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);
23049          return 0;
23050       } else if (req->debug) {
23051          if (resubscribe)
23052             ast_debug(1, "Got a re-subscribe on existing subscription %s\n", p->callid);
23053          else
23054             ast_debug(1, "Got a new subscription %s (possibly with auth)\n", p->callid);
23055       }
23056    }
23057 
23058    /* Check if we have a global disallow setting on subscriptions.
23059       if so, we don't have to check peer settings after auth, which saves a lot of processing
23060    */
23061    if (!sip_cfg.allowsubscribe) {
23062       transmit_response(p, "403 Forbidden (policy)", req);
23063       pvt_set_needdestroy(p, "forbidden");
23064       return 0;
23065    }
23066 
23067    if (!req->ignore && !resubscribe) { /* Set up dialog, new subscription */
23068       const char *to = get_header(req, "To");
23069       char totag[128];
23070       set_pvt_allowed_methods(p, req);
23071 
23072       /* Check to see if a tag was provided, if so this is actually a resubscription of a dialog we no longer know about */
23073       if (!ast_strlen_zero(to) && gettag(req, "To", totag, sizeof(totag))) {
23074          if (req->debug)
23075             ast_verbose("Received resubscription for a dialog we no longer know about. Telling remote side to subscribe again.\n");
23076          transmit_response(p, "481 Subscription does not exist", req);
23077          pvt_set_needdestroy(p, "subscription does not exist");
23078          return 0;
23079       }
23080 
23081       /* Use this as the basis */
23082       if (req->debug)
23083          ast_verbose("Creating new subscription\n");
23084 
23085       copy_request(&p->initreq, req);
23086       if (sipdebug)
23087          ast_debug(4, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
23088       check_via(p, req);
23089       build_route(p, req, 0);
23090    } else if (req->debug && req->ignore)
23091       ast_verbose("Ignoring this SUBSCRIBE request\n");
23092 
23093    /* Find parameters to Event: header value and remove them for now */
23094    if (ast_strlen_zero(eventheader)) {
23095       transmit_response(p, "489 Bad Event", req);
23096       ast_debug(2, "Received SIP subscribe for unknown event package: <none>\n");
23097       pvt_set_needdestroy(p, "unknown event package in subscribe");
23098       return 0;
23099    }
23100 
23101    if ( (strchr(eventheader, ';'))) {
23102       event = ast_strdupa(eventheader);   /* Since eventheader is a const, we can't change it */
23103       temp = strchr(event, ';');       
23104       *temp = '\0';           /* Remove any options for now */
23105                      /* We might need to use them later :-) */
23106    } else
23107       event = (char *) eventheader;    /* XXX is this legal ? */
23108 
23109    /* Handle authentication */
23110    res = check_user_full(p, req, SIP_SUBSCRIBE, e, 0, addr, &authpeer);
23111    /* if an authentication response was sent, we are done here */
23112    if (res == AUTH_CHALLENGE_SENT)  /* authpeer = NULL here */
23113       return 0;
23114    if (res < 0) {
23115       if (res == AUTH_FAKE_AUTH) {
23116          ast_log(LOG_NOTICE, "Sending fake auth rejection for device %s\n", get_header(req, "From"));
23117          transmit_fake_auth_response(p, SIP_SUBSCRIBE, req, XMIT_UNRELIABLE);
23118       } else {
23119          ast_log(LOG_NOTICE, "Failed to authenticate device %s for SUBSCRIBE\n", get_header(req, "From"));
23120          transmit_response_reliable(p, "403 Forbidden", req);
23121       }
23122       pvt_set_needdestroy(p, "authentication failed");
23123       return 0;
23124    }
23125 
23126    /* At this point, authpeer cannot be NULL. Remember we hold a reference,
23127     * so we must release it when done.
23128     * XXX must remove all the checks for authpeer == NULL.
23129     */
23130 
23131    /* Check if this device  is allowed to subscribe at all */
23132    if (!ast_test_flag(&p->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)) {
23133       transmit_response(p, "403 Forbidden (policy)", req);
23134       pvt_set_needdestroy(p, "subscription not allowed");
23135       if (authpeer)
23136          unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 1)");
23137       return 0;
23138    }
23139 
23140    if (strcmp(event, "message-summary") && strcmp(event, "call-completion")) {
23141       /* Get destination right away */
23142       gotdest = get_destination(p, NULL, NULL);
23143    }
23144 
23145    /* Get full contact header - this needs to be used as a request URI in NOTIFY's */
23146    parse_ok_contact(p, req);
23147 
23148    build_contact(p);
23149    if (gotdest != SIP_GET_DEST_EXTEN_FOUND) {
23150       if (gotdest == SIP_GET_DEST_INVALID_URI) {
23151          transmit_response(p, "416 Unsupported URI scheme", req);
23152       } else {
23153          transmit_response(p, "404 Not Found", req);
23154       }
23155       pvt_set_needdestroy(p, "subscription target not found");
23156       if (authpeer)
23157          unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 2)");
23158       return 0;
23159    }
23160 
23161    /* Initialize tag for new subscriptions */   
23162    if (ast_strlen_zero(p->tag))
23163       make_our_tag(p->tag, sizeof(p->tag));
23164 
23165    if (!strcmp(event, "presence") || !strcmp(event, "dialog")) { /* Presence, RFC 3842 */
23166       unsigned int pidf_xml;
23167       const char *accept;
23168       int start = 0;
23169       enum subscriptiontype subscribed = NONE;
23170       const char *unknown_acceptheader = NULL;
23171 
23172       if (authpeer)  /* We do not need the authpeer any more */
23173          unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 2)");
23174 
23175       /* Header from Xten Eye-beam Accept: multipart/related, application/rlmi+xml, application/pidf+xml, application/xpidf+xml */
23176       accept = __get_header(req, "Accept", &start);
23177       while ((subscribed == NONE) && !ast_strlen_zero(accept)) {
23178          pidf_xml = strstr(accept, "application/pidf+xml") ? 1 : 0;
23179 
23180          /* Older versions of Polycom firmware will claim pidf+xml, but really
23181           * they only support xpidf+xml. */
23182          if (pidf_xml && strstr(p->useragent, "Polycom")) {
23183             subscribed = XPIDF_XML;
23184          } else if (pidf_xml) {
23185             subscribed = PIDF_XML;         /* RFC 3863 format */
23186          } else if (strstr(accept, "application/dialog-info+xml")) {
23187             subscribed = DIALOG_INFO_XML;
23188             /* IETF draft: draft-ietf-sipping-dialog-package-05.txt */
23189          } else if (strstr(accept, "application/cpim-pidf+xml")) {
23190             subscribed = CPIM_PIDF_XML;    /* RFC 3863 format */
23191          } else if (strstr(accept, "application/xpidf+xml")) {
23192             subscribed = XPIDF_XML;        /* Early pre-RFC 3863 format with MSN additions (Microsoft Messenger) */
23193          } else {
23194             unknown_acceptheader = accept;
23195          }
23196          /* check to see if there is another Accept header present */
23197          accept = __get_header(req, "Accept", &start);
23198       }
23199 
23200       if (!start) {
23201          if (p->subscribed == NONE) { /* if the subscribed field is not already set, and there is no accept header... */
23202             transmit_response(p, "489 Bad Event", req);
23203             ast_log(LOG_WARNING,"SUBSCRIBE failure: no Accept header: pvt: "
23204                "stateid: %d, laststate: %d, dialogver: %d, subscribecont: "
23205                "'%s', subscribeuri: '%s'\n",
23206                p->stateid,
23207                p->laststate,
23208                p->dialogver,
23209                p->subscribecontext,
23210                p->subscribeuri);
23211             pvt_set_needdestroy(p, "no Accept header");
23212             return 0;
23213          }
23214          /* if p->subscribed is non-zero, then accept is not obligatory; according to rfc 3265 section 3.1.3, at least.
23215             so, we'll just let it ride, keeping the value from a previous subscription, and not abort the subscription */
23216       } else if (subscribed == NONE) {
23217          /* Can't find a format for events that we know about */
23218          char mybuf[200];
23219          if (!ast_strlen_zero(unknown_acceptheader)) {
23220             snprintf(mybuf, sizeof(mybuf), "489 Bad Event (format %s)", unknown_acceptheader);
23221          } else {
23222             snprintf(mybuf, sizeof(mybuf), "489 Bad Event");
23223          }
23224          transmit_response(p, mybuf, req);
23225          ast_log(LOG_WARNING,"SUBSCRIBE failure: unrecognized format:"
23226             "'%s' pvt: subscribed: %d, stateid: %d, laststate: %d,"
23227             "dialogver: %d, subscribecont: '%s', subscribeuri: '%s'\n",
23228             unknown_acceptheader,
23229             (int)p->subscribed,
23230             p->stateid,
23231             p->laststate,
23232             p->dialogver,
23233             p->subscribecontext,
23234             p->subscribeuri);
23235          pvt_set_needdestroy(p, "unrecognized format");
23236          return 0;
23237       } else {
23238          p->subscribed = subscribed;
23239       }
23240    } else if (!strcmp(event, "message-summary")) {
23241       int start = 0;
23242       int found_supported = 0;
23243       const char *acceptheader;
23244 
23245       acceptheader = __get_header(req, "Accept", &start);
23246       while (!found_supported && !ast_strlen_zero(acceptheader)) {
23247          found_supported = strcmp(acceptheader, "application/simple-message-summary") ? 0 : 1;
23248          if (!found_supported && (option_debug > 2)) {
23249             ast_log(LOG_DEBUG, "Received SIP mailbox subscription for unknown format: %s\n", acceptheader);
23250          }
23251          acceptheader = __get_header(req, "Accept", &start);
23252       }
23253       if (start && !found_supported) {
23254          /* Format requested that we do not support */
23255          transmit_response(p, "406 Not Acceptable", req);
23256          ast_debug(2, "Received SIP mailbox subscription for unknown format: %s\n", acceptheader);
23257          pvt_set_needdestroy(p, "unknown format");
23258          if (authpeer)
23259             unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 3)");
23260          return 0;
23261       }
23262       /* Looks like they actually want a mailbox status
23263         This version of Asterisk supports mailbox subscriptions
23264         The subscribed URI needs to exist in the dial plan
23265         In most devices, this is configurable to the voicemailmain extension you use
23266       */
23267       if (!authpeer || AST_LIST_EMPTY(&authpeer->mailboxes)) {
23268          transmit_response(p, "404 Not found (no mailbox)", req);
23269          pvt_set_needdestroy(p, "received 404 response");
23270          ast_log(LOG_NOTICE, "Received SIP subscribe for peer without mailbox: %s\n", authpeer->name);
23271          if (authpeer)
23272             unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 4)");
23273          return 0;
23274       }
23275 
23276       p->subscribed = MWI_NOTIFICATION;
23277       if (ast_test_flag(&authpeer->flags[1], SIP_PAGE2_SUBSCRIBEMWIONLY)) {
23278          add_peer_mwi_subs(authpeer);
23279       }
23280       if (authpeer->mwipvt && authpeer->mwipvt != p) {   /* Destroy old PVT if this is a new one */
23281          /* We only allow one subscription per peer */
23282          dialog_unlink_all(authpeer->mwipvt, TRUE, TRUE);
23283          authpeer->mwipvt = dialog_unref(authpeer->mwipvt, "unref dialog authpeer->mwipvt");
23284          /* sip_destroy(authpeer->mwipvt); */
23285       }
23286       if (authpeer->mwipvt)
23287          dialog_unref(authpeer->mwipvt, "Unref previously stored mwipvt dialog pointer");
23288       authpeer->mwipvt = dialog_ref(p, "setting peers' mwipvt to p");      /* Link from peer to pvt UH- should this be dialog_ref()? */
23289       if (p->relatedpeer)
23290          unref_peer(p->relatedpeer, "Unref previously stored relatedpeer ptr");
23291       p->relatedpeer = ref_peer(authpeer, "setting dialog's relatedpeer pointer");  /* already refcounted...Link from pvt to peer UH- should this be dialog_ref()? */
23292       /* Do not release authpeer here */
23293    } else if (!strcmp(event, "call-completion")) {
23294       handle_cc_subscribe(p, req);
23295    } else { /* At this point, Asterisk does not understand the specified event */
23296       transmit_response(p, "489 Bad Event", req);
23297       ast_debug(2, "Received SIP subscribe for unknown event package: %s\n", event);
23298       pvt_set_needdestroy(p, "unknown event package");
23299       if (authpeer)
23300          unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 5)");
23301       return 0;
23302    }
23303 
23304    /* Add subscription for extension state from the PBX core */
23305    if (p->subscribed != MWI_NOTIFICATION  && p->subscribed != CALL_COMPLETION && !resubscribe) {
23306       if (p->stateid > -1) {
23307          ast_extension_state_del(p->stateid, cb_extensionstate);
23308          /* we need to dec the refcount, now that the extensionstate is removed */
23309          dialog_unref(p, "the extensionstate containing this dialog ptr was deleted");
23310       }
23311       p->stateid = ast_extension_state_add(p->context, p->exten, cb_extensionstate, dialog_ref(p,"copying dialog ptr into extension state struct"));
23312    }
23313 
23314    if (!req->ignore && p)
23315       p->lastinvite = seqno;
23316    if (p && !p->needdestroy) {
23317       p->expiry = atoi(get_header(req, "Expires"));
23318 
23319       /* check if the requested expiry-time is within the approved limits from sip.conf */
23320       if (p->expiry > max_expiry) {
23321          p->expiry = max_expiry;
23322       } else if (p->expiry < min_expiry && p->expiry > 0) {
23323          transmit_response_with_minexpires(p, "423 Interval too small", req);
23324          ast_log(LOG_WARNING, "Received subscription for extension \"%s\" context \"%s\" "
23325             "with Expire header less that 'minexpire' limit. Received \"Expire: %d\" min is %d\n",
23326             p->exten, p->context, p->expiry, min_expiry);
23327          p->expiry = min_expiry;
23328          pvt_set_needdestroy(p, "Expires is less that the min expires allowed. ");
23329          return 0;
23330       }
23331 
23332       if (sipdebug) {
23333          if (p->subscribed == MWI_NOTIFICATION && p->relatedpeer) {
23334             ast_debug(2, "Adding subscription for mailbox notification - peer %s\n", p->relatedpeer->name);
23335          } else if (p->subscribed == CALL_COMPLETION) {
23336             ast_debug(2, "Adding CC subscription for peer %s\n", p->username);
23337          } else {
23338             ast_debug(2, "Adding subscription for extension %s context %s for peer %s\n", p->exten, p->context, p->username);
23339          }
23340       }
23341       if (p->autokillid > -1 && sip_cancel_destroy(p))   /* Remove subscription expiry for renewals */
23342          ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
23343       if (p->expiry > 0)
23344          sip_scheddestroy(p, (p->expiry + 10) * 1000);   /* Set timer for destruction of call at expiration */
23345 
23346       if (p->subscribed == MWI_NOTIFICATION) {
23347          ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
23348          transmit_response(p, "200 OK", req);
23349          if (p->relatedpeer) {   /* Send first notification */
23350             ao2_lock(p->relatedpeer); /* was WRLOCK */
23351             sip_send_mwi_to_peer(p->relatedpeer, NULL, 0);
23352             ao2_unlock(p->relatedpeer);
23353          }
23354       } else if (p->subscribed != CALL_COMPLETION) {
23355          if ((firststate = ast_extension_state(NULL, p->context, p->exten)) < 0) {
23356 
23357             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));
23358             transmit_response(p, "404 Not found", req);
23359             pvt_set_needdestroy(p, "no extension for SUBSCRIBE");
23360             return 0;
23361          }
23362          ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
23363          transmit_response(p, "200 OK", req);
23364          transmit_state_notify(p, firststate, 1, FALSE); /* Send first notification */
23365          append_history(p, "Subscribestatus", "%s", ast_extension_state2str(firststate));
23366          /* hide the 'complete' exten/context in the refer_to field for later display */
23367          ast_string_field_build(p, subscribeuri, "%s@%s", p->exten, p->context);
23368          /* Deleted the slow iteration of all sip dialogs to find old subscribes from this peer for exten@context */
23369 
23370       }
23371       if (!p->expiry) {
23372          pvt_set_needdestroy(p, "forcing expiration");
23373       }
23374    }
23375    return 1;
23376 }
23377 
23378 /*! \brief Handle incoming REGISTER request */
23379 static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, const char *e)
23380 {
23381    enum check_auth_result res;
23382 
23383    /* Use this as the basis */
23384    copy_request(&p->initreq, req);
23385    if (sipdebug)
23386       ast_debug(4, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
23387    check_via(p, req);
23388    if ((res = register_verify(p, addr, req, e)) < 0) {
23389       const char *reason;
23390 
23391       switch (res) {
23392       case AUTH_SECRET_FAILED:
23393          reason = "Wrong password";
23394          break;
23395       case AUTH_USERNAME_MISMATCH:
23396          reason = "Username/auth name mismatch";
23397          break;
23398       case AUTH_NOT_FOUND:
23399          reason = "No matching peer found";
23400          break;
23401       case AUTH_UNKNOWN_DOMAIN:
23402          reason = "Not a local domain";
23403          break;
23404       case AUTH_PEER_NOT_DYNAMIC:
23405          reason = "Peer is not supposed to register";
23406          break;
23407       case AUTH_ACL_FAILED:
23408          reason = "Device does not match ACL";
23409          break;
23410       case AUTH_BAD_TRANSPORT:
23411          reason = "Device not configured to use this transport type";
23412          break;
23413       default:
23414          reason = "Unknown failure";
23415          break;
23416       }
23417       ast_log(LOG_NOTICE, "Registration from '%s' failed for '%s' - %s\n",
23418          get_header(req, "To"), ast_sockaddr_stringify(addr),
23419          reason);
23420       append_history(p, "RegRequest", "Failed : Account %s : %s", get_header(req, "To"), reason);
23421    } else
23422       append_history(p, "RegRequest", "Succeeded : Account %s", get_header(req, "To"));
23423 
23424    if (res < 1) {
23425       /* Destroy the session, but keep us around for just a bit in case they don't
23426          get our 200 OK */
23427       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
23428    }
23429    return res;
23430 }
23431 
23432 /*!
23433  * \brief Handle incoming SIP requests (methods)
23434  * \note
23435  * This is where all incoming requests go first.
23436  * \note
23437  * called with p and p->owner locked
23438  */
23439 static int handle_incoming(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, int *recount, int *nounlock)
23440 {
23441    /* Called with p->lock held, as well as p->owner->lock if appropriate, keeping things
23442       relatively static */
23443    const char *cmd;
23444    const char *cseq;
23445    const char *useragent;
23446    int seqno;
23447    int len;
23448    int respid;
23449    int res = 0;
23450    int debug = sip_debug_test_pvt(p);
23451    const char *e;
23452    int error = 0;
23453    int oldmethod = p->method;
23454    int acked = 0;
23455 
23456    /* Get Method and Cseq */
23457    cseq = get_header(req, "Cseq");
23458    cmd = REQ_OFFSET_TO_STR(req, header[0]);
23459 
23460    /* Must have Cseq */
23461    if (ast_strlen_zero(cmd) || ast_strlen_zero(cseq)) {
23462       ast_log(LOG_ERROR, "Missing Cseq. Dropping this SIP message, it's incomplete.\n");
23463       error = 1;
23464    }
23465    if (!error && sscanf(cseq, "%30d%n", &seqno, &len) != 1) {
23466       ast_log(LOG_ERROR, "No seqno in '%s'. Dropping incomplete message.\n", cmd);
23467       error = 1;
23468    }
23469    if (error) {
23470       if (!p->initreq.headers) { /* New call */
23471          pvt_set_needdestroy(p, "no headers");
23472       }
23473       return -1;
23474    }
23475    /* Get the command XXX */
23476 
23477    cmd = REQ_OFFSET_TO_STR(req, rlPart1);
23478    e = ast_skip_blanks(REQ_OFFSET_TO_STR(req, rlPart2));
23479 
23480    /* Save useragent of the client */
23481    useragent = get_header(req, "User-Agent");
23482    if (!ast_strlen_zero(useragent))
23483       ast_string_field_set(p, useragent, useragent);
23484 
23485    /* Find out SIP method for incoming request */
23486    if (req->method == SIP_RESPONSE) {  /* Response to our request */
23487       /* ignore means "don't do anything with it" but still have to
23488        * respond appropriately.
23489        * But in this case this is a response already, so we really
23490        * have nothing to do with this message, and even setting the
23491        * ignore flag is pointless.
23492        */
23493       if (ast_strlen_zero(e)) {
23494          return 0;
23495       }
23496       if (sscanf(e, "%30d %n", &respid, &len) != 1) {
23497          ast_log(LOG_WARNING, "Invalid response: '%s'\n", e);
23498          return 0;
23499       }
23500       if (respid <= 0) {
23501          ast_log(LOG_WARNING, "Invalid SIP response code: '%d'\n", respid);
23502          return 0;
23503       }
23504       if (p->ocseq && (p->ocseq < seqno)) {
23505          ast_debug(1, "Ignoring out of order response %d (expecting %d)\n", seqno, p->ocseq);
23506          return -1;
23507       } else {
23508          char causevar[256], causeval[256];
23509 
23510          if ((respid == 200) || ((respid >= 300) && (respid <= 399))) {
23511             extract_uri(p, req);
23512          }
23513 
23514          handle_response(p, respid, e + len, req, seqno);
23515 
23516          if (p->owner) {
23517             struct ast_channel *owner = p->owner;
23518 
23519             snprintf(causevar, sizeof(causevar), "MASTER_CHANNEL(HASH(SIP_CAUSE,%s))", owner->name);
23520             snprintf(causeval, sizeof(causeval), "SIP %s", REQ_OFFSET_TO_STR(req, rlPart2));
23521 
23522             ast_channel_ref(owner);
23523             sip_pvt_unlock(p);
23524             ast_channel_unlock(owner);
23525             *nounlock = 1;
23526             pbx_builtin_setvar_helper(owner, causevar, causeval);
23527             ast_channel_unref(owner);
23528             sip_pvt_lock(p);
23529          }
23530       }
23531       return 0;
23532    }
23533 
23534    /* New SIP request coming in
23535       (could be new request in existing SIP dialog as well...)
23536     */         
23537    
23538    p->method = req->method;   /* Find out which SIP method they are using */
23539    ast_debug(4, "**** Received %s (%d) - Command in SIP %s\n", sip_methods[p->method].text, sip_methods[p->method].id, cmd);
23540 
23541    if (p->icseq && (p->icseq > seqno) ) {
23542       if (p->pendinginvite && seqno == p->pendinginvite && (req->method == SIP_ACK || req->method == SIP_CANCEL)) {
23543          ast_debug(2, "Got CANCEL or ACK on INVITE with transactions in between.\n");
23544       } else {
23545          ast_debug(1, "Ignoring too old SIP packet packet %d (expecting >= %d)\n", seqno, p->icseq);
23546          if (req->method == SIP_INVITE) {
23547             unsigned int ran = (ast_random() % 10) + 1;
23548             char seconds[4];
23549             snprintf(seconds, sizeof(seconds), "%u", ran);
23550             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 */
23551          } else if (req->method != SIP_ACK) {
23552             transmit_response(p, "500 Server error", req);  /* We must respond according to RFC 3261 sec 12.2 */
23553          }
23554          return -1;
23555       }
23556    } else if (p->icseq &&
23557          p->icseq == seqno &&
23558          req->method != SIP_ACK &&
23559          (p->method != SIP_CANCEL || p->alreadygone)) {
23560       /* ignore means "don't do anything with it" but still have to
23561          respond appropriately.  We do this if we receive a repeat of
23562          the last sequence number  */
23563       req->ignore = 1;
23564       ast_debug(3, "Ignoring SIP message because of retransmit (%s Seqno %d, ours %d)\n", sip_methods[p->method].text, p->icseq, seqno);
23565    }
23566 
23567    /* RFC 3261 section 9. "CANCEL has no effect on a request to which a UAS has
23568     * already given a final response." */
23569    if (!p->pendinginvite && (req->method == SIP_CANCEL)) {
23570       transmit_response(p, "481 Call/Transaction Does Not Exist", req);
23571       return res;
23572    }
23573 
23574    if (seqno >= p->icseq)
23575       /* Next should follow monotonically (but not necessarily
23576          incrementally -- thanks again to the genius authors of SIP --
23577          increasing */
23578       p->icseq = seqno;
23579 
23580    /* Find their tag if we haven't got it */
23581    if (ast_strlen_zero(p->theirtag)) {
23582       char tag[128];
23583 
23584       gettag(req, "From", tag, sizeof(tag));
23585       ast_string_field_set(p, theirtag, tag);
23586    }
23587    snprintf(p->lastmsg, sizeof(p->lastmsg), "Rx: %s", cmd);
23588 
23589    if (sip_cfg.pedanticsipchecking) {
23590       /* If this is a request packet without a from tag, it's not
23591          correct according to RFC 3261  */
23592       /* Check if this a new request in a new dialog with a totag already attached to it,
23593          RFC 3261 - section 12.2 - and we don't want to mess with recovery  */
23594       if (!p->initreq.headers && req->has_to_tag) {
23595          /* If this is a first request and it got a to-tag, it is not for us */
23596          if (!req->ignore && req->method == SIP_INVITE) {
23597             transmit_response_reliable(p, "481 Call/Transaction Does Not Exist", req);
23598             /* Will cease to exist after ACK */
23599          } else if (req->method != SIP_ACK) {
23600             transmit_response(p, "481 Call/Transaction Does Not Exist", req);
23601             sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
23602          } else {
23603             ast_debug(1, "Got ACK for unknown dialog... strange.\n");
23604          }
23605          return res;
23606       }
23607    }
23608 
23609    if (!e && (p->method == SIP_INVITE || p->method == SIP_SUBSCRIBE || p->method == SIP_REGISTER || p->method == SIP_NOTIFY || p->method == SIP_PUBLISH)) {
23610       transmit_response(p, "400 Bad request", req);
23611       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
23612       return -1;
23613    }
23614 
23615    /* Handle various incoming SIP methods in requests */
23616    switch (p->method) {
23617    case SIP_OPTIONS:
23618       res = handle_request_options(p, req, addr, e);
23619       break;
23620    case SIP_INVITE:
23621       res = handle_request_invite(p, req, debug, seqno, addr, recount, e, nounlock);
23622       break;
23623    case SIP_REFER:
23624       res = handle_request_refer(p, req, debug, seqno, nounlock);
23625       break;
23626    case SIP_CANCEL:
23627       res = handle_request_cancel(p, req);
23628       break;
23629    case SIP_BYE:
23630       res = handle_request_bye(p, req);
23631       break;
23632    case SIP_MESSAGE:
23633       res = handle_request_message(p, req);
23634       break;
23635    case SIP_PUBLISH:
23636       res = handle_request_publish(p, req, addr, seqno, e);
23637       break;
23638    case SIP_SUBSCRIBE:
23639       res = handle_request_subscribe(p, req, addr, seqno, e);
23640       break;
23641    case SIP_REGISTER:
23642       res = handle_request_register(p, req, addr, e);
23643       break;
23644    case SIP_INFO:
23645       if (req->debug)
23646          ast_verbose("Receiving INFO!\n");
23647       if (!req->ignore)
23648          handle_request_info(p, req);
23649       else  /* if ignoring, transmit response */
23650          transmit_response(p, "200 OK", req);
23651       break;
23652    case SIP_NOTIFY:
23653       res = handle_request_notify(p, req, addr, seqno, e);
23654       break;
23655    case SIP_UPDATE:
23656       res = handle_request_update(p, req);
23657       break;
23658    case SIP_ACK:
23659       /* Make sure we don't ignore this */
23660       if (seqno == p->pendinginvite) {
23661          p->invitestate = INV_TERMINATED;
23662          p->pendinginvite = 0;
23663          acked = __sip_ack(p, seqno, 1 /* response */, 0);
23664          if (find_sdp(req)) {
23665             if (process_sdp(p, req, SDP_T38_NONE))
23666                return -1;
23667          }
23668          check_pendings(p);
23669       } else if (p->glareinvite == seqno) {
23670          /* handle ack for the 491 pending sent for glareinvite */
23671          p->glareinvite = 0;
23672          acked = __sip_ack(p, seqno, 1, 0);
23673       }
23674       if (!acked) {
23675          /* Got an ACK that did not match anything. Ignore
23676           * silently and restore previous method */
23677          p->method = oldmethod;
23678       }
23679       if (!p->lastinvite && ast_strlen_zero(p->randdata)) {
23680          pvt_set_needdestroy(p, "unmatched ACK");
23681       }
23682       break;
23683    default:
23684       transmit_response_with_allow(p, "501 Method Not Implemented", req, 0);
23685       ast_log(LOG_NOTICE, "Unknown SIP command '%s' from '%s'\n",
23686          cmd, ast_sockaddr_stringify(&p->sa));
23687       /* If this is some new method, and we don't have a call, destroy it now */
23688       if (!p->initreq.headers) {
23689          pvt_set_needdestroy(p, "unimplemented method");
23690       }
23691       break;
23692    }
23693    return res;
23694 }
23695 
23696 static void process_request_queue(struct sip_pvt *p, int *recount, int *nounlock)
23697 {
23698    struct sip_request *req;
23699 
23700    while ((req = AST_LIST_REMOVE_HEAD(&p->request_queue, next))) {
23701       if (handle_incoming(p, req, &p->recv, recount, nounlock) == -1) {
23702          /* Request failed */
23703          ast_debug(1, "SIP message could not be handled, bad request: %-70.70s\n", p->callid[0] ? p->callid : "<no callid>");
23704       }
23705       ast_free(req);
23706    }
23707 }
23708 
23709 static int scheduler_process_request_queue(const void *data)
23710 {
23711    struct sip_pvt *p = (struct sip_pvt *) data;
23712    int recount = 0;
23713    int nounlock = 0;
23714    int lockretry;
23715 
23716    for (lockretry = 10; lockretry > 0; lockretry--) {
23717       sip_pvt_lock(p);
23718 
23719       /* lock the owner if it has one -- we may need it */
23720       /* because this is deadlock-prone, we need to try and unlock if failed */
23721       if (!p->owner || !ast_channel_trylock(p->owner)) {
23722          break;   /* locking succeeded */
23723       }
23724 
23725       if (lockretry != 1) {
23726          sip_pvt_unlock(p);
23727          /* Sleep for a very short amount of time */
23728          usleep(1);
23729       }
23730    }
23731 
23732    if (!lockretry) {
23733       int retry = !AST_LIST_EMPTY(&p->request_queue);
23734 
23735       /* we couldn't get the owner lock, which is needed to process
23736          the queued requests, so return a non-zero value, which will
23737          cause the scheduler to run this request again later if there
23738          still requests to be processed
23739       */
23740       sip_pvt_unlock(p);
23741       if (!retry) {
23742          dialog_unref(p, "The ref to a dialog passed to this sched callback is going out of scope; unref it.");
23743       }
23744       return retry;
23745    };
23746 
23747    process_request_queue(p, &recount, &nounlock);
23748    p->request_queue_sched_id = -1;
23749 
23750    if (p->owner && !nounlock) {
23751       ast_channel_unlock(p->owner);
23752    }
23753    sip_pvt_unlock(p);
23754 
23755    if (recount) {
23756       ast_update_use_count();
23757    }
23758 
23759    dialog_unref(p, "The ref to a dialog passed to this sched callback is going out of scope; unref it.");
23760 
23761    return 0;
23762 }
23763 
23764 static int queue_request(struct sip_pvt *p, const struct sip_request *req)
23765 {
23766    struct sip_request *newreq;
23767 
23768    if (!(newreq = ast_calloc(1, sizeof(*newreq)))) {
23769       return -1;
23770    }
23771 
23772    copy_request(newreq, req);
23773    AST_LIST_INSERT_TAIL(&p->request_queue, newreq, next);
23774    if (p->request_queue_sched_id == -1) {
23775       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) {
23776          dialog_unref(p, "Decrement refcount due to sched_add failure");
23777       }
23778    }
23779 
23780    return 0;
23781 }
23782 
23783 /*! \brief Read data from SIP UDP socket
23784 \note sipsock_read locks the owner channel while we are processing the SIP message
23785 \return 1 on error, 0 on success
23786 \note Successful messages is connected to SIP call and forwarded to handle_incoming()
23787 */
23788 static int sipsock_read(int *id, int fd, short events, void *ignore)
23789 {
23790    struct sip_request req;
23791    struct ast_sockaddr addr;
23792    int res;
23793    static char readbuf[65535];
23794 
23795    memset(&req, 0, sizeof(req));
23796    res = ast_recvfrom(fd, readbuf, sizeof(readbuf) - 1, 0, &addr);
23797    if (res < 0) {
23798 #if !defined(__FreeBSD__)
23799       if (errno == EAGAIN)
23800          ast_log(LOG_NOTICE, "SIP: Received packet with bad UDP checksum\n");
23801       else
23802 #endif
23803       if (errno != ECONNREFUSED)
23804          ast_log(LOG_WARNING, "Recv error: %s\n", strerror(errno));
23805       return 1;
23806    }
23807 
23808    readbuf[res] = '\0';
23809 
23810    if (!(req.data = ast_str_create(SIP_MIN_PACKET))) {
23811       return 1;
23812    }
23813 
23814    if (ast_str_set(&req.data, 0, "%s", readbuf) == AST_DYNSTR_BUILD_FAILED) {
23815       return -1;
23816    }
23817 
23818    req.len = res;
23819    req.socket.fd = sipsock;
23820    set_socket_transport(&req.socket, SIP_TRANSPORT_UDP);
23821    req.socket.tcptls_session  = NULL;
23822    req.socket.port = htons(ast_sockaddr_port(&bindaddr));
23823 
23824    handle_request_do(&req, &addr);
23825    deinit_req(&req);
23826 
23827    return 1;
23828 }
23829 
23830 /*! \brief Handle incoming SIP message - request or response
23831 
23832    This is used for all transports (udp, tcp and tcp/tls)
23833 */
23834 static int handle_request_do(struct sip_request *req, struct ast_sockaddr *addr)
23835 {
23836    struct sip_pvt *p;
23837    int recount = 0;
23838    int nounlock = 0;
23839    int lockretry;
23840 
23841    if (sip_debug_test_addr(addr))   /* Set the debug flag early on packet level */
23842       req->debug = 1;
23843    if (sip_cfg.pedanticsipchecking)
23844       req->len = lws2sws(req->data->str, req->len);   /* Fix multiline headers */
23845    if (req->debug) {
23846       ast_verbose("\n<--- SIP read from %s:%s --->\n%s\n<------------->\n",
23847          get_transport(req->socket.type), ast_sockaddr_stringify(addr), req->data->str);
23848    }
23849 
23850    if (parse_request(req) == -1) { /* Bad packet, can't parse */
23851       ast_str_reset(req->data); /* nulling this out is NOT a good idea here. */
23852       return 1;
23853    }
23854    req->method = find_sip_method(REQ_OFFSET_TO_STR(req, rlPart1));
23855 
23856    if (req->debug)
23857       ast_verbose("--- (%d headers %d lines)%s ---\n", req->headers, req->lines, (req->headers + req->lines == 0) ? " Nat keepalive" : "");
23858 
23859    if (req->headers < 2) { /* Must have at least two headers */
23860       ast_str_reset(req->data); /* nulling this out is NOT a good idea here. */
23861       return 1;
23862    }
23863 
23864    /* Process request, with netlock held, and with usual deadlock avoidance */
23865    for (lockretry = 10; lockretry > 0; lockretry--) {
23866       ast_mutex_lock(&netlock);
23867 
23868       /* Find the active SIP dialog or create a new one */
23869       p = find_call(req, addr, req->method); /* returns p locked */
23870       if (p == NULL) {
23871          ast_debug(1, "Invalid SIP message - rejected , no callid, len %d\n", req->len);
23872          ast_mutex_unlock(&netlock);
23873          return 1;
23874       }
23875 
23876       copy_socket_data(&p->socket, &req->socket);
23877 
23878       /* Go ahead and lock the owner if it has one -- we may need it */
23879       /* becaues this is deadlock-prone, we need to try and unlock if failed */
23880       if (!p->owner || !ast_channel_trylock(p->owner))
23881          break;   /* locking succeeded */
23882 
23883       if (lockretry != 1) {
23884          sip_pvt_unlock(p);
23885          ao2_t_ref(p, -1, "release p (from find_call) inside lockretry loop"); /* we'll look for it again, but p is dead now */
23886          ast_mutex_unlock(&netlock);
23887          /* Sleep for a very short amount of time */
23888          usleep(1);
23889       }
23890    }
23891    ast_sockaddr_copy(&p->recv, addr);
23892 
23893    if (p->do_history) /* This is a request or response, note what it was for */
23894       append_history(p, "Rx", "%s / %s / %s", req->data->str, get_header(req, "CSeq"), REQ_OFFSET_TO_STR(req, rlPart2));
23895 
23896    if (!lockretry) {
23897       if (!queue_request(p, req)) {
23898          /* the request has been queued for later handling */
23899          sip_pvt_unlock(p);
23900          ao2_t_ref(p, -1, "release p (from find_call) after queueing request");
23901          ast_mutex_unlock(&netlock);
23902          return 1;
23903       }
23904 
23905       if (p->owner)
23906          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 ??? - "));
23907       ast_log(LOG_ERROR, "SIP transaction failed: %s \n", p->callid);
23908       if (req->method != SIP_ACK)
23909          transmit_response(p, "503 Server error", req);  /* We must respond according to RFC 3261 sec 12.2 */
23910       /* XXX We could add retry-after to make sure they come back */
23911       append_history(p, "LockFail", "Owner lock failed, transaction failed.");
23912       sip_pvt_unlock(p);
23913       ao2_t_ref(p, -1, "release p (from find_call) at end of lockretry"); /* p is gone after the return */
23914       ast_mutex_unlock(&netlock);
23915       return 1;
23916    }
23917 
23918    /* if there are queued requests on this sip_pvt, process them first, so that everything is
23919       handled in order
23920    */
23921    if (!AST_LIST_EMPTY(&p->request_queue)) {
23922       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"));
23923       process_request_queue(p, &recount, &nounlock);
23924    }
23925 
23926    if (handle_incoming(p, req, addr, &recount, &nounlock) == -1) {
23927       /* Request failed */
23928       ast_debug(1, "SIP message could not be handled, bad request: %-70.70s\n", p->callid[0] ? p->callid : "<no callid>");
23929    }
23930       
23931    if (recount)
23932       ast_update_use_count();
23933 
23934    if (p->owner && !nounlock)
23935       ast_channel_unlock(p->owner);
23936    sip_pvt_unlock(p);
23937    ao2_t_ref(p, -1, "throw away dialog ptr from find_call at end of routine"); /* p is gone after the return */
23938    ast_mutex_unlock(&netlock);
23939    return 1;
23940 }
23941 
23942 /*! \brief Returns the port to use for this socket
23943  *
23944  * \param type The type of transport used
23945  * \param port Port we are checking to see if it's the standard port.
23946  * \note port is expected in host byte order
23947  */
23948 static int sip_standard_port(enum sip_transport type, int port)
23949 {
23950    if (type & SIP_TRANSPORT_TLS)
23951       return port == STANDARD_TLS_PORT;
23952    else
23953       return port == STANDARD_SIP_PORT;
23954 }
23955 
23956 static int threadinfo_locate_cb(void *obj, void *arg, int flags)
23957 {
23958    struct sip_threadinfo *th = obj;
23959    struct ast_sockaddr *s = arg;
23960 
23961    if (!ast_sockaddr_cmp(s, &th->tcptls_session->remote_address)) {
23962       return CMP_MATCH | CMP_STOP;
23963    }
23964 
23965    return 0;
23966 }
23967 
23968 /*!
23969  * \brief Find thread for TCP/TLS session (based on IP/Port
23970  *
23971  * \note This function returns an astobj2 reference
23972  */
23973 static struct ast_tcptls_session_instance *sip_tcp_locate(struct ast_sockaddr *s)
23974 {
23975    struct sip_threadinfo *th;
23976    struct ast_tcptls_session_instance *tcptls_instance = NULL;
23977 
23978    if ((th = ao2_callback(threadt, 0, threadinfo_locate_cb, s))) {
23979       tcptls_instance = (ao2_ref(th->tcptls_session, +1), th->tcptls_session);
23980       ao2_t_ref(th, -1, "decrement ref from callback");
23981    }
23982 
23983    return tcptls_instance;
23984 }
23985 
23986 /*!
23987  * \brief Helper for dns resolution to filter by address family.
23988  *
23989  * \note return 0 if addr is [::] else it returns addr's family.
23990  */
23991 int get_address_family_filter(const struct ast_sockaddr *addr)
23992 {
23993    if (ast_sockaddr_is_ipv6(addr) && ast_sockaddr_is_any(addr)) {
23994       return 0;
23995    }
23996 
23997    return addr->ss.ss_family;
23998 }
23999 
24000 /*! \todo Get socket for dialog, prepare if needed, and return file handle  */
24001 static int sip_prepare_socket(struct sip_pvt *p)
24002 {
24003    struct sip_socket *s = &p->socket;
24004    static const char name[] = "SIP socket";
24005    struct sip_threadinfo *th = NULL;
24006    struct ast_tcptls_session_instance *tcptls_session;
24007    struct ast_tcptls_session_args *ca;
24008    struct ast_sockaddr sa_tmp;
24009 
24010    /* check to see if a socket is already active */
24011    if ((s->fd != -1) && (s->type == SIP_TRANSPORT_UDP)) {
24012       return s->fd;
24013    }
24014    if ((s->type & (SIP_TRANSPORT_TCP | SIP_TRANSPORT_TLS)) &&
24015          (s->tcptls_session) &&
24016          (s->tcptls_session->fd != -1)) {
24017       return s->tcptls_session->fd;
24018    }
24019 
24020    /*! \todo Check this... This might be wrong, depending on the proxy configuration
24021       If proxy is in "force" mode its correct.
24022     */
24023    if (p->outboundproxy && p->outboundproxy->transport) {
24024       s->type = p->outboundproxy->transport;
24025    }
24026 
24027    if (s->type == SIP_TRANSPORT_UDP) {
24028       s->fd = sipsock;
24029       return s->fd;
24030    }
24031 
24032    /* At this point we are dealing with a TCP/TLS connection
24033     * 1. We need to check to see if a connectin thread exists
24034     *    for this address, if so use that.
24035     * 2. If a thread does not exist for this address, but the tcptls_session
24036     *    exists on the socket, the connection was closed.
24037     * 3. If no tcptls_session thread exists for the address, and no tcptls_session
24038     *    already exists on the socket, create a new one and launch a new thread.
24039     */
24040 
24041    /* 1.  check for existing threads */
24042    ast_sockaddr_copy(&sa_tmp, sip_real_dst(p));
24043    if ((tcptls_session = sip_tcp_locate(&sa_tmp))) {
24044       s->fd = tcptls_session->fd;
24045       if (s->tcptls_session) {
24046          ao2_ref(s->tcptls_session, -1);
24047          s->tcptls_session = NULL;
24048       }
24049       s->tcptls_session = tcptls_session;
24050       return s->fd;
24051    /* 2.  Thread not found, if tcptls_session already exists, it once had a thread and is now terminated */
24052    } else if (s->tcptls_session) {
24053       return s->fd; /* XXX whether reconnection is ever necessary here needs to be investigated further */
24054    }
24055 
24056    /* 3.  Create a new TCP/TLS client connection */
24057    /* create new session arguments for the client connection */
24058    if (!(ca = ao2_alloc(sizeof(*ca), sip_tcptls_client_args_destructor)) ||
24059       !(ca->name = ast_strdup(name))) {
24060       goto create_tcptls_session_fail;
24061    }
24062    ca->accept_fd = -1;
24063    ast_sockaddr_copy(&ca->remote_address,sip_real_dst(p));
24064    /* if type is TLS, we need to create a tls cfg for this session arg */
24065    if (s->type == SIP_TRANSPORT_TLS) {
24066       if (!(ca->tls_cfg = ast_calloc(1, sizeof(*ca->tls_cfg)))) {
24067          goto create_tcptls_session_fail;
24068       }
24069       memcpy(ca->tls_cfg, &default_tls_cfg, sizeof(*ca->tls_cfg));
24070 
24071       if (!(ca->tls_cfg->certfile = ast_strdup(default_tls_cfg.certfile)) ||
24072          !(ca->tls_cfg->pvtfile = ast_strdup(default_tls_cfg.pvtfile)) ||
24073          !(ca->tls_cfg->cipher = ast_strdup(default_tls_cfg.cipher)) ||
24074          !(ca->tls_cfg->cafile = ast_strdup(default_tls_cfg.cafile)) ||
24075          !(ca->tls_cfg->capath = ast_strdup(default_tls_cfg.capath))) {
24076 
24077          goto create_tcptls_session_fail;
24078       }
24079 
24080       /* this host is used as the common name in ssl/tls */
24081       if (!ast_strlen_zero(p->tohost)) {
24082          ast_copy_string(ca->hostname, p->tohost, sizeof(ca->hostname));
24083       }
24084    }
24085 
24086    /* Create a client connection for address, this does not start the connection, just sets it up. */
24087    if (!(s->tcptls_session = ast_tcptls_client_create(ca))) {
24088       goto create_tcptls_session_fail;
24089    }
24090 
24091    s->fd = s->tcptls_session->fd;
24092 
24093    /* client connections need to have the sip_threadinfo object created before
24094     * the thread is detached.  This ensures the alert_pipe is up before it will
24095     * be used.  Note that this function links the new threadinfo object into the
24096     * threadt container. */
24097    if (!(th = sip_threadinfo_create(s->tcptls_session, s->type))) {
24098       goto create_tcptls_session_fail;
24099    }
24100 
24101    /* Give the new thread a reference to the tcptls_session */
24102    ao2_ref(s->tcptls_session, +1);
24103 
24104    if (ast_pthread_create_background(&ca->master, NULL, sip_tcp_worker_fn, s->tcptls_session)) {
24105       ast_debug(1, "Unable to launch '%s'.", ca->name);
24106       ao2_ref(s->tcptls_session, -1); /* take away the thread ref we just gave it */
24107       goto create_tcptls_session_fail;
24108    }
24109 
24110    return s->fd;
24111 
24112 create_tcptls_session_fail:
24113    if (ca) {
24114       ao2_t_ref(ca, -1, "failed to create client, getting rid of client tcptls_session arguments");
24115    }
24116    if (s->tcptls_session) {
24117       close(tcptls_session->fd);
24118       s->fd = tcptls_session->fd = -1;
24119       ao2_ref(s->tcptls_session, -1);
24120       s->tcptls_session = NULL;
24121    }
24122    if (th) {
24123       ao2_t_unlink(threadt, th, "Removing tcptls thread info object, thread failed to open");
24124    }
24125 
24126    return -1;
24127 }
24128 
24129 /*!
24130  * \brief Get cached MWI info
24131  * \retval 0 At least one message is waiting
24132  * \retval 1 no messages waiting
24133  */
24134 static int get_cached_mwi(struct sip_peer *peer, int *new, int *old)
24135 {
24136    struct sip_mailbox *mailbox;
24137 
24138    AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
24139       struct ast_event *event;
24140       event = ast_event_get_cached(AST_EVENT_MWI,
24141          AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, mailbox->mailbox,
24142          AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, S_OR(mailbox->context, "default"),
24143          AST_EVENT_IE_END);
24144       if (!event)
24145          continue;
24146       *new += ast_event_get_ie_uint(event, AST_EVENT_IE_NEWMSGS);
24147       *old += ast_event_get_ie_uint(event, AST_EVENT_IE_OLDMSGS);
24148       ast_event_destroy(event);
24149    }
24150 
24151    return (*new || *old) ? 0 : 1;
24152 }
24153 
24154 /*! \brief Send message waiting indication to alert peer that they've got voicemail */
24155 static int sip_send_mwi_to_peer(struct sip_peer *peer, const struct ast_event *event, int cache_only)
24156 {
24157    /* Called with peerl lock, but releases it */
24158    struct sip_pvt *p;
24159    int newmsgs = 0, oldmsgs = 0;
24160 
24161    if (ast_test_flag((&peer->flags[1]), SIP_PAGE2_SUBSCRIBEMWIONLY) && !peer->mwipvt)
24162       return 0;
24163 
24164    /* Do we have an IP address? If not, skip this peer */
24165    if (ast_sockaddr_isnull(&peer->addr) && ast_sockaddr_isnull(&peer->defaddr))
24166       return 0;
24167 
24168    if (event) {
24169       newmsgs = ast_event_get_ie_uint(event, AST_EVENT_IE_NEWMSGS);
24170       oldmsgs = ast_event_get_ie_uint(event, AST_EVENT_IE_OLDMSGS);
24171    } else if (!cache_only) { /* Fall back to manually checking the mailbox */
24172       struct ast_str *mailbox_str = ast_str_alloca(512);
24173       peer_mailboxes_to_str(&mailbox_str, peer);
24174       ast_app_inboxcount(mailbox_str->str, &newmsgs, &oldmsgs);
24175    } else {
24176       get_cached_mwi(peer, &newmsgs, &oldmsgs);
24177    }
24178    
24179    if (peer->mwipvt) {
24180       /* Base message on subscription */
24181       p = dialog_ref(peer->mwipvt, "sip_send_mwi_to_peer: Setting dialog ptr p from peer->mwipvt-- should this be done?");
24182    } else {
24183       /* Build temporary dialog for this message */
24184       if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY, NULL)))
24185          return -1;
24186       /* If we don't set the socket type to 0, then create_addr_from_peer will fail immediately if the peer
24187        * uses any transport other than UDP. We set the type to 0 here and then let create_addr_from_peer copy
24188        * the peer's socket information to the sip_pvt we just allocated
24189        */
24190       set_socket_transport(&p->socket, 0);
24191       if (create_addr_from_peer(p, peer)) {
24192          /* Maybe they're not registered, etc. */
24193          dialog_unlink_all(p, TRUE, TRUE);
24194          dialog_unref(p, "unref dialog p just created via sip_alloc");
24195          /* sip_destroy(p); */
24196          return 0;
24197       }
24198       /* Recalculate our side, and recalculate Call ID */
24199       ast_sip_ouraddrfor(&p->sa, &p->ourip, p);
24200       build_via(p);
24201       ao2_t_unlink(dialogs, p, "About to change the callid -- remove the old name");
24202       build_callid_pvt(p);
24203       if (!ast_strlen_zero(peer->mwi_from)) {
24204          ast_string_field_set(p, mwi_from, peer->mwi_from);
24205       } else if (!ast_strlen_zero(default_mwi_from)) {
24206          ast_string_field_set(p, mwi_from, default_mwi_from);
24207       }
24208       ao2_t_link(dialogs, p, "Linking in under new name");
24209       /* Destroy this session after 32 secs */
24210       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
24211    }
24212 
24213    /* Send MWI */
24214    ast_set_flag(&p->flags[0], SIP_OUTGOING);
24215    /* the following will decrement the refcount on p as it finishes */
24216    transmit_notify_with_mwi(p, newmsgs, oldmsgs, peer->vmexten);
24217    dialog_unref(p, "unref dialog ptr p just before it goes out of scope at the end of sip_send_mwi_to_peer.");
24218    return 0;
24219 }
24220 
24221 /*! \brief helper function for the monitoring thread -- seems to be called with the assumption that the dialog is locked */
24222 static void check_rtp_timeout(struct sip_pvt *dialog, time_t t)
24223 {
24224    /* If we have no RTP or no active owner, no need to check timers */
24225    if (!dialog->rtp || !dialog->owner)
24226       return;
24227    /* If the call is not in UP state or redirected outside Asterisk, no need to check timers */
24228 
24229    if (dialog->owner->_state != AST_STATE_UP || !ast_sockaddr_isnull(&dialog->redirip))
24230       return;
24231 
24232    /* If the call is involved in a T38 fax session do not check RTP timeout */
24233    if (dialog->t38.state == T38_ENABLED)
24234       return;
24235 
24236    /* If we have no timers set, return now */
24237    if (!ast_rtp_instance_get_timeout(dialog->rtp) && !ast_rtp_instance_get_hold_timeout(dialog->rtp)) {
24238       return;
24239    }
24240 
24241    /*! \todo Check video RTP keepalives
24242 
24243       Do we need to move the lastrtptx to the RTP structure to have one for audio and one
24244       for video? It really does belong to the RTP structure.
24245    */
24246 
24247    /* Check AUDIO RTP timers */
24248    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))) {
24249       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)))) {
24250          /* Needs a hangup */
24251          if (ast_rtp_instance_get_timeout(dialog->rtp)) {
24252             while (dialog->owner && ast_channel_trylock(dialog->owner)) {
24253                sip_pvt_unlock(dialog);
24254                usleep(1);
24255                sip_pvt_lock(dialog);
24256             }
24257             if (!dialog->owner) {
24258                return; /* channel hangup can occur during deadlock avoidance. */
24259             }
24260             ast_log(LOG_NOTICE, "Disconnecting call '%s' for lack of RTP activity in %ld seconds\n",
24261                dialog->owner->name, (long) (t - dialog->lastrtprx));
24262             /* Issue a softhangup */
24263             ast_softhangup_nolock(dialog->owner, AST_SOFTHANGUP_DEV);
24264             ast_channel_unlock(dialog->owner);
24265             /* forget the timeouts for this call, since a hangup
24266                has already been requested and we don't want to
24267                repeatedly request hangups
24268             */
24269             ast_rtp_instance_set_timeout(dialog->rtp, 0);
24270             ast_rtp_instance_set_hold_timeout(dialog->rtp, 0);
24271             if (dialog->vrtp) {
24272                ast_rtp_instance_set_timeout(dialog->vrtp, 0);
24273                ast_rtp_instance_set_hold_timeout(dialog->vrtp, 0);
24274             }
24275          }
24276       }
24277    }
24278 }
24279 
24280 /*! \brief The SIP monitoring thread
24281 \note This thread monitors all the SIP sessions and peers that needs notification of mwi
24282    (and thus do not have a separate thread) indefinitely
24283 */
24284 static void *do_monitor(void *data)
24285 {
24286    int res;
24287    time_t t;
24288    int reloading;
24289 
24290    /* Add an I/O event to our SIP UDP socket */
24291    if (sipsock > -1)
24292       sipsock_read_id = ast_io_add(io, sipsock, sipsock_read, AST_IO_IN, NULL);
24293 
24294    /* From here on out, we die whenever asked */
24295    for(;;) {
24296       /* Check for a reload request */
24297       ast_mutex_lock(&sip_reload_lock);
24298       reloading = sip_reloading;
24299       sip_reloading = FALSE;
24300       ast_mutex_unlock(&sip_reload_lock);
24301       if (reloading) {
24302          ast_verb(1, "Reloading SIP\n");
24303          sip_do_reload(sip_reloadreason);
24304 
24305          /* Change the I/O fd of our UDP socket */
24306          if (sipsock > -1) {
24307             if (sipsock_read_id)
24308                sipsock_read_id = ast_io_change(io, sipsock_read_id, sipsock, NULL, 0, NULL);
24309             else
24310                sipsock_read_id = ast_io_add(io, sipsock, sipsock_read, AST_IO_IN, NULL);
24311          } else if (sipsock_read_id) {
24312             ast_io_remove(io, sipsock_read_id);
24313             sipsock_read_id = NULL;
24314          }
24315       }
24316 
24317       /* Check for dialogs needing to be killed */
24318       t = time(NULL);
24319       /* don't scan the dialogs list if it hasn't been a reasonable period
24320          of time since the last time we did it (when MWI is being sent, we can
24321          get back to this point every millisecond or less)
24322       */
24323       ao2_t_callback(dialogs, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, dialog_needdestroy, &t,
24324             "callback to remove dialogs w/needdestroy");
24325 
24326       /* the old methodology would be to restart the search for dialogs to delete with every
24327          dialog that was found and destroyed, probably because the list contents would change,
24328          so we'd need to restart. This isn't the best thing to do with callbacks. */
24329 
24330       /* XXX TODO The scheduler usage in this module does not have sufficient
24331        * synchronization being done between running the scheduler and places
24332        * scheduling tasks.  As it is written, any scheduled item may not run
24333        * any sooner than about  1 second, regardless of whether a sooner time
24334        * was asked for. */
24335 
24336       pthread_testcancel();
24337       /* Wait for sched or io */
24338       res = ast_sched_wait(sched);
24339       if ((res < 0) || (res > 1000))
24340          res = 1000;
24341       res = ast_io_wait(io, res);
24342       if (res > 20)
24343          ast_debug(1, "chan_sip: ast_io_wait ran %d all at once\n", res);
24344       ast_mutex_lock(&monlock);
24345       res = ast_sched_runq(sched);
24346       if (res >= 20)
24347          ast_debug(1, "chan_sip: ast_sched_runq ran %d all at once\n", res);
24348       ast_mutex_unlock(&monlock);
24349    }
24350 
24351    /* Never reached */
24352    return NULL;
24353 }
24354 
24355 /*! \brief Start the channel monitor thread */
24356 static int restart_monitor(void)
24357 {
24358    /* If we're supposed to be stopped -- stay stopped */
24359    if (monitor_thread == AST_PTHREADT_STOP)
24360       return 0;
24361    ast_mutex_lock(&monlock);
24362    if (monitor_thread == pthread_self()) {
24363       ast_mutex_unlock(&monlock);
24364       ast_log(LOG_WARNING, "Cannot kill myself\n");
24365       return -1;
24366    }
24367    if (monitor_thread != AST_PTHREADT_NULL) {
24368       /* Wake up the thread */
24369       pthread_kill(monitor_thread, SIGURG);
24370    } else {
24371       /* Start a new monitor */
24372       if (ast_pthread_create_background(&monitor_thread, NULL, do_monitor, NULL) < 0) {
24373          ast_mutex_unlock(&monlock);
24374          ast_log(LOG_ERROR, "Unable to start monitor thread.\n");
24375          return -1;
24376       }
24377    }
24378    ast_mutex_unlock(&monlock);
24379    return 0;
24380 }
24381 
24382 
24383 /*! \brief Session-Timers: Restart session timer */
24384 static void restart_session_timer(struct sip_pvt *p)
24385 {
24386    if (!p->stimer) {
24387       ast_log(LOG_WARNING, "Null stimer in restart_session_timer - %s\n", p->callid);
24388       return;
24389    }
24390 
24391    if (p->stimer->st_active == TRUE) {
24392       AST_SCHED_DEL_UNREF(sched, p->stimer->st_schedid,
24393             dialog_unref(p, "Removing session timer ref"));
24394       ast_debug(2, "Session timer stopped: %d - %s\n", p->stimer->st_schedid, p->callid);
24395       start_session_timer(p);
24396    }
24397 }
24398 
24399 
24400 /*! \brief Session-Timers: Stop session timer */
24401 static void stop_session_timer(struct sip_pvt *p)
24402 {
24403    if (!p->stimer) {
24404       ast_log(LOG_WARNING, "Null stimer in stop_session_timer - %s\n", p->callid);
24405       return;
24406    }
24407 
24408    if (p->stimer->st_active == TRUE) {
24409       p->stimer->st_active = FALSE;
24410       AST_SCHED_DEL_UNREF(sched, p->stimer->st_schedid,
24411             dialog_unref(p, "removing session timer ref"));
24412       ast_debug(2, "Session timer stopped: %d - %s\n", p->stimer->st_schedid, p->callid);
24413    }
24414 }
24415 
24416 
24417 /*! \brief Session-Timers: Start session timer */
24418 static void start_session_timer(struct sip_pvt *p)
24419 {
24420    if (!p->stimer) {
24421       ast_log(LOG_WARNING, "Null stimer in start_session_timer - %s\n", p->callid);
24422       return;
24423    }
24424 
24425    p->stimer->st_schedid  = ast_sched_add(sched, p->stimer->st_interval * 1000 / 2, proc_session_timer,
24426          dialog_ref(p, "adding session timer ref"));
24427    if (p->stimer->st_schedid < 0) {
24428       dialog_unref(p, "removing session timer ref");
24429       ast_log(LOG_ERROR, "ast_sched_add failed.\n");
24430    }
24431    ast_debug(2, "Session timer started: %d - %s\n", p->stimer->st_schedid, p->callid);
24432 }
24433 
24434 
24435 /*! \brief Session-Timers: Process session refresh timeout event */
24436 static int proc_session_timer(const void *vp)
24437 {
24438    struct sip_pvt *p = (struct sip_pvt *) vp;
24439    int sendreinv = FALSE;
24440    int res = 0;
24441 
24442    if (!p->stimer) {
24443       ast_log(LOG_WARNING, "Null stimer in proc_session_timer - %s\n", p->callid);
24444       goto return_unref;
24445    }
24446 
24447    ast_debug(2, "Session timer expired: %d - %s\n", p->stimer->st_schedid, p->callid);
24448 
24449    if (!p->owner) {
24450       goto return_unref;
24451    }
24452 
24453    if ((p->stimer->st_active != TRUE) || (p->owner->_state != AST_STATE_UP)) {
24454       goto return_unref;
24455    }
24456 
24457    switch (p->stimer->st_ref) {
24458    case SESSION_TIMER_REFRESHER_UAC:
24459       if (p->outgoing_call == TRUE) {
24460          sendreinv = TRUE;
24461       }
24462       break;
24463    case SESSION_TIMER_REFRESHER_UAS:
24464       if (p->outgoing_call != TRUE) {
24465          sendreinv = TRUE;
24466       }
24467       break;
24468    default:
24469       ast_log(LOG_ERROR, "Unknown session refresher %d\n", p->stimer->st_ref);
24470       goto return_unref;
24471    }
24472 
24473    if (sendreinv == TRUE) {
24474       res = 1;
24475       transmit_reinvite_with_sdp(p, FALSE, TRUE);
24476    } else {
24477       p->stimer->st_expirys++;
24478       if (p->stimer->st_expirys >= 2) {
24479          if (p->stimer->quit_flag) {
24480             goto return_unref;
24481          }
24482          ast_log(LOG_WARNING, "Session-Timer expired - %s\n", p->callid);
24483          sip_pvt_lock(p);
24484          while (p->owner && ast_channel_trylock(p->owner)) {
24485             sip_pvt_unlock(p);
24486             usleep(1);
24487             if (p->stimer && p->stimer->quit_flag) {
24488                goto return_unref;
24489             }
24490             sip_pvt_lock(p);
24491          }
24492 
24493          ast_softhangup_nolock(p->owner, AST_SOFTHANGUP_DEV);
24494          ast_channel_unlock(p->owner);
24495          sip_pvt_unlock(p);
24496       }
24497    }
24498 
24499 return_unref:
24500    if (!res) {
24501       /* An error occurred.  Stop session timer processing */
24502       if (p->stimer) {
24503          p->stimer->st_schedid = -1;
24504          stop_session_timer(p);
24505       }
24506 
24507       /* If we are not asking to be rescheduled, then we need to release our
24508        * reference to the dialog. */
24509       dialog_unref(p, "removing session timer ref");
24510    }
24511 
24512    return res;
24513 }
24514 
24515 
24516 /*! \brief Session-Timers: Function for parsing Min-SE header */
24517 int parse_minse (const char *p_hdrval, int *const p_interval)
24518 {
24519    if (ast_strlen_zero(p_hdrval)) {
24520       ast_log(LOG_WARNING, "Null Min-SE header\n");
24521       return -1;
24522    }
24523 
24524    *p_interval = 0;
24525    p_hdrval = ast_skip_blanks(p_hdrval);
24526    if (!sscanf(p_hdrval, "%30d", p_interval)) {
24527       ast_log(LOG_WARNING, "Parsing of Min-SE header failed %s\n", p_hdrval);
24528       return -1;
24529    }
24530 
24531    ast_debug(2, "Received Min-SE: %d\n", *p_interval);
24532    return 0;
24533 }
24534 
24535 
24536 /*! \brief Session-Timers: Function for parsing Session-Expires header */
24537 int parse_session_expires(const char *p_hdrval, int *const p_interval, enum st_refresher *const p_ref)
24538 {
24539    char *p_token;
24540    int  ref_idx;
24541    char *p_se_hdr;
24542 
24543    if (ast_strlen_zero(p_hdrval)) {
24544       ast_log(LOG_WARNING, "Null Session-Expires header\n");
24545       return -1;
24546    }
24547 
24548    *p_ref = SESSION_TIMER_REFRESHER_AUTO;
24549    *p_interval = 0;
24550 
24551    p_se_hdr = ast_strdupa(p_hdrval);
24552    p_se_hdr = ast_skip_blanks(p_se_hdr);
24553 
24554    while ((p_token = strsep(&p_se_hdr, ";"))) {
24555       p_token = ast_skip_blanks(p_token);
24556       if (!sscanf(p_token, "%30d", p_interval)) {
24557          ast_log(LOG_WARNING, "Parsing of Session-Expires failed\n");
24558          return -1;
24559       }
24560 
24561       ast_debug(2, "Session-Expires: %d\n", *p_interval);
24562 
24563       if (!p_se_hdr)
24564          continue;
24565 
24566       p_se_hdr = ast_skip_blanks(p_se_hdr);
24567       ref_idx = strlen("refresher=");
24568       if (!strncasecmp(p_se_hdr, "refresher=", ref_idx)) {
24569          p_se_hdr += ref_idx;
24570          p_se_hdr = ast_skip_blanks(p_se_hdr);
24571 
24572          if (!strncasecmp(p_se_hdr, "uac", strlen("uac"))) {
24573             *p_ref = SESSION_TIMER_REFRESHER_UAC;
24574             ast_debug(2, "Refresher: UAC\n");
24575          } else if (!strncasecmp(p_se_hdr, "uas", strlen("uas"))) {
24576             *p_ref = SESSION_TIMER_REFRESHER_UAS;
24577             ast_debug(2, "Refresher: UAS\n");
24578          } else {
24579             ast_log(LOG_WARNING, "Invalid refresher value %s\n", p_se_hdr);
24580             return -1;
24581          }
24582          break;
24583       }
24584    }
24585    return 0;
24586 }
24587 
24588 
24589 /*! \brief Handle 422 response to INVITE with session-timer requested
24590 
24591    Session-Timers:   An INVITE originated by Asterisk that asks for session-timers support
24592    from the UAS can result into a 422 response. This is how a UAS or an intermediary proxy
24593    server tells Asterisk that the session refresh interval offered by Asterisk is too low
24594    for them.  The proc_422_rsp() function handles a 422 response.  It extracts the Min-SE
24595    header that comes back in 422 and sends a new INVITE accordingly. */
24596 static void proc_422_rsp(struct sip_pvt *p, struct sip_request *rsp)
24597 {
24598    int rtn;
24599    const char *p_hdrval;
24600    int minse;
24601 
24602    p_hdrval = get_header(rsp, "Min-SE");
24603    if (ast_strlen_zero(p_hdrval)) {
24604       ast_log(LOG_WARNING, "422 response without a Min-SE header %s\n", p_hdrval);
24605       return;
24606    }
24607    rtn = parse_minse(p_hdrval, &minse);
24608    if (rtn != 0) {
24609       ast_log(LOG_WARNING, "Parsing of Min-SE header failed %s\n", p_hdrval);
24610       return;
24611    }
24612    p->stimer->st_interval = minse;
24613    transmit_invite(p, SIP_INVITE, 1, 2, NULL);
24614 }
24615 
24616 
24617 /*! \brief Get Max or Min SE (session timer expiry)
24618  * \param p pointer to the SIP dialog
24619  * \param max if true, get max se, otherwise min se
24620 */
24621 int st_get_se(struct sip_pvt *p, int max)
24622 {
24623    if (max == TRUE) {
24624       if (p->stimer->st_cached_max_se) {
24625          return  p->stimer->st_cached_max_se;
24626       }
24627       if (p->relatedpeer) {
24628          p->stimer->st_cached_max_se = p->relatedpeer->stimer.st_max_se;
24629          return (p->stimer->st_cached_max_se);
24630       }
24631       p->stimer->st_cached_max_se = global_max_se;
24632       return (p->stimer->st_cached_max_se);
24633    } 
24634    /* Find Min SE timer */
24635    if (p->stimer->st_cached_min_se) {
24636       return p->stimer->st_cached_min_se;
24637    } 
24638    if (p->relatedpeer) {
24639       p->stimer->st_cached_min_se = p->relatedpeer->stimer.st_min_se;
24640       return (p->stimer->st_cached_min_se);
24641    }
24642    p->stimer->st_cached_min_se = global_min_se;
24643    return (p->stimer->st_cached_min_se);
24644 }
24645 
24646 
24647 /*! \brief Get the entity (UAC or UAS) that's acting as the session-timer refresher
24648  * \param p pointer to the SIP dialog
24649 */
24650 enum st_refresher st_get_refresher(struct sip_pvt *p)
24651 {
24652    if (p->stimer->st_cached_ref != SESSION_TIMER_REFRESHER_AUTO)
24653       return p->stimer->st_cached_ref;
24654 
24655    if (p->relatedpeer) {
24656       p->stimer->st_cached_ref = p->relatedpeer->stimer.st_ref;
24657       return p->stimer->st_cached_ref;
24658    }
24659    
24660    p->stimer->st_cached_ref = global_st_refresher;
24661    return global_st_refresher;
24662 }
24663 
24664 
24665 /*! \brief Get the session-timer mode
24666  * \param p pointer to the SIP dialog
24667 */
24668 enum st_mode st_get_mode(struct sip_pvt *p)
24669 {
24670    if (!p->stimer)
24671       sip_st_alloc(p);
24672 
24673    if (p->stimer->st_cached_mode != SESSION_TIMER_MODE_INVALID)
24674       return p->stimer->st_cached_mode;
24675 
24676    if (p->relatedpeer) {
24677       p->stimer->st_cached_mode = p->relatedpeer->stimer.st_mode_oper;
24678       return p->stimer->st_cached_mode;
24679    }
24680 
24681    p->stimer->st_cached_mode = global_st_mode;
24682    return global_st_mode;
24683 }
24684 
24685 
24686 /*! \brief React to lack of answer to Qualify poke */
24687 static int sip_poke_noanswer(const void *data)
24688 {
24689    struct sip_peer *peer = (struct sip_peer *)data;
24690 
24691    peer->pokeexpire = -1;
24692 
24693    if (peer->lastms > -1) {
24694       ast_log(LOG_NOTICE, "Peer '%s' is now UNREACHABLE!  Last qualify: %d\n", peer->name, peer->lastms);
24695       if (sip_cfg.peer_rtupdate) {
24696          ast_update_realtime(ast_check_realtime("sipregs") ? "sipregs" : "sippeers", "name", peer->name, "lastms", "-1", SENTINEL);
24697       }
24698       manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: Unreachable\r\nTime: %d\r\n", peer->name, -1);
24699       if (sip_cfg.regextenonqualify) {
24700          register_peer_exten(peer, FALSE);
24701       }
24702    }
24703 
24704    if (peer->call) {
24705       dialog_unlink_all(peer->call, TRUE, TRUE);
24706       peer->call = dialog_unref(peer->call, "unref dialog peer->call");
24707       /* peer->call = sip_destroy(peer->call);*/
24708    }
24709 
24710    /* Don't send a devstate change if nothing changed. */
24711    if (peer->lastms > -1) {
24712       peer->lastms = -1;
24713       ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", peer->name);
24714    }
24715 
24716    /* Try again quickly */
24717    AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched,
24718          DEFAULT_FREQ_NOTOK, sip_poke_peer_s, peer,
24719          unref_peer(_data, "removing poke peer ref"),
24720          unref_peer(peer, "removing poke peer ref"),
24721          ref_peer(peer, "adding poke peer ref"));
24722 
24723    /* Release the ref held by the running scheduler entry */
24724    unref_peer(peer, "release peer poke noanswer ref");
24725 
24726    return 0;
24727 }
24728 
24729 /*! \brief Check availability of peer, also keep NAT open
24730 \note This is done with 60 seconds between each ping,
24731    unless forced by cli or manager. If peer is unreachable,
24732    we check every 10th second by default.
24733 */
24734 static int sip_poke_peer(struct sip_peer *peer, int force)
24735 {
24736    struct sip_pvt *p;
24737    int xmitres = 0;
24738    
24739    if ((!peer->maxms && !force) || ast_sockaddr_isnull(&peer->addr)) {
24740       /* IF we have no IP, or this isn't to be monitored, return
24741         immediately after clearing things out */
24742       AST_SCHED_DEL_UNREF(sched, peer->pokeexpire,
24743             unref_peer(peer, "removing poke peer ref"));
24744       
24745       peer->lastms = 0;
24746       if (peer->call) {
24747          peer->call = dialog_unref(peer->call, "unref dialog peer->call");
24748       }
24749       return 0;
24750    }
24751    if (peer->call) {
24752       if (sipdebug) {
24753          ast_log(LOG_NOTICE, "Still have a QUALIFY dialog active, deleting\n");
24754       }
24755       dialog_unlink_all(peer->call, TRUE, TRUE);
24756       peer->call = dialog_unref(peer->call, "unref dialog peer->call");
24757       /* peer->call = sip_destroy(peer->call); */
24758    }
24759    if (!(p = sip_alloc(NULL, NULL, 0, SIP_OPTIONS, NULL))) {
24760       return -1;
24761    }
24762    peer->call = dialog_ref(p, "copy sip alloc from p to peer->call");
24763    
24764    p->sa = peer->addr;
24765    p->recv = peer->addr;
24766    copy_socket_data(&p->socket, &peer->socket);
24767    ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
24768    ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
24769    ast_copy_flags(&p->flags[2], &peer->flags[2], SIP_PAGE3_FLAGS_TO_COPY);
24770 
24771    /* Send OPTIONs to peer's fullcontact */
24772    if (!ast_strlen_zero(peer->fullcontact))
24773       ast_string_field_set(p, fullcontact, peer->fullcontact);
24774 
24775    if (!ast_strlen_zero(peer->tohost))
24776       ast_string_field_set(p, tohost, peer->tohost);
24777    else
24778       ast_string_field_set(p, tohost, ast_sockaddr_stringify_host(&peer->addr));
24779 
24780    /* Recalculate our side, and recalculate Call ID */
24781    ast_sip_ouraddrfor(&p->sa, &p->ourip, p);
24782    build_via(p);
24783    ao2_t_unlink(dialogs, p, "About to change the callid -- remove the old name");
24784    build_callid_pvt(p);
24785    ao2_t_link(dialogs, p, "Linking in under new name");
24786 
24787    AST_SCHED_DEL_UNREF(sched, peer->pokeexpire,
24788          unref_peer(peer, "removing poke peer ref"));
24789    
24790    if (p->relatedpeer)
24791       p->relatedpeer = unref_peer(p->relatedpeer,"unsetting the relatedpeer field in the dialog, before it is set to something else.");
24792    p->relatedpeer = ref_peer(peer, "setting the relatedpeer field in the dialog");
24793    ast_set_flag(&p->flags[0], SIP_OUTGOING);
24794 #ifdef VOCAL_DATA_HACK
24795    ast_copy_string(p->username, "__VOCAL_DATA_SHOULD_READ_THE_SIP_SPEC__", sizeof(p->username));
24796    xmitres = transmit_invite(p, SIP_INVITE, 0, 2, NULL); /* sinks the p refcount */
24797 #else
24798    xmitres = transmit_invite(p, SIP_OPTIONS, 0, 2, NULL); /* sinks the p refcount */
24799 #endif
24800    peer->ps = ast_tvnow();
24801    if (xmitres == XMIT_ERROR) {
24802       sip_poke_noanswer(peer);   /* Immediately unreachable, network problems */
24803    } else if (!force) {
24804       AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched, peer->maxms * 2, sip_poke_noanswer, peer,
24805             unref_peer(_data, "removing poke peer ref"),
24806             unref_peer(peer, "removing poke peer ref"),
24807             ref_peer(peer, "adding poke peer ref"));
24808    }
24809    dialog_unref(p, "unref dialog at end of sip_poke_peer, obtained from sip_alloc, just before it goes out of scope");
24810    return 0;
24811 }
24812 
24813 /*! \brief Part of PBX channel interface
24814 \note
24815 \par  Return values:---
24816 
24817    If we have qualify on and the device is not reachable, regardless of registration
24818    state we return AST_DEVICE_UNAVAILABLE
24819 
24820    For peers with call limit:
24821       - not registered        AST_DEVICE_UNAVAILABLE
24822       - registered, no call         AST_DEVICE_NOT_INUSE
24823       - registered, active calls    AST_DEVICE_INUSE
24824       - registered, call limit reached AST_DEVICE_BUSY
24825       - registered, onhold       AST_DEVICE_ONHOLD
24826       - registered, ringing         AST_DEVICE_RINGING
24827 
24828    For peers without call limit:
24829       - not registered        AST_DEVICE_UNAVAILABLE
24830       - registered            AST_DEVICE_NOT_INUSE
24831       - fixed IP (!dynamic)         AST_DEVICE_NOT_INUSE
24832    
24833    Peers that does not have a known call and can't be reached by OPTIONS
24834       - unreachable           AST_DEVICE_UNAVAILABLE
24835 
24836    If we return AST_DEVICE_UNKNOWN, the device state engine will try to find
24837    out a state by walking the channel list.
24838 
24839    The queue system (\ref app_queue.c) treats a member as "active"
24840    if devicestate is != AST_DEVICE_UNAVAILBALE && != AST_DEVICE_INVALID
24841 
24842    When placing a call to the queue member, queue system sets a member to busy if
24843    != AST_DEVICE_NOT_INUSE and != AST_DEVICE_UNKNOWN
24844 
24845 */
24846 static int sip_devicestate(void *data)
24847 {
24848    char *host;
24849    char *tmp;
24850    struct sip_peer *p;
24851 
24852    int res = AST_DEVICE_INVALID;
24853 
24854    /* make sure data is not null. Maybe unnecessary, but better be safe */
24855    host = ast_strdupa(data ? data : "");
24856    if ((tmp = strchr(host, '@')))
24857       host = tmp + 1;
24858 
24859    ast_debug(3, "Checking device state for peer %s\n", host);
24860 
24861    /* If find_peer asks for a realtime peer, then this breaks rtautoclear.  This
24862     * is because when a peer tries to autoexpire, the last thing it does is to
24863     * queue up an event telling the system that the devicestate has changed
24864     * (presumably to unavailable).  If we ask for a realtime peer here, this would
24865     * load it BACK into memory, thus defeating the point of trying to clear dead
24866     * hosts out of memory.
24867     */
24868    if ((p = find_peer(host, NULL, FALSE, FINDALLDEVICES, TRUE, 0))) {
24869       if (!(ast_sockaddr_isnull(&p->addr) && ast_sockaddr_isnull(&p->defaddr))) {
24870          /* we have an address for the peer */
24871       
24872          /* Check status in this order
24873             - Hold
24874             - Ringing
24875             - Busy (enforced only by call limit)
24876             - Inuse (we have a call)
24877             - Unreachable (qualify)
24878             If we don't find any of these state, report AST_DEVICE_NOT_INUSE
24879             for registered devices */
24880 
24881          if (p->onHold)
24882             /* First check for hold or ring states */
24883             res = AST_DEVICE_ONHOLD;
24884          else if (p->inRinging) {
24885             if (p->inRinging == p->inUse)
24886                res = AST_DEVICE_RINGING;
24887             else
24888                res = AST_DEVICE_RINGINUSE;
24889          } else if (p->call_limit && (p->inUse == p->call_limit))
24890             /* check call limit */
24891             res = AST_DEVICE_BUSY;
24892          else if (p->call_limit && p->busy_level && p->inUse >= p->busy_level)
24893             /* We're forcing busy before we've reached the call limit */
24894             res = AST_DEVICE_BUSY;
24895          else if (p->call_limit && p->inUse)
24896             /* Not busy, but we do have a call */
24897             res = AST_DEVICE_INUSE;
24898          else if (p->maxms && ((p->lastms > p->maxms) || (p->lastms < 0)))
24899             /* We don't have a call. Are we reachable at all? Requires qualify= */
24900             res = AST_DEVICE_UNAVAILABLE;
24901          else  /* Default reply if we're registered and have no other data */
24902             res = AST_DEVICE_NOT_INUSE;
24903       } else {
24904          /* there is no address, it's unavailable */
24905          res = AST_DEVICE_UNAVAILABLE;
24906       }
24907       unref_peer(p, "unref_peer, from sip_devicestate, release ref from find_peer");
24908    } else {
24909       res = AST_DEVICE_UNKNOWN;
24910    }
24911 
24912    return res;
24913 }
24914 
24915 /*! \brief PBX interface function -build SIP pvt structure
24916  * SIP calls initiated by the PBX arrive here.
24917  *
24918  * \verbatim   
24919  *    SIP Dial string syntax
24920  *    SIP/exten@host!dnid
24921  * or SIP/host/exten!dnid
24922  * or SIP/host!dnid
24923  * \endverbatim
24924 */
24925 static struct ast_channel *sip_request_call(const char *type, format_t format, const struct ast_channel *requestor, void *data, int *cause)
24926 {
24927    struct sip_pvt *p;
24928    struct ast_channel *tmpc = NULL;
24929    char *ext = NULL, *host;
24930    char tmp[256];
24931    char *dest = data;
24932    char *dnid;
24933    char *secret = NULL;
24934    char *md5secret = NULL;
24935    char *authname = NULL;
24936    char *trans = NULL;
24937    char dialstring[256];
24938    char *remote_address;
24939    enum sip_transport transport = 0;
24940    struct ast_sockaddr remote_address_sa = { {0,} };
24941    format_t oldformat = format;
24942    AST_DECLARE_APP_ARGS(args,
24943       AST_APP_ARG(peerorhost);
24944       AST_APP_ARG(exten);
24945       AST_APP_ARG(remote_address);
24946    );
24947 
24948    /* mask request with some set of allowed formats.
24949     * XXX this needs to be fixed.
24950     * The original code uses AST_FORMAT_AUDIO_MASK, but it is
24951     * unclear what to use here. We have global_capabilities, which is
24952     * configured from sip.conf, and sip_tech.capabilities, which is
24953     * hardwired to all audio formats.
24954     */
24955    format &= AST_FORMAT_AUDIO_MASK;
24956    if (!format) {
24957       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));
24958       *cause = AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;   /* Can't find codec to connect to host */
24959       return NULL;
24960    }
24961    ast_debug(1, "Asked to create a SIP channel with formats: %s\n", ast_getformatname_multiple(tmp, sizeof(tmp), oldformat));
24962 
24963    if (!(p = sip_alloc(NULL, NULL, 0, SIP_INVITE, NULL))) {
24964       ast_log(LOG_ERROR, "Unable to build sip pvt data for '%s' (Out of memory or socket error)\n", dest);
24965       *cause = AST_CAUSE_SWITCH_CONGESTION;
24966       return NULL;
24967    }
24968 
24969    p->outgoing_call = TRUE;
24970 
24971    snprintf(dialstring, sizeof(dialstring), "%s/%s", type, dest);
24972    ast_string_field_set(p, dialstring, dialstring);
24973 
24974    if (!(p->options = ast_calloc(1, sizeof(*p->options)))) {
24975       dialog_unlink_all(p, TRUE, TRUE);
24976       dialog_unref(p, "unref dialog p from mem fail");
24977       /* sip_destroy(p); */
24978       ast_log(LOG_ERROR, "Unable to build option SIP data structure - Out of memory\n");
24979       *cause = AST_CAUSE_SWITCH_CONGESTION;
24980       return NULL;
24981    }
24982 
24983    /* Save the destination, the SIP dial string */
24984    ast_copy_string(tmp, dest, sizeof(tmp));
24985 
24986    /* Find DNID and take it away */
24987    dnid = strchr(tmp, '!');
24988    if (dnid != NULL) {
24989       *dnid++ = '\0';
24990       ast_string_field_set(p, todnid, dnid);
24991    }
24992 
24993    /* Divvy up the items separated by slashes */
24994    AST_NONSTANDARD_APP_ARGS(args, tmp, '/');
24995 
24996    /* Find at sign - @ */
24997    host = strchr(args.peerorhost, '@');
24998    if (host) {
24999       *host++ = '\0';
25000       ext = args.peerorhost;
25001       secret = strchr(ext, ':');
25002    }
25003    if (secret) {
25004       *secret++ = '\0';
25005       md5secret = strchr(secret, ':');
25006    }
25007    if (md5secret) {
25008       *md5secret++ = '\0';
25009       authname = strchr(md5secret, ':');
25010    }
25011    if (authname) {
25012       *authname++ = '\0';
25013       trans = strchr(authname, ':');
25014    }
25015    if (trans) {
25016       *trans++ = '\0';
25017       if (!strcasecmp(trans, "tcp"))
25018          transport = SIP_TRANSPORT_TCP;
25019       else if (!strcasecmp(trans, "tls"))
25020          transport = SIP_TRANSPORT_TLS;
25021       else {
25022          if (strcasecmp(trans, "udp"))
25023             ast_log(LOG_WARNING, "'%s' is not a valid transport option to Dial() for SIP calls, using udp by default.\n", trans);
25024          transport = SIP_TRANSPORT_UDP;
25025       }
25026    } else { /* use default */
25027       transport = SIP_TRANSPORT_UDP;
25028    }
25029 
25030    if (!host) {
25031       ext = args.exten;
25032       host = args.peerorhost;
25033       remote_address = args.remote_address;
25034    } else {
25035       remote_address = args.remote_address;
25036       if (!ast_strlen_zero(args.exten)) {
25037          ast_log(LOG_NOTICE, "Conflicting extension values given. Using '%s' and not '%s'\n", ext, args.exten);
25038       }
25039    }
25040 
25041    if (!ast_strlen_zero(remote_address)) {
25042       if (ast_sockaddr_resolve_first(&remote_address_sa, remote_address, 0)) {
25043          ast_log(LOG_WARNING, "Unable to find IP address for host %s. We will not use this remote IP address\n", remote_address);
25044       } else {
25045          if (!ast_sockaddr_port(&remote_address_sa)) {
25046             ast_sockaddr_set_port(&remote_address_sa,
25047                         transport & SIP_TRANSPORT_TLS ?
25048                         STANDARD_TLS_PORT :
25049                         STANDARD_SIP_PORT);
25050          }
25051       }
25052    }
25053 
25054    set_socket_transport(&p->socket, transport);
25055 
25056    /* We now have
25057       host = peer name, DNS host name or DNS domain (for SRV)
25058       ext = extension (user part of URI)
25059       dnid = destination of the call (applies to the To: header)
25060    */
25061    if (create_addr(p, host, NULL, 1, &remote_address_sa)) {
25062       *cause = AST_CAUSE_UNREGISTERED;
25063       ast_debug(3, "Cant create SIP call - target device not registered\n");
25064       dialog_unlink_all(p, TRUE, TRUE);
25065       dialog_unref(p, "unref dialog p UNREGISTERED");
25066       /* sip_destroy(p); */
25067       return NULL;
25068    }
25069    if (ast_strlen_zero(p->peername) && ext)
25070       ast_string_field_set(p, peername, ext);
25071    /* Recalculate our side, and recalculate Call ID */
25072    ast_sip_ouraddrfor(&p->sa, &p->ourip, p);
25073    build_via(p);
25074    ao2_t_unlink(dialogs, p, "About to change the callid -- remove the old name");
25075    build_callid_pvt(p);
25076    ao2_t_link(dialogs, p, "Linking in under new name");
25077    
25078    /* We have an extension to call, don't use the full contact here */
25079    /* This to enable dialing registered peers with extension dialling,
25080       like SIP/peername/extension   
25081       SIP/peername will still use the full contact
25082     */
25083    if (ext) {
25084       ast_string_field_set(p, username, ext);
25085       ast_string_field_set(p, fullcontact, NULL);
25086    }
25087    if (secret && !ast_strlen_zero(secret))
25088       ast_string_field_set(p, peersecret, secret);
25089 
25090    if (md5secret && !ast_strlen_zero(md5secret))
25091       ast_string_field_set(p, peermd5secret, md5secret);
25092 
25093    if (authname && !ast_strlen_zero(authname))
25094       ast_string_field_set(p, authname, authname);
25095 #if 0
25096    printf("Setting up to call extension '%s' at '%s'\n", ext ? ext : "<none>", host);
25097 #endif
25098    p->prefcodec = oldformat;           /* Format for this call */
25099    p->jointcapability = oldformat & p->capability;
25100    sip_pvt_lock(p);
25101    tmpc = sip_new(p, AST_STATE_DOWN, host, requestor ? requestor->linkedid : NULL); /* Place the call */
25102    if (sip_cfg.callevents)
25103       manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
25104          "Channel: %s\r\nChanneltype: %s\r\nSIPcallid: %s\r\nSIPfullcontact: %s\r\nPeername: %s\r\n",
25105          p->owner? p->owner->name : "", "SIP", p->callid, p->fullcontact, p->peername);
25106    sip_pvt_unlock(p);
25107    if (!tmpc) {
25108       dialog_unlink_all(p, TRUE, TRUE);
25109       /* sip_destroy(p); */
25110    }
25111    dialog_unref(p, "toss pvt ptr at end of sip_request_call");
25112    ast_update_use_count();
25113    restart_monitor();
25114    return tmpc;
25115 }
25116 
25117 /*! \brief Parse insecure= setting in sip.conf and set flags according to setting */
25118 static void set_insecure_flags (struct ast_flags *flags, const char *value, int lineno)
25119 {
25120    if (ast_strlen_zero(value))
25121       return;
25122 
25123    if (!ast_false(value)) {
25124       char buf[64];
25125       char *word, *next;
25126 
25127       ast_copy_string(buf, value, sizeof(buf));
25128       next = buf;
25129       while ((word = strsep(&next, ","))) {
25130          if (!strcasecmp(word, "port"))
25131             ast_set_flag(&flags[0], SIP_INSECURE_PORT);
25132          else if (!strcasecmp(word, "invite"))
25133             ast_set_flag(&flags[0], SIP_INSECURE_INVITE);
25134          else
25135             ast_log(LOG_WARNING, "Unknown insecure mode '%s' on line %d\n", value, lineno);
25136       }
25137    }
25138 }
25139 
25140 /*!
25141   \brief Handle T.38 configuration options common to users and peers
25142   \returns non-zero if any config options were handled, zero otherwise
25143 */
25144 static int handle_t38_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v,
25145                int *maxdatagram)
25146 {
25147    int res = 1;
25148 
25149    if (!strcasecmp(v->name, "t38pt_udptl")) {
25150       char *buf = ast_strdupa(v->value);
25151       char *word, *next = buf;
25152 
25153       ast_set_flag(&mask[1], SIP_PAGE2_T38SUPPORT);
25154 
25155       while ((word = strsep(&next, ","))) {
25156          if (ast_true(word) || !strcasecmp(word, "fec")) {
25157             ast_clear_flag(&flags[1], SIP_PAGE2_T38SUPPORT);
25158             ast_set_flag(&flags[1], SIP_PAGE2_T38SUPPORT_UDPTL_FEC);
25159          } else if (!strcasecmp(word, "redundancy")) {
25160             ast_clear_flag(&flags[1], SIP_PAGE2_T38SUPPORT);
25161             ast_set_flag(&flags[1], SIP_PAGE2_T38SUPPORT_UDPTL_REDUNDANCY);
25162          } else if (!strcasecmp(word, "none")) {
25163             ast_clear_flag(&flags[1], SIP_PAGE2_T38SUPPORT);
25164             ast_set_flag(&flags[1], SIP_PAGE2_T38SUPPORT_UDPTL);
25165          } else if (!strncasecmp(word, "maxdatagram=", 12)) {
25166             if (sscanf(&word[12], "%30u", maxdatagram) != 1) {
25167                ast_log(LOG_WARNING, "Invalid maxdatagram '%s' at line %d of %s\n", v->value, v->lineno, config);
25168                *maxdatagram = global_t38_maxdatagram;
25169             }
25170          }
25171       }
25172    } else if (!strcasecmp(v->name, "t38pt_usertpsource")) {
25173       ast_set_flag(&mask[1], SIP_PAGE2_UDPTL_DESTINATION);
25174       ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_UDPTL_DESTINATION);
25175    } else {
25176       res = 0;
25177    }
25178 
25179    return res;
25180 }
25181 
25182 /*!
25183   \brief Handle flag-type options common to configuration of devices - peers
25184   \param flags array of two struct ast_flags
25185   \param mask array of two struct ast_flags
25186   \param v linked list of config variables to process
25187   \returns non-zero if any config options were handled, zero otherwise
25188 */
25189 static int handle_common_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v)
25190 {
25191    int res = 1;
25192 
25193    if (!strcasecmp(v->name, "trustrpid")) {
25194       ast_set_flag(&mask[0], SIP_TRUSTRPID);
25195       ast_set2_flag(&flags[0], ast_true(v->value), SIP_TRUSTRPID);
25196    } else if (!strcasecmp(v->name, "sendrpid")) {
25197       ast_set_flag(&mask[0], SIP_SENDRPID);
25198       if (!strcasecmp(v->value, "pai")) {
25199          ast_set_flag(&flags[0], SIP_SENDRPID_PAI);
25200       } else if (!strcasecmp(v->value, "rpid")) {
25201          ast_set_flag(&flags[0], SIP_SENDRPID_RPID);
25202       } else if (ast_true(v->value)) {
25203          ast_set_flag(&flags[0], SIP_SENDRPID_RPID);
25204       }
25205    } else if (!strcasecmp(v->name, "rpid_update")) {
25206       ast_set_flag(&mask[1], SIP_PAGE2_RPID_UPDATE);
25207       ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_RPID_UPDATE);
25208    } else if (!strcasecmp(v->name, "rpid_immediate")) {
25209       ast_set_flag(&mask[1], SIP_PAGE2_RPID_IMMEDIATE);
25210       ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_RPID_IMMEDIATE);
25211    } else if (!strcasecmp(v->name, "g726nonstandard")) {
25212       ast_set_flag(&mask[0], SIP_G726_NONSTANDARD);
25213       ast_set2_flag(&flags[0], ast_true(v->value), SIP_G726_NONSTANDARD);
25214    } else if (!strcasecmp(v->name, "useclientcode")) {
25215       ast_set_flag(&mask[0], SIP_USECLIENTCODE);
25216       ast_set2_flag(&flags[0], ast_true(v->value), SIP_USECLIENTCODE);
25217    } else if (!strcasecmp(v->name, "dtmfmode")) {
25218       ast_set_flag(&mask[0], SIP_DTMF);
25219       ast_clear_flag(&flags[0], SIP_DTMF);
25220       if (!strcasecmp(v->value, "inband"))
25221          ast_set_flag(&flags[0], SIP_DTMF_INBAND);
25222       else if (!strcasecmp(v->value, "rfc2833"))
25223          ast_set_flag(&flags[0], SIP_DTMF_RFC2833);
25224       else if (!strcasecmp(v->value, "info"))
25225          ast_set_flag(&flags[0], SIP_DTMF_INFO);
25226       else if (!strcasecmp(v->value, "shortinfo"))
25227          ast_set_flag(&flags[0], SIP_DTMF_SHORTINFO);
25228       else if (!strcasecmp(v->value, "auto"))
25229          ast_set_flag(&flags[0], SIP_DTMF_AUTO);
25230       else {
25231          ast_log(LOG_WARNING, "Unknown dtmf mode '%s' on line %d, using rfc2833\n", v->value, v->lineno);
25232          ast_set_flag(&flags[0], SIP_DTMF_RFC2833);
25233       }
25234    } else if (!strcasecmp(v->name, "nat")) {
25235       ast_set_flag(&mask[0], SIP_NAT_FORCE_RPORT);
25236       if (!strcasecmp(v->value, "no")) {
25237          ast_clear_flag(&flags[0], SIP_NAT_FORCE_RPORT);
25238       } else if (!strcasecmp(v->value, "force_rport")) {
25239          ast_set_flag(&flags[0], SIP_NAT_FORCE_RPORT);
25240       } else if (!strcasecmp(v->value, "yes")) {
25241          ast_set_flag(&flags[0], SIP_NAT_FORCE_RPORT);
25242          ast_set_flag(&mask[1], SIP_PAGE2_SYMMETRICRTP);
25243          ast_set_flag(&flags[1], SIP_PAGE2_SYMMETRICRTP);
25244       } else if (!strcasecmp(v->value, "comedia")) {
25245          ast_clear_flag(&flags[0], SIP_NAT_FORCE_RPORT);
25246          ast_set_flag(&mask[1], SIP_PAGE2_SYMMETRICRTP);
25247          ast_set_flag(&flags[1], SIP_PAGE2_SYMMETRICRTP);
25248       }
25249    } else if (!strcasecmp(v->name, "directmedia") || !strcasecmp(v->name, "canreinvite")) {
25250       ast_set_flag(&mask[0], SIP_REINVITE);
25251       ast_clear_flag(&flags[0], SIP_REINVITE);
25252       if (ast_true(v->value)) {
25253          ast_set_flag(&flags[0], SIP_DIRECT_MEDIA | SIP_DIRECT_MEDIA_NAT);
25254       } else if (!ast_false(v->value)) {
25255          char buf[64];
25256          char *word, *next = buf;
25257 
25258          ast_copy_string(buf, v->value, sizeof(buf));
25259          while ((word = strsep(&next, ","))) {
25260             if (!strcasecmp(word, "update")) {
25261                ast_set_flag(&flags[0], SIP_REINVITE_UPDATE | SIP_DIRECT_MEDIA);
25262             } else if (!strcasecmp(word, "nonat")) {
25263                ast_set_flag(&flags[0], SIP_DIRECT_MEDIA);
25264                ast_clear_flag(&flags[0], SIP_DIRECT_MEDIA_NAT);
25265             } else {
25266                ast_log(LOG_WARNING, "Unknown directmedia mode '%s' on line %d\n", v->value, v->lineno);
25267             }
25268          }
25269       }
25270    } else if (!strcasecmp(v->name, "insecure")) {
25271       ast_set_flag(&mask[0], SIP_INSECURE);
25272       ast_clear_flag(&flags[0], SIP_INSECURE);
25273       set_insecure_flags(&flags[0], v->value, v->lineno);   
25274    } else if (!strcasecmp(v->name, "progressinband")) {
25275       ast_set_flag(&mask[0], SIP_PROG_INBAND);
25276       ast_clear_flag(&flags[0], SIP_PROG_INBAND);
25277       if (ast_true(v->value))
25278          ast_set_flag(&flags[0], SIP_PROG_INBAND_YES);
25279       else if (strcasecmp(v->value, "never"))
25280          ast_set_flag(&flags[0], SIP_PROG_INBAND_NO);
25281    } else if (!strcasecmp(v->name, "promiscredir")) {
25282       ast_set_flag(&mask[0], SIP_PROMISCREDIR);
25283       ast_set2_flag(&flags[0], ast_true(v->value), SIP_PROMISCREDIR);
25284    } else if (!strcasecmp(v->name, "videosupport")) {
25285       if (!strcasecmp(v->value, "always")) {
25286          ast_set_flag(&mask[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS);
25287          ast_set_flag(&flags[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS);
25288       } else {
25289          ast_set_flag(&mask[1], SIP_PAGE2_VIDEOSUPPORT);
25290          ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_VIDEOSUPPORT);
25291       }
25292    } else if (!strcasecmp(v->name, "textsupport")) {
25293       ast_set_flag(&mask[1], SIP_PAGE2_TEXTSUPPORT);
25294       ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_TEXTSUPPORT);
25295       res = 1;
25296    } else if (!strcasecmp(v->name, "allowoverlap")) {
25297       ast_set_flag(&mask[1], SIP_PAGE2_ALLOWOVERLAP);
25298       ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_ALLOWOVERLAP);
25299    } else if (!strcasecmp(v->name, "allowsubscribe")) {
25300       ast_set_flag(&mask[1], SIP_PAGE2_ALLOWSUBSCRIBE);
25301       ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_ALLOWSUBSCRIBE);
25302    } else if (!strcasecmp(v->name, "ignoresdpversion")) {
25303       ast_set_flag(&mask[1], SIP_PAGE2_IGNORESDPVERSION);
25304       ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_IGNORESDPVERSION);
25305    } else if (!strcasecmp(v->name, "faxdetect")) {
25306       ast_set_flag(&mask[1], SIP_PAGE2_FAX_DETECT);
25307       if (ast_true(v->value)) {
25308          ast_set_flag(&flags[1], SIP_PAGE2_FAX_DETECT_BOTH);
25309       } else if (ast_false(v->value)) {
25310          ast_clear_flag(&flags[1], SIP_PAGE2_FAX_DETECT_BOTH);
25311       } else {
25312          char *buf = ast_strdupa(v->value);
25313          char *word, *next = buf;
25314 
25315          while ((word = strsep(&next, ","))) {
25316             if (!strcasecmp(word, "cng")) {
25317                ast_set_flag(&flags[1], SIP_PAGE2_FAX_DETECT_CNG);
25318             } else if (!strcasecmp(word, "t38")) {
25319                ast_set_flag(&flags[1], SIP_PAGE2_FAX_DETECT_T38);
25320             } else {
25321                ast_log(LOG_WARNING, "Unknown faxdetect mode '%s' on line %d.\n", word, v->lineno);
25322             }
25323          }
25324       }
25325    } else if (!strcasecmp(v->name, "rfc2833compensate")) {
25326       ast_set_flag(&mask[1], SIP_PAGE2_RFC2833_COMPENSATE);
25327       ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_RFC2833_COMPENSATE);
25328    } else if (!strcasecmp(v->name, "buggymwi")) {
25329       ast_set_flag(&mask[1], SIP_PAGE2_BUGGY_MWI);
25330       ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_BUGGY_MWI);
25331    } else
25332       res = 0;
25333 
25334    return res;
25335 }
25336 
25337 /*! \brief Add SIP domain to list of domains we are responsible for */
25338 static int add_sip_domain(const char *domain, const enum domain_mode mode, const char *context)
25339 {
25340    struct domain *d;
25341 
25342    if (ast_strlen_zero(domain)) {
25343       ast_log(LOG_WARNING, "Zero length domain.\n");
25344       return 1;
25345    }
25346 
25347    if (!(d = ast_calloc(1, sizeof(*d))))
25348       return 0;
25349 
25350    ast_copy_string(d->domain, domain, sizeof(d->domain));
25351 
25352    if (!ast_strlen_zero(context))
25353       ast_copy_string(d->context, context, sizeof(d->context));
25354 
25355    d->mode = mode;
25356 
25357    AST_LIST_LOCK(&domain_list);
25358    AST_LIST_INSERT_TAIL(&domain_list, d, list);
25359    AST_LIST_UNLOCK(&domain_list);
25360 
25361    if (sipdebug)  
25362       ast_debug(1, "Added local SIP domain '%s'\n", domain);
25363 
25364    return 1;
25365 }
25366 
25367 /*! \brief  check_sip_domain: Check if domain part of uri is local to our server */
25368 static int check_sip_domain(const char *domain, char *context, size_t len)
25369 {
25370    struct domain *d;
25371    int result = 0;
25372 
25373    AST_LIST_LOCK(&domain_list);
25374    AST_LIST_TRAVERSE(&domain_list, d, list) {
25375       if (strcasecmp(d->domain, domain))
25376          continue;
25377 
25378       if (len && !ast_strlen_zero(d->context))
25379          ast_copy_string(context, d->context, len);
25380       
25381       result = 1;
25382       break;
25383    }
25384    AST_LIST_UNLOCK(&domain_list);
25385 
25386    return result;
25387 }
25388 
25389 /*! \brief Clear our domain list (at reload) */
25390 static void clear_sip_domains(void)
25391 {
25392    struct domain *d;
25393 
25394    AST_LIST_LOCK(&domain_list);
25395    while ((d = AST_LIST_REMOVE_HEAD(&domain_list, list)))
25396       ast_free(d);
25397    AST_LIST_UNLOCK(&domain_list);
25398 }
25399 
25400 
25401 /*! \brief Add realm authentication in list */
25402 static struct sip_auth *add_realm_authentication(struct sip_auth *authlist, const char *configuration, int lineno)
25403 {
25404    char authcopy[256];
25405    char *username=NULL, *realm=NULL, *secret=NULL, *md5secret=NULL;
25406    struct sip_auth *a, *b, *auth;
25407 
25408    if (ast_strlen_zero(configuration))
25409       return authlist;
25410 
25411    ast_debug(1, "Auth config ::  %s\n", configuration);
25412 
25413    ast_copy_string(authcopy, configuration, sizeof(authcopy));
25414    username = authcopy;
25415 
25416    /* split user[:secret] and relm */
25417    realm = strrchr(username, '@');
25418    if (realm)
25419       *realm++ = '\0';
25420    if (ast_strlen_zero(username) || ast_strlen_zero(realm)) {
25421       ast_log(LOG_WARNING, "Format for authentication entry is user[:secret]@realm at line %d\n", lineno);
25422       return authlist;
25423    }
25424 
25425    /* parse username at ':' for secret, or '#" for md5secret */
25426    if ((secret = strchr(username, ':'))) {
25427       *secret++ = '\0';
25428    } else if ((md5secret = strchr(username, '#'))) {
25429       *md5secret++ = '\0';
25430    }
25431 
25432    if (!(auth = ast_calloc(1, sizeof(*auth))))
25433       return authlist;
25434 
25435    ast_copy_string(auth->realm, realm, sizeof(auth->realm));
25436    ast_copy_string(auth->username, username, sizeof(auth->username));
25437    if (secret)
25438       ast_copy_string(auth->secret, secret, sizeof(auth->secret));
25439    if (md5secret)
25440       ast_copy_string(auth->md5secret, md5secret, sizeof(auth->md5secret));
25441 
25442    /* find the end of the list */
25443    for (b = NULL, a = authlist; a ; b = a, a = a->next)
25444       ;
25445    if (b)
25446       b->next = auth;   /* Add structure add end of list */
25447    else
25448       authlist = auth;
25449 
25450    ast_verb(3, "Added authentication for realm %s\n", realm);
25451 
25452    return authlist;
25453 
25454 }
25455 
25456 /*! \brief Clear realm authentication list (at reload) */
25457 static int clear_realm_authentication(struct sip_auth *authlist)
25458 {
25459    struct sip_auth *a = authlist;
25460    struct sip_auth *b;
25461 
25462    while (a) {
25463       b = a;
25464       a = a->next;
25465       ast_free(b);
25466    }
25467 
25468    return 1;
25469 }
25470 
25471 /*! \brief Find authentication for a specific realm */
25472 static struct sip_auth *find_realm_authentication(struct sip_auth *authlist, const char *realm)
25473 {
25474    struct sip_auth *a;
25475 
25476    for (a = authlist; a; a = a->next) {
25477       if (!strcasecmp(a->realm, realm))
25478          break;
25479    }
25480 
25481    return a;
25482 }
25483 
25484 /*! \brief
25485  * implement the setvar config line
25486  */
25487 static struct ast_variable *add_var(const char *buf, struct ast_variable *list)
25488 {
25489    struct ast_variable *tmpvar = NULL;
25490    char *varname = ast_strdupa(buf), *varval = NULL;
25491    
25492    if ((varval = strchr(varname, '='))) {
25493       *varval++ = '\0';
25494       if ((tmpvar = ast_variable_new(varname, varval, ""))) {
25495          tmpvar->next = list;
25496          list = tmpvar;
25497       }
25498    }
25499    return list;
25500 }
25501 
25502 /*! \brief Set peer defaults before configuring specific configurations */
25503 static void set_peer_defaults(struct sip_peer *peer)
25504 {
25505    if (peer->expire == 0) {
25506       /* Don't reset expire or port time during reload
25507          if we have an active registration
25508       */
25509       peer->expire = -1;
25510       peer->pokeexpire = -1;
25511       set_socket_transport(&peer->socket, SIP_TRANSPORT_UDP);
25512    }
25513    peer->type = SIP_TYPE_PEER;
25514    ast_copy_flags(&peer->flags[0], &global_flags[0], SIP_FLAGS_TO_COPY);
25515    ast_copy_flags(&peer->flags[1], &global_flags[1], SIP_PAGE2_FLAGS_TO_COPY);
25516    ast_copy_flags(&peer->flags[2], &global_flags[2], SIP_PAGE3_FLAGS_TO_COPY);
25517    ast_string_field_set(peer, context, sip_cfg.default_context);
25518    ast_string_field_set(peer, subscribecontext, sip_cfg.default_subscribecontext);
25519    ast_string_field_set(peer, language, default_language);
25520    ast_string_field_set(peer, mohinterpret, default_mohinterpret);
25521    ast_string_field_set(peer, mohsuggest, default_mohsuggest);
25522    ast_string_field_set(peer, engine, default_engine);
25523    ast_sockaddr_setnull(&peer->addr);
25524    ast_sockaddr_setnull(&peer->defaddr);
25525    peer->capability = sip_cfg.capability;
25526    peer->maxcallbitrate = default_maxcallbitrate;
25527    peer->rtptimeout = global_rtptimeout;
25528    peer->rtpholdtimeout = global_rtpholdtimeout;
25529    peer->rtpkeepalive = global_rtpkeepalive;
25530    peer->allowtransfer = sip_cfg.allowtransfer;
25531    peer->autoframing = global_autoframing;
25532    peer->t38_maxdatagram = global_t38_maxdatagram;
25533    peer->qualifyfreq = global_qualifyfreq;
25534    if (global_callcounter)
25535       peer->call_limit=INT_MAX;
25536    ast_string_field_set(peer, vmexten, default_vmexten);
25537    ast_string_field_set(peer, secret, "");
25538    ast_string_field_set(peer, remotesecret, "");
25539    ast_string_field_set(peer, md5secret, "");
25540    ast_string_field_set(peer, cid_num, "");
25541    ast_string_field_set(peer, cid_name, "");
25542    ast_string_field_set(peer, cid_tag, "");
25543    ast_string_field_set(peer, fromdomain, "");
25544    ast_string_field_set(peer, fromuser, "");
25545    ast_string_field_set(peer, regexten, "");
25546    peer->callgroup = 0;
25547    peer->pickupgroup = 0;
25548    peer->maxms = default_qualify;
25549    peer->prefs = default_prefs;
25550    peer->stimer.st_mode_oper = global_st_mode;  /* Session-Timers */
25551    peer->stimer.st_ref = global_st_refresher;
25552    peer->stimer.st_min_se = global_min_se;
25553    peer->stimer.st_max_se = global_max_se;
25554    peer->timer_t1 = global_t1;
25555    peer->timer_b = global_timer_b;
25556    clear_peer_mailboxes(peer);
25557    peer->disallowed_methods = sip_cfg.disallowed_methods;
25558    peer->transports = default_transports;
25559    peer->default_outbound_transport = default_primary_transport;
25560 }
25561 
25562 /*! \brief Create temporary peer (used in autocreatepeer mode) */
25563 static struct sip_peer *temp_peer(const char *name)
25564 {
25565    struct sip_peer *peer;
25566 
25567    if (!(peer = ao2_t_alloc(sizeof(*peer), sip_destroy_peer_fn, "allocate a peer struct")))
25568       return NULL;
25569 
25570    if (ast_string_field_init(peer, 512)) {
25571       ao2_t_ref(peer, -1, "failed to string_field_init, drop peer");
25572       return NULL;
25573    }
25574 
25575    ast_atomic_fetchadd_int(&apeerobjs, 1);
25576    set_peer_defaults(peer);
25577 
25578    ast_copy_string(peer->name, name, sizeof(peer->name));
25579 
25580    peer->selfdestruct = TRUE;
25581    peer->host_dynamic = TRUE;
25582    peer->prefs = default_prefs;
25583    reg_source_db(peer);
25584 
25585    return peer;
25586 }
25587 
25588 /*! \todo document this function */
25589 static void add_peer_mailboxes(struct sip_peer *peer, const char *value)
25590 {
25591    char *next, *mbox, *context;
25592 
25593    next = ast_strdupa(value);
25594 
25595    while ((mbox = context = strsep(&next, ","))) {
25596       struct sip_mailbox *mailbox;
25597       int duplicate = 0;
25598 
25599       strsep(&context, "@");
25600 
25601       if (ast_strlen_zero(mbox)) {
25602          continue;
25603       }
25604 
25605       /* Check whether the mailbox is already in the list */
25606       AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
25607          if (!strcmp(mailbox->mailbox, mbox) && !strcmp(S_OR(mailbox->context, ""), S_OR(context, ""))) {
25608             duplicate = 1;
25609             mailbox->delme = 0;
25610             break;
25611          }
25612       }
25613       if (duplicate) {
25614          continue;
25615       }
25616 
25617       if (!(mailbox = ast_calloc(1, sizeof(*mailbox) + strlen(mbox) + strlen(S_OR(context, ""))))) {
25618          continue;
25619       }
25620 
25621       if (!ast_strlen_zero(context)) {
25622          mailbox->context = mailbox->mailbox + strlen(mbox) + 1;
25623          strcpy(mailbox->context, context); /* SAFE */
25624       }
25625       strcpy(mailbox->mailbox, mbox); /* SAFE */
25626 
25627       AST_LIST_INSERT_TAIL(&peer->mailboxes, mailbox, entry);
25628    }
25629 }
25630 
25631 /*! \brief Build peer from configuration (file or realtime static/dynamic) */
25632 static struct sip_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime, int devstate_only)
25633 {
25634    struct sip_peer *peer = NULL;
25635    struct ast_ha *oldha = NULL;
25636    struct ast_ha *olddirectmediaha = NULL;
25637    int found = 0;
25638    int firstpass = 1;
25639    uint16_t port = 0;
25640    int format = 0;      /* Ama flags */
25641    int timerb_set = 0, timert1_set = 0;
25642    time_t regseconds = 0;
25643    struct ast_flags peerflags[3] = {{(0)}};
25644    struct ast_flags mask[3] = {{(0)}};
25645    char callback[256] = "";
25646    struct sip_peer tmp_peer;
25647    const char *srvlookup = NULL;
25648    static int deprecation_warning = 1;
25649    int alt_fullcontact = alt ? 1 : 0, headercount = 0;
25650    struct ast_str *fullcontact = ast_str_alloca(512);
25651 
25652    if (!realtime || ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
25653       /* Note we do NOT use find_peer here, to avoid realtime recursion */
25654       /* We also use a case-sensitive comparison (unlike find_peer) so
25655          that case changes made to the peer name will be properly handled
25656          during reload
25657       */
25658       ast_copy_string(tmp_peer.name, name, sizeof(tmp_peer.name));
25659       peer = ao2_t_find(peers, &tmp_peer, OBJ_POINTER | OBJ_UNLINK, "find and unlink peer from peers table");
25660    }
25661 
25662    if (peer) {
25663       /* Already in the list, remove it and it will be added back (or FREE'd)  */
25664       found++;
25665       if (!(peer->the_mark))
25666          firstpass = 0;
25667    } else {
25668       if (!(peer = ao2_t_alloc(sizeof(*peer), sip_destroy_peer_fn, "allocate a peer struct")))
25669          return NULL;
25670 
25671       if (ast_string_field_init(peer, 512)) {
25672          ao2_t_ref(peer, -1, "failed to string_field_init, drop peer");
25673          return NULL;
25674       }
25675 
25676       if (!(peer->cc_params = ast_cc_config_params_init())) {
25677          ao2_t_ref(peer, -1, "failed to allocate cc_params for peer");
25678          return NULL;
25679       }
25680 
25681       if (realtime && !ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
25682          ast_atomic_fetchadd_int(&rpeerobjs, 1);
25683          ast_debug(3, "-REALTIME- peer built. Name: %s. Peer objects: %d\n", name, rpeerobjs);
25684       } else
25685          ast_atomic_fetchadd_int(&speerobjs, 1);
25686    }
25687 
25688    /* Note that our peer HAS had its reference count increased */
25689    if (firstpass) {
25690       peer->lastmsgssent = -1;
25691       oldha = peer->ha;
25692       peer->ha = NULL;
25693       olddirectmediaha = peer->directmediaha;
25694       peer->directmediaha = NULL;
25695       set_peer_defaults(peer);   /* Set peer defaults */
25696       peer->type = 0;
25697    }
25698    if (!found && name)
25699       ast_copy_string(peer->name, name, sizeof(peer->name));
25700 
25701    /* If we have channel variables, remove them (reload) */
25702    if (peer->chanvars) {
25703       ast_variables_destroy(peer->chanvars);
25704       peer->chanvars = NULL;
25705       /* XXX should unregister ? */
25706    }
25707 
25708    if (found)
25709       peer->portinuri = 0;
25710 
25711    /* If we have realm authentication information, remove them (reload) */
25712    clear_realm_authentication(peer->auth);
25713    peer->auth = NULL;
25714    /* clear the transport information.  We will detect if a default value is required after parsing the config */
25715    peer->default_outbound_transport = 0;
25716    peer->transports = 0;
25717 
25718    if (!devstate_only) {
25719       struct sip_mailbox *mailbox;
25720       AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
25721          mailbox->delme = 1;
25722       }
25723    }
25724 
25725    for (; v || ((v = alt) && !(alt=NULL)); v = v->next) {
25726       if (!devstate_only) {
25727          if (handle_common_options(&peerflags[0], &mask[0], v)) {
25728             continue;
25729          }
25730          if (handle_t38_options(&peerflags[0], &mask[0], v, &peer->t38_maxdatagram)) {
25731             continue;
25732          }
25733          if (!strcasecmp(v->name, "transport") && !ast_strlen_zero(v->value)) {
25734             char *val = ast_strdupa(v->value);
25735             char *trans;
25736 
25737             while ((trans = strsep(&val, ","))) {
25738                trans = ast_skip_blanks(trans);
25739 
25740                if (!strncasecmp(trans, "udp", 3)) {
25741                   peer->transports |= SIP_TRANSPORT_UDP;
25742                } else if (!strncasecmp(trans, "tcp", 3)) {
25743                   peer->transports |= SIP_TRANSPORT_TCP;
25744                } else if (!strncasecmp(trans, "tls", 3)) {
25745                   peer->transports |= SIP_TRANSPORT_TLS;
25746                } else {
25747                   ast_log(LOG_NOTICE, "'%s' is not a valid transport type. if no other is specified, udp will be used.\n", trans);
25748                }
25749 
25750                if (!peer->default_outbound_transport) { /*!< The first transport listed should be default outbound */
25751                   peer->default_outbound_transport = peer->transports;
25752                }
25753             }
25754          } else if (realtime && !strcasecmp(v->name, "regseconds")) {
25755             ast_get_time_t(v->value, &regseconds, 0, NULL);
25756          } else if (realtime && !strcasecmp(v->name, "name")) {
25757             ast_copy_string(peer->name, v->value, sizeof(peer->name));
25758          } else if (realtime && !strcasecmp(v->name, "useragent")) {
25759             ast_string_field_set(peer, useragent, v->value);
25760          } else if (!strcasecmp(v->name, "type")) {
25761             if (!strcasecmp(v->value, "peer")) {
25762                peer->type |= SIP_TYPE_PEER;
25763             } else if (!strcasecmp(v->value, "user")) {
25764                peer->type |= SIP_TYPE_USER;
25765             } else if (!strcasecmp(v->value, "friend")) {
25766                peer->type = SIP_TYPE_USER | SIP_TYPE_PEER;
25767             }
25768          } else if (!strcasecmp(v->name, "remotesecret")) {
25769             ast_string_field_set(peer, remotesecret, v->value);
25770          } else if (!strcasecmp(v->name, "secret")) {
25771             ast_string_field_set(peer, secret, v->value);
25772          } else if (!strcasecmp(v->name, "md5secret")) {
25773             ast_string_field_set(peer, md5secret, v->value);
25774          } else if (!strcasecmp(v->name, "auth")) {
25775             peer->auth = add_realm_authentication(peer->auth, v->value, v->lineno);
25776          } else if (!strcasecmp(v->name, "callerid")) {
25777             char cid_name[80] = { '\0' }, cid_num[80] = { '\0' };
25778 
25779             ast_callerid_split(v->value, cid_name, sizeof(cid_name), cid_num, sizeof(cid_num));
25780             ast_string_field_set(peer, cid_name, cid_name);
25781             ast_string_field_set(peer, cid_num, cid_num);
25782          } else if (!strcasecmp(v->name, "mwi_from")) {
25783             ast_string_field_set(peer, mwi_from, v->value);
25784          } else if (!strcasecmp(v->name, "fullname")) {
25785             ast_string_field_set(peer, cid_name, v->value);
25786          } else if (!strcasecmp(v->name, "trunkname")) {
25787             /* This is actually for a trunk, so we don't want to override callerid */
25788             ast_string_field_set(peer, cid_name, "");
25789          } else if (!strcasecmp(v->name, "cid_number")) {
25790             ast_string_field_set(peer, cid_num, v->value);
25791          } else if (!strcasecmp(v->name, "cid_tag")) {
25792             ast_string_field_set(peer, cid_tag, v->value);
25793          } else if (!strcasecmp(v->name, "context")) {
25794             ast_string_field_set(peer, context, v->value);
25795             ast_set_flag(&peer->flags[1], SIP_PAGE2_HAVEPEERCONTEXT);
25796          } else if (!strcasecmp(v->name, "subscribecontext")) {
25797             ast_string_field_set(peer, subscribecontext, v->value);
25798          } else if (!strcasecmp(v->name, "fromdomain")) {
25799             char *fromdomainport;
25800             ast_string_field_set(peer, fromdomain, v->value);
25801             if ((fromdomainport = strchr(peer->fromdomain, ':'))) {
25802                *fromdomainport++ = '\0';
25803                if (!(peer->fromdomainport = port_str2int(fromdomainport, 0))) {
25804                   ast_log(LOG_NOTICE, "'%s' is not a valid port number for fromdomain.\n",fromdomainport);
25805                }
25806             } else {
25807                peer->fromdomainport = STANDARD_SIP_PORT;
25808             }
25809          } else if (!strcasecmp(v->name, "usereqphone")) {
25810             ast_set2_flag(&peer->flags[0], ast_true(v->value), SIP_USEREQPHONE);
25811          } else if (!strcasecmp(v->name, "fromuser")) {
25812             ast_string_field_set(peer, fromuser, v->value);
25813          } else if (!strcasecmp(v->name, "outboundproxy")) {
25814             char *tok, *proxyname;
25815 
25816             if (ast_strlen_zero(v->value)) {
25817                ast_log(LOG_WARNING, "no value given for outbound proxy on line %d of sip.conf.", v->lineno);
25818                continue;
25819             }
25820 
25821             peer->outboundproxy =
25822                 ao2_alloc(sizeof(*peer->outboundproxy), NULL);
25823 
25824             tok = ast_skip_blanks(strtok(ast_strdupa(v->value), ","));
25825 
25826             sip_parse_host(tok, v->lineno, &proxyname,
25827                       &peer->outboundproxy->port,
25828                       &peer->outboundproxy->transport);
25829 
25830             tok = ast_skip_blanks(strtok(ast_strdupa(v->value), ","));
25831 
25832             if ((tok = strtok(NULL, ","))) {
25833                peer->outboundproxy->force = !strncasecmp(ast_skip_blanks(tok), "force", 5);
25834             } else {
25835                peer->outboundproxy->force = FALSE;
25836             }
25837 
25838             if (ast_strlen_zero(proxyname)) {
25839                ast_log(LOG_WARNING, "you must specify a name for the outboundproxy on line %d of sip.conf.", v->lineno);
25840                sip_cfg.outboundproxy.name[0] = '\0';
25841                continue;
25842             }
25843 
25844             ast_copy_string(peer->outboundproxy->name, proxyname, sizeof(peer->outboundproxy->name));
25845 
25846             proxy_update(peer->outboundproxy);
25847          } else if (!strcasecmp(v->name, "host")) {
25848             if (!strcasecmp(v->value, "dynamic")) {
25849                /* They'll register with us */
25850                if (!found || !peer->host_dynamic) {
25851                   /* Initialize stuff if this is a new peer, or if it used to
25852                    * not be dynamic before the reload. */
25853                   ast_sockaddr_setnull(&peer->addr);
25854                }
25855                peer->host_dynamic = TRUE;
25856             } else {
25857                /* Non-dynamic.  Make sure we become that way if we're not */
25858                AST_SCHED_DEL_UNREF(sched, peer->expire,
25859                      unref_peer(peer, "removing register expire ref"));
25860                peer->host_dynamic = FALSE;
25861                srvlookup = v->value;
25862             }
25863          } else if (!strcasecmp(v->name, "defaultip")) {
25864             if (!ast_strlen_zero(v->value) && ast_get_ip(&peer->defaddr, v->value)) {
25865                unref_peer(peer, "unref_peer: from build_peer defaultip");
25866                return NULL;
25867             }
25868          } else if (!strcasecmp(v->name, "permit") || !strcasecmp(v->name, "deny")) {
25869             int ha_error = 0;
25870             if (!ast_strlen_zero(v->value)) {
25871                peer->ha = ast_append_ha(v->name, v->value, peer->ha, &ha_error);
25872             }
25873             if (ha_error) {
25874                ast_log(LOG_ERROR, "Bad ACL entry in configuration line %d : %s\n", v->lineno, v->value);
25875             }
25876          } else if (!strcasecmp(v->name, "contactpermit") || !strcasecmp(v->name, "contactdeny")) {
25877             int ha_error = 0;
25878             if (!ast_strlen_zero(v->value)) {
25879                peer->contactha = ast_append_ha(v->name + 7, v->value, peer->contactha, &ha_error);
25880             }
25881             if (ha_error) {
25882                ast_log(LOG_ERROR, "Bad ACL entry in configuration line %d : %s\n", v->lineno, v->value);
25883             }
25884          } else if (!strcasecmp(v->name, "directmediapermit") || !strcasecmp(v->name, "directmediadeny")) {
25885             int ha_error = 0;
25886             peer->directmediaha = ast_append_ha(v->name + 11, v->value, peer->directmediaha, &ha_error);
25887             if (ha_error) {
25888                ast_log(LOG_ERROR, "Bad directmedia ACL entry in configuration line %d : %s\n", v->lineno, v->value);
25889             }
25890          } else if (!strcasecmp(v->name, "port")) {
25891             peer->portinuri = 1;
25892             if (!(port = port_str2int(v->value, 0))) {
25893                if (realtime) {
25894                   /* If stored as integer, could be 0 for some DBs (notably MySQL) */
25895                   peer->portinuri = 0;
25896                } else {
25897                   ast_log(LOG_WARNING, "Invalid peer port configuration at line %d : %s\n", v->lineno, v->value);
25898                }
25899             }
25900          } else if (!strcasecmp(v->name, "callingpres")) {
25901             peer->callingpres = ast_parse_caller_presentation(v->value);
25902             if (peer->callingpres == -1) {
25903                peer->callingpres = atoi(v->value);
25904             }
25905          } else if (!strcasecmp(v->name, "username") || !strcmp(v->name, "defaultuser")) {   /* "username" is deprecated */
25906             ast_string_field_set(peer, username, v->value);
25907             if (!strcasecmp(v->name, "username")) {
25908                if (deprecation_warning) {
25909                   ast_log(LOG_NOTICE, "The 'username' field for sip peers has been deprecated in favor of the term 'defaultuser'\n");
25910                   deprecation_warning = 0;
25911                }
25912                peer->deprecated_username = 1;
25913             }
25914          } else if (!strcasecmp(v->name, "language")) {
25915             ast_string_field_set(peer, language, v->value);
25916          } else if (!strcasecmp(v->name, "regexten")) {
25917             ast_string_field_set(peer, regexten, v->value);
25918          } else if (!strcasecmp(v->name, "callbackextension")) {
25919             ast_copy_string(callback, v->value, sizeof(callback));
25920          } else if (!strcasecmp(v->name, "amaflags")) {
25921             format = ast_cdr_amaflags2int(v->value);
25922             if (format < 0) {
25923                ast_log(LOG_WARNING, "Invalid AMA Flags for peer: %s at line %d\n", v->value, v->lineno);
25924             } else {
25925                peer->amaflags = format;
25926             }
25927          } else if (!strcasecmp(v->name, "maxforwards")) {
25928             if ((sscanf(v->value, "%30d", &peer->maxforwards) != 1) || (peer->maxforwards < 1)) {
25929                ast_log(LOG_WARNING, "'%s' is not a valid maxforwards value at line %d.  Using default.\n", v->value, v->lineno);
25930                peer->maxforwards = sip_cfg.default_max_forwards;
25931             }
25932          } else if (!strcasecmp(v->name, "accountcode")) {
25933             ast_string_field_set(peer, accountcode, v->value);
25934          } else if (!strcasecmp(v->name, "mohinterpret")) {
25935             ast_string_field_set(peer, mohinterpret, v->value);
25936          } else if (!strcasecmp(v->name, "mohsuggest")) {
25937             ast_string_field_set(peer, mohsuggest, v->value);
25938          } else if (!strcasecmp(v->name, "parkinglot")) {
25939             ast_string_field_set(peer, parkinglot, v->value);
25940          } else if (!strcasecmp(v->name, "rtp_engine")) {
25941             ast_string_field_set(peer, engine, v->value);
25942          } else if (!strcasecmp(v->name, "mailbox")) {
25943             add_peer_mailboxes(peer, v->value);
25944          } else if (!strcasecmp(v->name, "hasvoicemail")) {
25945             /* People expect that if 'hasvoicemail' is set, that the mailbox will
25946              * be also set, even if not explicitly specified. */
25947             if (ast_true(v->value) && AST_LIST_EMPTY(&peer->mailboxes)) {
25948                add_peer_mailboxes(peer, name);
25949             }
25950          } else if (!strcasecmp(v->name, "subscribemwi")) {
25951             ast_set2_flag(&peer->flags[1], ast_true(v->value), SIP_PAGE2_SUBSCRIBEMWIONLY);
25952          } else if (!strcasecmp(v->name, "vmexten")) {
25953             ast_string_field_set(peer, vmexten, v->value);
25954          } else if (!strcasecmp(v->name, "callgroup")) {
25955             peer->callgroup = ast_get_group(v->value);
25956          } else if (!strcasecmp(v->name, "allowtransfer")) {
25957             peer->allowtransfer = ast_true(v->value) ? TRANSFER_OPENFORALL : TRANSFER_CLOSED;
25958          } else if (!strcasecmp(v->name, "pickupgroup")) {
25959             peer->pickupgroup = ast_get_group(v->value);
25960          } else if (!strcasecmp(v->name, "allow")) {
25961             int error =  ast_parse_allow_disallow(&peer->prefs, &peer->capability, v->value, TRUE);
25962             if (error) {
25963                ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
25964             }
25965          } else if (!strcasecmp(v->name, "disallow")) {
25966             int error =  ast_parse_allow_disallow(&peer->prefs, &peer->capability, v->value, FALSE);
25967             if (error) {
25968                ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
25969             }
25970          } else if (!strcasecmp(v->name, "preferred_codec_only")) {
25971             ast_set2_flag(&peer->flags[1], ast_true(v->value), SIP_PAGE2_PREFERRED_CODEC);
25972          } else if (!strcasecmp(v->name, "registertrying")) {
25973             ast_set2_flag(&peer->flags[1], ast_true(v->value), SIP_PAGE2_REGISTERTRYING);
25974          } else if (!strcasecmp(v->name, "autoframing")) {
25975             peer->autoframing = ast_true(v->value);
25976          } else if (!strcasecmp(v->name, "rtptimeout")) {
25977             if ((sscanf(v->value, "%30d", &peer->rtptimeout) != 1) || (peer->rtptimeout < 0)) {
25978                ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d.  Using default.\n", v->value, v->lineno);
25979                peer->rtptimeout = global_rtptimeout;
25980             }
25981          } else if (!strcasecmp(v->name, "rtpholdtimeout")) {
25982             if ((sscanf(v->value, "%30d", &peer->rtpholdtimeout) != 1) || (peer->rtpholdtimeout < 0)) {
25983                ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d.  Using default.\n", v->value, v->lineno);
25984                peer->rtpholdtimeout = global_rtpholdtimeout;
25985             }
25986          } else if (!strcasecmp(v->name, "rtpkeepalive")) {
25987             if ((sscanf(v->value, "%30d", &peer->rtpkeepalive) != 1) || (peer->rtpkeepalive < 0)) {
25988                ast_log(LOG_WARNING, "'%s' is not a valid RTP keepalive time at line %d.  Using default.\n", v->value, v->lineno);
25989                peer->rtpkeepalive = global_rtpkeepalive;
25990             }
25991          } else if (!strcasecmp(v->name, "timert1")) {
25992             if ((sscanf(v->value, "%30d", &peer->timer_t1) != 1) || (peer->timer_t1 < 200) || (peer->timer_t1 < global_t1min)) {
25993                ast_log(LOG_WARNING, "'%s' is not a valid T1 time at line %d.  Using default.\n", v->value, v->lineno);
25994                peer->timer_t1 = global_t1min;
25995             }
25996             timert1_set = 1;
25997          } else if (!strcasecmp(v->name, "timerb")) {
25998             if ((sscanf(v->value, "%30d", &peer->timer_b) != 1) || (peer->timer_b < 200)) {
25999                ast_log(LOG_WARNING, "'%s' is not a valid Timer B time at line %d.  Using default.\n", v->value, v->lineno);
26000                peer->timer_b = global_timer_b;
26001             }
26002             timerb_set = 1;
26003          } else if (!strcasecmp(v->name, "setvar")) {
26004             peer->chanvars = add_var(v->value, peer->chanvars);
26005          } else if (!strcasecmp(v->name, "header")) {
26006             char tmp[4096];
26007             snprintf(tmp, sizeof(tmp), "__SIPADDHEADERpre%2d=%s", ++headercount, v->value);
26008             peer->chanvars = add_var(tmp, peer->chanvars);
26009          } else if (!strcasecmp(v->name, "qualifyfreq")) {
26010             int i;
26011             if (sscanf(v->value, "%30d", &i) == 1) {
26012                peer->qualifyfreq = i * 1000;
26013             } else {
26014                ast_log(LOG_WARNING, "Invalid qualifyfreq number '%s' at line %d of %s\n", v->value, v->lineno, config);
26015                peer->qualifyfreq = global_qualifyfreq;
26016             }
26017          } else if (!strcasecmp(v->name, "maxcallbitrate")) {
26018             peer->maxcallbitrate = atoi(v->value);
26019             if (peer->maxcallbitrate < 0) {
26020                peer->maxcallbitrate = default_maxcallbitrate;
26021             }
26022          } else if (!strcasecmp(v->name, "session-timers")) {
26023             int i = (int) str2stmode(v->value);
26024             if (i < 0) {
26025                ast_log(LOG_WARNING, "Invalid session-timers '%s' at line %d of %s\n", v->value, v->lineno, config);
26026                peer->stimer.st_mode_oper = global_st_mode;
26027             } else {
26028                peer->stimer.st_mode_oper = i;
26029             }
26030          } else if (!strcasecmp(v->name, "session-expires")) {
26031             if (sscanf(v->value, "%30d", &peer->stimer.st_max_se) != 1) {
26032                ast_log(LOG_WARNING, "Invalid session-expires '%s' at line %d of %s\n", v->value, v->lineno, config);
26033                peer->stimer.st_max_se = global_max_se;
26034             }
26035          } else if (!strcasecmp(v->name, "session-minse")) {
26036             if (sscanf(v->value, "%30d", &peer->stimer.st_min_se) != 1) {
26037                ast_log(LOG_WARNING, "Invalid session-minse '%s' at line %d of %s\n", v->value, v->lineno, config);
26038                peer->stimer.st_min_se = global_min_se;
26039             }
26040             if (peer->stimer.st_min_se < 90) {
26041                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);
26042                peer->stimer.st_min_se = global_min_se;
26043             }
26044          } else if (!strcasecmp(v->name, "session-refresher")) {
26045             int i = (int) str2strefresher(v->value);
26046             if (i < 0) {
26047                ast_log(LOG_WARNING, "Invalid session-refresher '%s' at line %d of %s\n", v->value, v->lineno, config);
26048                peer->stimer.st_ref = global_st_refresher;
26049             } else {
26050                peer->stimer.st_ref = i;
26051             }
26052          } else if (!strcasecmp(v->name, "disallowed_methods")) {
26053             char *disallow = ast_strdupa(v->value);
26054             mark_parsed_methods(&peer->disallowed_methods, disallow);
26055          } else if (!strcasecmp(v->name, "unsolicited_mailbox")) {
26056             ast_string_field_set(peer, unsolicited_mailbox, v->value);
26057          } else if (!strcasecmp(v->name, "use_q850_reason")) {
26058             ast_set2_flag(&peer->flags[1], ast_true(v->value), SIP_PAGE2_Q850_REASON);
26059          } else if (!strcasecmp(v->name, "encryption")) {
26060             ast_set2_flag(&peer->flags[1], ast_true(v->value), SIP_PAGE2_USE_SRTP);
26061          } else if (!strcasecmp(v->name, "snom_aoc_enabled")) {
26062             ast_set2_flag(&peer->flags[2], ast_true(v->value), SIP_PAGE3_SNOM_AOC);
26063          }
26064       }
26065 
26066       /* These apply to devstate lookups */
26067       if (realtime && !strcasecmp(v->name, "lastms")) {
26068          sscanf(v->value, "%30d", &peer->lastms);
26069       } else if (realtime && !strcasecmp(v->name, "ipaddr") && !ast_strlen_zero(v->value) ) {
26070          ast_sockaddr_parse(&peer->addr, v->value, PARSE_PORT_FORBID);
26071       } else if (realtime && !strcasecmp(v->name, "fullcontact")) {
26072          if (alt_fullcontact && !alt) {
26073             /* Reset, because the alternate also has a fullcontact and we
26074              * do NOT want the field value to be doubled. It might be
26075              * tempting to skip this, but the first table might not have
26076              * fullcontact and since we're here, we know that the alternate
26077              * absolutely does. */
26078             alt_fullcontact = 0;
26079             ast_str_reset(fullcontact);
26080          }
26081          /* Reconstruct field, because realtime separates our value at the ';' */
26082          if (fullcontact->used > 0) {
26083             ast_str_append(&fullcontact, 0, ";%s", v->value);
26084          } else {
26085             ast_str_set(&fullcontact, 0, "%s", v->value);
26086          }
26087       } else if (!strcasecmp(v->name, "qualify")) {
26088          if (!strcasecmp(v->value, "no")) {
26089             peer->maxms = 0;
26090          } else if (!strcasecmp(v->value, "yes")) {
26091             peer->maxms = default_qualify ? default_qualify : DEFAULT_MAXMS;
26092          } else if (sscanf(v->value, "%30d", &peer->maxms) != 1) {
26093             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);
26094             peer->maxms = 0;
26095          }
26096          if (realtime && !ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) && peer->maxms > 0) {
26097             /* This would otherwise cause a network storm, where the
26098              * qualify response refreshes the peer from the database,
26099              * which in turn causes another qualify to be sent, ad
26100              * infinitum. */
26101             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);
26102             peer->maxms = 0;
26103          }
26104       } else if (!strcasecmp(v->name, "callcounter")) {
26105          peer->call_limit = ast_true(v->value) ? INT_MAX : 0;
26106       } else if (!strcasecmp(v->name, "call-limit")) {
26107          peer->call_limit = atoi(v->value);
26108          if (peer->call_limit < 0) {
26109             peer->call_limit = 0;
26110          }
26111       } else if (!strcasecmp(v->name, "busylevel")) {
26112          peer->busy_level = atoi(v->value);
26113          if (peer->busy_level < 0) {
26114             peer->busy_level = 0;
26115          }
26116       } else if (ast_cc_is_config_param(v->name)) {
26117          ast_cc_set_param(peer->cc_params, v->name, v->value);
26118       }
26119    }
26120 
26121    if (!devstate_only) {
26122       struct sip_mailbox *mailbox;
26123       AST_LIST_TRAVERSE_SAFE_BEGIN(&peer->mailboxes, mailbox, entry) {
26124          if (mailbox->delme) {
26125             AST_LIST_REMOVE_CURRENT(entry);
26126             destroy_mailbox(mailbox);
26127          }
26128       }
26129       AST_LIST_TRAVERSE_SAFE_END;
26130    }
26131 
26132    if (!can_parse_xml && (ast_get_cc_agent_policy(peer->cc_params) == AST_CC_AGENT_NATIVE)) {
26133       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);
26134       ast_set_cc_agent_policy(peer->cc_params, AST_CC_AGENT_NEVER);
26135    }
26136 
26137    /* Note that Timer B is dependent upon T1 and MUST NOT be lower
26138     * than T1 * 64, according to RFC 3261, Section 17.1.1.2 */
26139    if (peer->timer_b < peer->timer_t1 * 64) {
26140       if (timerb_set && timert1_set) {
26141          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);
26142       } else if (timerb_set) {
26143          if ((peer->timer_t1 = peer->timer_b / 64) < global_t1min) {
26144             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);
26145             peer->timer_t1 = global_t1min;
26146             peer->timer_b = peer->timer_t1 * 64;
26147          }
26148          peer->timer_t1 = peer->timer_b / 64;
26149       } else {
26150          peer->timer_b = peer->timer_t1 * 64;
26151       }
26152    }
26153 
26154    if (!peer->default_outbound_transport) {
26155       /* Set default set of transports */
26156       peer->transports = default_transports;
26157       /* Set default primary transport */
26158       peer->default_outbound_transport = default_primary_transport;
26159    }
26160 
26161    /* The default transport type set during build_peer should only replace the socket.type when...
26162     * 1. Registration is not present and the socket.type and default transport types are different.
26163     * 2. The socket.type is not an acceptable transport type after rebuilding peer.
26164     * 3. The socket.type is not set yet. */
26165    if (((peer->socket.type != peer->default_outbound_transport) && (peer->expire == -1)) ||
26166       !(peer->socket.type & peer->transports) || !(peer->socket.type)) {
26167 
26168       set_socket_transport(&peer->socket, peer->default_outbound_transport);
26169    }
26170 
26171    if (ast_str_strlen(fullcontact)) {
26172       ast_string_field_set(peer, fullcontact, ast_str_buffer(fullcontact));
26173       peer->rt_fromcontact = TRUE;
26174       /* We have a hostname in the fullcontact, but if we don't have an
26175        * address listed on the entry (or if it's 'dynamic'), then we need to
26176        * parse the entry to obtain the IP address, so a dynamic host can be
26177        * contacted immediately after reload (as opposed to waiting for it to
26178        * register once again). But if we have an address for this peer and NAT was
26179        * specified, use that address instead. */
26180       /* XXX May need to revisit the final argument; does the realtime DB store whether
26181        * the original contact was over TLS or not? XXX */
26182       if (!ast_test_flag(&peer->flags[0], SIP_NAT_RPORT_PRESENT) || ast_sockaddr_isnull(&peer->addr)) {
26183          __set_address_from_contact(fullcontact->str, &peer->addr, 0);
26184       }
26185    }
26186 
26187    if (srvlookup && peer->dnsmgr == NULL) {
26188       char transport[MAXHOSTNAMELEN];
26189       char _srvlookup[MAXHOSTNAMELEN];
26190       char *params;
26191 
26192       ast_copy_string(_srvlookup, srvlookup, sizeof(_srvlookup));
26193       if ((params = strchr(_srvlookup, ';'))) {
26194          *params++ = '\0';
26195       }
26196 
26197       snprintf(transport, sizeof(transport), "_%s._%s", get_srv_service(peer->socket.type), get_srv_protocol(peer->socket.type));
26198 
26199       peer->addr.ss.ss_family = get_address_family_filter(&bindaddr); /* Filter address family */
26200       if (ast_dnsmgr_lookup(_srvlookup, &peer->addr, &peer->dnsmgr, sip_cfg.srvlookup && !peer->portinuri ? transport : NULL)) {
26201          ast_log(LOG_ERROR, "srvlookup failed for host: %s, on peer %s, removing peer\n", _srvlookup, peer->name);
26202          unref_peer(peer, "getting rid of a peer pointer");
26203          return NULL;
26204       }
26205 
26206       ast_string_field_set(peer, tohost, srvlookup);
26207 
26208       if (global_dynamic_exclude_static) {
26209          int err = 0;
26210          sip_cfg.contact_ha = ast_append_ha("deny", ast_sockaddr_stringify_addr(&peer->addr), 
26211                      sip_cfg.contact_ha, &err);
26212          if (err) {
26213             ast_log(LOG_ERROR, "Bad ACL entry in configuration line %d : %s\n", v->lineno, v->value);
26214          }
26215       }
26216    } else if (peer->dnsmgr && !peer->host_dynamic) {
26217       /* force a refresh here on reload if dnsmgr already exists and host is set. */
26218       ast_dnsmgr_refresh(peer->dnsmgr);
26219    }
26220 
26221    if (port && !realtime && peer->host_dynamic) {
26222       ast_sockaddr_set_port(&peer->defaddr, port);
26223    } else if (port) {
26224       ast_sockaddr_set_port(&peer->addr, port);
26225    }
26226 
26227    if (ast_sockaddr_port(&peer->addr) == 0) {
26228       ast_sockaddr_set_port(&peer->addr,
26229                   (peer->socket.type & SIP_TRANSPORT_TLS) ?
26230                   STANDARD_TLS_PORT : STANDARD_SIP_PORT);
26231    }
26232    if (ast_sockaddr_port(&peer->defaddr) == 0) {
26233       ast_sockaddr_set_port(&peer->defaddr,
26234                   (peer->socket.type & SIP_TRANSPORT_TLS) ?
26235                   STANDARD_TLS_PORT : STANDARD_SIP_PORT);
26236    }
26237    if (!peer->socket.port) {
26238       peer->socket.port = htons(((peer->socket.type & SIP_TRANSPORT_TLS) ? STANDARD_TLS_PORT : STANDARD_SIP_PORT));
26239    }
26240 
26241    if (!sip_cfg.ignore_regexpire && peer->host_dynamic && realtime) {
26242       time_t nowtime = time(NULL);
26243 
26244       if ((nowtime - regseconds) > 0) {
26245          destroy_association(peer);
26246          memset(&peer->addr, 0, sizeof(peer->addr));
26247          peer->lastms = -1;
26248          ast_debug(1, "Bah, we're expired (%d/%d/%d)!\n", (int)(nowtime - regseconds), (int)regseconds, (int)nowtime);
26249       }
26250    }
26251 
26252    /* Startup regular pokes */
26253    if (!devstate_only && realtime && peer->lastms > 0) {
26254       ref_peer(peer, "schedule qualify");
26255       sip_poke_peer(peer, 0);
26256    }
26257 
26258    ast_copy_flags(&peer->flags[0], &peerflags[0], mask[0].flags);
26259    ast_copy_flags(&peer->flags[1], &peerflags[1], mask[1].flags);
26260    ast_copy_flags(&peer->flags[2], &peerflags[2], mask[2].flags);
26261    if (ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)) {
26262       sip_cfg.allowsubscribe = TRUE;   /* No global ban any more */
26263    }
26264    if (peer->host_dynamic && !peer->is_realtime) {
26265       reg_source_db(peer);
26266    }
26267 
26268    /* If they didn't request that MWI is sent *only* on subscribe, go ahead and
26269     * subscribe to it now. */
26270    if (!devstate_only && !ast_test_flag(&peer->flags[1], SIP_PAGE2_SUBSCRIBEMWIONLY) &&
26271       !AST_LIST_EMPTY(&peer->mailboxes)) {
26272       add_peer_mwi_subs(peer);
26273       /* Send MWI from the event cache only.  This is so we can send initial
26274        * MWI if app_voicemail got loaded before chan_sip.  If it is the other
26275        * way, then we will get events when app_voicemail gets loaded. */
26276       sip_send_mwi_to_peer(peer, NULL, 1);
26277    }
26278 
26279    peer->the_mark = 0;
26280 
26281    ast_free_ha(oldha);
26282    ast_free_ha(olddirectmediaha);
26283    if (!ast_strlen_zero(callback)) { /* build string from peer info */
26284       char *reg_string;
26285       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) {
26286          ast_log(LOG_WARNING, "asprintf() failed: %s\n", strerror(errno));
26287       } else if (reg_string) {
26288          sip_register(reg_string, 0); /* XXX TODO: count in registry_count */
26289          ast_free(reg_string);
26290       }
26291    }
26292    return peer;
26293 }
26294 
26295 static int peer_markall_func(void *device, void *arg, int flags)
26296 {
26297    struct sip_peer *peer = device;
26298    peer->the_mark = 1;
26299    return 0;
26300 }
26301 
26302 /*! \brief Re-read SIP.conf config file
26303 \note This function reloads all config data, except for
26304    active peers (with registrations). They will only
26305    change configuration data at restart, not at reload.
26306    SIP debug and recordhistory state will not change
26307  */
26308 static int reload_config(enum channelreloadreason reason)
26309 {
26310    struct ast_config *cfg, *ucfg;
26311    struct ast_variable *v;
26312    struct sip_peer *peer;
26313    char *cat, *stringp, *context, *oldregcontext;
26314    char newcontexts[AST_MAX_CONTEXT], oldcontexts[AST_MAX_CONTEXT];
26315    struct ast_flags dummy[2];
26316    struct ast_flags config_flags = { reason == CHANNEL_MODULE_LOAD ? 0 : ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) ? 0 : CONFIG_FLAG_FILEUNCHANGED };
26317    int auto_sip_domains = FALSE;
26318    struct ast_sockaddr old_bindaddr = bindaddr;
26319    int registry_count = 0, peer_count = 0, timerb_set = 0, timert1_set = 0;
26320    int subscribe_network_change = 1;
26321    time_t run_start, run_end;
26322    int bindport = 0;
26323 
26324    run_start = time(0);
26325    ast_unload_realtime("sipregs");
26326    ast_unload_realtime("sippeers");
26327    cfg = ast_config_load(config, config_flags);
26328 
26329    /* We *must* have a config file otherwise stop immediately */
26330    if (!cfg) {
26331       ast_log(LOG_NOTICE, "Unable to load config %s\n", config);
26332       return -1;
26333    } else if (cfg == CONFIG_STATUS_FILEUNCHANGED) {
26334       ucfg = ast_config_load("users.conf", config_flags);
26335       if (ucfg == CONFIG_STATUS_FILEUNCHANGED) {
26336          return 1;
26337       } else if (ucfg == CONFIG_STATUS_FILEINVALID) {
26338          ast_log(LOG_ERROR, "Contents of users.conf are invalid and cannot be parsed\n");
26339          return 1;
26340       }
26341       /* Must reread both files, because one changed */
26342       ast_clear_flag(&config_flags, CONFIG_FLAG_FILEUNCHANGED);
26343       if ((cfg = ast_config_load(config, config_flags)) == CONFIG_STATUS_FILEINVALID) {
26344          ast_log(LOG_ERROR, "Contents of %s are invalid and cannot be parsed\n", config);
26345          ast_config_destroy(ucfg);
26346          return 1;
26347       }
26348    } else if (cfg == CONFIG_STATUS_FILEINVALID) {
26349       ast_log(LOG_ERROR, "Contents of %s are invalid and cannot be parsed\n", config);
26350       return 1;
26351    } else {
26352       ast_clear_flag(&config_flags, CONFIG_FLAG_FILEUNCHANGED);
26353       if ((ucfg = ast_config_load("users.conf", config_flags)) == CONFIG_STATUS_FILEINVALID) {
26354          ast_log(LOG_ERROR, "Contents of users.conf are invalid and cannot be parsed\n");
26355          ast_config_destroy(cfg);
26356          return 1;
26357       }
26358    }
26359 
26360    ast_free_ha(sip_cfg.contact_ha);
26361    sip_cfg.contact_ha = NULL;
26362 
26363    default_tls_cfg.enabled = FALSE;    /* Default: Disable TLS */
26364 
26365    if (reason != CHANNEL_MODULE_LOAD) {
26366       ast_debug(4, "--------------- SIP reload started\n");
26367 
26368       clear_realm_authentication(authl);
26369       clear_sip_domains();
26370       authl = NULL;
26371 
26372       /* First, destroy all outstanding registry calls */
26373       /* This is needed, since otherwise active registry entries will not be destroyed */
26374       ASTOBJ_CONTAINER_TRAVERSE(&regl, 1, do {  /* regl is locked */
26375 
26376             ASTOBJ_RDLOCK(iterator); /* now regl is locked, and the object is also locked */
26377             if (iterator->call) {
26378                ast_debug(3, "Destroying active SIP dialog for registry %s@%s\n", iterator->username, iterator->hostname);
26379                /* This will also remove references to the registry */
26380                dialog_unlink_all(iterator->call, TRUE, TRUE);
26381                iterator->call = dialog_unref(iterator->call, "remove iterator->call from registry traversal");
26382             }
26383             if (iterator->expire > -1) {
26384                AST_SCHED_DEL_UNREF(sched, iterator->expire, registry_unref(iterator, "reg ptr unref from reload config"));
26385             }
26386             if (iterator->timeout > -1) {
26387                AST_SCHED_DEL_UNREF(sched, iterator->timeout, registry_unref(iterator, "reg ptr unref from reload config"));
26388             }
26389             ASTOBJ_UNLOCK(iterator);
26390       } while(0));
26391 
26392       /* Then, actually destroy users and registry */
26393       ASTOBJ_CONTAINER_DESTROYALL(&regl, sip_registry_destroy);
26394       ast_debug(4, "--------------- Done destroying registry list\n");
26395       ao2_t_callback(peers, OBJ_NODATA, peer_markall_func, NULL, "callback to mark all peers");
26396    }
26397 
26398    /* Reset certificate handling for TLS sessions */
26399    if (reason != CHANNEL_MODULE_LOAD) {
26400       ast_free(default_tls_cfg.certfile);
26401       ast_free(default_tls_cfg.pvtfile);
26402       ast_free(default_tls_cfg.cipher);
26403       ast_free(default_tls_cfg.cafile);
26404       ast_free(default_tls_cfg.capath);
26405    }
26406    default_tls_cfg.certfile = ast_strdup(AST_CERTFILE); /*XXX Not sure if this is useful */
26407    default_tls_cfg.pvtfile = ast_strdup("");
26408    default_tls_cfg.cipher = ast_strdup("");
26409    default_tls_cfg.cafile = ast_strdup("");
26410    default_tls_cfg.capath = ast_strdup("");
26411 
26412    /* Initialize copy of current sip_cfg.regcontext for later use in removing stale contexts */
26413    ast_copy_string(oldcontexts, sip_cfg.regcontext, sizeof(oldcontexts));
26414    oldregcontext = oldcontexts;
26415 
26416    /* Clear all flags before setting default values */
26417    /* Preserve debugging settings for console */
26418    sipdebug &= sip_debug_console;
26419    ast_clear_flag(&global_flags[0], AST_FLAGS_ALL);
26420    ast_clear_flag(&global_flags[1], AST_FLAGS_ALL);
26421 
26422    /* Reset IP addresses  */
26423    ast_sockaddr_parse(&bindaddr, "0.0.0.0:0", 0);
26424    memset(&internip, 0, sizeof(internip));
26425 
26426    /* Free memory for local network address mask */
26427    ast_free_ha(localaddr);
26428    memset(&localaddr, 0, sizeof(localaddr));
26429    memset(&externaddr, 0, sizeof(externaddr));
26430    memset(&media_address, 0, sizeof(media_address));
26431    memset(&default_prefs, 0 , sizeof(default_prefs));
26432    memset(&sip_cfg.outboundproxy, 0, sizeof(struct sip_proxy));
26433    sip_cfg.outboundproxy.force = FALSE;      /*!< Don't force proxy usage, use route: headers */
26434    default_transports = 0;          /*!< Reset default transport to zero here, default value later on */
26435    default_primary_transport = 0;         /*!< Reset default primary transport to zero here, default value later on */
26436    ourport_tcp = STANDARD_SIP_PORT;
26437    ourport_tls = STANDARD_TLS_PORT;
26438    externtcpport = STANDARD_SIP_PORT;
26439    externtlsport = STANDARD_TLS_PORT;
26440    sip_cfg.srvlookup = DEFAULT_SRVLOOKUP;
26441    global_tos_sip = DEFAULT_TOS_SIP;
26442    global_tos_audio = DEFAULT_TOS_AUDIO;
26443    global_tos_video = DEFAULT_TOS_VIDEO;
26444    global_tos_text = DEFAULT_TOS_TEXT;
26445    global_cos_sip = DEFAULT_COS_SIP;
26446    global_cos_audio = DEFAULT_COS_AUDIO;
26447    global_cos_video = DEFAULT_COS_VIDEO;
26448    global_cos_text = DEFAULT_COS_TEXT;
26449 
26450    externhost[0] = '\0';         /* External host name (for behind NAT DynDNS support) */
26451    externexpire = 0;       /* Expiration for DNS re-issuing */
26452    externrefresh = 10;
26453 
26454    /* Reset channel settings to default before re-configuring */
26455    sip_cfg.allow_external_domains = DEFAULT_ALLOW_EXT_DOM;           /* Allow external invites */
26456    sip_cfg.regcontext[0] = '\0';
26457    sip_cfg.capability = DEFAULT_CAPABILITY;
26458    sip_cfg.regextenonqualify = DEFAULT_REGEXTENONQUALIFY;
26459    sip_cfg.notifyringing = DEFAULT_NOTIFYRINGING;
26460    sip_cfg.notifycid = DEFAULT_NOTIFYCID;
26461    sip_cfg.notifyhold = FALSE;      /*!< Keep track of hold status for a peer */
26462    sip_cfg.directrtpsetup = FALSE;     /* Experimental feature, disabled by default */
26463    sip_cfg.alwaysauthreject = DEFAULT_ALWAYSAUTHREJECT;
26464    sip_cfg.auth_options_requests = DEFAULT_AUTH_OPTIONS;
26465    sip_cfg.allowsubscribe = FALSE;
26466    sip_cfg.disallowed_methods = SIP_UNKNOWN;
26467    sip_cfg.contact_ha = NULL;    /* Reset the contact ACL */
26468    snprintf(global_useragent, sizeof(global_useragent), "%s %s", DEFAULT_USERAGENT, ast_get_version());
26469    snprintf(global_sdpsession, sizeof(global_sdpsession), "%s %s", DEFAULT_SDPSESSION, ast_get_version());
26470    snprintf(global_sdpowner, sizeof(global_sdpowner), "%s", DEFAULT_SDPOWNER);
26471    global_prematuremediafilter = TRUE;
26472    ast_copy_string(default_notifymime, DEFAULT_NOTIFYMIME, sizeof(default_notifymime));
26473    ast_copy_string(sip_cfg.realm, S_OR(ast_config_AST_SYSTEM_NAME, DEFAULT_REALM), sizeof(sip_cfg.realm));
26474    sip_cfg.domainsasrealm = DEFAULT_DOMAINSASREALM;
26475    ast_copy_string(default_callerid, DEFAULT_CALLERID, sizeof(default_callerid));
26476    ast_copy_string(default_mwi_from, DEFAULT_MWI_FROM, sizeof(default_mwi_from));
26477    sip_cfg.compactheaders = DEFAULT_COMPACTHEADERS;
26478    global_reg_timeout = DEFAULT_REGISTRATION_TIMEOUT;
26479    global_regattempts_max = 0;
26480    sip_cfg.pedanticsipchecking = DEFAULT_PEDANTIC;
26481    sip_cfg.autocreatepeer = DEFAULT_AUTOCREATEPEER;
26482    global_autoframing = 0;
26483    sip_cfg.allowguest = DEFAULT_ALLOWGUEST;
26484    global_callcounter = DEFAULT_CALLCOUNTER;
26485    global_match_auth_username = FALSE;    /*!< Match auth username if available instead of From: Default off. */
26486    global_rtptimeout = 0;
26487    global_rtpholdtimeout = 0;
26488    global_rtpkeepalive = DEFAULT_RTPKEEPALIVE;
26489    sip_cfg.allowtransfer = TRANSFER_OPENFORALL; /* Merrily accept all transfers by default */
26490    sip_cfg.rtautoclear = 120;
26491    ast_set_flag(&global_flags[1], SIP_PAGE2_ALLOWSUBSCRIBE);   /* Default for all devices: TRUE */
26492    ast_set_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP);     /* Default for all devices: TRUE */
26493    sip_cfg.peer_rtupdate = TRUE;
26494    global_dynamic_exclude_static = 0;  /* Exclude static peers */
26495    sip_cfg.tcp_enabled = FALSE;
26496 
26497    /* Session-Timers */
26498    global_st_mode = SESSION_TIMER_MODE_ACCEPT;
26499    global_st_refresher = SESSION_TIMER_REFRESHER_UAS;
26500    global_min_se  = DEFAULT_MIN_SE;
26501    global_max_se  = DEFAULT_MAX_SE;
26502 
26503    /* Peer poking settings */
26504    global_qualify_gap = DEFAULT_QUALIFY_GAP;
26505    global_qualify_peers = DEFAULT_QUALIFY_PEERS;
26506 
26507    /* Initialize some reasonable defaults at SIP reload (used both for channel and as default for devices */
26508    ast_copy_string(sip_cfg.default_context, DEFAULT_CONTEXT, sizeof(sip_cfg.default_context));
26509    sip_cfg.default_subscribecontext[0] = '\0';
26510    sip_cfg.default_max_forwards = DEFAULT_MAX_FORWARDS;
26511    default_language[0] = '\0';
26512    default_fromdomain[0] = '\0';
26513    default_fromdomainport = 0;
26514    default_qualify = DEFAULT_QUALIFY;
26515    default_maxcallbitrate = DEFAULT_MAX_CALL_BITRATE;
26516    ast_copy_string(default_mohinterpret, DEFAULT_MOHINTERPRET, sizeof(default_mohinterpret));
26517    ast_copy_string(default_mohsuggest, DEFAULT_MOHSUGGEST, sizeof(default_mohsuggest));
26518    ast_copy_string(default_vmexten, DEFAULT_VMEXTEN, sizeof(default_vmexten));
26519    ast_set_flag(&global_flags[0], SIP_DTMF_RFC2833);        /*!< Default DTMF setting: RFC2833 */
26520    ast_set_flag(&global_flags[0], SIP_DIRECT_MEDIA);        /*!< Allow re-invites */
26521    ast_copy_string(default_engine, DEFAULT_ENGINE, sizeof(default_engine));
26522    ast_copy_string(default_parkinglot, DEFAULT_PARKINGLOT, sizeof(default_parkinglot));
26523 
26524    /* Debugging settings, always default to off */
26525    dumphistory = FALSE;
26526    recordhistory = FALSE;
26527    sipdebug &= ~sip_debug_config;
26528 
26529    /* Misc settings for the channel */
26530    global_relaxdtmf = FALSE;
26531    sip_cfg.callevents = DEFAULT_CALLEVENTS;
26532    global_authfailureevents = FALSE;
26533    global_t1 = DEFAULT_TIMER_T1;
26534    global_timer_b = 64 * DEFAULT_TIMER_T1;
26535    global_t1min = DEFAULT_T1MIN;
26536    global_qualifyfreq = DEFAULT_QUALIFYFREQ;
26537    global_t38_maxdatagram = -1;
26538    global_shrinkcallerid = 1;
26539 
26540    sip_cfg.matchexternaddrlocally = DEFAULT_MATCHEXTERNADDRLOCALLY;
26541 
26542    /* Copy the default jb config over global_jbconf */
26543    memcpy(&global_jbconf, &default_jbconf, sizeof(struct ast_jb_conf));
26544 
26545    ast_clear_flag(&global_flags[1], SIP_PAGE2_FAX_DETECT);
26546    ast_clear_flag(&global_flags[1], SIP_PAGE2_VIDEOSUPPORT | SIP_PAGE2_VIDEOSUPPORT_ALWAYS);
26547    ast_clear_flag(&global_flags[1], SIP_PAGE2_TEXTSUPPORT);
26548    ast_clear_flag(&global_flags[1], SIP_PAGE2_IGNORESDPVERSION);
26549 
26550 
26551    /* Read the [general] config section of sip.conf (or from realtime config) */
26552    for (v = ast_variable_browse(cfg, "general"); v; v = v->next) {
26553       if (handle_common_options(&global_flags[0], &dummy[0], v)) {
26554          continue;
26555       }
26556       if (handle_t38_options(&global_flags[0], &dummy[0], v, &global_t38_maxdatagram)) {
26557          continue;
26558       }
26559       /* handle jb conf */
26560       if (!ast_jb_read_conf(&global_jbconf, v->name, v->value))
26561          continue;
26562 
26563       /* handle tls conf */
26564       if (!ast_tls_read_conf(&default_tls_cfg, &sip_tls_desc, v->name, v->value)) {
26565          continue;
26566       }
26567 
26568       if (!strcasecmp(v->name, "context")) {
26569          ast_copy_string(sip_cfg.default_context, v->value, sizeof(sip_cfg.default_context));
26570       } else if (!strcasecmp(v->name, "subscribecontext")) {
26571          ast_copy_string(sip_cfg.default_subscribecontext, v->value, sizeof(sip_cfg.default_subscribecontext));
26572       } else if (!strcasecmp(v->name, "callcounter")) {
26573          global_callcounter = ast_true(v->value) ? 1 : 0;
26574       } else if (!strcasecmp(v->name, "allowguest")) {
26575          sip_cfg.allowguest = ast_true(v->value) ? 1 : 0;
26576       } else if (!strcasecmp(v->name, "realm")) {
26577          ast_copy_string(sip_cfg.realm, v->value, sizeof(sip_cfg.realm));
26578       } else if (!strcasecmp(v->name, "domainsasrealm")) {
26579          sip_cfg.domainsasrealm = ast_true(v->value);
26580       } else if (!strcasecmp(v->name, "useragent")) {
26581          ast_copy_string(global_useragent, v->value, sizeof(global_useragent));
26582          ast_debug(1, "Setting SIP channel User-Agent Name to %s\n", global_useragent);
26583       } else if (!strcasecmp(v->name, "sdpsession")) {
26584          ast_copy_string(global_sdpsession, v->value, sizeof(global_sdpsession));
26585       } else if (!strcasecmp(v->name, "sdpowner")) {
26586          /* Field cannot contain spaces */
26587          if (!strstr(v->value, " ")) {
26588             ast_copy_string(global_sdpowner, v->value, sizeof(global_sdpowner));
26589          } else {
26590             ast_log(LOG_WARNING, "'%s' must not contain spaces at line %d.  Using default.\n", v->value, v->lineno);
26591          }
26592       } else if (!strcasecmp(v->name, "allowtransfer")) {
26593          sip_cfg.allowtransfer = ast_true(v->value) ? TRANSFER_OPENFORALL : TRANSFER_CLOSED;
26594       } else if (!strcasecmp(v->name, "rtcachefriends")) {
26595          ast_set2_flag(&global_flags[1], ast_true(v->value), SIP_PAGE2_RTCACHEFRIENDS);
26596       } else if (!strcasecmp(v->name, "rtsavesysname")) {
26597          sip_cfg.rtsave_sysname = ast_true(v->value);
26598       } else if (!strcasecmp(v->name, "rtupdate")) {
26599          sip_cfg.peer_rtupdate = ast_true(v->value);
26600       } else if (!strcasecmp(v->name, "ignoreregexpire")) {
26601          sip_cfg.ignore_regexpire = ast_true(v->value);
26602       } else if (!strcasecmp(v->name, "timert1")) {
26603          /* Defaults to 500ms, but RFC 3261 states that it is recommended
26604           * for the value to be set higher, though a lower value is only
26605           * allowed on private networks unconnected to the Internet. */
26606          global_t1 = atoi(v->value);
26607       } else if (!strcasecmp(v->name, "timerb")) {
26608          int tmp = atoi(v->value);
26609          if (tmp < 500) {
26610             global_timer_b = global_t1 * 64;
26611             ast_log(LOG_WARNING, "Invalid value for timerb ('%s').  Setting to default ('%d').\n", v->value, global_timer_b);
26612          }
26613          timerb_set = 1;
26614       } else if (!strcasecmp(v->name, "t1min")) {
26615          global_t1min = atoi(v->value);
26616       } else if (!strcasecmp(v->name, "transport") && !ast_strlen_zero(v->value)) {
26617          char *val = ast_strdupa(v->value);
26618          char *trans;
26619 
26620          while ((trans = strsep(&val, ","))) {
26621             trans = ast_skip_blanks(trans);
26622 
26623             if (!strncasecmp(trans, "udp", 3)) {
26624                default_transports |= SIP_TRANSPORT_UDP;
26625             } else if (!strncasecmp(trans, "tcp", 3)) {
26626                default_transports |= SIP_TRANSPORT_TCP;
26627             } else if (!strncasecmp(trans, "tls", 3)) {
26628                default_transports |= SIP_TRANSPORT_TLS;
26629             } else {
26630                ast_log(LOG_NOTICE, "'%s' is not a valid transport type. if no other is specified, udp will be used.\n", trans);
26631             }
26632             if (default_primary_transport == 0) {
26633                default_primary_transport = default_transports;
26634             }
26635          }
26636       } else if (!strcasecmp(v->name, "tcpenable")) {
26637          if (!ast_false(v->value)) {
26638             ast_debug(2, "Enabling TCP socket for listening\n");
26639             sip_cfg.tcp_enabled = TRUE;
26640          }
26641       } else if (!strcasecmp(v->name, "tcpbindaddr")) {
26642          if (ast_parse_arg(v->value, PARSE_ADDR,
26643                  &sip_tcp_desc.local_address)) {
26644             ast_log(LOG_WARNING, "Invalid %s '%s' at line %d of %s\n",
26645                v->name, v->value, v->lineno, config);
26646          }
26647          ast_debug(2, "Setting TCP socket address to %s\n",
26648               ast_sockaddr_stringify(&sip_tcp_desc.local_address));
26649       } else if (!strcasecmp(v->name, "dynamic_exclude_static") || !strcasecmp(v->name, "dynamic_excludes_static")) {
26650          global_dynamic_exclude_static = ast_true(v->value);
26651       } else if (!strcasecmp(v->name, "contactpermit") || !strcasecmp(v->name, "contactdeny")) {
26652          int ha_error = 0;
26653          sip_cfg.contact_ha = ast_append_ha(v->name + 7, v->value, sip_cfg.contact_ha, &ha_error);
26654          if (ha_error) {
26655             ast_log(LOG_ERROR, "Bad ACL entry in configuration line %d : %s\n", v->lineno, v->value);
26656          }
26657       } else if (!strcasecmp(v->name, "rtautoclear")) {
26658          int i = atoi(v->value);
26659          if (i > 0) {
26660             sip_cfg.rtautoclear = i;
26661          } else {
26662             i = 0;
26663          }
26664          ast_set2_flag(&global_flags[1], i || ast_true(v->value), SIP_PAGE2_RTAUTOCLEAR);
26665       } else if (!strcasecmp(v->name, "usereqphone")) {
26666          ast_set2_flag(&global_flags[0], ast_true(v->value), SIP_USEREQPHONE);
26667       } else if (!strcasecmp(v->name, "prematuremedia")) {
26668          global_prematuremediafilter = ast_true(v->value);
26669       } else if (!strcasecmp(v->name, "relaxdtmf")) {
26670          global_relaxdtmf = ast_true(v->value);
26671       } else if (!strcasecmp(v->name, "vmexten")) {
26672          ast_copy_string(default_vmexten, v->value, sizeof(default_vmexten));
26673       } else if (!strcasecmp(v->name, "rtptimeout")) {
26674          if ((sscanf(v->value, "%30d", &global_rtptimeout) != 1) || (global_rtptimeout < 0)) {
26675             ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d.  Using default.\n", v->value, v->lineno);
26676             global_rtptimeout = 0;
26677          }
26678       } else if (!strcasecmp(v->name, "rtpholdtimeout")) {
26679          if ((sscanf(v->value, "%30d", &global_rtpholdtimeout) != 1) || (global_rtpholdtimeout < 0)) {
26680             ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d.  Using default.\n", v->value, v->lineno);
26681             global_rtpholdtimeout = 0;
26682          }
26683       } else if (!strcasecmp(v->name, "rtpkeepalive")) {
26684          if ((sscanf(v->value, "%30d", &global_rtpkeepalive) != 1) || (global_rtpkeepalive < 0)) {
26685             ast_log(LOG_WARNING, "'%s' is not a valid RTP keepalive time at line %d.  Using default.\n", v->value, v->lineno);
26686             global_rtpkeepalive = DEFAULT_RTPKEEPALIVE;
26687          }
26688       } else if (!strcasecmp(v->name, "compactheaders")) {
26689          sip_cfg.compactheaders = ast_true(v->value);
26690       } else if (!strcasecmp(v->name, "notifymimetype")) {
26691          ast_copy_string(default_notifymime, v->value, sizeof(default_notifymime));
26692       } else if (!strcasecmp(v->name, "directrtpsetup")) {
26693          sip_cfg.directrtpsetup = ast_true(v->value);
26694       } else if (!strcasecmp(v->name, "notifyringing")) {
26695          sip_cfg.notifyringing = ast_true(v->value);
26696       } else if (!strcasecmp(v->name, "notifyhold")) {
26697          sip_cfg.notifyhold = ast_true(v->value);
26698       } else if (!strcasecmp(v->name, "notifycid")) {
26699          if (!strcasecmp(v->value, "ignore-context")) {
26700             sip_cfg.notifycid = IGNORE_CONTEXT;
26701          } else {
26702             sip_cfg.notifycid = ast_true(v->value);
26703          }
26704       } else if (!strcasecmp(v->name, "alwaysauthreject")) {
26705          sip_cfg.alwaysauthreject = ast_true(v->value);
26706       } else if (!strcasecmp(v->name, "auth_options_requests")) {
26707          if (ast_true(v->value)) {
26708             sip_cfg.auth_options_requests = 1;
26709          }
26710       } else if (!strcasecmp(v->name, "mohinterpret")) {
26711          ast_copy_string(default_mohinterpret, v->value, sizeof(default_mohinterpret));
26712       } else if (!strcasecmp(v->name, "mohsuggest")) {
26713          ast_copy_string(default_mohsuggest, v->value, sizeof(default_mohsuggest));
26714       } else if (!strcasecmp(v->name, "language")) {
26715          ast_copy_string(default_language, v->value, sizeof(default_language));
26716       } else if (!strcasecmp(v->name, "regcontext")) {
26717          ast_copy_string(newcontexts, v->value, sizeof(newcontexts));
26718          stringp = newcontexts;
26719          /* Let's remove any contexts that are no longer defined in regcontext */
26720          cleanup_stale_contexts(stringp, oldregcontext);
26721          /* Create contexts if they don't exist already */
26722          while ((context = strsep(&stringp, "&"))) {
26723             ast_copy_string(used_context, context, sizeof(used_context));
26724             ast_context_find_or_create(NULL, NULL, context, "SIP");
26725          }
26726          ast_copy_string(sip_cfg.regcontext, v->value, sizeof(sip_cfg.regcontext));
26727       } else if (!strcasecmp(v->name, "regextenonqualify")) {
26728          sip_cfg.regextenonqualify = ast_true(v->value);
26729       } else if (!strcasecmp(v->name, "callerid")) {
26730          ast_copy_string(default_callerid, v->value, sizeof(default_callerid));
26731       } else if (!strcasecmp(v->name, "mwi_from")) {
26732          ast_copy_string(default_mwi_from, v->value, sizeof(default_mwi_from));
26733       } else if (!strcasecmp(v->name, "fromdomain")) {
26734          char *fromdomainport;
26735          ast_copy_string(default_fromdomain, v->value, sizeof(default_fromdomain));
26736          if ((fromdomainport = strchr(default_fromdomain, ':'))) {
26737             *fromdomainport++ = '\0';
26738             if (!(default_fromdomainport = port_str2int(fromdomainport, 0))) {
26739                ast_log(LOG_NOTICE, "'%s' is not a valid port number for fromdomain.\n",fromdomainport);
26740             }
26741          } else {
26742             default_fromdomainport = STANDARD_SIP_PORT;
26743          }
26744       } else if (!strcasecmp(v->name, "outboundproxy")) {
26745          char *tok, *proxyname;
26746 
26747          if (ast_strlen_zero(v->value)) {
26748             ast_log(LOG_WARNING, "no value given for outbound proxy on line %d of sip.conf.", v->lineno);
26749             continue;
26750          }
26751 
26752          tok = ast_skip_blanks(strtok(ast_strdupa(v->value), ","));
26753 
26754          sip_parse_host(tok, v->lineno, &proxyname,
26755                    &sip_cfg.outboundproxy.port,
26756                    &sip_cfg.outboundproxy.transport);
26757 
26758          if ((tok = strtok(NULL, ","))) {
26759             sip_cfg.outboundproxy.force = !strncasecmp(ast_skip_blanks(tok), "force", 5);
26760          } else {
26761             sip_cfg.outboundproxy.force = FALSE;
26762          }
26763 
26764          if (ast_strlen_zero(proxyname)) {
26765             ast_log(LOG_WARNING, "you must specify a name for the outboundproxy on line %d of sip.conf.", v->lineno);
26766             sip_cfg.outboundproxy.name[0] = '\0';
26767             continue;
26768          }
26769 
26770          ast_copy_string(sip_cfg.outboundproxy.name, proxyname, sizeof(sip_cfg.outboundproxy.name));
26771 
26772          proxy_update(&sip_cfg.outboundproxy);
26773       } else if (!strcasecmp(v->name, "autocreatepeer")) {
26774          sip_cfg.autocreatepeer = ast_true(v->value);
26775       } else if (!strcasecmp(v->name, "match_auth_username")) {
26776          global_match_auth_username = ast_true(v->value);
26777       } else if (!strcasecmp(v->name, "srvlookup")) {
26778          sip_cfg.srvlookup = ast_true(v->value);
26779       } else if (!strcasecmp(v->name, "pedantic")) {
26780          sip_cfg.pedanticsipchecking = ast_true(v->value);
26781       } else if (!strcasecmp(v->name, "maxexpirey") || !strcasecmp(v->name, "maxexpiry")) {
26782          max_expiry = atoi(v->value);
26783          if (max_expiry < 1) {
26784             max_expiry = DEFAULT_MAX_EXPIRY;
26785          }
26786       } else if (!strcasecmp(v->name, "minexpirey") || !strcasecmp(v->name, "minexpiry")) {
26787          min_expiry = atoi(v->value);
26788          if (min_expiry < 1) {
26789             min_expiry = DEFAULT_MIN_EXPIRY;
26790          }
26791       } else if (!strcasecmp(v->name, "defaultexpiry") || !strcasecmp(v->name, "defaultexpirey")) {
26792          default_expiry = atoi(v->value);
26793          if (default_expiry < 1) {
26794             default_expiry = DEFAULT_DEFAULT_EXPIRY;
26795          }
26796       } else if (!strcasecmp(v->name, "mwiexpiry") || !strcasecmp(v->name, "mwiexpirey")) {
26797          mwi_expiry = atoi(v->value);
26798          if (mwi_expiry < 1) {
26799             mwi_expiry = DEFAULT_MWI_EXPIRY;
26800          }
26801       } else if (!strcasecmp(v->name, "sipdebug")) {
26802          if (ast_true(v->value))
26803             sipdebug |= sip_debug_config;
26804       } else if (!strcasecmp(v->name, "dumphistory")) {
26805          dumphistory = ast_true(v->value);
26806       } else if (!strcasecmp(v->name, "recordhistory")) {
26807          recordhistory = ast_true(v->value);
26808       } else if (!strcasecmp(v->name, "registertimeout")) {
26809          global_reg_timeout = atoi(v->value);
26810          if (global_reg_timeout < 1) {
26811             global_reg_timeout = DEFAULT_REGISTRATION_TIMEOUT;
26812          }
26813       } else if (!strcasecmp(v->name, "registerattempts")) {
26814          global_regattempts_max = atoi(v->value);
26815       } else if (!strcasecmp(v->name, "bindaddr") || !strcasecmp(v->name, "udpbindaddr")) {
26816          if (ast_parse_arg(v->value, PARSE_ADDR, &bindaddr)) {
26817             ast_log(LOG_WARNING, "Invalid address: %s\n", v->value);
26818          }
26819       } else if (!strcasecmp(v->name, "localnet")) {
26820          struct ast_ha *na;
26821          int ha_error = 0;
26822 
26823          if (!(na = ast_append_ha("d", v->value, localaddr, &ha_error))) {
26824             ast_log(LOG_WARNING, "Invalid localnet value: %s\n", v->value);
26825          } else {
26826             localaddr = na;
26827          }
26828          if (ha_error) {
26829             ast_log(LOG_ERROR, "Bad localnet configuration value line %d : %s\n", v->lineno, v->value);
26830          }
26831       } else if (!strcasecmp(v->name, "media_address")) {
26832          if (ast_parse_arg(v->value, PARSE_ADDR, &media_address))
26833             ast_log(LOG_WARNING, "Invalid address for media_address keyword: %s\n", v->value);
26834       } else if (!strcasecmp(v->name, "externaddr") || !strcasecmp(v->name, "externip")) {
26835          if (ast_parse_arg(v->value, PARSE_ADDR, &externaddr)) {
26836             ast_log(LOG_WARNING,
26837                "Invalid address for externaddr keyword: %s\n",
26838                v->value);
26839          }
26840          externexpire = 0;
26841       } else if (!strcasecmp(v->name, "externhost")) {
26842          ast_copy_string(externhost, v->value, sizeof(externhost));
26843          if (ast_sockaddr_resolve_first(&externaddr, externhost, 0)) {
26844             ast_log(LOG_WARNING, "Invalid address for externhost keyword: %s\n", externhost);
26845          }
26846          externexpire = time(NULL);
26847       } else if (!strcasecmp(v->name, "externrefresh")) {
26848          if (sscanf(v->value, "%30d", &externrefresh) != 1) {
26849             ast_log(LOG_WARNING, "Invalid externrefresh value '%s', must be an integer >0 at line %d\n", v->value, v->lineno);
26850             externrefresh = 10;
26851          }
26852       } else if (!strcasecmp(v->name, "externtcpport")) {
26853          if (!(externtcpport = port_str2int(v->value, 0))) {
26854             ast_log(LOG_WARNING, "Invalid externtcpport value, must be a positive integer between 1 and 65535 at line %d\n", v->lineno);
26855             externtcpport = 0;
26856          }
26857       } else if (!strcasecmp(v->name, "externtlsport")) {
26858          if (!(externtlsport = port_str2int(v->value, STANDARD_TLS_PORT))) {
26859             ast_log(LOG_WARNING, "Invalid externtlsport value, must be a positive integer between 1 and 65535 at line %d\n", v->lineno);
26860          }
26861       } else if (!strcasecmp(v->name, "allow")) {
26862          int error =  ast_parse_allow_disallow(&default_prefs, &sip_cfg.capability, v->value, TRUE);
26863          if (error) {
26864             ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
26865          }
26866       } else if (!strcasecmp(v->name, "disallow")) {
26867          int error =  ast_parse_allow_disallow(&default_prefs, &sip_cfg.capability, v->value, FALSE);
26868          if (error) {
26869             ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
26870          }
26871       } else if (!strcasecmp(v->name, "preferred_codec_only")) {
26872          ast_set2_flag(&global_flags[1], ast_true(v->value), SIP_PAGE2_PREFERRED_CODEC);
26873       } else if (!strcasecmp(v->name, "autoframing")) {
26874          global_autoframing = ast_true(v->value);
26875       } else if (!strcasecmp(v->name, "allowexternaldomains")) {
26876          sip_cfg.allow_external_domains = ast_true(v->value);
26877       } else if (!strcasecmp(v->name, "autodomain")) {
26878          auto_sip_domains = ast_true(v->value);
26879       } else if (!strcasecmp(v->name, "domain")) {
26880          char *domain = ast_strdupa(v->value);
26881          char *cntx = strchr(domain, ',');
26882 
26883          if (cntx) {
26884             *cntx++ = '\0';
26885          }
26886 
26887          if (ast_strlen_zero(cntx)) {
26888             ast_debug(1, "No context specified at line %d for domain '%s'\n", v->lineno, domain);
26889          }
26890          if (ast_strlen_zero(domain)) {
26891             ast_log(LOG_WARNING, "Empty domain specified at line %d\n", v->lineno);
26892          } else {
26893             add_sip_domain(ast_strip(domain), SIP_DOMAIN_CONFIG, cntx ? ast_strip(cntx) : "");
26894          }
26895       } else if (!strcasecmp(v->name, "register")) {
26896          if (sip_register(v->value, v->lineno) == 0) {
26897             registry_count++;
26898          }
26899       } else if (!strcasecmp(v->name, "mwi")) {
26900          sip_subscribe_mwi(v->value, v->lineno);
26901       } else if (!strcasecmp(v->name, "tos_sip")) {
26902          if (ast_str2tos(v->value, &global_tos_sip)) {
26903             ast_log(LOG_WARNING, "Invalid tos_sip value at line %d, refer to QoS documentation\n", v->lineno);
26904          }
26905       } else if (!strcasecmp(v->name, "tos_audio")) {
26906          if (ast_str2tos(v->value, &global_tos_audio)) {
26907             ast_log(LOG_WARNING, "Invalid tos_audio value at line %d, refer to QoS documentation\n", v->lineno);
26908          }
26909       } else if (!strcasecmp(v->name, "tos_video")) {
26910          if (ast_str2tos(v->value, &global_tos_video)) {
26911             ast_log(LOG_WARNING, "Invalid tos_video value at line %d, refer to QoS documentation\n", v->lineno);
26912          }
26913       } else if (!strcasecmp(v->name, "tos_text")) {
26914          if (ast_str2tos(v->value, &global_tos_text)) {
26915             ast_log(LOG_WARNING, "Invalid tos_text value at line %d, refer to QoS documentation\n", v->lineno);
26916          }
26917       } else if (!strcasecmp(v->name, "cos_sip")) {
26918          if (ast_str2cos(v->value, &global_cos_sip)) {
26919             ast_log(LOG_WARNING, "Invalid cos_sip value at line %d, refer to QoS documentation\n", v->lineno);
26920          }
26921       } else if (!strcasecmp(v->name, "cos_audio")) {
26922          if (ast_str2cos(v->value, &global_cos_audio)) {
26923             ast_log(LOG_WARNING, "Invalid cos_audio value at line %d, refer to QoS documentation\n", v->lineno);
26924          }
26925       } else if (!strcasecmp(v->name, "cos_video")) {
26926          if (ast_str2cos(v->value, &global_cos_video)) {
26927             ast_log(LOG_WARNING, "Invalid cos_video value at line %d, refer to QoS documentation\n", v->lineno);
26928          }
26929       } else if (!strcasecmp(v->name, "cos_text")) {
26930          if (ast_str2cos(v->value, &global_cos_text)) {
26931             ast_log(LOG_WARNING, "Invalid cos_text value at line %d, refer to QoS documentation\n", v->lineno);
26932          }
26933       } else if (!strcasecmp(v->name, "bindport")) {
26934          if (sscanf(v->value, "%5d", &bindport) != 1) {
26935             ast_log(LOG_WARNING, "Invalid port number '%s' at line %d of %s\n", v->value, v->lineno, config);
26936          }
26937       } else if (!strcasecmp(v->name, "qualify")) {
26938          if (!strcasecmp(v->value, "no")) {
26939             default_qualify = 0;
26940          } else if (!strcasecmp(v->value, "yes")) {
26941             default_qualify = DEFAULT_MAXMS;
26942          } else if (sscanf(v->value, "%30d", &default_qualify) != 1) {
26943             ast_log(LOG_WARNING, "Qualification default should be 'yes', 'no', or a number of milliseconds at line %d of sip.conf\n", v->lineno);
26944             default_qualify = 0;
26945          }
26946       } else if (!strcasecmp(v->name, "qualifyfreq")) {
26947          int i;
26948          if (sscanf(v->value, "%30d", &i) == 1) {
26949             global_qualifyfreq = i * 1000;
26950          } else {
26951             ast_log(LOG_WARNING, "Invalid qualifyfreq number '%s' at line %d of %s\n", v->value, v->lineno, config);
26952             global_qualifyfreq = DEFAULT_QUALIFYFREQ;
26953          }
26954       } else if (!strcasecmp(v->name, "callevents")) {
26955          sip_cfg.callevents = ast_true(v->value);
26956       } else if (!strcasecmp(v->name, "authfailureevents")) {
26957          global_authfailureevents = ast_true(v->value);
26958       } else if (!strcasecmp(v->name, "maxcallbitrate")) {
26959          default_maxcallbitrate = atoi(v->value);
26960          if (default_maxcallbitrate < 0)
26961             default_maxcallbitrate = DEFAULT_MAX_CALL_BITRATE;
26962       } else if (!strcasecmp(v->name, "matchexternaddrlocally") || !strcasecmp(v->name, "matchexterniplocally")) {
26963          sip_cfg.matchexternaddrlocally = ast_true(v->value);
26964       } else if (!strcasecmp(v->name, "session-timers")) {
26965          int i = (int) str2stmode(v->value);
26966          if (i < 0) {
26967             ast_log(LOG_WARNING, "Invalid session-timers '%s' at line %d of %s\n", v->value, v->lineno, config);
26968             global_st_mode = SESSION_TIMER_MODE_ACCEPT;
26969          } else {
26970             global_st_mode = i;
26971          }
26972       } else if (!strcasecmp(v->name, "session-expires")) {
26973          if (sscanf(v->value, "%30d", &global_max_se) != 1) {
26974             ast_log(LOG_WARNING, "Invalid session-expires '%s' at line %d of %s\n", v->value, v->lineno, config);
26975             global_max_se = DEFAULT_MAX_SE;
26976          }
26977       } else if (!strcasecmp(v->name, "session-minse")) {
26978          if (sscanf(v->value, "%30d", &global_min_se) != 1) {
26979             ast_log(LOG_WARNING, "Invalid session-minse '%s' at line %d of %s\n", v->value, v->lineno, config);
26980             global_min_se = DEFAULT_MIN_SE;
26981          }
26982          if (global_min_se < 90) {
26983             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);
26984             global_min_se = DEFAULT_MIN_SE;
26985          }
26986       } else if (!strcasecmp(v->name, "session-refresher")) {
26987          int i = (int) str2strefresher(v->value);
26988          if (i < 0) {
26989             ast_log(LOG_WARNING, "Invalid session-refresher '%s' at line %d of %s\n", v->value, v->lineno, config);
26990             global_st_refresher = SESSION_TIMER_REFRESHER_UAS;
26991          } else {
26992             global_st_refresher = i;
26993          }
26994       } else if (!strcasecmp(v->name, "qualifygap")) {
26995          if (sscanf(v->value, "%30d", &global_qualify_gap) != 1) {
26996             ast_log(LOG_WARNING, "Invalid qualifygap '%s' at line %d of %s\n", v->value, v->lineno, config);
26997             global_qualify_gap = DEFAULT_QUALIFY_GAP;
26998          }
26999       } else if (!strcasecmp(v->name, "qualifypeers")) {
27000          if (sscanf(v->value, "%30d", &global_qualify_peers) != 1) {
27001             ast_log(LOG_WARNING, "Invalid pokepeers '%s' at line %d of %s\n", v->value, v->lineno, config);
27002             global_qualify_peers = DEFAULT_QUALIFY_PEERS;
27003          }
27004       } else if (!strcasecmp(v->name, "disallowed_methods")) {
27005          char *disallow = ast_strdupa(v->value);
27006          mark_parsed_methods(&sip_cfg.disallowed_methods, disallow);
27007       } else if (!strcasecmp(v->name, "shrinkcallerid")) {
27008          if (ast_true(v->value)) {
27009             global_shrinkcallerid = 1;
27010          } else if (ast_false(v->value)) {
27011             global_shrinkcallerid = 0;
27012          } else {
27013             ast_log(LOG_WARNING, "shrinkcallerid value %s is not valid at line %d.\n", v->value, v->lineno);
27014          }
27015       } else if (!strcasecmp(v->name, "use_q850_reason")) {
27016          ast_set2_flag(&global_flags[1], ast_true(v->value), SIP_PAGE2_Q850_REASON);
27017       } else if (!strcasecmp(v->name, "maxforwards")) {
27018          if ((sscanf(v->value, "%30d", &sip_cfg.default_max_forwards) != 1) || (sip_cfg.default_max_forwards < 1)) {
27019             ast_log(LOG_WARNING, "'%s' is not a valid maxforwards value at line %d.  Using default.\n", v->value, v->lineno);
27020             sip_cfg.default_max_forwards = DEFAULT_MAX_FORWARDS;
27021          }
27022       } else if (!strcasecmp(v->name, "subscribe_network_change_event")) {
27023          if (ast_true(v->value)) {
27024             subscribe_network_change = 1;
27025          } else if (ast_false(v->value)) {
27026             subscribe_network_change = 0;
27027          } else {
27028             ast_log(LOG_WARNING, "subscribe_network_change_event value %s is not valid at line %d.\n", v->value, v->lineno);
27029          }
27030       } else if (!strcasecmp(v->name, "snom_aoc_enabled")) {
27031          ast_set2_flag(&global_flags[2], ast_true(v->value), SIP_PAGE3_SNOM_AOC);
27032       } else if (!strcasecmp(v->name, "parkinglot")) {
27033          ast_copy_string(default_parkinglot, v->value, sizeof(default_parkinglot));
27034       }
27035    }
27036 
27037    if (subscribe_network_change) {
27038       network_change_event_subscribe();
27039    } else {
27040       network_change_event_unsubscribe();
27041    }
27042 
27043    if (global_t1 < global_t1min) {
27044       ast_log(LOG_WARNING, "'t1min' (%d) cannot be greater than 't1timer' (%d).  Resetting 't1timer' to the value of 't1min'\n", global_t1min, global_t1);
27045       global_t1 = global_t1min;
27046    }
27047 
27048    if (global_timer_b < global_t1 * 64) {
27049       if (timerb_set && timert1_set) {
27050          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);
27051       } else if (timerb_set) {
27052          if ((global_t1 = global_timer_b / 64) < global_t1min) {
27053             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);
27054             global_t1 = global_t1min;
27055             global_timer_b = global_t1 * 64;
27056          }
27057       } else {
27058          global_timer_b = global_t1 * 64;
27059       }
27060    }
27061    if (!sip_cfg.allow_external_domains && AST_LIST_EMPTY(&domain_list)) {
27062       ast_log(LOG_WARNING, "To disallow external domains, you need to configure local SIP domains.\n");
27063       sip_cfg.allow_external_domains = 1;
27064    }
27065    /* If not configured, set default transports */
27066    if (default_transports == 0) {
27067       default_transports = default_primary_transport = SIP_TRANSPORT_UDP;
27068    }
27069 
27070    /* Build list of authentication to various SIP realms, i.e. service providers */
27071    for (v = ast_variable_browse(cfg, "authentication"); v ; v = v->next) {
27072       /* Format for authentication is auth = username:password@realm */
27073       if (!strcasecmp(v->name, "auth")) {
27074          authl = add_realm_authentication(authl, v->value, v->lineno);
27075       }
27076    }
27077 
27078    if (bindport) {
27079       if (ast_sockaddr_port(&bindaddr)) {
27080          ast_log(LOG_WARNING, "bindport is also specified in bindaddr. "
27081             "Using %d.\n", bindport);
27082       }
27083       ast_sockaddr_set_port(&bindaddr, bindport);
27084    }
27085 
27086    if (!ast_sockaddr_port(&bindaddr)) {
27087       ast_sockaddr_set_port(&bindaddr, STANDARD_SIP_PORT);
27088    }
27089 
27090    /* Set UDP address and open socket */
27091    ast_sockaddr_copy(&internip, &bindaddr);
27092    if (ast_find_ourip(&internip, &bindaddr, 0)) {
27093       ast_log(LOG_WARNING, "Unable to get own IP address, SIP disabled\n");
27094       ast_config_destroy(cfg);
27095       return 0;
27096    }
27097 
27098    ast_mutex_lock(&netlock);
27099    if ((sipsock > -1) && (ast_sockaddr_cmp(&old_bindaddr, &bindaddr))) {
27100       close(sipsock);
27101       sipsock = -1;
27102    }
27103    if (sipsock < 0) {
27104       sipsock = socket(ast_sockaddr_is_ipv6(&bindaddr) ?
27105              AF_INET6 : AF_INET, SOCK_DGRAM, 0);
27106       if (sipsock < 0) {
27107          ast_log(LOG_WARNING, "Unable to create SIP socket: %s\n", strerror(errno));
27108          ast_config_destroy(cfg);
27109          ast_mutex_unlock(&netlock);
27110          return -1;
27111       } else {
27112          /* Allow SIP clients on the same host to access us: */
27113          const int reuseFlag = 1;
27114 
27115          setsockopt(sipsock, SOL_SOCKET, SO_REUSEADDR,
27116                (const char*)&reuseFlag,
27117                sizeof reuseFlag);
27118 
27119          ast_enable_packet_fragmentation(sipsock);
27120 
27121          if (ast_bind(sipsock, &bindaddr) < 0) {
27122             ast_log(LOG_WARNING, "Failed to bind to %s: %s\n",
27123                ast_sockaddr_stringify(&bindaddr), strerror(errno));
27124             close(sipsock);
27125             sipsock = -1;
27126          } else {
27127             ast_verb(2, "SIP Listening on %s\n", ast_sockaddr_stringify(&bindaddr));
27128             ast_set_qos(sipsock, global_tos_sip, global_cos_sip, "SIP");
27129          }
27130       }
27131    } else {
27132       ast_set_qos(sipsock, global_tos_sip, global_cos_sip, "SIP");
27133    }
27134    ast_mutex_unlock(&netlock);
27135 
27136    /* Start TCP server */
27137    if (sip_cfg.tcp_enabled) {
27138       if (ast_sockaddr_isnull(&sip_tcp_desc.local_address)) {
27139          ast_sockaddr_copy(&sip_tcp_desc.local_address, &bindaddr);
27140       }
27141       if (!ast_sockaddr_port(&sip_tcp_desc.local_address)) {
27142          ast_sockaddr_set_port(&sip_tcp_desc.local_address, STANDARD_SIP_PORT);
27143       }
27144    } else {
27145       ast_sockaddr_setnull(&sip_tcp_desc.local_address);
27146    }
27147    ast_tcptls_server_start(&sip_tcp_desc);
27148    if (sip_cfg.tcp_enabled && sip_tcp_desc.accept_fd == -1) {
27149       /* TCP server start failed. Tell the admin */
27150       ast_log(LOG_ERROR, "SIP TCP Server start failed. Not listening on TCP socket.\n");
27151    } else {
27152       ast_debug(2, "SIP TCP server started\n");
27153    }
27154 
27155    /* Start TLS server if needed */
27156    memcpy(sip_tls_desc.tls_cfg, &default_tls_cfg, sizeof(default_tls_cfg));
27157 
27158    if (ast_ssl_setup(sip_tls_desc.tls_cfg)) {
27159       if (ast_sockaddr_isnull(&sip_tls_desc.local_address)) {
27160          ast_sockaddr_copy(&sip_tls_desc.local_address, &bindaddr);
27161          ast_sockaddr_set_port(&sip_tls_desc.local_address,
27162                      STANDARD_TLS_PORT);
27163       }
27164       if (!ast_sockaddr_port(&sip_tls_desc.local_address)) {
27165          ast_sockaddr_set_port(&sip_tls_desc.local_address,
27166                      STANDARD_TLS_PORT);
27167       }
27168       ast_tcptls_server_start(&sip_tls_desc);
27169       if (default_tls_cfg.enabled && sip_tls_desc.accept_fd == -1) {
27170          ast_log(LOG_ERROR, "TLS Server start failed. Not listening on TLS socket.\n");
27171          sip_tls_desc.tls_cfg = NULL;
27172       }
27173    } else if (sip_tls_desc.tls_cfg->enabled) {
27174       sip_tls_desc.tls_cfg = NULL;
27175       ast_log(LOG_WARNING, "SIP TLS server did not load because of errors.\n");
27176    }
27177 
27178    if (ucfg) {
27179       struct ast_variable *gen;
27180       int genhassip, genregistersip;
27181       const char *hassip, *registersip;
27182       
27183       genhassip = ast_true(ast_variable_retrieve(ucfg, "general", "hassip"));
27184       genregistersip = ast_true(ast_variable_retrieve(ucfg, "general", "registersip"));
27185       gen = ast_variable_browse(ucfg, "general");
27186       cat = ast_category_browse(ucfg, NULL);
27187       while (cat) {
27188          if (strcasecmp(cat, "general")) {
27189             hassip = ast_variable_retrieve(ucfg, cat, "hassip");
27190             registersip = ast_variable_retrieve(ucfg, cat, "registersip");
27191             if (ast_true(hassip) || (!hassip && genhassip)) {
27192                peer = build_peer(cat, gen, ast_variable_browse(ucfg, cat), 0, 0);
27193                if (peer) {
27194                   /* user.conf entries are always of type friend */
27195                   peer->type = SIP_TYPE_USER | SIP_TYPE_PEER;
27196                   ao2_t_link(peers, peer, "link peer into peer table");
27197                   if ((peer->type & SIP_TYPE_PEER) && !ast_sockaddr_isnull(&peer->addr)) {
27198                      ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
27199                   }
27200                   
27201                   unref_peer(peer, "unref_peer: from reload_config");
27202                   peer_count++;
27203                }
27204             }
27205             if (ast_true(registersip) || (!registersip && genregistersip)) {
27206                char tmp[256];
27207                const char *host = ast_variable_retrieve(ucfg, cat, "host");
27208                const char *username = ast_variable_retrieve(ucfg, cat, "username");
27209                const char *secret = ast_variable_retrieve(ucfg, cat, "secret");
27210                const char *contact = ast_variable_retrieve(ucfg, cat, "contact");
27211                const char *authuser = ast_variable_retrieve(ucfg, cat, "authuser");
27212                if (!host) {
27213                   host = ast_variable_retrieve(ucfg, "general", "host");
27214                }
27215                if (!username) {
27216                   username = ast_variable_retrieve(ucfg, "general", "username");
27217                }
27218                if (!secret) {
27219                   secret = ast_variable_retrieve(ucfg, "general", "secret");
27220                }
27221                if (!contact) {
27222                   contact = "s";
27223                }
27224                if (!ast_strlen_zero(username) && !ast_strlen_zero(host)) {
27225                   if (!ast_strlen_zero(secret)) {
27226                      if (!ast_strlen_zero(authuser)) {
27227                         snprintf(tmp, sizeof(tmp), "%s?%s:%s:%s@%s/%s", cat, username, secret, authuser, host, contact);
27228                      } else {
27229                         snprintf(tmp, sizeof(tmp), "%s?%s:%s@%s/%s", cat, username, secret, host, contact);
27230                      }
27231                   } else if (!ast_strlen_zero(authuser)) {
27232                      snprintf(tmp, sizeof(tmp), "%s?%s::%s@%s/%s", cat, username, authuser, host, contact);
27233                   } else {
27234                      snprintf(tmp, sizeof(tmp), "%s?%s@%s/%s", cat, username, host, contact);
27235                   }
27236                   if (sip_register(tmp, 0) == 0) {
27237                      registry_count++;
27238                   }
27239                }
27240             }
27241          }
27242          cat = ast_category_browse(ucfg, cat);
27243       }
27244       ast_config_destroy(ucfg);
27245    }
27246 
27247    /* Load peers, users and friends */
27248    cat = NULL;
27249    while ( (cat = ast_category_browse(cfg, cat)) ) {
27250       const char *utype;
27251       if (!strcasecmp(cat, "general") || !strcasecmp(cat, "authentication"))
27252          continue;
27253       utype = ast_variable_retrieve(cfg, cat, "type");
27254       if (!utype) {
27255          ast_log(LOG_WARNING, "Section '%s' lacks type\n", cat);
27256          continue;
27257       } else {
27258          if (!strcasecmp(utype, "user")) {
27259             ;
27260          } else if (!strcasecmp(utype, "friend")) {
27261             ;
27262          } else if (!strcasecmp(utype, "peer")) {
27263             ;
27264          } else {
27265             ast_log(LOG_WARNING, "Unknown type '%s' for '%s' in %s\n", utype, cat, "sip.conf");
27266             continue;
27267          }
27268          peer = build_peer(cat, ast_variable_browse(cfg, cat), NULL, 0, 0);
27269          if (peer) {
27270             ao2_t_link(peers, peer, "link peer into peers table");
27271             if ((peer->type & SIP_TYPE_PEER) && !ast_sockaddr_isnull(&peer->addr)) {
27272                ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
27273             }
27274             unref_peer(peer, "unref the result of the build_peer call. Now, the links from the tables are the only ones left.");
27275             peer_count++;
27276          }
27277       }
27278    }
27279 
27280    /* Add default domains - host name, IP address and IP:port
27281     * Only do this if user added any sip domain with "localdomains"
27282     * In order to *not* break backwards compatibility
27283     *    Some phones address us at IP only, some with additional port number
27284     */
27285    if (auto_sip_domains) {
27286       char temp[MAXHOSTNAMELEN];
27287 
27288       /* First our default IP address */
27289       if (!ast_sockaddr_isnull(&bindaddr) && !ast_sockaddr_is_any(&bindaddr)) {
27290          add_sip_domain(ast_sockaddr_stringify_addr(&bindaddr),
27291                    SIP_DOMAIN_AUTO, NULL);
27292       } else if (!ast_sockaddr_isnull(&internip) && !ast_sockaddr_is_any(&internip)) {
27293       /* Our internal IP address, if configured */
27294          add_sip_domain(ast_sockaddr_stringify_addr(&internip),
27295                    SIP_DOMAIN_AUTO, NULL);
27296       } else {
27297          ast_log(LOG_NOTICE, "Can't add wildcard IP address to domain list, please add IP address to domain manually.\n");
27298       }
27299 
27300       /* If TCP is running on a different IP than UDP, then add it too */
27301       if (!ast_sockaddr_isnull(&sip_tcp_desc.local_address) &&
27302           !ast_sockaddr_cmp(&bindaddr, &sip_tcp_desc.local_address)) {
27303          add_sip_domain(ast_sockaddr_stringify_addr(&sip_tcp_desc.local_address),
27304                    SIP_DOMAIN_AUTO, NULL);
27305       }
27306 
27307       /* If TLS is running on a different IP than UDP and TCP, then add that too */
27308       if (!ast_sockaddr_isnull(&sip_tls_desc.local_address) &&
27309           !ast_sockaddr_cmp(&bindaddr, &sip_tls_desc.local_address) &&
27310           !ast_sockaddr_cmp(&sip_tcp_desc.local_address,
27311                   &sip_tls_desc.local_address)) {
27312          add_sip_domain(ast_sockaddr_stringify_addr(&sip_tcp_desc.local_address),
27313                    SIP_DOMAIN_AUTO, NULL);
27314       }
27315 
27316       /* Our extern IP address, if configured */
27317       if (!ast_sockaddr_isnull(&externaddr)) {
27318          add_sip_domain(ast_sockaddr_stringify_addr(&externaddr),
27319                    SIP_DOMAIN_AUTO, NULL);
27320       }
27321 
27322       /* Extern host name (NAT traversal support) */
27323       if (!ast_strlen_zero(externhost)) {
27324          add_sip_domain(externhost, SIP_DOMAIN_AUTO, NULL);
27325       }
27326       
27327       /* Our host name */
27328       if (!gethostname(temp, sizeof(temp))) {
27329          add_sip_domain(temp, SIP_DOMAIN_AUTO, NULL);
27330       }
27331    }
27332 
27333    /* Release configuration from memory */
27334    ast_config_destroy(cfg);
27335 
27336    /* Load the list of manual NOTIFY types to support */
27337    if (notify_types)
27338       ast_config_destroy(notify_types);
27339    if ((notify_types = ast_config_load(notify_config, config_flags)) == CONFIG_STATUS_FILEINVALID) {
27340       ast_log(LOG_ERROR, "Contents of %s are invalid and cannot be parsed.\n", notify_config);
27341       notify_types = NULL;
27342    }
27343 
27344    /* Done, tell the manager */
27345    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);
27346    run_end = time(0);
27347    ast_debug(4, "SIP reload_config done...Runtime= %d sec\n", (int)(run_end-run_start));
27348 
27349    return 0;
27350 }
27351 
27352 static int apply_directmedia_ha(struct sip_pvt *p, const char *op)
27353 {
27354    struct ast_sockaddr us = { { 0, }, }, them = { { 0, }, };
27355    int res = AST_SENSE_ALLOW;
27356 
27357    ast_rtp_instance_get_remote_address(p->rtp, &them);
27358    ast_rtp_instance_get_local_address(p->rtp, &us);
27359 
27360    if ((res = ast_apply_ha(p->directmediaha, &them)) == AST_SENSE_DENY) {
27361       const char *us_addr = ast_strdupa(ast_sockaddr_stringify(&us));
27362       const char *them_addr = ast_strdupa(ast_sockaddr_stringify(&them));
27363 
27364       ast_debug(3, "Reinvite %s to %s denied by directmedia ACL on %s\n",
27365          op, them_addr, us_addr);
27366    }
27367 
27368    return res;
27369 }
27370 
27371 static struct ast_udptl *sip_get_udptl_peer(struct ast_channel *chan)
27372 {
27373    struct sip_pvt *p;
27374    struct ast_udptl *udptl = NULL;
27375    
27376    p = chan->tech_pvt;
27377    if (!p) {
27378       return NULL;
27379    }
27380    
27381    sip_pvt_lock(p);
27382    if (p->udptl && ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA)) {
27383       if (apply_directmedia_ha(p, "UDPTL T.38 data")) {
27384          udptl = p->udptl;
27385       }
27386    }
27387    sip_pvt_unlock(p);
27388    return udptl;
27389 }
27390 
27391 static int sip_set_udptl_peer(struct ast_channel *chan, struct ast_udptl *udptl)
27392 {
27393    struct sip_pvt *p;
27394    
27395    p = chan->tech_pvt;
27396    if (!p) {
27397       return -1;
27398    }
27399    sip_pvt_lock(p);
27400    if (udptl) {
27401       ast_udptl_get_peer(udptl, &p->udptlredirip);
27402    } else {
27403       memset(&p->udptlredirip, 0, sizeof(p->udptlredirip));
27404    }
27405    if (!ast_test_flag(&p->flags[0], SIP_GOTREFER)) {
27406       if (!p->pendinginvite) {
27407          ast_debug(3, "Sending reinvite on SIP '%s' - It's UDPTL soon redirected to IP %s\n",
27408                p->callid, ast_sockaddr_stringify(udptl ? &p->udptlredirip : &p->ourip));
27409          transmit_reinvite_with_sdp(p, TRUE, FALSE);
27410       } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
27411          ast_debug(3, "Deferring reinvite on SIP '%s' - It's UDPTL will be redirected to IP %s\n",
27412                p->callid, ast_sockaddr_stringify(udptl ? &p->udptlredirip : &p->ourip));
27413          ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
27414       }
27415    }
27416    /* Reset lastrtprx timer */
27417    p->lastrtprx = p->lastrtptx = time(NULL);
27418    sip_pvt_unlock(p);
27419    return 0;
27420 }
27421 
27422 static enum ast_rtp_glue_result sip_get_rtp_peer(struct ast_channel *chan, struct ast_rtp_instance **instance)
27423 {
27424    struct sip_pvt *p = NULL;
27425    enum ast_rtp_glue_result res = AST_RTP_GLUE_RESULT_LOCAL;
27426 
27427    if (!(p = chan->tech_pvt)) {
27428       return AST_RTP_GLUE_RESULT_FORBID;
27429    }
27430 
27431    sip_pvt_lock(p);
27432    if (!(p->rtp)) {
27433       sip_pvt_unlock(p);
27434       return AST_RTP_GLUE_RESULT_FORBID;
27435    }
27436 
27437    ao2_ref(p->rtp, +1);
27438    *instance = p->rtp;
27439 
27440    if (ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA)) {
27441       res = AST_RTP_GLUE_RESULT_REMOTE;
27442       if (!apply_directmedia_ha(p, "audio")) {
27443          res = AST_RTP_GLUE_RESULT_FORBID;
27444       }
27445    } else if (ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA_NAT)) {
27446       res = AST_RTP_GLUE_RESULT_REMOTE;
27447    } else if (ast_test_flag(&global_jbconf, AST_JB_FORCED)) {
27448       res = AST_RTP_GLUE_RESULT_FORBID;
27449    }
27450 
27451    if (p->srtp) {
27452       res = AST_RTP_GLUE_RESULT_FORBID;
27453    }
27454 
27455    sip_pvt_unlock(p);
27456 
27457    return res;
27458 }
27459 
27460 static enum ast_rtp_glue_result sip_get_vrtp_peer(struct ast_channel *chan, struct ast_rtp_instance **instance)
27461 {
27462    struct sip_pvt *p = NULL;
27463    enum ast_rtp_glue_result res = AST_RTP_GLUE_RESULT_FORBID;
27464 
27465    if (!(p = chan->tech_pvt)) {
27466       return AST_RTP_GLUE_RESULT_FORBID;
27467    }
27468 
27469    sip_pvt_lock(p);
27470    if (!(p->vrtp)) {
27471       sip_pvt_unlock(p);
27472       return AST_RTP_GLUE_RESULT_FORBID;
27473    }
27474 
27475    ao2_ref(p->vrtp, +1);
27476    *instance = p->vrtp;
27477 
27478    if (ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA)) {
27479       res = AST_RTP_GLUE_RESULT_REMOTE;
27480       if (!apply_directmedia_ha(p, "video")) {
27481          res = AST_RTP_GLUE_RESULT_FORBID;
27482       }
27483    }
27484 
27485    sip_pvt_unlock(p);
27486 
27487    return res;
27488 }
27489 
27490 static enum ast_rtp_glue_result sip_get_trtp_peer(struct ast_channel *chan, struct ast_rtp_instance **instance)
27491 {
27492    struct sip_pvt *p = NULL;
27493    enum ast_rtp_glue_result res = AST_RTP_GLUE_RESULT_FORBID;
27494 
27495    if (!(p = chan->tech_pvt)) {
27496       return AST_RTP_GLUE_RESULT_FORBID;
27497    }
27498 
27499    sip_pvt_lock(p);
27500    if (!(p->trtp)) {
27501       sip_pvt_unlock(p);
27502       return AST_RTP_GLUE_RESULT_FORBID;
27503    }
27504 
27505    ao2_ref(p->trtp, +1);
27506    *instance = p->trtp;
27507 
27508    if (ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA)) {
27509       res = AST_RTP_GLUE_RESULT_REMOTE;
27510       if (!apply_directmedia_ha(p, "text")) {
27511          res = AST_RTP_GLUE_RESULT_FORBID;
27512       }
27513    }
27514 
27515    sip_pvt_unlock(p);
27516 
27517    return res;
27518 }
27519 
27520 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)
27521 {
27522    struct sip_pvt *p;
27523    int changed = 0;
27524 
27525    p = chan->tech_pvt;
27526    if (!p) {
27527       return -1;
27528    }
27529 
27530    /* Disable early RTP bridge  */
27531    if (!ast_bridged_channel(chan) && !sip_cfg.directrtpsetup)  /* We are in early state */
27532       return 0;
27533 
27534    sip_pvt_lock(p);
27535    if (p->alreadygone) {
27536       /* If we're destroyed, don't bother */
27537       sip_pvt_unlock(p);
27538       return 0;
27539    }
27540 
27541    /* if this peer cannot handle reinvites of the media stream to devices
27542       that are known to be behind a NAT, then stop the process now
27543    */
27544    if (nat_active && !ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA_NAT)) {
27545       sip_pvt_unlock(p);
27546       return 0;
27547    }
27548 
27549    if (instance) {
27550       changed |= ast_rtp_instance_get_remote_address(instance, &p->redirip);
27551    } else if (!ast_sockaddr_isnull(&p->redirip)) {
27552       memset(&p->redirip, 0, sizeof(p->redirip));
27553       changed = 1;
27554    }
27555    if (vinstance) {
27556       changed |= ast_rtp_instance_get_remote_address(vinstance, &p->vredirip);
27557    } else if (!ast_sockaddr_isnull(&p->vredirip)) {
27558       memset(&p->vredirip, 0, sizeof(p->vredirip));
27559       changed = 1;
27560    }
27561    if (tinstance) {
27562       changed |= ast_rtp_instance_get_remote_address(tinstance, &p->tredirip);
27563    } else if (!ast_sockaddr_isnull(&p->tredirip)) {
27564       memset(&p->tredirip, 0, sizeof(p->tredirip));
27565       changed = 1;
27566    }
27567    if (codecs && (p->redircodecs != codecs)) {
27568       p->redircodecs = codecs;
27569       changed = 1;
27570    }
27571    if (changed && !ast_test_flag(&p->flags[0], SIP_GOTREFER) && !ast_test_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER)) {
27572       if (chan->_state != AST_STATE_UP) {     /* We are in early state */
27573          if (p->do_history)
27574             append_history(p, "ExtInv", "Initial invite sent with remote bridge proposal.");
27575          ast_debug(1, "Early remote bridge setting SIP '%s' - Sending media to %s\n", p->callid, ast_sockaddr_stringify(instance ? &p->redirip : &p->ourip));
27576       } else if (!p->pendinginvite) {   /* We are up, and have no outstanding invite */
27577          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));
27578          transmit_reinvite_with_sdp(p, FALSE, FALSE);
27579       } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
27580          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));
27581          /* We have a pending Invite. Send re-invite when we're done with the invite */
27582          ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
27583       }
27584    }
27585    /* Reset lastrtprx timer */
27586    p->lastrtprx = p->lastrtptx = time(NULL);
27587    sip_pvt_unlock(p);
27588    return 0;
27589 }
27590 
27591 static format_t sip_get_codec(struct ast_channel *chan)
27592 {
27593    struct sip_pvt *p = chan->tech_pvt;
27594    return p->peercapability ? p->peercapability : p->capability;
27595 }
27596 
27597 static struct ast_rtp_glue sip_rtp_glue = {
27598    .type = "SIP",
27599    .get_rtp_info = sip_get_rtp_peer,
27600    .get_vrtp_info = sip_get_vrtp_peer,
27601    .get_trtp_info = sip_get_trtp_peer,
27602    .update_peer = sip_set_rtp_peer,
27603    .get_codec = sip_get_codec,
27604 };
27605 
27606 static char *app_dtmfmode = "SIPDtmfMode";
27607 static char *app_sipaddheader = "SIPAddHeader";
27608 static char *app_sipremoveheader = "SIPRemoveHeader";
27609 
27610 /*! \brief Set the DTMFmode for an outbound SIP call (application) */
27611 static int sip_dtmfmode(struct ast_channel *chan, const char *data)
27612 {
27613    struct sip_pvt *p;
27614    const char *mode = data;
27615 
27616    if (!data) {
27617       ast_log(LOG_WARNING, "This application requires the argument: info, inband, rfc2833\n");
27618       return 0;
27619    }
27620    ast_channel_lock(chan);
27621    if (!IS_SIP_TECH(chan->tech)) {
27622       ast_log(LOG_WARNING, "Call this application only on SIP incoming calls\n");
27623       ast_channel_unlock(chan);
27624       return 0;
27625    }
27626    p = chan->tech_pvt;
27627    if (!p) {
27628       ast_channel_unlock(chan);
27629       return 0;
27630    }
27631    sip_pvt_lock(p);
27632    if (!strcasecmp(mode, "info")) {
27633       ast_clear_flag(&p->flags[0], SIP_DTMF);
27634       ast_set_flag(&p->flags[0], SIP_DTMF_INFO);
27635       p->jointnoncodeccapability &= ~AST_RTP_DTMF;
27636    } else if (!strcasecmp(mode, "shortinfo")) {
27637       ast_clear_flag(&p->flags[0], SIP_DTMF);
27638       ast_set_flag(&p->flags[0], SIP_DTMF_SHORTINFO);
27639       p->jointnoncodeccapability &= ~AST_RTP_DTMF;
27640    } else if (!strcasecmp(mode, "rfc2833")) {
27641       ast_clear_flag(&p->flags[0], SIP_DTMF);
27642       ast_set_flag(&p->flags[0], SIP_DTMF_RFC2833);
27643       p->jointnoncodeccapability |= AST_RTP_DTMF;
27644    } else if (!strcasecmp(mode, "inband")) {
27645       ast_clear_flag(&p->flags[0], SIP_DTMF);
27646       ast_set_flag(&p->flags[0], SIP_DTMF_INBAND);
27647       p->jointnoncodeccapability &= ~AST_RTP_DTMF;
27648    } else {
27649       ast_log(LOG_WARNING, "I don't know about this dtmf mode: %s\n", mode);
27650    }
27651    if (p->rtp)
27652       ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_DTMF, ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
27653    if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) ||
27654        (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO)) {
27655       enable_dsp_detect(p);
27656    } else {
27657       disable_dsp_detect(p);
27658    }
27659    sip_pvt_unlock(p);
27660    ast_channel_unlock(chan);
27661    return 0;
27662 }
27663 
27664 /*! \brief Add a SIP header to an outbound INVITE */
27665 static int sip_addheader(struct ast_channel *chan, const char *data)
27666 {
27667    int no = 0;
27668    int ok = FALSE;
27669    char varbuf[30];
27670    const char *inbuf = data;
27671    char *subbuf;
27672    
27673    if (ast_strlen_zero(inbuf)) {
27674       ast_log(LOG_WARNING, "This application requires the argument: Header\n");
27675       return 0;
27676    }
27677    ast_channel_lock(chan);
27678 
27679    /* Check for headers */
27680    while (!ok && no <= 50) {
27681       no++;
27682       snprintf(varbuf, sizeof(varbuf), "__SIPADDHEADER%.2d", no);
27683 
27684       /* Compare without the leading underscores */
27685       if ((pbx_builtin_getvar_helper(chan, (const char *) varbuf + 2) == (const char *) NULL)) {
27686          ok = TRUE;
27687       }
27688    }
27689    if (ok) {
27690       size_t len = strlen(inbuf);
27691       subbuf = alloca(len + 1);
27692       ast_get_encoded_str(inbuf, subbuf, len + 1);
27693       pbx_builtin_setvar_helper(chan, varbuf, subbuf);
27694       if (sipdebug) {
27695          ast_debug(1, "SIP Header added \"%s\" as %s\n", inbuf, varbuf);
27696       }
27697    } else {
27698       ast_log(LOG_WARNING, "Too many SIP headers added, max 50\n");
27699    }
27700    ast_channel_unlock(chan);
27701    return 0;
27702 }
27703 
27704 /*! \brief Remove SIP headers added previously with SipAddHeader application */
27705 static int sip_removeheader(struct ast_channel *chan, const char *data)
27706 {
27707    struct ast_var_t *newvariable;
27708    struct varshead *headp;
27709    int removeall = 0;
27710    char *inbuf = (char *) data;
27711 
27712    if (ast_strlen_zero(inbuf)) {
27713       removeall = 1;
27714    }
27715    ast_channel_lock(chan);
27716 
27717    headp=&chan->varshead;
27718    AST_LIST_TRAVERSE_SAFE_BEGIN (headp, newvariable, entries) {
27719       if (strncasecmp(ast_var_name(newvariable), "SIPADDHEADER", strlen("SIPADDHEADER")) == 0) {
27720          if (removeall || (!strncasecmp(ast_var_value(newvariable),inbuf,strlen(inbuf)))) {
27721             if (sipdebug)
27722                ast_debug(1,"removing SIP Header \"%s\" as %s\n",
27723                   ast_var_value(newvariable),
27724                   ast_var_name(newvariable));
27725             AST_LIST_REMOVE_CURRENT(entries);
27726             ast_var_delete(newvariable);
27727          }
27728       }
27729    }
27730    AST_LIST_TRAVERSE_SAFE_END;
27731 
27732    ast_channel_unlock(chan);
27733    return 0;
27734 }
27735 
27736 /*! \brief Transfer call before connect with a 302 redirect
27737 \note Called by the transfer() dialplan application through the sip_transfer()
27738    pbx interface function if the call is in ringing state
27739 \todo Fix this function so that we wait for reply to the REFER and
27740    react to errors, denials or other issues the other end might have.
27741  */
27742 static int sip_sipredirect(struct sip_pvt *p, const char *dest)
27743 {
27744    char *cdest;
27745    char *extension, *domain;
27746 
27747    cdest = ast_strdupa(dest);
27748    
27749    extension = strsep(&cdest, "@");
27750    domain = strsep(&cdest, ":");
27751    if (ast_strlen_zero(extension)) {
27752       ast_log(LOG_ERROR, "Missing mandatory argument: extension\n");
27753       return 0;
27754    }
27755 
27756    /* we'll issue the redirect message here */
27757    if (!domain) {
27758       char *local_to_header;
27759       char to_header[256];
27760 
27761       ast_copy_string(to_header, get_header(&p->initreq, "To"), sizeof(to_header));
27762       if (ast_strlen_zero(to_header)) {
27763          ast_log(LOG_ERROR, "Cannot retrieve the 'To' header from the original SIP request!\n");
27764          return 0;
27765       }
27766       if (((local_to_header = strcasestr(to_header, "sip:")) || (local_to_header = strcasestr(to_header, "sips:")))
27767          && (local_to_header = strchr(local_to_header, '@'))) {
27768          char ldomain[256];
27769 
27770          memset(ldomain, 0, sizeof(ldomain));
27771          local_to_header++;
27772          /* This is okey because lhost and lport are as big as tmp */
27773          sscanf(local_to_header, "%256[^<>; ]", ldomain);
27774          if (ast_strlen_zero(ldomain)) {
27775             ast_log(LOG_ERROR, "Can't find the host address\n");
27776             return 0;
27777          }
27778          domain = ast_strdupa(ldomain);
27779       }
27780    }
27781 
27782    ast_string_field_build(p, our_contact, "Transfer <sip:%s@%s>", extension, domain);
27783    transmit_response_reliable(p, "302 Moved Temporarily", &p->initreq);
27784 
27785    sip_scheddestroy(p, SIP_TRANS_TIMEOUT);   /* Make sure we stop send this reply. */
27786    sip_alreadygone(p);
27787 
27788    if (p->owner) {
27789       enum ast_control_transfer message = AST_TRANSFER_SUCCESS;
27790       ast_queue_control_data(p->owner, AST_CONTROL_TRANSFER, &message, sizeof(message));
27791    }
27792    /* hangup here */
27793    return 0;
27794 }
27795 
27796 static int sip_is_xml_parsable(void)
27797 {
27798 #ifdef HAVE_LIBXML2
27799    return TRUE;
27800 #else
27801    return FALSE;
27802 #endif
27803 }
27804 
27805 /*! \brief Send a poke to all known peers */
27806 static void sip_poke_all_peers(void)
27807 {
27808    int ms = 0, num = 0;
27809    struct ao2_iterator i;
27810    struct sip_peer *peer;
27811 
27812    if (!speerobjs) { /* No peers, just give up */
27813       return;
27814    }
27815 
27816    i = ao2_iterator_init(peers, 0);
27817    while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
27818       ao2_lock(peer);
27819       if (num == global_qualify_peers) {
27820          ms += global_qualify_gap;
27821          num = 0;
27822       } else {
27823          num++;
27824       }
27825       AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched, ms, sip_poke_peer_s, peer,
27826             unref_peer(_data, "removing poke peer ref"),
27827             unref_peer(peer, "removing poke peer ref"),
27828             ref_peer(peer, "adding poke peer ref"));
27829       ao2_unlock(peer);
27830       unref_peer(peer, "toss iterator peer ptr");
27831    }
27832    ao2_iterator_destroy(&i);
27833 }
27834 
27835 /*! \brief Send all known registrations */
27836 static void sip_send_all_registers(void)
27837 {
27838    int ms;
27839    int regspacing;
27840    if (!regobjs)
27841       return;
27842    regspacing = default_expiry * 1000/regobjs;
27843    if (regspacing > 100) {
27844       regspacing = 100;
27845    }
27846    ms = regspacing;
27847    ASTOBJ_CONTAINER_TRAVERSE(&regl, 1, do {
27848       ASTOBJ_WRLOCK(iterator);
27849       ms += regspacing;
27850       AST_SCHED_REPLACE_UNREF(iterator->expire, sched, ms, sip_reregister, iterator,
27851                         registry_unref(_data, "REPLACE sched del decs the refcount"),
27852                         registry_unref(iterator, "REPLACE sched add failure decs the refcount"),
27853                         registry_addref(iterator, "REPLACE sched add incs the refcount"));
27854       ASTOBJ_UNLOCK(iterator);
27855    } while (0)
27856    );
27857 }
27858 
27859 /*! \brief Send all MWI subscriptions */
27860 static void sip_send_all_mwi_subscriptions(void)
27861 {
27862    ASTOBJ_CONTAINER_TRAVERSE(&submwil, 1, do {
27863       ASTOBJ_WRLOCK(iterator);
27864       AST_SCHED_DEL(sched, iterator->resub);
27865       if ((iterator->resub = ast_sched_add(sched, 1, sip_subscribe_mwi_do, ASTOBJ_REF(iterator))) < 0) {
27866          ASTOBJ_UNREF(iterator, sip_subscribe_mwi_destroy);
27867       }
27868       ASTOBJ_UNLOCK(iterator);
27869    } while (0));
27870 }
27871 
27872 /* SRTP */
27873 static int setup_srtp(struct sip_srtp **srtp)
27874 {
27875    if (!ast_rtp_engine_srtp_is_registered()) {
27876       ast_log(LOG_ERROR, "No SRTP module loaded, can't setup SRTP session.\n");
27877       return -1;
27878    }
27879 
27880    if (!(*srtp = sip_srtp_alloc())) { /* Allocate SRTP data structure */
27881       return -1;
27882    }
27883 
27884    return 0;
27885 }
27886 
27887 static int process_crypto(struct sip_pvt *p, struct ast_rtp_instance *rtp, struct sip_srtp **srtp, const char *a)
27888 {
27889    if (strncasecmp(a, "crypto:", 7)) {
27890       return FALSE;
27891    }
27892    if (!*srtp) {
27893       if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
27894          ast_log(LOG_WARNING, "Ignoring unexpected crypto attribute in SDP answer\n");
27895          return FALSE;
27896       }
27897 
27898       if (setup_srtp(srtp) < 0) {
27899          return FALSE;
27900       }
27901    }
27902 
27903    /* For now, when we receive an INVITE just take the first successful crypto line */
27904    if ((*srtp)->crypto && !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
27905       ast_debug(3, "We've already processed a crypto attribute, skipping '%s'\n", a);
27906       return FALSE;
27907    }
27908 
27909    if (!(*srtp)->crypto && !((*srtp)->crypto = sdp_crypto_setup())) {
27910       return FALSE;
27911    }
27912 
27913    if (sdp_crypto_process((*srtp)->crypto, a, rtp) < 0) {
27914       return FALSE;
27915    }
27916 
27917    ast_set_flag(*srtp, SRTP_CRYPTO_OFFER_OK);
27918 
27919    return TRUE;
27920 }
27921 
27922 /*! \brief Reload module */
27923 static int sip_do_reload(enum channelreloadreason reason)
27924 {
27925    time_t start_poke, end_poke;
27926    
27927    reload_config(reason);
27928    ast_sched_dump(sched);
27929 
27930    start_poke = time(0);
27931    /* Prune peers who still are supposed to be deleted */
27932    unlink_marked_peers_from_tables();
27933 
27934    ast_debug(4, "--------------- Done destroying pruned peers\n");
27935 
27936    /* Send qualify (OPTIONS) to all peers */
27937    sip_poke_all_peers();
27938 
27939    /* Register with all services */
27940    sip_send_all_registers();
27941 
27942    sip_send_all_mwi_subscriptions();
27943 
27944    end_poke = time(0);
27945    
27946    ast_debug(4, "do_reload finished. peer poke/prune reg contact time = %d sec.\n", (int)(end_poke-start_poke));
27947 
27948    ast_debug(4, "--------------- SIP reload done\n");
27949 
27950    return 0;
27951 }
27952 
27953 /*! \brief Force reload of module from cli */
27954 static char *sip_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
27955 {
27956    
27957    switch (cmd) {
27958    case CLI_INIT:
27959       e->command = "sip reload";
27960       e->usage =
27961          "Usage: sip reload\n"
27962          "       Reloads SIP configuration from sip.conf\n";
27963       return NULL;
27964    case CLI_GENERATE:
27965       return NULL;
27966    }
27967 
27968    ast_mutex_lock(&sip_reload_lock);
27969    if (sip_reloading) {
27970       ast_verbose("Previous SIP reload not yet done\n");
27971    } else {
27972       sip_reloading = TRUE;
27973       sip_reloadreason = (a && a->fd) ? CHANNEL_CLI_RELOAD : CHANNEL_MODULE_RELOAD;
27974    }
27975    ast_mutex_unlock(&sip_reload_lock);
27976    restart_monitor();
27977 
27978    return CLI_SUCCESS;
27979 }
27980 
27981 /*! \brief  Part of Asterisk module interface */
27982 static int reload(void)
27983 {
27984    if (sip_reload(0, 0, NULL))
27985       return 0;
27986    return 1;
27987 }
27988 
27989 /*! \brief  Return the first entry from ast_sockaddr_resolve filtered by address family
27990  *
27991  * \warn Using this function probably means you have a faulty design.
27992  */
27993 static int ast_sockaddr_resolve_first_af(struct ast_sockaddr *addr,
27994                   const char* name, int flag, int family)
27995 {
27996    struct ast_sockaddr *addrs;
27997    int addrs_cnt;
27998 
27999    addrs_cnt = ast_sockaddr_resolve(&addrs, name, flag, family);
28000    if (addrs_cnt <= 0) {
28001       return 1;
28002    }
28003    if (addrs_cnt > 1) {
28004       ast_debug(1, "Multiple addresses, using the first one only\n");
28005    }
28006 
28007    ast_sockaddr_copy(addr, &addrs[0]);
28008 
28009    ast_free(addrs);
28010    return 0;
28011 }
28012 
28013 /*! \brief  Return the first entry from ast_sockaddr_resolve filtered by family of binddaddr
28014  *
28015  * \warn Using this function probably means you have a faulty design.
28016  */
28017 static int ast_sockaddr_resolve_first(struct ast_sockaddr *addr,
28018                   const char* name, int flag)
28019 {
28020    return ast_sockaddr_resolve_first_af(addr, name, flag, get_address_family_filter(&bindaddr));
28021 }
28022 
28023 /*! \brief
28024  * \note The only member of the peer used here is the name field
28025  */
28026 static int peer_hash_cb(const void *obj, const int flags)
28027 {
28028    const struct sip_peer *peer = obj;
28029 
28030    return ast_str_case_hash(peer->name);
28031 }
28032 
28033 /*!
28034  * \note The only member of the peer used here is the name field
28035  */
28036 static int peer_cmp_cb(void *obj, void *arg, int flags)
28037 {
28038    struct sip_peer *peer = obj, *peer2 = arg;
28039 
28040    return !strcasecmp(peer->name, peer2->name) ? CMP_MATCH | CMP_STOP : 0;
28041 }
28042 
28043 /*!
28044  * Hash function based on the the peer's ip address.  For IPv6, we use the end
28045  * of the address.
28046  * \todo Find a better hashing function
28047  */
28048 static int peer_iphash_cb(const void *obj, const int flags)
28049 {
28050    const struct sip_peer *peer = obj;
28051    int ret = 0;
28052 
28053    if (ast_sockaddr_isnull(&peer->addr)) {
28054       ast_log(LOG_ERROR, "Empty address\n");
28055    }
28056 
28057    ret = ast_sockaddr_hash(&peer->addr);
28058 
28059    if (ret < 0) {
28060       ret = -ret;
28061    }
28062 
28063    return ret;
28064 }
28065 
28066 /*!
28067  * Match Peers by IP and Port number.
28068  *
28069  * This function has two modes.
28070  *  - If the peer arg does not have INSECURE_PORT set, then we will only return
28071  *    a match for a peer that matches both the IP and port.
28072  *  - If the peer arg does have the INSECURE_PORT flag set, then we will only
28073  *    return a match for a peer that matches the IP and has insecure=port
28074  *    in its configuration.
28075  *
28076  * This callback will be used twice when doing peer matching.  There is a first
28077  * pass for full IP+port matching, and a second pass in case there is a match
28078  * that meets the insecure=port criteria.
28079  *
28080  * \note Connections coming in over TCP or TLS should never be matched by port.
28081  *
28082  * \note the peer's addr struct provides to fields combined to make a key: the sin_addr.s_addr and sin_port fields.
28083  */
28084 static int peer_ipcmp_cb(void *obj, void *arg, int flags)
28085 {
28086    struct sip_peer *peer = obj, *peer2 = arg;
28087 
28088    if (ast_sockaddr_cmp_addr(&peer->addr, &peer2->addr)) {
28089       /* IP doesn't match */
28090       return 0;
28091    }
28092 
28093    /* We matched the IP, check to see if we need to match by port as well. */
28094    if ((peer->transports & peer2->transports) & (SIP_TRANSPORT_TLS | SIP_TRANSPORT_TCP)) {
28095       /* peer matching on port is not possible with TCP/TLS */
28096       return CMP_MATCH | CMP_STOP;
28097    } else if (ast_test_flag(&peer2->flags[0], SIP_INSECURE_PORT)) {
28098       /* We are allowing match without port for peers configured that
28099        * way in this pass through the peers. */
28100       return ast_test_flag(&peer->flags[0], SIP_INSECURE_PORT) ?
28101             (CMP_MATCH | CMP_STOP) : 0;
28102    }
28103 
28104    /* Now only return a match if the port matches, as well. */
28105    return ast_sockaddr_port(&peer->addr) == ast_sockaddr_port(&peer2->addr) ?
28106          (CMP_MATCH | CMP_STOP) : 0;
28107 }
28108 
28109 
28110 static int threadt_hash_cb(const void *obj, const int flags)
28111 {
28112    const struct sip_threadinfo *th = obj;
28113 
28114    return ast_sockaddr_hash(&th->tcptls_session->remote_address);
28115 }
28116 
28117 static int threadt_cmp_cb(void *obj, void *arg, int flags)
28118 {
28119    struct sip_threadinfo *th = obj, *th2 = arg;
28120 
28121    return (th->tcptls_session == th2->tcptls_session) ? CMP_MATCH | CMP_STOP : 0;
28122 }
28123 
28124 /*!
28125  * \note The only member of the dialog used here callid string
28126  */
28127 static int dialog_hash_cb(const void *obj, const int flags)
28128 {
28129    const struct sip_pvt *pvt = obj;
28130 
28131    return ast_str_case_hash(pvt->callid);
28132 }
28133 
28134 /*!
28135  * \note Same as dialog_cmp_cb, except without the CMP_STOP on match
28136  */
28137 static int dialog_find_multiple(void *obj, void *arg, int flags)
28138 {
28139    struct sip_pvt *pvt = obj, *pvt2 = arg;
28140 
28141    return !strcasecmp(pvt->callid, pvt2->callid) ? CMP_MATCH : 0;
28142 }
28143 
28144 /*!
28145  * \note The only member of the dialog used here callid string
28146  */
28147 static int dialog_cmp_cb(void *obj, void *arg, int flags)
28148 {
28149    struct sip_pvt *pvt = obj, *pvt2 = arg;
28150 
28151    return !strcasecmp(pvt->callid, pvt2->callid) ? CMP_MATCH | CMP_STOP : 0;
28152 }
28153 
28154 /*! \brief SIP Cli commands definition */
28155 static struct ast_cli_entry cli_sip[] = {
28156    AST_CLI_DEFINE(sip_show_channels, "List active SIP channels or subscriptions"),
28157    AST_CLI_DEFINE(sip_show_channelstats, "List statistics for active SIP channels"),
28158    AST_CLI_DEFINE(sip_show_domains, "List our local SIP domains"),
28159    AST_CLI_DEFINE(sip_show_inuse, "List all inuse/limits"),
28160    AST_CLI_DEFINE(sip_show_objects, "List all SIP object allocations"),
28161    AST_CLI_DEFINE(sip_show_peers, "List defined SIP peers"),
28162    AST_CLI_DEFINE(sip_show_registry, "List SIP registration status"),
28163    AST_CLI_DEFINE(sip_unregister, "Unregister (force expiration) a SIP peer from the registry"),
28164    AST_CLI_DEFINE(sip_show_settings, "Show SIP global settings"),
28165    AST_CLI_DEFINE(sip_show_mwi, "Show MWI subscriptions"),
28166    AST_CLI_DEFINE(sip_cli_notify, "Send a notify packet to a SIP peer"),
28167    AST_CLI_DEFINE(sip_show_channel, "Show detailed SIP channel info"),
28168    AST_CLI_DEFINE(sip_show_history, "Show SIP dialog history"),
28169    AST_CLI_DEFINE(sip_show_peer, "Show details on specific SIP peer"),
28170    AST_CLI_DEFINE(sip_show_users, "List defined SIP users"),
28171    AST_CLI_DEFINE(sip_show_user, "Show details on specific SIP user"),
28172    AST_CLI_DEFINE(sip_qualify_peer, "Send an OPTIONS packet to a peer"),
28173    AST_CLI_DEFINE(sip_show_sched, "Present a report on the status of the scheduler queue"),
28174    AST_CLI_DEFINE(sip_prune_realtime, "Prune cached Realtime users/peers"),
28175    AST_CLI_DEFINE(sip_do_debug, "Enable/Disable SIP debugging"),
28176    AST_CLI_DEFINE(sip_set_history, "Enable/Disable SIP history"),
28177    AST_CLI_DEFINE(sip_reload, "Reload SIP configuration"),
28178    AST_CLI_DEFINE(sip_show_tcp, "List TCP Connections")
28179 };
28180 
28181 /*! \brief SIP test registration */
28182 static void sip_register_tests(void)
28183 {
28184    sip_config_parser_register_tests();
28185    sip_request_parser_register_tests();
28186    sip_dialplan_function_register_tests();
28187 }
28188 
28189 /*! \brief SIP test registration */
28190 static void sip_unregister_tests(void)
28191 {
28192    sip_config_parser_unregister_tests();
28193    sip_request_parser_unregister_tests();
28194    sip_dialplan_function_unregister_tests();
28195 }
28196 
28197 #ifdef TEST_FRAMEWORK
28198 AST_TEST_DEFINE(test_sip_peers_get)
28199 {
28200    struct sip_peer *peer;
28201    struct ast_data *node;
28202    struct ast_data_query query = {
28203       .path = "/asterisk/channel/sip/peers",
28204       .search = "peers/peer/name=test_peer_data_provider"
28205    };
28206 
28207    switch (cmd) {
28208       case TEST_INIT:
28209          info->name = "sip_peers_get_data_test";
28210          info->category = "/main/data/sip/peers/";
28211          info->summary = "SIP peers data providers unit test";
28212          info->description =
28213             "Tests whether the SIP peers data provider implementation works as expected.";
28214          return AST_TEST_NOT_RUN;
28215       case TEST_EXECUTE:
28216          break;
28217    }
28218 
28219    /* Create the peer that we will retrieve. */
28220    peer = build_peer("test_peer_data_provider", NULL, NULL, 0, 0);
28221    if (!peer) {
28222       return AST_TEST_FAIL;
28223    }
28224    peer->type = SIP_TYPE_USER;
28225    peer->call_limit = 10;
28226    ao2_link(peers, peer);
28227 
28228    /* retrieve the chan_sip/peers tree and check the created peer. */
28229    node = ast_data_get(&query);
28230    if (!node) {
28231       ao2_unlink(peers, peer);
28232       ao2_ref(peer, -1);
28233       return AST_TEST_FAIL;
28234    }
28235 
28236    /* compare item. */
28237    if (strcmp(ast_data_retrieve_string(node, "peer/name"), "test_peer_data_provider")) {
28238       ao2_unlink(peers, peer);
28239       ao2_ref(peer, -1);
28240       ast_data_free(node);
28241       return AST_TEST_FAIL;
28242    }
28243 
28244    if (strcmp(ast_data_retrieve_string(node, "peer/type"), "user")) {
28245       ao2_unlink(peers, peer);
28246       ao2_ref(peer, -1);
28247       ast_data_free(node);
28248       return AST_TEST_FAIL;
28249    }
28250 
28251    if (ast_data_retrieve_int(node, "peer/call_limit") != 10) {
28252       ao2_unlink(peers, peer);
28253       ao2_ref(peer, -1);
28254       ast_data_free(node);
28255       return AST_TEST_FAIL;
28256    }
28257 
28258    /* release resources */
28259    ast_data_free(node);
28260 
28261    ao2_unlink(peers, peer);
28262    ao2_ref(peer, -1);
28263 
28264    return AST_TEST_PASS;
28265 }
28266 
28267 #endif
28268 
28269 #define DATA_EXPORT_SIP_PEER(MEMBER)            \
28270    MEMBER(sip_peer, name, AST_DATA_STRING)         \
28271    MEMBER(sip_peer, secret, AST_DATA_PASSWORD)     \
28272    MEMBER(sip_peer, md5secret, AST_DATA_PASSWORD)     \
28273    MEMBER(sip_peer, remotesecret, AST_DATA_PASSWORD)  \
28274    MEMBER(sip_peer, context, AST_DATA_STRING)      \
28275    MEMBER(sip_peer, subscribecontext, AST_DATA_STRING)   \
28276    MEMBER(sip_peer, username, AST_DATA_STRING)     \
28277    MEMBER(sip_peer, accountcode, AST_DATA_STRING)     \
28278    MEMBER(sip_peer, tohost, AST_DATA_STRING)    \
28279    MEMBER(sip_peer, regexten, AST_DATA_STRING)     \
28280    MEMBER(sip_peer, fromuser, AST_DATA_STRING)     \
28281    MEMBER(sip_peer, fromdomain, AST_DATA_STRING)      \
28282    MEMBER(sip_peer, fullcontact, AST_DATA_STRING)     \
28283    MEMBER(sip_peer, cid_num, AST_DATA_STRING)      \
28284    MEMBER(sip_peer, cid_name, AST_DATA_STRING)     \
28285    MEMBER(sip_peer, vmexten, AST_DATA_STRING)      \
28286    MEMBER(sip_peer, language, AST_DATA_STRING)     \
28287    MEMBER(sip_peer, mohinterpret, AST_DATA_STRING)    \
28288    MEMBER(sip_peer, mohsuggest, AST_DATA_STRING)      \
28289    MEMBER(sip_peer, parkinglot, AST_DATA_STRING)      \
28290    MEMBER(sip_peer, useragent, AST_DATA_STRING)    \
28291    MEMBER(sip_peer, mwi_from, AST_DATA_STRING)     \
28292    MEMBER(sip_peer, engine, AST_DATA_STRING)    \
28293    MEMBER(sip_peer, unsolicited_mailbox, AST_DATA_STRING)   \
28294    MEMBER(sip_peer, is_realtime, AST_DATA_BOOLEAN)    \
28295    MEMBER(sip_peer, host_dynamic, AST_DATA_BOOLEAN)   \
28296    MEMBER(sip_peer, autoframing, AST_DATA_BOOLEAN)    \
28297    MEMBER(sip_peer, inUse, AST_DATA_INTEGER)    \
28298    MEMBER(sip_peer, inRinging, AST_DATA_INTEGER)      \
28299    MEMBER(sip_peer, onHold, AST_DATA_INTEGER)      \
28300    MEMBER(sip_peer, call_limit, AST_DATA_INTEGER)     \
28301    MEMBER(sip_peer, t38_maxdatagram, AST_DATA_INTEGER)   \
28302    MEMBER(sip_peer, maxcallbitrate, AST_DATA_INTEGER) \
28303    MEMBER(sip_peer, rtptimeout, AST_DATA_SECONDS)     \
28304    MEMBER(sip_peer, rtpholdtimeout, AST_DATA_SECONDS) \
28305    MEMBER(sip_peer, rtpkeepalive, AST_DATA_SECONDS)   \
28306    MEMBER(sip_peer, lastms, AST_DATA_MILLISECONDS)    \
28307    MEMBER(sip_peer, maxms, AST_DATA_MILLISECONDS)     \
28308    MEMBER(sip_peer, qualifyfreq, AST_DATA_MILLISECONDS)  \
28309    MEMBER(sip_peer, timer_t1, AST_DATA_MILLISECONDS)  \
28310    MEMBER(sip_peer, timer_b, AST_DATA_MILLISECONDS)
28311 
28312 AST_DATA_STRUCTURE(sip_peer, DATA_EXPORT_SIP_PEER);
28313 
28314 static int peers_data_provider_get(const struct ast_data_search *search,
28315    struct ast_data *data_root)
28316 {
28317    struct sip_peer *peer;
28318    struct ao2_iterator i;
28319    struct ast_data *data_peer, *data_peer_mailboxes = NULL, *data_peer_mailbox, *enum_node;
28320    struct ast_data *data_sip_options;
28321    int total_mailboxes, x;
28322    struct sip_mailbox *mailbox;
28323 
28324    i = ao2_iterator_init(peers, 0);
28325    while ((peer = ao2_iterator_next(&i))) {
28326       ao2_lock(peer);
28327 
28328       data_peer = ast_data_add_node(data_root, "peer");
28329       if (!data_peer) {
28330          ao2_unlock(peer);
28331          ao2_ref(peer, -1);
28332          continue;
28333       }
28334 
28335       ast_data_add_structure(sip_peer, data_peer, peer);
28336 
28337       /* transfer mode */
28338       enum_node = ast_data_add_node(data_peer, "allowtransfer");
28339       if (!enum_node) {
28340          continue;
28341       }
28342       ast_data_add_str(enum_node, "text", transfermode2str(peer->allowtransfer));
28343       ast_data_add_int(enum_node, "value", peer->allowtransfer);
28344 
28345       /* transports */
28346       ast_data_add_str(data_peer, "transports", get_transport_list(peer->transports));
28347 
28348       /* peer type */
28349       if ((peer->type & SIP_TYPE_USER) && (peer->type & SIP_TYPE_PEER)) {
28350          ast_data_add_str(data_peer, "type", "friend");
28351       } else if (peer->type & SIP_TYPE_PEER) {
28352          ast_data_add_str(data_peer, "type", "peer");
28353       } else if (peer->type & SIP_TYPE_USER) {
28354          ast_data_add_str(data_peer, "type", "user");
28355       }
28356 
28357       /* mailboxes */
28358       total_mailboxes = 0;
28359       AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
28360          if (!total_mailboxes) {
28361             data_peer_mailboxes = ast_data_add_node(data_peer, "mailboxes");
28362             if (!data_peer_mailboxes) {
28363                break;
28364             }
28365             total_mailboxes++;
28366          }
28367 
28368          data_peer_mailbox = ast_data_add_node(data_peer_mailboxes, "mailbox");
28369          if (!data_peer_mailbox) {
28370             continue;
28371          }
28372          ast_data_add_str(data_peer_mailbox, "mailbox", mailbox->mailbox);
28373          ast_data_add_str(data_peer_mailbox, "context", mailbox->context);
28374       }
28375 
28376       /* amaflags */
28377       enum_node = ast_data_add_node(data_peer, "amaflags");
28378       if (!enum_node) {
28379          continue;
28380       }
28381       ast_data_add_int(enum_node, "value", peer->amaflags);
28382       ast_data_add_str(enum_node, "text", ast_cdr_flags2str(peer->amaflags));
28383 
28384       /* sip options */
28385       data_sip_options = ast_data_add_node(data_peer, "sipoptions");
28386       if (!data_sip_options) {
28387          continue;
28388       }
28389       for (x = 0 ; x < ARRAY_LEN(sip_options); x++) {
28390          ast_data_add_bool(data_sip_options, sip_options[x].text, peer->sipoptions & sip_options[x].id);
28391       }
28392 
28393       /* callingpres */
28394       enum_node = ast_data_add_node(data_peer, "callingpres");
28395       if (!enum_node) {
28396          continue;
28397       }
28398       ast_data_add_int(enum_node, "value", peer->callingpres);
28399       ast_data_add_str(enum_node, "text", ast_describe_caller_presentation(peer->callingpres));
28400 
28401       /* codecs */
28402       ast_data_add_codecs(data_peer, "codecs", peer->capability);
28403 
28404       if (!ast_data_search_match(search, data_peer)) {
28405          ast_data_remove_node(data_root, data_peer);
28406       }
28407 
28408       ao2_unlock(peer);
28409       ao2_ref(peer, -1);
28410    }
28411    ao2_iterator_destroy(&i);
28412 
28413    return 0;
28414 }
28415 
28416 static const struct ast_data_handler peers_data_provider = {
28417    .version = AST_DATA_HANDLER_VERSION,
28418    .get = peers_data_provider_get
28419 };
28420 
28421 static const struct ast_data_entry sip_data_providers[] = {
28422    AST_DATA_ENTRY("asterisk/channel/sip/peers", &peers_data_provider),
28423 };
28424 
28425 /*! \brief PBX load module - initialization */
28426 static int load_module(void)
28427 {
28428    ast_verbose("SIP channel loading...\n");
28429    /* the fact that ao2_containers can't resize automatically is a major worry! */
28430    /* if the number of objects gets above MAX_XXX_BUCKETS, things will slow down */
28431    peers = ao2_t_container_alloc(HASH_PEER_SIZE, peer_hash_cb, peer_cmp_cb, "allocate peers");
28432    peers_by_ip = ao2_t_container_alloc(HASH_PEER_SIZE, peer_iphash_cb, peer_ipcmp_cb, "allocate peers_by_ip");
28433    dialogs = ao2_t_container_alloc(HASH_DIALOG_SIZE, dialog_hash_cb, dialog_cmp_cb, "allocate dialogs");
28434    threadt = ao2_t_container_alloc(HASH_DIALOG_SIZE, threadt_hash_cb, threadt_cmp_cb, "allocate threadt table");
28435    
28436    ASTOBJ_CONTAINER_INIT(&regl); /* Registry object list -- not searched for anything */
28437    ASTOBJ_CONTAINER_INIT(&submwil); /* MWI subscription object list */
28438 
28439    if (!(sched = sched_context_create())) {
28440       ast_log(LOG_ERROR, "Unable to create scheduler context\n");
28441       return AST_MODULE_LOAD_FAILURE;
28442    }
28443 
28444    if (!(io = io_context_create())) {
28445       ast_log(LOG_ERROR, "Unable to create I/O context\n");
28446       sched_context_destroy(sched);
28447       return AST_MODULE_LOAD_FAILURE;
28448    }
28449 
28450    sip_reloadreason = CHANNEL_MODULE_LOAD;
28451 
28452    can_parse_xml = sip_is_xml_parsable();
28453    if(reload_config(sip_reloadreason)) {  /* Load the configuration from sip.conf */
28454       return AST_MODULE_LOAD_DECLINE;
28455    }
28456 
28457    /* Prepare the version that does not require DTMF BEGIN frames.
28458     * We need to use tricks such as memcpy and casts because the variable
28459     * has const fields.
28460     */
28461    memcpy(&sip_tech_info, &sip_tech, sizeof(sip_tech));
28462    memset((void *) &sip_tech_info.send_digit_begin, 0, sizeof(sip_tech_info.send_digit_begin));
28463 
28464    /* Make sure we can register our sip channel type */
28465    if (ast_channel_register(&sip_tech)) {
28466       ast_log(LOG_ERROR, "Unable to register channel type 'SIP'\n");
28467       io_context_destroy(io);
28468       sched_context_destroy(sched);
28469       return AST_MODULE_LOAD_FAILURE;
28470    }
28471 
28472 #ifdef TEST_FRAMEWORK
28473    AST_TEST_REGISTER(test_sip_peers_get);
28474 #endif
28475 
28476    /* Register AstData providers */
28477    ast_data_register_multiple(sip_data_providers, ARRAY_LEN(sip_data_providers));
28478 
28479    /* Register all CLI functions for SIP */
28480    ast_cli_register_multiple(cli_sip, ARRAY_LEN(cli_sip));
28481 
28482    /* Tell the UDPTL subdriver that we're here */
28483    ast_udptl_proto_register(&sip_udptl);
28484 
28485    /* Tell the RTP engine about our RTP glue */
28486    ast_rtp_glue_register(&sip_rtp_glue);
28487 
28488    /* Register dialplan applications */
28489    ast_register_application_xml(app_dtmfmode, sip_dtmfmode);
28490    ast_register_application_xml(app_sipaddheader, sip_addheader);
28491    ast_register_application_xml(app_sipremoveheader, sip_removeheader);
28492 
28493    /* Register dialplan functions */
28494    ast_custom_function_register(&sip_header_function);
28495    ast_custom_function_register(&sippeer_function);
28496    ast_custom_function_register(&sipchaninfo_function);
28497    ast_custom_function_register(&checksipdomain_function);
28498 
28499    /* Register manager commands */
28500    ast_manager_register_xml("SIPpeers", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_sip_show_peers);
28501    ast_manager_register_xml("SIPshowpeer", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_sip_show_peer);
28502    ast_manager_register_xml("SIPqualifypeer", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_sip_qualify_peer);
28503    ast_manager_register_xml("SIPshowregistry", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_show_registry);
28504    ast_manager_register_xml("SIPnotify", EVENT_FLAG_SYSTEM, manager_sipnotify);
28505    sip_poke_all_peers();   
28506    sip_send_all_registers();
28507    sip_send_all_mwi_subscriptions();
28508    initialize_escs();
28509 
28510    if (sip_epa_register(&cc_epa_static_data)) {
28511       return AST_MODULE_LOAD_DECLINE;
28512    }
28513 
28514    if (sip_reqresp_parser_init() == -1) {
28515       ast_log(LOG_ERROR, "Unable to initialize the SIP request and response parser\n");
28516       return AST_MODULE_LOAD_DECLINE;
28517    }
28518 
28519    if (can_parse_xml) {
28520       /* SIP CC agents require the ability to parse XML PIDF bodies
28521        * in incoming PUBLISH requests
28522        */
28523       if (ast_cc_agent_register(&sip_cc_agent_callbacks)) {
28524          return AST_MODULE_LOAD_DECLINE;
28525       }
28526    }
28527    if (ast_cc_monitor_register(&sip_cc_monitor_callbacks)) {
28528       return AST_MODULE_LOAD_DECLINE;
28529    }
28530    if (!(sip_monitor_instances = ao2_container_alloc(37, sip_monitor_instance_hash_fn, sip_monitor_instance_cmp_fn))) {
28531       return AST_MODULE_LOAD_DECLINE;
28532    }
28533 
28534    /* And start the monitor for the first time */
28535    restart_monitor();
28536 
28537    ast_realtime_require_field(ast_check_realtime("sipregs") ? "sipregs" : "sippeers",
28538       "name", RQ_CHAR, 10,
28539       "ipaddr", RQ_CHAR, 15,
28540       "port", RQ_UINTEGER2, 5,
28541       "regseconds", RQ_INTEGER4, 11,
28542       "defaultuser", RQ_CHAR, 10,
28543       "fullcontact", RQ_CHAR, 35,
28544       "regserver", RQ_CHAR, 20,
28545       "useragent", RQ_CHAR, 20,
28546       "lastms", RQ_INTEGER4, 11,
28547       SENTINEL);
28548 
28549 
28550    sip_register_tests();
28551    network_change_event_subscribe();
28552 
28553    return AST_MODULE_LOAD_SUCCESS;
28554 }
28555 
28556 /*! \brief PBX unload module API */
28557 static int unload_module(void)
28558 {
28559    struct sip_pvt *p;
28560    struct sip_threadinfo *th;
28561    struct ast_context *con;
28562    struct ao2_iterator i;
28563 
28564    network_change_event_unsubscribe();
28565 
28566    ast_sched_dump(sched);
28567    
28568    /* First, take us out of the channel type list */
28569    ast_channel_unregister(&sip_tech);
28570 
28571    /* Unregister dial plan functions */
28572    ast_custom_function_unregister(&sipchaninfo_function);
28573    ast_custom_function_unregister(&sippeer_function);
28574    ast_custom_function_unregister(&sip_header_function);
28575    ast_custom_function_unregister(&checksipdomain_function);
28576 
28577    /* Unregister dial plan applications */
28578    ast_unregister_application(app_dtmfmode);
28579    ast_unregister_application(app_sipaddheader);
28580    ast_unregister_application(app_sipremoveheader);
28581 
28582 #ifdef TEST_FRAMEWORK
28583    AST_TEST_UNREGISTER(test_sip_peers_get);
28584 #endif
28585    /* Unregister all the AstData providers */
28586    ast_data_unregister(NULL);
28587 
28588    /* Unregister CLI commands */
28589    ast_cli_unregister_multiple(cli_sip, ARRAY_LEN(cli_sip));
28590 
28591    /* Disconnect from UDPTL */
28592    ast_udptl_proto_unregister(&sip_udptl);
28593 
28594    /* Disconnect from RTP engine */
28595    ast_rtp_glue_unregister(&sip_rtp_glue);
28596 
28597    /* Unregister AMI actions */
28598    ast_manager_unregister("SIPpeers");
28599    ast_manager_unregister("SIPshowpeer");
28600    ast_manager_unregister("SIPqualifypeer");
28601    ast_manager_unregister("SIPshowregistry");
28602    ast_manager_unregister("SIPnotify");
28603    
28604    /* Kill TCP/TLS server threads */
28605    if (sip_tcp_desc.master) {
28606       ast_tcptls_server_stop(&sip_tcp_desc);
28607    }
28608    if (sip_tls_desc.master) {
28609       ast_tcptls_server_stop(&sip_tls_desc);
28610    }
28611 
28612    /* Kill all existing TCP/TLS threads */
28613    i = ao2_iterator_init(threadt, 0);
28614    while ((th = ao2_t_iterator_next(&i, "iterate through tcp threads for 'sip show tcp'"))) {
28615       pthread_t thread = th->threadid;
28616       th->stop = 1;
28617       pthread_kill(thread, SIGURG);
28618       pthread_join(thread, NULL);
28619       ao2_t_ref(th, -1, "decrement ref from iterator");
28620    }
28621    ao2_iterator_destroy(&i);
28622 
28623    /* Hangup all dialogs if they have an owner */
28624    i = ao2_iterator_init(dialogs, 0);
28625    while ((p = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
28626       if (p->owner)
28627          ast_softhangup(p->owner, AST_SOFTHANGUP_APPUNLOAD);
28628       ao2_t_ref(p, -1, "toss dialog ptr from iterator_next");
28629    }
28630    ao2_iterator_destroy(&i);
28631 
28632    ast_mutex_lock(&monlock);
28633    if (monitor_thread && (monitor_thread != AST_PTHREADT_STOP) && (monitor_thread != AST_PTHREADT_NULL)) {
28634       pthread_cancel(monitor_thread);
28635       pthread_kill(monitor_thread, SIGURG);
28636       pthread_join(monitor_thread, NULL);
28637    }
28638    monitor_thread = AST_PTHREADT_STOP;
28639    ast_mutex_unlock(&monlock);
28640 
28641    /* Destroy all the dialogs and free their memory */
28642    i = ao2_iterator_init(dialogs, 0);
28643    while ((p = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
28644       dialog_unlink_all(p, TRUE, TRUE);
28645       ao2_t_ref(p, -1, "throw away iterator result");
28646    }
28647    ao2_iterator_destroy(&i);
28648 
28649    /* Free memory for local network address mask */
28650    ast_free_ha(localaddr);
28651 
28652    clear_realm_authentication(authl);
28653 
28654    destroy_escs();
28655 
28656    if (default_tls_cfg.certfile) {
28657       ast_free(default_tls_cfg.certfile);
28658    }
28659    if (default_tls_cfg.pvtfile) {
28660       ast_free(default_tls_cfg.pvtfile);
28661    }
28662    if (default_tls_cfg.cipher) {
28663       ast_free(default_tls_cfg.cipher);
28664    }
28665    if (default_tls_cfg.cafile) {
28666       ast_free(default_tls_cfg.cafile);
28667    }
28668    if (default_tls_cfg.capath) {
28669       ast_free(default_tls_cfg.capath);
28670    }
28671 
28672    ASTOBJ_CONTAINER_DESTROYALL(&regl, sip_registry_destroy);
28673    ASTOBJ_CONTAINER_DESTROY(&regl);
28674    ASTOBJ_CONTAINER_DESTROYALL(&submwil, sip_subscribe_mwi_destroy);
28675    ASTOBJ_CONTAINER_DESTROY(&submwil);
28676 
28677    ao2_t_ref(peers, -1, "unref the peers table");
28678    ao2_t_ref(peers_by_ip, -1, "unref the peers_by_ip table");
28679    ao2_t_ref(dialogs, -1, "unref the dialogs table");
28680    ao2_t_ref(threadt, -1, "unref the thread table");
28681 
28682    clear_sip_domains();
28683    ast_free_ha(sip_cfg.contact_ha);
28684    close(sipsock);
28685    sched_context_destroy(sched);
28686    con = ast_context_find(used_context);
28687    if (con) {
28688       ast_context_destroy(con, "SIP");
28689    }
28690    ast_unload_realtime("sipregs");
28691    ast_unload_realtime("sippeers");
28692    ast_cc_monitor_unregister(&sip_cc_monitor_callbacks);
28693    ast_cc_agent_unregister(&sip_cc_agent_callbacks);
28694 
28695    sip_reqresp_parser_exit();
28696    sip_unregister_tests();
28697 
28698    return 0;
28699 }
28700 
28701 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "Session Initiation Protocol (SIP)",
28702       .load = load_module,
28703       .unload = unload_module,
28704       .reload = reload,
28705       .load_pri = AST_MODPRI_CHANNEL_DRIVER,
28706       .nonoptreq = "res_crypto,chan_local",
28707           );

Generated on Sat Mar 26 11:07:19 2011 for Asterisk - The Open Source Telephony Project by  doxygen 1.5.9