Sat Feb 11 06:33:10 2012

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 type="module">res_crypto</use>
00166    <depend>chan_local</depend>
00167    <support_level>core</support_level>
00168  ***/
00169 
00170 /*!  \page sip_session_timers SIP Session Timers in Asterisk Chan_sip
00171 
00172    The SIP Session-Timers is an extension of the SIP protocol that allows end-points and proxies to
00173    refresh a session periodically. The sessions are kept alive by sending a RE-INVITE or UPDATE
00174    request at a negotiated interval. If a session refresh fails then all the entities that support Session-
00175    Timers clear their internal session state. In addition, UAs generate a BYE request in order to clear
00176    the state in the proxies and the remote UA (this is done for the benefit of SIP entities in the path
00177    that do not support Session-Timers).
00178 
00179    The Session-Timers can be configured on a system-wide, per-user, or per-peer basis. The peruser/
00180    per-peer settings override the global settings. The following new parameters have been
00181    added to the sip.conf file.
00182       session-timers=["accept", "originate", "refuse"]
00183       session-expires=[integer]
00184       session-minse=[integer]
00185       session-refresher=["uas", "uac"]
00186 
00187    The session-timers parameter in sip.conf defines the mode of operation of SIP session-timers feature in
00188    Asterisk. The Asterisk can be configured in one of the following three modes:
00189 
00190    1. Accept :: In the "accept" mode, the Asterisk server honors session-timers requests
00191       made by remote end-points. A remote end-point can request Asterisk to engage
00192       session-timers by either sending it an INVITE request with a "Supported: timer"
00193       header in it or by responding to Asterisk's INVITE with a 200 OK that contains
00194       Session-Expires: header in it. In this mode, the Asterisk server does not
00195       request session-timers from remote end-points. This is the default mode.
00196    2. Originate :: In the "originate" mode, the Asterisk server requests the remote
00197       end-points to activate session-timers in addition to honoring such requests
00198       made by the remote end-pints. In order to get as much protection as possible
00199       against hanging SIP channels due to network or end-point failures, Asterisk
00200       resends periodic re-INVITEs even if a remote end-point does not support
00201       the session-timers feature.
00202    3. Refuse :: In the "refuse" mode, Asterisk acts as if it does not support session-
00203       timers for inbound or outbound requests. If a remote end-point requests
00204       session-timers in a dialog, then Asterisk ignores that request unless it's
00205       noted as a requirement (Require: header), in which case the INVITE is
00206       rejected with a 420 Bad Extension response.
00207 
00208 */
00209 
00210 #include "asterisk.h"
00211 
00212 ASTERISK_FILE_VERSION(__FILE__, "$Revision: 354704 $")
00213 
00214 #include <signal.h>
00215 #include <sys/signal.h>
00216 #include <regex.h>
00217 #include <inttypes.h>
00218 
00219 #include "asterisk/network.h"
00220 #include "asterisk/paths.h"   /* need ast_config_AST_SYSTEM_NAME */
00221 /*
00222    Uncomment the define below,  if you are having refcount related memory leaks.
00223    With this uncommented, this module will generate a file, /tmp/refs, which contains
00224    a history of the ao2_ref() calls. To be useful, all calls to ao2_* functions should
00225    be modified to ao2_t_* calls, and include a tag describing what is happening with
00226    enough detail, to make pairing up a reference count increment with its corresponding decrement.
00227    The refcounter program in utils/ can be invaluable in highlighting objects that are not
00228    balanced, along with the complete history for that object.
00229    In normal operation, the macros defined will throw away the tags, so they do not
00230    affect the speed of the program at all. They can be considered to be documentation.
00231 */
00232 /* #define  REF_DEBUG 1 */
00233 #include "asterisk/lock.h"
00234 #include "asterisk/config.h"
00235 #include "asterisk/module.h"
00236 #include "asterisk/pbx.h"
00237 #include "asterisk/sched.h"
00238 #include "asterisk/io.h"
00239 #include "asterisk/rtp_engine.h"
00240 #include "asterisk/udptl.h"
00241 #include "asterisk/acl.h"
00242 #include "asterisk/manager.h"
00243 #include "asterisk/callerid.h"
00244 #include "asterisk/cli.h"
00245 #include "asterisk/musiconhold.h"
00246 #include "asterisk/dsp.h"
00247 #include "asterisk/features.h"
00248 #include "asterisk/srv.h"
00249 #include "asterisk/astdb.h"
00250 #include "asterisk/causes.h"
00251 #include "asterisk/utils.h"
00252 #include "asterisk/file.h"
00253 #include "asterisk/astobj2.h"
00254 #include "asterisk/dnsmgr.h"
00255 #include "asterisk/devicestate.h"
00256 #include "asterisk/monitor.h"
00257 #include "asterisk/netsock2.h"
00258 #include "asterisk/localtime.h"
00259 #include "asterisk/abstract_jb.h"
00260 #include "asterisk/threadstorage.h"
00261 #include "asterisk/translate.h"
00262 #include "asterisk/ast_version.h"
00263 #include "asterisk/event.h"
00264 #include "asterisk/cel.h"
00265 #include "asterisk/data.h"
00266 #include "asterisk/aoc.h"
00267 #include "asterisk/message.h"
00268 #include "sip/include/sip.h"
00269 #include "sip/include/globals.h"
00270 #include "sip/include/config_parser.h"
00271 #include "sip/include/reqresp_parser.h"
00272 #include "sip/include/sip_utils.h"
00273 #include "sip/include/srtp.h"
00274 #include "sip/include/sdp_crypto.h"
00275 #include "asterisk/ccss.h"
00276 #include "asterisk/xml.h"
00277 #include "sip/include/dialog.h"
00278 #include "sip/include/dialplan_functions.h"
00279 #include "sip/include/security_events.h"
00280 
00281 
00282 /*** DOCUMENTATION
00283    <application name="SIPDtmfMode" language="en_US">
00284       <synopsis>
00285          Change the dtmfmode for a SIP call.
00286       </synopsis>
00287       <syntax>
00288          <parameter name="mode" required="true">
00289             <enumlist>
00290                <enum name="inband" />
00291                <enum name="info" />
00292                <enum name="rfc2833" />
00293             </enumlist>
00294          </parameter>
00295       </syntax>
00296       <description>
00297          <para>Changes the dtmfmode for a SIP call.</para>
00298       </description>
00299    </application>
00300    <application name="SIPAddHeader" language="en_US">
00301       <synopsis>
00302          Add a SIP header to the outbound call.
00303       </synopsis>
00304       <syntax argsep=":">
00305          <parameter name="Header" required="true" />
00306          <parameter name="Content" required="true" />
00307       </syntax>
00308       <description>
00309          <para>Adds a header to a SIP call placed with DIAL.</para>
00310          <para>Remember to use the X-header if you are adding non-standard SIP
00311          headers, like <literal>X-Asterisk-Accountcode:</literal>. Use this with care.
00312          Adding the wrong headers may jeopardize the SIP dialog.</para>
00313          <para>Always returns <literal>0</literal>.</para>
00314       </description>
00315    </application>
00316    <application name="SIPRemoveHeader" language="en_US">
00317       <synopsis>
00318          Remove SIP headers previously added with SIPAddHeader
00319       </synopsis>
00320       <syntax>
00321          <parameter name="Header" required="false" />
00322       </syntax>
00323       <description>
00324          <para>SIPRemoveHeader() allows you to remove headers which were previously
00325          added with SIPAddHeader(). If no parameter is supplied, all previously added
00326          headers will be removed. If a parameter is supplied, only the matching headers
00327          will be removed.</para>
00328          <para>For example you have added these 2 headers:</para>
00329          <para>SIPAddHeader(P-Asserted-Identity: sip:foo@bar);</para>
00330          <para>SIPAddHeader(P-Preferred-Identity: sip:bar@foo);</para>
00331          <para></para>
00332          <para>// remove all headers</para>
00333          <para>SIPRemoveHeader();</para>
00334          <para>// remove all P- headers</para>
00335          <para>SIPRemoveHeader(P-);</para>
00336          <para>// remove only the PAI header (note the : at the end)</para>
00337          <para>SIPRemoveHeader(P-Asserted-Identity:);</para>
00338          <para></para>
00339          <para>Always returns <literal>0</literal>.</para>
00340       </description>
00341    </application>
00342    <function name="SIP_HEADER" language="en_US">
00343       <synopsis>
00344          Gets the specified SIP header from an incoming INVITE message.
00345       </synopsis>
00346       <syntax>
00347          <parameter name="name" required="true" />
00348          <parameter name="number">
00349             <para>If not specified, defaults to <literal>1</literal>.</para>
00350          </parameter>
00351       </syntax>
00352       <description>
00353          <para>Since there are several headers (such as Via) which can occur multiple
00354          times, SIP_HEADER takes an optional second argument to specify which header with
00355          that name to retrieve. Headers start at offset <literal>1</literal>.</para>
00356          <para>Please observe that contents of the SDP (an attachment to the 
00357          SIP request) can't be accessed with this function.</para>
00358       </description>
00359    </function>
00360    <function name="SIPPEER" language="en_US">
00361       <synopsis>
00362          Gets SIP peer information.
00363       </synopsis>
00364       <syntax>
00365          <parameter name="peername" required="true" />
00366          <parameter name="item">
00367             <enumlist>
00368                <enum name="ip">
00369                   <para>(default) The IP address.</para>
00370                </enum>
00371                <enum name="port">
00372                   <para>The port number.</para>
00373                </enum>
00374                <enum name="mailbox">
00375                   <para>The configured mailbox.</para>
00376                </enum>
00377                <enum name="context">
00378                   <para>The configured context.</para>
00379                </enum>
00380                <enum name="expire">
00381                   <para>The epoch time of the next expire.</para>
00382                </enum>
00383                <enum name="dynamic">
00384                   <para>Is it dynamic? (yes/no).</para>
00385                </enum>
00386                <enum name="callerid_name">
00387                   <para>The configured Caller ID name.</para>
00388                </enum>
00389                <enum name="callerid_num">
00390                   <para>The configured Caller ID number.</para>
00391                </enum>
00392                <enum name="callgroup">
00393                   <para>The configured Callgroup.</para>
00394                </enum>
00395                <enum name="pickupgroup">
00396                   <para>The configured Pickupgroup.</para>
00397                </enum>
00398                <enum name="codecs">
00399                   <para>The configured codecs.</para>
00400                </enum>
00401                <enum name="status">
00402                   <para>Status (if qualify=yes).</para>
00403                </enum>
00404                <enum name="regexten">
00405                   <para>Extension activated at registration.</para>
00406                </enum>
00407                <enum name="limit">
00408                   <para>Call limit (call-limit).</para>
00409                </enum>
00410                <enum name="busylevel">
00411                   <para>Configured call level for signalling busy.</para>
00412                </enum>
00413                <enum name="curcalls">
00414                   <para>Current amount of calls. Only available if call-limit is set.</para>
00415                </enum>
00416                <enum name="language">
00417                   <para>Default language for peer.</para>
00418                </enum>
00419                <enum name="accountcode">
00420                   <para>Account code for this peer.</para>
00421                </enum>
00422                <enum name="useragent">
00423                   <para>Current user agent header used by peer.</para>
00424                </enum>
00425                <enum name="maxforwards">
00426                   <para>The value used for SIP loop prevention in outbound requests</para>
00427                </enum>
00428                <enum name="chanvar[name]">
00429                   <para>A channel variable configured with setvar for this peer.</para>
00430                </enum>
00431                <enum name="codec[x]">
00432                   <para>Preferred codec index number <replaceable>x</replaceable> (beginning with zero).</para>
00433                </enum>
00434             </enumlist>
00435          </parameter>
00436       </syntax>
00437       <description></description>
00438    </function>
00439    <function name="SIPCHANINFO" language="en_US">
00440       <synopsis>
00441          Gets the specified SIP parameter from the current channel.
00442       </synopsis>
00443       <syntax>
00444          <parameter name="item" required="true">
00445             <enumlist>
00446                <enum name="peerip">
00447                   <para>The IP address of the peer.</para>
00448                </enum>
00449                <enum name="recvip">
00450                   <para>The source IP address of the peer.</para>
00451                </enum>
00452                <enum name="from">
00453                   <para>The SIP URI from the <literal>From:</literal> header.</para>
00454                </enum>
00455                <enum name="uri">
00456                   <para>The SIP URI from the <literal>Contact:</literal> header.</para>
00457                </enum>
00458                <enum name="useragent">
00459                   <para>The Useragent header used by the peer.</para>
00460                </enum>
00461                <enum name="peername">
00462                   <para>The name of the peer.</para>
00463                </enum>
00464                <enum name="t38passthrough">
00465                   <para><literal>1</literal> if T38 is offered or enabled in this channel,
00466                   otherwise <literal>0</literal>.</para>
00467                </enum>
00468             </enumlist>
00469          </parameter>
00470       </syntax>
00471       <description></description>
00472    </function>
00473    <function name="CHECKSIPDOMAIN" language="en_US">
00474       <synopsis>
00475          Checks if domain is a local domain.
00476       </synopsis>
00477       <syntax>
00478          <parameter name="domain" required="true" />
00479       </syntax>
00480       <description>
00481          <para>This function checks if the <replaceable>domain</replaceable> in the argument is configured
00482          as a local SIP domain that this Asterisk server is configured to handle.
00483          Returns the domain name if it is locally handled, otherwise an empty string.
00484          Check the <literal>domain=</literal> configuration in <filename>sip.conf</filename>.</para>
00485       </description>
00486    </function>
00487    <manager name="SIPpeers" language="en_US">
00488       <synopsis>
00489          List SIP peers (text format).
00490       </synopsis>
00491       <syntax>
00492          <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
00493       </syntax>
00494       <description>
00495          <para>Lists SIP peers in text format with details on current status.
00496          <literal>Peerlist</literal> will follow as separate events, followed by a final event called
00497          <literal>PeerlistComplete</literal>.</para>
00498       </description>
00499    </manager>
00500    <manager name="SIPshowpeer" language="en_US">
00501       <synopsis>
00502          show SIP peer (text format).
00503       </synopsis>
00504       <syntax>
00505          <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
00506          <parameter name="Peer" required="true">
00507             <para>The peer name you want to check.</para>
00508          </parameter>
00509       </syntax>
00510       <description>
00511          <para>Show one SIP peer with details on current status.</para>
00512       </description>
00513    </manager>
00514    <manager name="SIPqualifypeer" language="en_US">
00515       <synopsis>
00516          Qualify SIP peers.
00517       </synopsis>
00518       <syntax>
00519          <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
00520          <parameter name="Peer" required="true">
00521             <para>The peer name you want to qualify.</para>
00522          </parameter>
00523       </syntax>
00524       <description>
00525          <para>Qualify a SIP peer.</para>
00526       </description>
00527    </manager>
00528    <manager name="SIPshowregistry" language="en_US">
00529       <synopsis>
00530          Show SIP registrations (text format).
00531       </synopsis>
00532       <syntax>
00533          <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
00534       </syntax>
00535       <description>
00536          <para>Lists all registration requests and status. Registrations will follow as separate
00537          events followed by a final event called <literal>RegistrationsComplete</literal>.</para>
00538       </description>
00539    </manager>
00540    <manager name="SIPnotify" language="en_US">
00541       <synopsis>
00542          Send a SIP notify.
00543       </synopsis>
00544       <syntax>
00545          <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
00546          <parameter name="Channel" required="true">
00547             <para>Peer to receive the notify.</para>
00548          </parameter>
00549          <parameter name="Variable" required="true">
00550             <para>At least one variable pair must be specified.
00551             <replaceable>name</replaceable>=<replaceable>value</replaceable></para>
00552          </parameter>
00553       </syntax>
00554       <description>
00555          <para>Sends a SIP Notify event.</para>
00556          <para>All parameters for this event must be specified in the body of this request
00557          via multiple <literal>Variable: name=value</literal> sequences.</para>
00558       </description>
00559    </manager>
00560  ***/
00561 
00562 static int min_expiry = DEFAULT_MIN_EXPIRY;        /*!< Minimum accepted registration time */
00563 static int max_expiry = DEFAULT_MAX_EXPIRY;        /*!< Maximum accepted registration time */
00564 static int default_expiry = DEFAULT_DEFAULT_EXPIRY;
00565 static int mwi_expiry = DEFAULT_MWI_EXPIRY;
00566 
00567 static int unauth_sessions = 0;
00568 static int authlimit = DEFAULT_AUTHLIMIT;
00569 static int authtimeout = DEFAULT_AUTHTIMEOUT;
00570 
00571 /*! \brief Global jitterbuffer configuration - by default, jb is disabled
00572  *  \note Values shown here match the defaults shown in sip.conf.sample */
00573 static struct ast_jb_conf default_jbconf =
00574 {
00575    .flags = 0,
00576    .max_size = 200,
00577    .resync_threshold = 1000,
00578    .impl = "fixed",
00579    .target_extra = 40,
00580 };
00581 static struct ast_jb_conf global_jbconf;                /*!< Global jitterbuffer configuration */
00582 
00583 static const char config[] = "sip.conf";                /*!< Main configuration file */
00584 static const char notify_config[] = "sip_notify.conf";  /*!< Configuration file for sending Notify with CLI commands to reconfigure or reboot phones */
00585 
00586 /*! \brief Readable descriptions of device states.
00587  *  \note Should be aligned to above table as index */
00588 static const struct invstate2stringtable {
00589    const enum invitestates state;
00590    const char *desc;
00591 } invitestate2string[] = {
00592    {INV_NONE,              "None"  },
00593    {INV_CALLING,           "Calling (Trying)"},
00594    {INV_PROCEEDING,        "Proceeding "},
00595    {INV_EARLY_MEDIA,       "Early media"},
00596    {INV_COMPLETED,         "Completed (done)"},
00597    {INV_CONFIRMED,         "Confirmed (up)"},
00598    {INV_TERMINATED,        "Done"},
00599    {INV_CANCELLED,         "Cancelled"}
00600 };
00601 
00602 /*! \brief Subscription types that we support. We support
00603  * - dialoginfo updates (really device status, not dialog info as was the original intent of the standard)
00604  * - SIMPLE presence used for device status
00605  * - Voicemail notification subscriptions
00606  */
00607 static const struct cfsubscription_types {
00608    enum subscriptiontype type;
00609    const char * const event;
00610    const char * const mediatype;
00611    const char * const text;
00612 } subscription_types[] = {
00613    { NONE,        "-",        "unknown",               "unknown" },
00614    /* RFC 4235: SIP Dialog event package */
00615    { DIALOG_INFO_XML, "dialog",   "application/dialog-info+xml", "dialog-info+xml" },
00616    { CPIM_PIDF_XML,   "presence", "application/cpim-pidf+xml",   "cpim-pidf+xml" },  /* RFC 3863 */
00617    { PIDF_XML,        "presence", "application/pidf+xml",        "pidf+xml" },       /* RFC 3863 */
00618    { XPIDF_XML,       "presence", "application/xpidf+xml",       "xpidf+xml" },       /* Pre-RFC 3863 with MS additions */
00619    { MWI_NOTIFICATION,  "message-summary", "application/simple-message-summary", "mwi" } /* RFC 3842: Mailbox notification */
00620 };
00621 
00622 /*! \brief The core structure to setup dialogs. We parse incoming messages by using
00623  *  structure and then route the messages according to the type.
00624  *
00625  *  \note Note that sip_methods[i].id == i must hold or the code breaks
00626  */
00627 static const struct  cfsip_methods {
00628    enum sipmethod id;
00629    int need_rtp;     /*!< when this is the 'primary' use for a pvt structure, does it need RTP? */
00630    char * const text;
00631    enum can_create_dialog can_create;
00632 } sip_methods[] = {
00633    { SIP_UNKNOWN,   RTP,    "-UNKNOWN-",CAN_CREATE_DIALOG },
00634    { SIP_RESPONSE,  NO_RTP, "SIP/2.0",  CAN_NOT_CREATE_DIALOG },
00635    { SIP_REGISTER,  NO_RTP, "REGISTER", CAN_CREATE_DIALOG },
00636    { SIP_OPTIONS,   NO_RTP, "OPTIONS",  CAN_CREATE_DIALOG },
00637    { SIP_NOTIFY,    NO_RTP, "NOTIFY",   CAN_CREATE_DIALOG },
00638    { SIP_INVITE,    RTP,    "INVITE",   CAN_CREATE_DIALOG },
00639    { SIP_ACK,       NO_RTP, "ACK",      CAN_NOT_CREATE_DIALOG },
00640    { SIP_PRACK,     NO_RTP, "PRACK",    CAN_NOT_CREATE_DIALOG },
00641    { SIP_BYE,       NO_RTP, "BYE",      CAN_NOT_CREATE_DIALOG },
00642    { SIP_REFER,     NO_RTP, "REFER",    CAN_CREATE_DIALOG },
00643    { SIP_SUBSCRIBE, NO_RTP, "SUBSCRIBE",CAN_CREATE_DIALOG },
00644    { SIP_MESSAGE,   NO_RTP, "MESSAGE",  CAN_CREATE_DIALOG },
00645    { SIP_UPDATE,    NO_RTP, "UPDATE",   CAN_NOT_CREATE_DIALOG },
00646    { SIP_INFO,      NO_RTP, "INFO",     CAN_NOT_CREATE_DIALOG },
00647    { SIP_CANCEL,    NO_RTP, "CANCEL",   CAN_NOT_CREATE_DIALOG },
00648    { SIP_PUBLISH,   NO_RTP, "PUBLISH",  CAN_CREATE_DIALOG },
00649    { SIP_PING,      NO_RTP, "PING",     CAN_CREATE_DIALOG_UNSUPPORTED_METHOD }
00650 };
00651 
00652 /*! \brief Diversion header reasons
00653  *
00654  * The core defines a bunch of constants used to define
00655  * redirecting reasons. This provides a translation table
00656  * between those and the strings which may be present in
00657  * a SIP Diversion header
00658  */
00659 static const struct sip_reasons {
00660    enum AST_REDIRECTING_REASON code;
00661    char * const text;
00662 } sip_reason_table[] = {
00663    { AST_REDIRECTING_REASON_UNKNOWN, "unknown" },
00664    { AST_REDIRECTING_REASON_USER_BUSY, "user-busy" },
00665    { AST_REDIRECTING_REASON_NO_ANSWER, "no-answer" },
00666    { AST_REDIRECTING_REASON_UNAVAILABLE, "unavailable" },
00667    { AST_REDIRECTING_REASON_UNCONDITIONAL, "unconditional" },
00668    { AST_REDIRECTING_REASON_TIME_OF_DAY, "time-of-day" },
00669    { AST_REDIRECTING_REASON_DO_NOT_DISTURB, "do-not-disturb" },
00670    { AST_REDIRECTING_REASON_DEFLECTION, "deflection" },
00671    { AST_REDIRECTING_REASON_FOLLOW_ME, "follow-me" },
00672    { AST_REDIRECTING_REASON_OUT_OF_ORDER, "out-of-service" },
00673    { AST_REDIRECTING_REASON_AWAY, "away" },
00674    { AST_REDIRECTING_REASON_CALL_FWD_DTE, "unknown"}
00675 };
00676 
00677 
00678 /*! \name DefaultSettings
00679    Default setttings are used as a channel setting and as a default when
00680    configuring devices
00681 */
00682 /*@{*/
00683 static char default_language[MAX_LANGUAGE];      /*!< Default language setting for new channels */
00684 static char default_callerid[AST_MAX_EXTENSION]; /*!< Default caller ID for sip messages */
00685 static char default_mwi_from[80];                /*!< Default caller ID for MWI updates */
00686 static char default_fromdomain[AST_MAX_EXTENSION]; /*!< Default domain on outound messages */
00687 static int default_fromdomainport;                 /*!< Default domain port on outbound messages */
00688 static char default_notifymime[AST_MAX_EXTENSION]; /*!< Default MIME media type for MWI notify messages */
00689 static char default_vmexten[AST_MAX_EXTENSION];    /*!< Default From Username on MWI updates */
00690 static int default_qualify;                        /*!< Default Qualify= setting */
00691 static char default_mohinterpret[MAX_MUSICCLASS];  /*!< Global setting for moh class to use when put on hold */
00692 static char default_mohsuggest[MAX_MUSICCLASS];    /*!< Global setting for moh class to suggest when putting
00693                                                     *   a bridged channel on hold */
00694 static char default_parkinglot[AST_MAX_CONTEXT];   /*!< Parkinglot */
00695 static char default_engine[256];                   /*!< Default RTP engine */
00696 static int default_maxcallbitrate;                 /*!< Maximum bitrate for call */
00697 static struct ast_codec_pref default_prefs;        /*!< Default codec prefs */
00698 static char default_zone[MAX_TONEZONE_COUNTRY];        /*!< Default tone zone for channels created from the SIP driver */
00699 static unsigned int default_transports;            /*!< Default Transports (enum sip_transport) that are acceptable */
00700 static unsigned int default_primary_transport;     /*!< Default primary Transport (enum sip_transport) for outbound connections to devices */
00701 /*@}*/
00702 
00703 static struct sip_settings sip_cfg;    /*!< SIP configuration data.
00704                \note in the future we could have multiple of these (per domain, per device group etc) */
00705 
00706 /*!< use this macro when ast_uri_decode is dependent on pedantic checking to be on. */
00707 #define SIP_PEDANTIC_DECODE(str) \
00708    if (sip_cfg.pedanticsipchecking && !ast_strlen_zero(str)) { \
00709       ast_uri_decode(str, ast_uri_sip_user); \
00710    }  \
00711 
00712 static unsigned int chan_idx;       /*!< used in naming sip channel */
00713 static int global_match_auth_username;    /*!< Match auth username if available instead of From: Default off. */
00714 
00715 static int global_relaxdtmf;        /*!< Relax DTMF */
00716 static int global_prematuremediafilter;   /*!< Enable/disable premature frames in a call (causing 183 early media) */
00717 static int global_rtptimeout;       /*!< Time out call if no RTP */
00718 static int global_rtpholdtimeout;   /*!< Time out call if no RTP during hold */
00719 static int global_rtpkeepalive;     /*!< Send RTP keepalives */
00720 static int global_reg_timeout;      /*!< Global time between attempts for outbound registrations */
00721 static int global_regattempts_max;  /*!< Registration attempts before giving up */
00722 static int global_shrinkcallerid;   /*!< enable or disable shrinking of caller id  */
00723 static int global_callcounter;      /*!< Enable call counters for all devices. This is currently enabled by setting the peer
00724                                      *   call-limit to INT_MAX. When we remove the call-limit from the code, we can make it
00725                                      *   with just a boolean flag in the device structure */
00726 static unsigned int global_tos_sip;      /*!< IP type of service for SIP packets */
00727 static unsigned int global_tos_audio;    /*!< IP type of service for audio RTP packets */
00728 static unsigned int global_tos_video;    /*!< IP type of service for video RTP packets */
00729 static unsigned int global_tos_text;     /*!< IP type of service for text RTP packets */
00730 static unsigned int global_cos_sip;      /*!< 802.1p class of service for SIP packets */
00731 static unsigned int global_cos_audio;    /*!< 802.1p class of service for audio RTP packets */
00732 static unsigned int global_cos_video;    /*!< 802.1p class of service for video RTP packets */
00733 static unsigned int global_cos_text;     /*!< 802.1p class of service for text RTP packets */
00734 static unsigned int recordhistory;       /*!< Record SIP history. Off by default */
00735 static unsigned int dumphistory;         /*!< Dump history to verbose before destroying SIP dialog */
00736 static char global_useragent[AST_MAX_EXTENSION];    /*!< Useragent for the SIP channel */
00737 static char global_sdpsession[AST_MAX_EXTENSION];   /*!< SDP session name for the SIP channel */
00738 static char global_sdpowner[AST_MAX_EXTENSION];     /*!< SDP owner name for the SIP channel */
00739 static int global_authfailureevents;     /*!< Whether we send authentication failure manager events or not. Default no. */
00740 static int global_t1;           /*!< T1 time */
00741 static int global_t1min;        /*!< T1 roundtrip time minimum */
00742 static int global_timer_b;      /*!< Timer B - RFC 3261 Section 17.1.1.2 */
00743 static unsigned int global_autoframing; /*!< Turn autoframing on or off. */
00744 static int global_qualifyfreq;          /*!< Qualify frequency */
00745 static int global_qualify_gap;          /*!< Time between our group of peer pokes */
00746 static int global_qualify_peers;        /*!< Number of peers to poke at a given time */
00747 
00748 static enum st_mode global_st_mode;           /*!< Mode of operation for Session-Timers           */
00749 static enum st_refresher global_st_refresher; /*!< Session-Timer refresher                        */
00750 static int global_min_se;                     /*!< Lowest threshold for session refresh interval  */
00751 static int global_max_se;                     /*!< Highest threshold for session refresh interval */
00752 
00753 static int global_store_sip_cause;    /*!< Whether the MASTER_CHANNEL(HASH(SIP_CAUSE,[chan_name])) var should be set */
00754 
00755 static int global_dynamic_exclude_static = 0; /*!< Exclude static peers from contact registrations */
00756 /*@}*/
00757 
00758 /*!
00759  * We use libxml2 in order to parse XML that may appear in the body of a SIP message. Currently,
00760  * the only usage is for parsing PIDF bodies of incoming PUBLISH requests in the call-completion
00761  * event package. This variable is set at module load time and may be checked at runtime to determine
00762  * if XML parsing support was found.
00763  */
00764 static int can_parse_xml;
00765 
00766 /*! \name Object counters @{
00767  *  \bug These counters are not handled in a thread-safe way ast_atomic_fetchadd_int()
00768  *  should be used to modify these values. */
00769 static int speerobjs = 0;     /*!< Static peers */
00770 static int rpeerobjs = 0;     /*!< Realtime peers */
00771 static int apeerobjs = 0;     /*!< Autocreated peer objects */
00772 static int regobjs = 0;       /*!< Registry objects */
00773 /* }@ */
00774 
00775 static struct ast_flags global_flags[3] = {{0}};  /*!< global SIP_ flags */
00776 static int global_t38_maxdatagram;                /*!< global T.38 FaxMaxDatagram override */
00777 
00778 static struct ast_event_sub *network_change_event_subscription; /*!< subscription id for network change events */
00779 static int network_change_event_sched_id = -1;
00780 
00781 static char used_context[AST_MAX_CONTEXT];        /*!< name of automatically created context for unloading */
00782 
00783 AST_MUTEX_DEFINE_STATIC(netlock);
00784 
00785 /*! \brief Protect the monitoring thread, so only one process can kill or start it, and not
00786    when it's doing something critical. */
00787 AST_MUTEX_DEFINE_STATIC(monlock);
00788 
00789 AST_MUTEX_DEFINE_STATIC(sip_reload_lock);
00790 
00791 /*! \brief This is the thread for the monitor which checks for input on the channels
00792    which are not currently in use.  */
00793 static pthread_t monitor_thread = AST_PTHREADT_NULL;
00794 
00795 static int sip_reloading = FALSE;                       /*!< Flag for avoiding multiple reloads at the same time */
00796 static enum channelreloadreason sip_reloadreason;       /*!< Reason for last reload/load of configuration */
00797 
00798 struct ast_sched_context *sched;     /*!< The scheduling context */
00799 static struct io_context *io;           /*!< The IO context */
00800 static int *sipsock_read_id;            /*!< ID of IO entry for sipsock FD */
00801 struct sip_pkt;
00802 static AST_LIST_HEAD_STATIC(domain_list, domain);    /*!< The SIP domain list */
00803 
00804 AST_LIST_HEAD_NOLOCK(sip_history_head, sip_history); /*!< history list, entry in sip_pvt */
00805 
00806 static enum sip_debug_e sipdebug;
00807 
00808 /*! \brief extra debugging for 'text' related events.
00809  *  At the moment this is set together with sip_debug_console.
00810  *  \note It should either go away or be implemented properly.
00811  */
00812 static int sipdebug_text;
00813 
00814 static const struct _map_x_s referstatusstrings[] = {
00815    { REFER_IDLE,      "<none>" },
00816    { REFER_SENT,      "Request sent" },
00817    { REFER_RECEIVED,  "Request received" },
00818    { REFER_CONFIRMED, "Confirmed" },
00819    { REFER_ACCEPTED,  "Accepted" },
00820    { REFER_RINGING,   "Target ringing" },
00821    { REFER_200OK,     "Done" },
00822    { REFER_FAILED,    "Failed" },
00823    { REFER_NOAUTH,    "Failed - auth failure" },
00824    { -1,               NULL} /* terminator */
00825 };
00826 
00827 /* --- Hash tables of various objects --------*/
00828 #ifdef LOW_MEMORY
00829 static const int HASH_PEER_SIZE = 17;
00830 static const int HASH_DIALOG_SIZE = 17;
00831 #else
00832 static const int HASH_PEER_SIZE = 563; /*!< Size of peer hash table, prime number preferred! */
00833 static const int HASH_DIALOG_SIZE = 563;
00834 #endif
00835 
00836 static const struct {
00837    enum ast_cc_service_type service;
00838    const char *service_string;
00839 } sip_cc_service_map [] = {
00840    [AST_CC_NONE] = { AST_CC_NONE, "" },
00841    [AST_CC_CCBS] = { AST_CC_CCBS, "BS" },
00842    [AST_CC_CCNR] = { AST_CC_CCNR, "NR" },
00843    [AST_CC_CCNL] = { AST_CC_CCNL, "NL" },
00844 };
00845 
00846 static enum ast_cc_service_type service_string_to_service_type(const char * const service_string)
00847 {
00848    enum ast_cc_service_type service;
00849    for (service = AST_CC_CCBS; service <= AST_CC_CCNL; ++service) {
00850       if (!strcasecmp(service_string, sip_cc_service_map[service].service_string)) {
00851          return service;
00852       }
00853    }
00854    return AST_CC_NONE;
00855 }
00856 
00857 static const struct {
00858    enum sip_cc_notify_state state;
00859    const char *state_string;
00860 } sip_cc_notify_state_map [] = {
00861    [CC_QUEUED] = {CC_QUEUED, "cc-state: queued"},
00862    [CC_READY] = {CC_READY, "cc-state: ready"},
00863 };
00864 
00865 AST_LIST_HEAD_STATIC(epa_static_data_list, epa_backend);
00866 
00867 static int sip_epa_register(const struct epa_static_data *static_data)
00868 {
00869    struct epa_backend *backend = ast_calloc(1, sizeof(*backend));
00870 
00871    if (!backend) {
00872       return -1;
00873    }
00874 
00875    backend->static_data = static_data;
00876 
00877    AST_LIST_LOCK(&epa_static_data_list);
00878    AST_LIST_INSERT_TAIL(&epa_static_data_list, backend, next);
00879    AST_LIST_UNLOCK(&epa_static_data_list);
00880    return 0;
00881 }
00882 
00883 static void sip_epa_unregister_all(void)
00884 {
00885    struct epa_backend *backend;
00886 
00887    AST_LIST_LOCK(&epa_static_data_list);
00888    while ((backend = AST_LIST_REMOVE_HEAD(&epa_static_data_list, next))) {
00889       ast_free(backend);
00890    }
00891    AST_LIST_UNLOCK(&epa_static_data_list);
00892 }
00893 
00894 static void cc_handle_publish_error(struct sip_pvt *pvt, const int resp, struct sip_request *req, struct sip_epa_entry *epa_entry);
00895 
00896 static void cc_epa_destructor(void *data)
00897 {
00898    struct sip_epa_entry *epa_entry = data;
00899    struct cc_epa_entry *cc_entry = epa_entry->instance_data;
00900    ast_free(cc_entry);
00901 }
00902 
00903 static const struct epa_static_data cc_epa_static_data  = {
00904    .event = CALL_COMPLETION,
00905    .name = "call-completion",
00906    .handle_error = cc_handle_publish_error,
00907    .destructor = cc_epa_destructor,
00908 };
00909 
00910 static const struct epa_static_data *find_static_data(const char * const event_package)
00911 {
00912    const struct epa_backend *backend = NULL;
00913 
00914    AST_LIST_LOCK(&epa_static_data_list);
00915    AST_LIST_TRAVERSE(&epa_static_data_list, backend, next) {
00916       if (!strcmp(backend->static_data->name, event_package)) {
00917          break;
00918       }
00919    }
00920    AST_LIST_UNLOCK(&epa_static_data_list);
00921    return backend ? backend->static_data : NULL;
00922 }
00923 
00924 static struct sip_epa_entry *create_epa_entry (const char * const event_package, const char * const destination)
00925 {
00926    struct sip_epa_entry *epa_entry;
00927    const struct epa_static_data *static_data;
00928 
00929    if (!(static_data = find_static_data(event_package))) {
00930       return NULL;
00931    }
00932 
00933    if (!(epa_entry = ao2_t_alloc(sizeof(*epa_entry), static_data->destructor, "Allocate new EPA entry"))) {
00934       return NULL;
00935    }
00936 
00937    epa_entry->static_data = static_data;
00938    ast_copy_string(epa_entry->destination, destination, sizeof(epa_entry->destination));
00939    return epa_entry;
00940 }
00941 
00942 /*!
00943  * Used to create new entity IDs by ESCs.
00944  */
00945 static int esc_etag_counter;
00946 static const int DEFAULT_PUBLISH_EXPIRES = 3600;
00947 
00948 #ifdef HAVE_LIBXML2
00949 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);
00950 
00951 static const struct sip_esc_publish_callbacks cc_esc_publish_callbacks = {
00952    .initial_handler = cc_esc_publish_handler,
00953    .modify_handler = cc_esc_publish_handler,
00954 };
00955 #endif
00956 
00957 /*!
00958  * \brief The Event State Compositors
00959  *
00960  * An Event State Compositor is an entity which
00961  * accepts PUBLISH requests and acts appropriately
00962  * based on these requests.
00963  *
00964  * The actual event_state_compositor structure is simply
00965  * an ao2_container of sip_esc_entrys. When an incoming
00966  * PUBLISH is received, we can match the appropriate sip_esc_entry
00967  * using the entity ID of the incoming PUBLISH.
00968  */
00969 static struct event_state_compositor {
00970    enum subscriptiontype event;
00971    const char * name;
00972    const struct sip_esc_publish_callbacks *callbacks;
00973    struct ao2_container *compositor;
00974 } event_state_compositors [] = {
00975 #ifdef HAVE_LIBXML2
00976    {CALL_COMPLETION, "call-completion", &cc_esc_publish_callbacks},
00977 #endif
00978 };
00979 
00980 static const int ESC_MAX_BUCKETS = 37;
00981 
00982 static void esc_entry_destructor(void *obj)
00983 {
00984    struct sip_esc_entry *esc_entry = obj;
00985    if (esc_entry->sched_id > -1) {
00986       AST_SCHED_DEL(sched, esc_entry->sched_id);
00987    }
00988 }
00989 
00990 static int esc_hash_fn(const void *obj, const int flags)
00991 {
00992    const struct sip_esc_entry *entry = obj;
00993    return ast_str_hash(entry->entity_tag);
00994 }
00995 
00996 static int esc_cmp_fn(void *obj, void *arg, int flags)
00997 {
00998    struct sip_esc_entry *entry1 = obj;
00999    struct sip_esc_entry *entry2 = arg;
01000 
01001    return (!strcmp(entry1->entity_tag, entry2->entity_tag)) ? (CMP_MATCH | CMP_STOP) : 0;
01002 }
01003 
01004 static struct event_state_compositor *get_esc(const char * const event_package) {
01005    int i;
01006    for (i = 0; i < ARRAY_LEN(event_state_compositors); i++) {
01007       if (!strcasecmp(event_package, event_state_compositors[i].name)) {
01008          return &event_state_compositors[i];
01009       }
01010    }
01011    return NULL;
01012 }
01013 
01014 static struct sip_esc_entry *get_esc_entry(const char * entity_tag, struct event_state_compositor *esc) {
01015    struct sip_esc_entry *entry;
01016    struct sip_esc_entry finder;
01017 
01018    ast_copy_string(finder.entity_tag, entity_tag, sizeof(finder.entity_tag));
01019 
01020    entry = ao2_find(esc->compositor, &finder, OBJ_POINTER);
01021 
01022    return entry;
01023 }
01024 
01025 static int publish_expire(const void *data)
01026 {
01027    struct sip_esc_entry *esc_entry = (struct sip_esc_entry *) data;
01028    struct event_state_compositor *esc = get_esc(esc_entry->event);
01029 
01030    ast_assert(esc != NULL);
01031 
01032    ao2_unlink(esc->compositor, esc_entry);
01033    ao2_ref(esc_entry, -1);
01034    return 0;
01035 }
01036 
01037 static void create_new_sip_etag(struct sip_esc_entry *esc_entry, int is_linked)
01038 {
01039    int new_etag = ast_atomic_fetchadd_int(&esc_etag_counter, +1);
01040    struct event_state_compositor *esc = get_esc(esc_entry->event);
01041 
01042    ast_assert(esc != NULL);
01043    if (is_linked) {
01044       ao2_unlink(esc->compositor, esc_entry);
01045    }
01046    snprintf(esc_entry->entity_tag, sizeof(esc_entry->entity_tag), "%d", new_etag);
01047    ao2_link(esc->compositor, esc_entry);
01048 }
01049 
01050 static struct sip_esc_entry *create_esc_entry(struct event_state_compositor *esc, struct sip_request *req, const int expires)
01051 {
01052    struct sip_esc_entry *esc_entry;
01053    int expires_ms;
01054 
01055    if (!(esc_entry = ao2_alloc(sizeof(*esc_entry), esc_entry_destructor))) {
01056       return NULL;
01057    }
01058 
01059    esc_entry->event = esc->name;
01060 
01061    expires_ms = expires * 1000;
01062    /* Bump refcount for scheduler */
01063    ao2_ref(esc_entry, +1);
01064    esc_entry->sched_id = ast_sched_add(sched, expires_ms, publish_expire, esc_entry);
01065 
01066    /* Note: This links the esc_entry into the ESC properly */
01067    create_new_sip_etag(esc_entry, 0);
01068 
01069    return esc_entry;
01070 }
01071 
01072 static int initialize_escs(void)
01073 {
01074    int i, res = 0;
01075    for (i = 0; i < ARRAY_LEN(event_state_compositors); i++) {
01076       if (!((event_state_compositors[i].compositor) =
01077                ao2_container_alloc(ESC_MAX_BUCKETS, esc_hash_fn, esc_cmp_fn))) {
01078          res = -1;
01079       }
01080    }
01081    return res;
01082 }
01083 
01084 static void destroy_escs(void)
01085 {
01086    int i;
01087    for (i = 0; i < ARRAY_LEN(event_state_compositors); i++) {
01088       ao2_ref(event_state_compositors[i].compositor, -1);
01089    }
01090 }
01091 
01092 /*!
01093  * \details
01094  * Here we implement the container for dialogs which are in the
01095  * dialog_needdestroy state to iterate only through the dialogs
01096  * unlink them instead of iterate through all dialogs
01097  */
01098 struct ao2_container *dialogs_needdestroy;
01099 
01100 /*!
01101  * \details
01102  * Here we implement the container for dialogs which have rtp
01103  * traffic and rtptimeout, rtpholdtimeout or rtpkeepalive
01104  * set. We use this container instead the whole dialog list.
01105  */
01106 struct ao2_container *dialogs_rtpcheck;
01107 
01108 /*!
01109  * \details
01110  * Here we implement the container for dialogs (sip_pvt), defining
01111  * generic wrapper functions to ease the transition from the current
01112  * implementation (a single linked list) to a different container.
01113  * In addition to a reference to the container, we need functions to lock/unlock
01114  * the container and individual items, and functions to add/remove
01115  * references to the individual items.
01116  */
01117 static struct ao2_container *dialogs;
01118 #define sip_pvt_lock(x) ao2_lock(x)
01119 #define sip_pvt_trylock(x) ao2_trylock(x)
01120 #define sip_pvt_unlock(x) ao2_unlock(x)
01121 
01122 /*! \brief  The table of TCP threads */
01123 static struct ao2_container *threadt;
01124 
01125 /*! \brief  The peer list: Users, Peers and Friends */
01126 static struct ao2_container *peers;
01127 static struct ao2_container *peers_by_ip;
01128 
01129 /*! \brief  The register list: Other SIP proxies we register with and receive calls from */
01130 static struct ast_register_list {
01131    ASTOBJ_CONTAINER_COMPONENTS(struct sip_registry);
01132    int recheck;
01133 } regl;
01134 
01135 /*! \brief  The MWI subscription list */
01136 static struct ast_subscription_mwi_list {
01137    ASTOBJ_CONTAINER_COMPONENTS(struct sip_subscription_mwi);
01138 } submwil;
01139 static int temp_pvt_init(void *);
01140 static void temp_pvt_cleanup(void *);
01141 
01142 /*! \brief A per-thread temporary pvt structure */
01143 AST_THREADSTORAGE_CUSTOM(ts_temp_pvt, temp_pvt_init, temp_pvt_cleanup);
01144 
01145 /*! \brief Authentication container for realm authentication */
01146 static struct sip_auth_container *authl = NULL;
01147 /*! \brief Global authentication container protection while adjusting the references. */
01148 AST_MUTEX_DEFINE_STATIC(authl_lock);
01149 
01150 /* --- Sockets and networking --------------*/
01151 
01152 /*! \brief Main socket for UDP SIP communication.
01153  *
01154  * sipsock is shared between the SIP manager thread (which handles reload
01155  * requests), the udp io handler (sipsock_read()) and the user routines that
01156  * issue udp writes (using __sip_xmit()).
01157  * The socket is -1 only when opening fails (this is a permanent condition),
01158  * or when we are handling a reload() that changes its address (this is
01159  * a transient situation during which we might have a harmless race, see
01160  * below). Because the conditions for the race to be possible are extremely
01161  * rare, we don't want to pay the cost of locking on every I/O.
01162  * Rather, we remember that when the race may occur, communication is
01163  * bound to fail anyways, so we just live with this event and let
01164  * the protocol handle this above us.
01165  */
01166 static int sipsock  = -1;
01167 
01168 struct ast_sockaddr bindaddr; /*!< UDP: The address we bind to */
01169 
01170 /*! \brief our (internal) default address/port to put in SIP/SDP messages
01171  *  internip is initialized picking a suitable address from one of the
01172  * interfaces, and the same port number we bind to. It is used as the
01173  * default address/port in SIP messages, and as the default address
01174  * (but not port) in SDP messages.
01175  */
01176 static struct ast_sockaddr internip;
01177 
01178 /*! \brief our external IP address/port for SIP sessions.
01179  * externaddr.sin_addr is only set when we know we might be behind
01180  * a NAT, and this is done using a variety of (mutually exclusive)
01181  * ways from the config file:
01182  *
01183  * + with "externaddr = host[:port]" we specify the address/port explicitly.
01184  *   The address is looked up only once when (re)loading the config file;
01185  *
01186  * + with "externhost = host[:port]" we do a similar thing, but the
01187  *   hostname is stored in externhost, and the hostname->IP mapping
01188  *   is refreshed every 'externrefresh' seconds;
01189  *
01190  * Other variables (externhost, externexpire, externrefresh) are used
01191  * to support the above functions.
01192  */
01193 static struct ast_sockaddr externaddr;      /*!< External IP address if we are behind NAT */
01194 static struct ast_sockaddr media_address; /*!< External RTP IP address if we are behind NAT */
01195 
01196 static char externhost[MAXHOSTNAMELEN];   /*!< External host name */
01197 static time_t externexpire;             /*!< Expiration counter for re-resolving external host name in dynamic DNS */
01198 static int externrefresh = 10;          /*!< Refresh timer for DNS-based external address (dyndns) */
01199 static uint16_t externtcpport;          /*!< external tcp port */
01200 static uint16_t externtlsport;          /*!< external tls port */
01201 
01202 /*! \brief  List of local networks
01203  * We store "localnet" addresses from the config file into an access list,
01204  * marked as 'DENY', so the call to ast_apply_ha() will return
01205  * AST_SENSE_DENY for 'local' addresses, and AST_SENSE_ALLOW for 'non local'
01206  * (i.e. presumably public) addresses.
01207  */
01208 static struct ast_ha *localaddr;    /*!< List of local networks, on the same side of NAT as this Asterisk */
01209 
01210 static int ourport_tcp;             /*!< The port used for TCP connections */
01211 static int ourport_tls;             /*!< The port used for TCP/TLS connections */
01212 static struct ast_sockaddr debugaddr;
01213 
01214 static struct ast_config *notify_types = NULL;    /*!< The list of manual NOTIFY types we know how to send */
01215 
01216 /*! some list management macros. */
01217 
01218 #define UNLINK(element, head, prev) do {  \
01219    if (prev)            \
01220       (prev)->next = (element)->next;  \
01221    else              \
01222       (head) = (element)->next;  \
01223    } while (0)
01224 
01225 /*---------------------------- Forward declarations of functions in chan_sip.c */
01226 /* Note: This is added to help splitting up chan_sip.c into several files
01227    in coming releases. */
01228 
01229 /*--- PBX interface functions */
01230 static struct ast_channel *sip_request_call(const char *type, struct ast_format_cap *cap, const struct ast_channel *requestor, const char *dest, int *cause);
01231 static int sip_devicestate(const char *data);
01232 static int sip_sendtext(struct ast_channel *ast, const char *text);
01233 static int sip_call(struct ast_channel *ast, const char *dest, int timeout);
01234 static int sip_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen);
01235 static int sip_hangup(struct ast_channel *ast);
01236 static int sip_answer(struct ast_channel *ast);
01237 static struct ast_frame *sip_read(struct ast_channel *ast);
01238 static int sip_write(struct ast_channel *ast, struct ast_frame *frame);
01239 static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen);
01240 static int sip_transfer(struct ast_channel *ast, const char *dest);
01241 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
01242 static int sip_senddigit_begin(struct ast_channel *ast, char digit);
01243 static int sip_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration);
01244 static int sip_setoption(struct ast_channel *chan, int option, void *data, int datalen);
01245 static int sip_queryoption(struct ast_channel *chan, int option, void *data, int *datalen);
01246 static const char *sip_get_callid(struct ast_channel *chan);
01247 
01248 static int handle_request_do(struct sip_request *req, struct ast_sockaddr *addr);
01249 static int sip_standard_port(enum sip_transport type, int port);
01250 static int sip_prepare_socket(struct sip_pvt *p);
01251 static int get_address_family_filter(const struct ast_sockaddr *addr);
01252 
01253 /*--- Transmitting responses and requests */
01254 static int sipsock_read(int *id, int fd, short events, void *ignore);
01255 static int __sip_xmit(struct sip_pvt *p, struct ast_str *data);
01256 static int __sip_reliable_xmit(struct sip_pvt *p, uint32_t seqno, int resp, struct ast_str *data, int fatal, int sipmethod);
01257 static void add_cc_call_info_to_response(struct sip_pvt *p, struct sip_request *resp);
01258 static int __transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
01259 static int retrans_pkt(const void *data);
01260 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);
01261 static int transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req);
01262 static int transmit_response_reliable(struct sip_pvt *p, const char *msg, const struct sip_request *req);
01263 static int transmit_response_with_date(struct sip_pvt *p, const char *msg, const struct sip_request *req);
01264 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);
01265 static int transmit_response_with_unsupported(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *unsupported);
01266 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);
01267 static int transmit_provisional_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, int with_sdp);
01268 static int transmit_response_with_allow(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
01269 static void transmit_fake_auth_response(struct sip_pvt *p, int sipmethod, struct sip_request *req, enum xmittype reliable);
01270 static int transmit_request(struct sip_pvt *p, int sipmethod, uint32_t seqno, enum xmittype reliable, int newbranch);
01271 static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, uint32_t seqno, enum xmittype reliable, int newbranch);
01272 static int transmit_publish(struct sip_epa_entry *epa_entry, enum sip_publish_type publish_type, const char * const explicit_uri);
01273 static int transmit_invite(struct sip_pvt *p, int sipmethod, int sdp, int init, const char * const explicit_uri);
01274 static int transmit_reinvite_with_sdp(struct sip_pvt *p, int t38version, int oldsdp);
01275 static int transmit_info_with_aoc(struct sip_pvt *p, struct ast_aoc_decoded *decoded);
01276 static int transmit_info_with_digit(struct sip_pvt *p, const char digit, unsigned int duration);
01277 static int transmit_info_with_vidupdate(struct sip_pvt *p);
01278 static int transmit_message(struct sip_pvt *p, int init, int auth);
01279 static int transmit_refer(struct sip_pvt *p, const char *dest);
01280 static int transmit_notify_with_mwi(struct sip_pvt *p, int newmsgs, int oldmsgs, const char *vmexten);
01281 static int transmit_notify_with_sipfrag(struct sip_pvt *p, int cseq, char *message, int terminate);
01282 static int transmit_cc_notify(struct ast_cc_agent *agent, struct sip_pvt *subscription, enum sip_cc_notify_state state);
01283 static int transmit_register(struct sip_registry *r, int sipmethod, const char *auth, const char *authheader);
01284 static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, uint32_t seqno);
01285 static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, uint32_t seqno);
01286 static void copy_request(struct sip_request *dst, const struct sip_request *src);
01287 static void receive_message(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, const char *e);
01288 static void parse_moved_contact(struct sip_pvt *p, struct sip_request *req, char **name, char **number, int set_call_forward);
01289 static int sip_send_mwi_to_peer(struct sip_peer *peer, int cache_only);
01290 
01291 /* Misc dialog routines */
01292 static int __sip_autodestruct(const void *data);
01293 static void *registry_unref(struct sip_registry *reg, char *tag);
01294 static int update_call_counter(struct sip_pvt *fup, int event);
01295 static int auto_congest(const void *arg);
01296 static struct sip_pvt *find_call(struct sip_request *req, struct ast_sockaddr *addr, const int intended_method);
01297 static void free_old_route(struct sip_route *route);
01298 static void list_route(struct sip_route *route);
01299 static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards);
01300 static enum check_auth_result register_verify(struct sip_pvt *p, struct ast_sockaddr *addr,
01301                      struct sip_request *req, const char *uri);
01302 static struct sip_pvt *get_sip_pvt_byid_locked(const char *callid, const char *totag, const char *fromtag);
01303 static void check_pendings(struct sip_pvt *p);
01304 static void *sip_park_thread(void *stuff);
01305 static int sip_park(struct ast_channel *chan1, struct ast_channel *chan2, struct sip_request *req, uint32_t seqno, const char *park_exten, const char *park_context);
01306 
01307 static void *sip_pickup_thread(void *stuff);
01308 static int sip_pickup(struct ast_channel *chan);
01309 
01310 static int sip_sipredirect(struct sip_pvt *p, const char *dest);
01311 static int is_method_allowed(unsigned int *allowed_methods, enum sipmethod method);
01312 
01313 /*--- Codec handling / SDP */
01314 static void try_suggested_sip_codec(struct sip_pvt *p);
01315 static const char *get_sdp_iterate(int* start, struct sip_request *req, const char *name);
01316 static char get_sdp_line(int *start, int stop, struct sip_request *req, const char **value);
01317 static int find_sdp(struct sip_request *req);
01318 static int process_sdp(struct sip_pvt *p, struct sip_request *req, int t38action);
01319 static int process_sdp_o(const char *o, struct sip_pvt *p);
01320 static int process_sdp_c(const char *c, struct ast_sockaddr *addr);
01321 static int process_sdp_a_sendonly(const char *a, int *sendonly);
01322 static int process_sdp_a_audio(const char *a, struct sip_pvt *p, struct ast_rtp_codecs *newaudiortp, int *last_rtpmap_codec);
01323 static int process_sdp_a_video(const char *a, struct sip_pvt *p, struct ast_rtp_codecs *newvideortp, int *last_rtpmap_codec);
01324 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);
01325 static int process_sdp_a_image(const char *a, struct sip_pvt *p);
01326 static void add_codec_to_sdp(const struct sip_pvt *p, struct ast_format *codec,
01327               struct ast_str **m_buf, struct ast_str **a_buf,
01328               int debug, int *min_packet_size);
01329 static void add_noncodec_to_sdp(const struct sip_pvt *p, int format,
01330             struct ast_str **m_buf, struct ast_str **a_buf,
01331             int debug);
01332 static enum sip_result add_sdp(struct sip_request *resp, struct sip_pvt *p, int oldsdp, int add_audio, int add_t38);
01333 static void do_setnat(struct sip_pvt *p);
01334 static void stop_media_flows(struct sip_pvt *p);
01335 
01336 /*--- Authentication stuff */
01337 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod, char *digest, int digest_len);
01338 static int build_reply_digest(struct sip_pvt *p, int method, char *digest, int digest_len);
01339 static enum check_auth_result check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
01340                 const char *secret, const char *md5secret, int sipmethod,
01341                 const char *uri, enum xmittype reliable, int ignore);
01342 static enum check_auth_result check_user_full(struct sip_pvt *p, struct sip_request *req,
01343                      int sipmethod, const char *uri, enum xmittype reliable,
01344                      struct ast_sockaddr *addr, struct sip_peer **authpeer);
01345 static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, const char *uri, enum xmittype reliable, struct ast_sockaddr *addr);
01346 
01347 /*--- Domain handling */
01348 static int check_sip_domain(const char *domain, char *context, size_t len); /* Check if domain is one of our local domains */
01349 static int add_sip_domain(const char *domain, const enum domain_mode mode, const char *context);
01350 static void clear_sip_domains(void);
01351 
01352 /*--- SIP realm authentication */
01353 static void add_realm_authentication(struct sip_auth_container **credentials, const char *configuration, int lineno);
01354 static struct sip_auth *find_realm_authentication(struct sip_auth_container *credentials, const char *realm);
01355 
01356 /*--- Misc functions */
01357 static int check_rtp_timeout(struct sip_pvt *dialog, time_t t);
01358 static int reload_config(enum channelreloadreason reason);
01359 static void add_diversion_header(struct sip_request *req, struct sip_pvt *pvt);
01360 static int expire_register(const void *data);
01361 static void *do_monitor(void *data);
01362 static int restart_monitor(void);
01363 static void peer_mailboxes_to_str(struct ast_str **mailbox_str, struct sip_peer *peer);
01364 static struct ast_variable *copy_vars(struct ast_variable *src);
01365 static int dialog_find_multiple(void *obj, void *arg, int flags);
01366 static struct ast_channel *sip_pvt_lock_full(struct sip_pvt *pvt);
01367 /* static int sip_addrcmp(char *name, struct sockaddr_in *sin);   Support for peer matching */
01368 static int sip_refer_allocate(struct sip_pvt *p);
01369 static int sip_notify_allocate(struct sip_pvt *p);
01370 static void ast_quiet_chan(struct ast_channel *chan);
01371 static int attempt_transfer(struct sip_dual *transferer, struct sip_dual *target);
01372 static int do_magic_pickup(struct ast_channel *channel, const char *extension, const char *context);
01373 
01374 /*--- Device monitoring and Device/extension state/event handling */
01375 static int cb_extensionstate(const char *context, const char *exten, enum ast_extension_states state, void *data);
01376 static int sip_poke_noanswer(const void *data);
01377 static int sip_poke_peer(struct sip_peer *peer, int force);
01378 static void sip_poke_all_peers(void);
01379 static void sip_peer_hold(struct sip_pvt *p, int hold);
01380 static void mwi_event_cb(const struct ast_event *, void *);
01381 static void network_change_event_cb(const struct ast_event *, void *);
01382 
01383 /*--- Applications, functions, CLI and manager command helpers */
01384 static const char *sip_nat_mode(const struct sip_pvt *p);
01385 static char *sip_show_inuse(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01386 static char *transfermode2str(enum transfermodes mode) attribute_const;
01387 static int peer_status(struct sip_peer *peer, char *status, int statuslen);
01388 static char *sip_show_sched(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01389 static char * _sip_show_peers(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char *argv[]);
01390 static char *sip_show_peers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01391 static char *sip_show_objects(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01392 static void  print_group(int fd, ast_group_t group, int crlf);
01393 static const char *dtmfmode2str(int mode) attribute_const;
01394 static int str2dtmfmode(const char *str) attribute_unused;
01395 static const char *insecure2str(int mode) attribute_const;
01396 static const char *allowoverlap2str(int mode) attribute_const;
01397 static void cleanup_stale_contexts(char *new, char *old);
01398 static void print_codec_to_cli(int fd, struct ast_codec_pref *pref);
01399 static const char *domain_mode_to_text(const enum domain_mode mode);
01400 static char *sip_show_domains(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01401 static char *_sip_show_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[]);
01402 static char *sip_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01403 static char *_sip_qualify_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[]);
01404 static char *sip_qualify_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01405 static char *sip_show_registry(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01406 static char *sip_unregister(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01407 static char *sip_show_settings(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01408 static char *sip_show_mwi(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01409 static const char *subscription_type2str(enum subscriptiontype subtype) attribute_pure;
01410 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
01411 static char *complete_sip_peer(const char *word, int state, int flags2);
01412 static char *complete_sip_registered_peer(const char *word, int state, int flags2);
01413 static char *complete_sip_show_history(const char *line, const char *word, int pos, int state);
01414 static char *complete_sip_show_peer(const char *line, const char *word, int pos, int state);
01415 static char *complete_sip_unregister(const char *line, const char *word, int pos, int state);
01416 static char *complete_sipnotify(const char *line, const char *word, int pos, int state);
01417 static char *sip_show_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01418 static char *sip_show_channelstats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01419 static char *sip_show_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01420 static char *sip_do_debug_ip(int fd, const char *arg);
01421 static char *sip_do_debug_peer(int fd, const char *arg);
01422 static char *sip_do_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01423 static char *sip_cli_notify(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01424 static char *sip_set_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01425 static int sip_dtmfmode(struct ast_channel *chan, const char *data);
01426 static int sip_addheader(struct ast_channel *chan, const char *data);
01427 static int sip_do_reload(enum channelreloadreason reason);
01428 static char *sip_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01429 static int ast_sockaddr_resolve_first_af(struct ast_sockaddr *addr,
01430                   const char *name, int flag, int family);
01431 static int ast_sockaddr_resolve_first(struct ast_sockaddr *addr,
01432                   const char *name, int flag);
01433 
01434 /*--- Debugging
01435    Functions for enabling debug per IP or fully, or enabling history logging for
01436    a SIP dialog
01437 */
01438 static void sip_dump_history(struct sip_pvt *dialog); /* Dump history to debuglog at end of dialog, before destroying data */
01439 static inline int sip_debug_test_addr(const struct ast_sockaddr *addr);
01440 static inline int sip_debug_test_pvt(struct sip_pvt *p);
01441 static void append_history_full(struct sip_pvt *p, const char *fmt, ...);
01442 static void sip_dump_history(struct sip_pvt *dialog);
01443 
01444 /*--- Device object handling */
01445 static struct sip_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime, int devstate_only);
01446 static int update_call_counter(struct sip_pvt *fup, int event);
01447 static void sip_destroy_peer(struct sip_peer *peer);
01448 static void sip_destroy_peer_fn(void *peer);
01449 static void set_peer_defaults(struct sip_peer *peer);
01450 static struct sip_peer *temp_peer(const char *name);
01451 static void register_peer_exten(struct sip_peer *peer, int onoff);
01452 static int sip_poke_peer_s(const void *data);
01453 static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *p, struct sip_request *req);
01454 static void reg_source_db(struct sip_peer *peer);
01455 static void destroy_association(struct sip_peer *peer);
01456 static void set_insecure_flags(struct ast_flags *flags, const char *value, int lineno);
01457 static int handle_common_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v);
01458 static void set_socket_transport(struct sip_socket *socket, int transport);
01459 static int peer_ipcmp_cb_full(void *obj, void *arg, void *data, int flags);
01460 
01461 /* Realtime device support */
01462 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);
01463 static void update_peer(struct sip_peer *p, int expire);
01464 static struct ast_variable *get_insecure_variable_from_config(struct ast_config *config);
01465 static const char *get_name_from_variable(const struct ast_variable *var);
01466 static struct sip_peer *realtime_peer(const char *peername, struct ast_sockaddr *sin, char *callbackexten, int devstate_only, int which_objects);
01467 static char *sip_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01468 
01469 /*--- Internal UA client handling (outbound registrations) */
01470 static void ast_sip_ouraddrfor(const struct ast_sockaddr *them, struct ast_sockaddr *us, struct sip_pvt *p);
01471 static void sip_registry_destroy(struct sip_registry *reg);
01472 static int sip_register(const char *value, int lineno);
01473 static const char *regstate2str(enum sipregistrystate regstate) attribute_const;
01474 static int sip_reregister(const void *data);
01475 static int __sip_do_register(struct sip_registry *r);
01476 static int sip_reg_timeout(const void *data);
01477 static void sip_send_all_registers(void);
01478 static int sip_reinvite_retry(const void *data);
01479 
01480 /*--- Parsing SIP requests and responses */
01481 static void append_date(struct sip_request *req);  /* Append date to SIP packet */
01482 static int determine_firstline_parts(struct sip_request *req);
01483 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
01484 static const char *gettag(const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize);
01485 static int find_sip_method(const char *msg);
01486 static unsigned int parse_allowed_methods(struct sip_request *req);
01487 static unsigned int set_pvt_allowed_methods(struct sip_pvt *pvt, struct sip_request *req);
01488 static int parse_request(struct sip_request *req);
01489 static const char *referstatus2str(enum referstatus rstatus) attribute_pure;
01490 static int method_match(enum sipmethod id, const char *name);
01491 static void parse_copy(struct sip_request *dst, const struct sip_request *src);
01492 static const char *find_alias(const char *name, const char *_default);
01493 static const char *__get_header(const struct sip_request *req, const char *name, int *start);
01494 static void lws2sws(struct ast_str *msgbuf);
01495 static void extract_uri(struct sip_pvt *p, struct sip_request *req);
01496 static char *remove_uri_parameters(char *uri);
01497 static int get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req);
01498 static int get_also_info(struct sip_pvt *p, struct sip_request *oreq);
01499 static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req);
01500 static int set_address_from_contact(struct sip_pvt *pvt);
01501 static void check_via(struct sip_pvt *p, struct sip_request *req);
01502 static int get_rpid(struct sip_pvt *p, struct sip_request *oreq);
01503 static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq, char **name, char **number, int *reason);
01504 static enum sip_get_dest_result get_destination(struct sip_pvt *p, struct sip_request *oreq, int *cc_recall_core_id);
01505 static int get_msg_text(char *buf, int len, struct sip_request *req);
01506 static int transmit_state_notify(struct sip_pvt *p, int state, int full, int timeout);
01507 static void update_connectedline(struct sip_pvt *p, const void *data, size_t datalen);
01508 static void update_redirecting(struct sip_pvt *p, const void *data, size_t datalen);
01509 static int get_domain(const char *str, char *domain, int len);
01510 static void get_realm(struct sip_pvt *p, const struct sip_request *req);
01511 
01512 /*-- TCP connection handling ---*/
01513 static void *_sip_tcp_helper_thread(struct sip_pvt *pvt, struct ast_tcptls_session_instance *tcptls_session);
01514 static void *sip_tcp_worker_fn(void *);
01515 
01516 /*--- Constructing requests and responses */
01517 static void initialize_initreq(struct sip_pvt *p, struct sip_request *req);
01518 static int init_req(struct sip_request *req, int sipmethod, const char *recip);
01519 static void deinit_req(struct sip_request *req);
01520 static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, uint32_t seqno, int newbranch);
01521 static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, const char * const explicit_uri);
01522 static int init_resp(struct sip_request *resp, const char *msg);
01523 static inline int resp_needs_contact(const char *msg, enum sipmethod method);
01524 static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req);
01525 static const struct ast_sockaddr *sip_real_dst(const struct sip_pvt *p);
01526 static void build_via(struct sip_pvt *p);
01527 static int create_addr_from_peer(struct sip_pvt *r, struct sip_peer *peer);
01528 static int create_addr(struct sip_pvt *dialog, const char *opeer, struct ast_sockaddr *addr, int newdialog, struct ast_sockaddr *remote_address);
01529 static char *generate_random_string(char *buf, size_t size);
01530 static void build_callid_pvt(struct sip_pvt *pvt);
01531 static void change_callid_pvt(struct sip_pvt *pvt, const char *callid);
01532 static void build_callid_registry(struct sip_registry *reg, const struct ast_sockaddr *ourip, const char *fromdomain);
01533 static void make_our_tag(char *tagbuf, size_t len);
01534 static int add_header(struct sip_request *req, const char *var, const char *value);
01535 static int add_header_max_forwards(struct sip_pvt *dialog, struct sip_request *req);
01536 static int add_content(struct sip_request *req, const char *line);
01537 static int finalize_content(struct sip_request *req);
01538 static void destroy_msg_headers(struct sip_pvt *pvt);
01539 static int add_text(struct sip_request *req, struct sip_pvt *p);
01540 static int add_digit(struct sip_request *req, char digit, unsigned int duration, int mode);
01541 static int add_rpid(struct sip_request *req, struct sip_pvt *p);
01542 static int add_vidupdate(struct sip_request *req);
01543 static void add_route(struct sip_request *req, struct sip_route *route);
01544 static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field);
01545 static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field);
01546 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field);
01547 static void set_destination(struct sip_pvt *p, char *uri);
01548 static void append_date(struct sip_request *req);
01549 static void build_contact(struct sip_pvt *p);
01550 
01551 /*------Request handling functions */
01552 static int handle_incoming(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, int *recount, int *nounlock);
01553 static int handle_request_update(struct sip_pvt *p, struct sip_request *req);
01554 static int handle_request_invite(struct sip_pvt *p, struct sip_request *req, int debug, uint32_t seqno, struct ast_sockaddr *addr, int *recount, const char *e, int *nounlock);
01555 static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, int debug, uint32_t seqno, int *nounlock);
01556 static int handle_request_bye(struct sip_pvt *p, struct sip_request *req);
01557 static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *sin, const char *e);
01558 static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req);
01559 static int handle_request_message(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, const char *e);
01560 static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, uint32_t seqno, const char *e);
01561 static void handle_request_info(struct sip_pvt *p, struct sip_request *req);
01562 static int handle_request_options(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, const char *e);
01563 static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req, int debug, uint32_t seqno, struct ast_sockaddr *addr, int *nounlock);
01564 static int handle_request_notify(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, uint32_t seqno, const char *e);
01565 static int local_attended_transfer(struct sip_pvt *transferer, struct sip_dual *current, struct sip_request *req, uint32_t seqno, int *nounlock);
01566 
01567 /*------Response handling functions */
01568 static void handle_response_publish(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
01569 static void handle_response_invite(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
01570 static void handle_response_notify(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
01571 static void handle_response_refer(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
01572 static void handle_response_subscribe(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
01573 static int handle_response_register(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
01574 static void handle_response(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
01575 
01576 /*------ SRTP Support -------- */
01577 static int setup_srtp(struct sip_srtp **srtp);
01578 static int process_crypto(struct sip_pvt *p, struct ast_rtp_instance *rtp, struct sip_srtp **srtp, const char *a);
01579 
01580 /*------ T38 Support --------- */
01581 static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans);
01582 static struct ast_udptl *sip_get_udptl_peer(struct ast_channel *chan);
01583 static int sip_set_udptl_peer(struct ast_channel *chan, struct ast_udptl *udptl);
01584 static void change_t38_state(struct sip_pvt *p, int state);
01585 
01586 /*------ Session-Timers functions --------- */
01587 static void proc_422_rsp(struct sip_pvt *p, struct sip_request *rsp);
01588 static int  proc_session_timer(const void *vp);
01589 static void stop_session_timer(struct sip_pvt *p);
01590 static void start_session_timer(struct sip_pvt *p);
01591 static void restart_session_timer(struct sip_pvt *p);
01592 static const char *strefresher2str(enum st_refresher r);
01593 static int parse_session_expires(const char *p_hdrval, int *const p_interval, enum st_refresher *const p_ref);
01594 static int parse_minse(const char *p_hdrval, int *const p_interval);
01595 static int st_get_se(struct sip_pvt *, int max);
01596 static enum st_refresher st_get_refresher(struct sip_pvt *);
01597 static enum st_mode st_get_mode(struct sip_pvt *, int no_cached);
01598 static struct sip_st_dlg* sip_st_alloc(struct sip_pvt *const p);
01599 
01600 /*------- RTP Glue functions -------- */
01601 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, const struct ast_format_cap *cap, int nat_active);
01602 
01603 /*!--- SIP MWI Subscription support */
01604 static int sip_subscribe_mwi(const char *value, int lineno);
01605 static void sip_subscribe_mwi_destroy(struct sip_subscription_mwi *mwi);
01606 static void sip_send_all_mwi_subscriptions(void);
01607 static int sip_subscribe_mwi_do(const void *data);
01608 static int __sip_subscribe_mwi_do(struct sip_subscription_mwi *mwi);
01609 
01610 /*! \brief Definition of this channel for PBX channel registration */
01611 struct ast_channel_tech sip_tech = {
01612    .type = "SIP",
01613    .description = "Session Initiation Protocol (SIP)",
01614    .properties = AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER,
01615    .requester = sip_request_call,         /* called with chan unlocked */
01616    .devicestate = sip_devicestate,        /* called with chan unlocked (not chan-specific) */
01617    .call = sip_call,       /* called with chan locked */
01618    .send_html = sip_sendhtml,
01619    .hangup = sip_hangup,         /* called with chan locked */
01620    .answer = sip_answer,         /* called with chan locked */
01621    .read = sip_read,       /* called with chan locked */
01622    .write = sip_write,        /* called with chan locked */
01623    .write_video = sip_write,     /* called with chan locked */
01624    .write_text = sip_write,
01625    .indicate = sip_indicate,     /* called with chan locked */
01626    .transfer = sip_transfer,     /* called with chan locked */
01627    .fixup = sip_fixup,        /* called with chan locked */
01628    .send_digit_begin = sip_senddigit_begin,  /* called with chan unlocked */
01629    .send_digit_end = sip_senddigit_end,
01630    .bridge = ast_rtp_instance_bridge,        /* XXX chan unlocked ? */
01631    .early_bridge = ast_rtp_instance_early_bridge,
01632    .send_text = sip_sendtext,    /* called with chan locked */
01633    .func_channel_read = sip_acf_channel_read,
01634    .setoption = sip_setoption,
01635    .queryoption = sip_queryoption,
01636    .get_pvt_uniqueid = sip_get_callid,
01637 };
01638 
01639 /*! \brief This version of the sip channel tech has no send_digit_begin
01640  * callback so that the core knows that the channel does not want
01641  * DTMF BEGIN frames.
01642  * The struct is initialized just before registering the channel driver,
01643  * and is for use with channels using SIP INFO DTMF.
01644  */
01645 struct ast_channel_tech sip_tech_info;
01646 
01647 /*------- CC Support -------- */
01648 static int sip_cc_agent_init(struct ast_cc_agent *agent, struct ast_channel *chan);
01649 static int sip_cc_agent_start_offer_timer(struct ast_cc_agent *agent);
01650 static int sip_cc_agent_stop_offer_timer(struct ast_cc_agent *agent);
01651 static void sip_cc_agent_respond(struct ast_cc_agent *agent, enum ast_cc_agent_response_reason reason);
01652 static int sip_cc_agent_status_request(struct ast_cc_agent *agent);
01653 static int sip_cc_agent_start_monitoring(struct ast_cc_agent *agent);
01654 static int sip_cc_agent_recall(struct ast_cc_agent *agent);
01655 static void sip_cc_agent_destructor(struct ast_cc_agent *agent);
01656 
01657 static struct ast_cc_agent_callbacks sip_cc_agent_callbacks = {
01658    .type = "SIP",
01659    .init = sip_cc_agent_init,
01660    .start_offer_timer = sip_cc_agent_start_offer_timer,
01661    .stop_offer_timer = sip_cc_agent_stop_offer_timer,
01662    .respond = sip_cc_agent_respond,
01663    .status_request = sip_cc_agent_status_request,
01664    .start_monitoring = sip_cc_agent_start_monitoring,
01665    .callee_available = sip_cc_agent_recall,
01666    .destructor = sip_cc_agent_destructor,
01667 };
01668 
01669 static int find_by_notify_uri_helper(void *obj, void *arg, int flags)
01670 {
01671    struct ast_cc_agent *agent = obj;
01672    struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01673    const char *uri = arg;
01674 
01675    return !sip_uri_cmp(agent_pvt->notify_uri, uri) ? CMP_MATCH | CMP_STOP : 0;
01676 }
01677 
01678 static struct ast_cc_agent *find_sip_cc_agent_by_notify_uri(const char * const uri)
01679 {
01680    struct ast_cc_agent *agent = ast_cc_agent_callback(0, find_by_notify_uri_helper, (char *)uri, "SIP");
01681    return agent;
01682 }
01683 
01684 static int find_by_subscribe_uri_helper(void *obj, void *arg, int flags)
01685 {
01686    struct ast_cc_agent *agent = obj;
01687    struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01688    const char *uri = arg;
01689 
01690    return !sip_uri_cmp(agent_pvt->subscribe_uri, uri) ? CMP_MATCH | CMP_STOP : 0;
01691 }
01692 
01693 static struct ast_cc_agent *find_sip_cc_agent_by_subscribe_uri(const char * const uri)
01694 {
01695    struct ast_cc_agent *agent = ast_cc_agent_callback(0, find_by_subscribe_uri_helper, (char *)uri, "SIP");
01696    return agent;
01697 }
01698 
01699 static int find_by_callid_helper(void *obj, void *arg, int flags)
01700 {
01701    struct ast_cc_agent *agent = obj;
01702    struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01703    struct sip_pvt *call_pvt = arg;
01704 
01705    return !strcmp(agent_pvt->original_callid, call_pvt->callid) ? CMP_MATCH | CMP_STOP : 0;
01706 }
01707 
01708 static struct ast_cc_agent *find_sip_cc_agent_by_original_callid(struct sip_pvt *pvt)
01709 {
01710    struct ast_cc_agent *agent = ast_cc_agent_callback(0, find_by_callid_helper, pvt, "SIP");
01711    return agent;
01712 }
01713 
01714 static int sip_cc_agent_init(struct ast_cc_agent *agent, struct ast_channel *chan)
01715 {
01716    struct sip_cc_agent_pvt *agent_pvt = ast_calloc(1, sizeof(*agent_pvt));
01717    struct sip_pvt *call_pvt = chan->tech_pvt;
01718 
01719    if (!agent_pvt) {
01720       return -1;
01721    }
01722 
01723    ast_assert(!strcmp(chan->tech->type, "SIP"));
01724 
01725    ast_copy_string(agent_pvt->original_callid, call_pvt->callid, sizeof(agent_pvt->original_callid));
01726    ast_copy_string(agent_pvt->original_exten, call_pvt->exten, sizeof(agent_pvt->original_exten));
01727    agent_pvt->offer_timer_id = -1;
01728    agent->private_data = agent_pvt;
01729    sip_pvt_lock(call_pvt);
01730    ast_set_flag(&call_pvt->flags[0], SIP_OFFER_CC);
01731    sip_pvt_unlock(call_pvt);
01732    return 0;
01733 }
01734 
01735 static int sip_offer_timer_expire(const void *data)
01736 {
01737    struct ast_cc_agent *agent = (struct ast_cc_agent *) data;
01738    struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01739 
01740    agent_pvt->offer_timer_id = -1;
01741 
01742    return ast_cc_failed(agent->core_id, "SIP agent %s's offer timer expired", agent->device_name);
01743 }
01744 
01745 static int sip_cc_agent_start_offer_timer(struct ast_cc_agent *agent)
01746 {
01747    struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01748    int when;
01749 
01750    when = ast_get_cc_offer_timer(agent->cc_params) * 1000;
01751    agent_pvt->offer_timer_id = ast_sched_add(sched, when, sip_offer_timer_expire, agent);
01752    return 0;
01753 }
01754 
01755 static int sip_cc_agent_stop_offer_timer(struct ast_cc_agent *agent)
01756 {
01757    struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01758 
01759    AST_SCHED_DEL(sched, agent_pvt->offer_timer_id);
01760    return 0;
01761 }
01762 
01763 static void sip_cc_agent_respond(struct ast_cc_agent *agent, enum ast_cc_agent_response_reason reason)
01764 {
01765    struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01766 
01767    sip_pvt_lock(agent_pvt->subscribe_pvt);
01768    ast_set_flag(&agent_pvt->subscribe_pvt->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
01769    if (reason == AST_CC_AGENT_RESPONSE_SUCCESS || !ast_strlen_zero(agent_pvt->notify_uri)) {
01770       /* The second half of this if statement may be a bit hard to grasp,
01771        * so here's an explanation. When a subscription comes into
01772        * chan_sip, as long as it is not malformed, it will be passed
01773        * to the CC core. If the core senses an out-of-order state transition,
01774        * then the core will call this callback with the "reason" set to a
01775        * failure condition.
01776        * However, an out-of-order state transition will occur during a resubscription
01777        * for CC. In such a case, we can see that we have already generated a notify_uri
01778        * and so we can detect that this isn't a *real* failure. Rather, it is just
01779        * something the core doesn't recognize as a legitimate SIP state transition.
01780        * Thus we respond with happiness and flowers.
01781        */
01782       transmit_response(agent_pvt->subscribe_pvt, "200 OK", &agent_pvt->subscribe_pvt->initreq);
01783       transmit_cc_notify(agent, agent_pvt->subscribe_pvt, CC_QUEUED);
01784    } else {
01785       transmit_response(agent_pvt->subscribe_pvt, "500 Internal Error", &agent_pvt->subscribe_pvt->initreq);
01786    }
01787    sip_pvt_unlock(agent_pvt->subscribe_pvt);
01788    agent_pvt->is_available = TRUE;
01789 }
01790 
01791 static int sip_cc_agent_status_request(struct ast_cc_agent *agent)
01792 {
01793    struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01794    enum ast_device_state state = agent_pvt->is_available ? AST_DEVICE_NOT_INUSE : AST_DEVICE_INUSE;
01795    return ast_cc_agent_status_response(agent->core_id, state);
01796 }
01797 
01798 static int sip_cc_agent_start_monitoring(struct ast_cc_agent *agent)
01799 {
01800    /* To start monitoring just means to wait for an incoming PUBLISH
01801     * to tell us that the caller has become available again. No special
01802     * action is needed
01803     */
01804    return 0;
01805 }
01806 
01807 static int sip_cc_agent_recall(struct ast_cc_agent *agent)
01808 {
01809    struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01810    /* If we have received a PUBLISH beforehand stating that the caller in question
01811     * is not available, we can save ourself a bit of effort here and just report
01812     * the caller as busy
01813     */
01814    if (!agent_pvt->is_available) {
01815       return ast_cc_agent_caller_busy(agent->core_id, "Caller %s is busy, reporting to the core",
01816             agent->device_name);
01817    }
01818    /* Otherwise, we transmit a NOTIFY to the caller and await either
01819     * a PUBLISH or an INVITE
01820     */
01821    sip_pvt_lock(agent_pvt->subscribe_pvt);
01822    transmit_cc_notify(agent, agent_pvt->subscribe_pvt, CC_READY);
01823    sip_pvt_unlock(agent_pvt->subscribe_pvt);
01824    return 0;
01825 }
01826 
01827 static void sip_cc_agent_destructor(struct ast_cc_agent *agent)
01828 {
01829    struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01830 
01831    if (!agent_pvt) {
01832       /* The agent constructor probably failed. */
01833       return;
01834    }
01835 
01836    sip_cc_agent_stop_offer_timer(agent);
01837    if (agent_pvt->subscribe_pvt) {
01838       sip_pvt_lock(agent_pvt->subscribe_pvt);
01839       if (!ast_test_flag(&agent_pvt->subscribe_pvt->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED)) {
01840          /* If we haven't sent a 200 OK for the SUBSCRIBE dialog yet, then we need to send a response letting
01841           * the subscriber know something went wrong
01842           */
01843          transmit_response(agent_pvt->subscribe_pvt, "500 Internal Server Error", &agent_pvt->subscribe_pvt->initreq);
01844       }
01845       sip_pvt_unlock(agent_pvt->subscribe_pvt);
01846       agent_pvt->subscribe_pvt = dialog_unref(agent_pvt->subscribe_pvt, "SIP CC agent destructor: Remove ref to subscription");
01847    }
01848    ast_free(agent_pvt);
01849 }
01850 
01851 struct ao2_container *sip_monitor_instances;
01852 
01853 static int sip_monitor_instance_hash_fn(const void *obj, const int flags)
01854 {
01855    const struct sip_monitor_instance *monitor_instance = obj;
01856    return monitor_instance->core_id;
01857 }
01858 
01859 static int sip_monitor_instance_cmp_fn(void *obj, void *arg, int flags)
01860 {
01861    struct sip_monitor_instance *monitor_instance1 = obj;
01862    struct sip_monitor_instance *monitor_instance2 = arg;
01863 
01864    return monitor_instance1->core_id == monitor_instance2->core_id ? CMP_MATCH | CMP_STOP : 0;
01865 }
01866 
01867 static void sip_monitor_instance_destructor(void *data)
01868 {
01869    struct sip_monitor_instance *monitor_instance = data;
01870    if (monitor_instance->subscription_pvt) {
01871       sip_pvt_lock(monitor_instance->subscription_pvt);
01872       monitor_instance->subscription_pvt->expiry = 0;
01873       transmit_invite(monitor_instance->subscription_pvt, SIP_SUBSCRIBE, FALSE, 0, monitor_instance->subscribe_uri);
01874       sip_pvt_unlock(monitor_instance->subscription_pvt);
01875       dialog_unref(monitor_instance->subscription_pvt, "Unref monitor instance ref of subscription pvt");
01876    }
01877    if (monitor_instance->suspension_entry) {
01878       monitor_instance->suspension_entry->body[0] = '\0';
01879       transmit_publish(monitor_instance->suspension_entry, SIP_PUBLISH_REMOVE ,monitor_instance->notify_uri);
01880       ao2_t_ref(monitor_instance->suspension_entry, -1, "Decrementing suspension entry refcount in sip_monitor_instance_destructor");
01881    }
01882    ast_string_field_free_memory(monitor_instance);
01883 }
01884 
01885 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)
01886 {
01887    struct sip_monitor_instance *monitor_instance = ao2_alloc(sizeof(*monitor_instance), sip_monitor_instance_destructor);
01888 
01889    if (!monitor_instance) {
01890       return NULL;
01891    }
01892 
01893    if (ast_string_field_init(monitor_instance, 256)) {
01894       ao2_ref(monitor_instance, -1);
01895       return NULL;
01896    }
01897 
01898    ast_string_field_set(monitor_instance, subscribe_uri, subscribe_uri);
01899    ast_string_field_set(monitor_instance, peername, peername);
01900    ast_string_field_set(monitor_instance, device_name, device_name);
01901    monitor_instance->core_id = core_id;
01902    ao2_link(sip_monitor_instances, monitor_instance);
01903    return monitor_instance;
01904 }
01905 
01906 static int find_sip_monitor_instance_by_subscription_pvt(void *obj, void *arg, int flags)
01907 {
01908    struct sip_monitor_instance *monitor_instance = obj;
01909    return monitor_instance->subscription_pvt == arg ? CMP_MATCH | CMP_STOP : 0;
01910 }
01911 
01912 static int find_sip_monitor_instance_by_suspension_entry(void *obj, void *arg, int flags)
01913 {
01914    struct sip_monitor_instance *monitor_instance = obj;
01915    return monitor_instance->suspension_entry == arg ? CMP_MATCH | CMP_STOP : 0;
01916 }
01917 
01918 static int sip_cc_monitor_request_cc(struct ast_cc_monitor *monitor, int *available_timer_id);
01919 static int sip_cc_monitor_suspend(struct ast_cc_monitor *monitor);
01920 static int sip_cc_monitor_unsuspend(struct ast_cc_monitor *monitor);
01921 static int sip_cc_monitor_cancel_available_timer(struct ast_cc_monitor *monitor, int *sched_id);
01922 static void sip_cc_monitor_destructor(void *private_data);
01923 
01924 static struct ast_cc_monitor_callbacks sip_cc_monitor_callbacks = {
01925    .type = "SIP",
01926    .request_cc = sip_cc_monitor_request_cc,
01927    .suspend = sip_cc_monitor_suspend,
01928    .unsuspend = sip_cc_monitor_unsuspend,
01929    .cancel_available_timer = sip_cc_monitor_cancel_available_timer,
01930    .destructor = sip_cc_monitor_destructor,
01931 };
01932 
01933 static int sip_cc_monitor_request_cc(struct ast_cc_monitor *monitor, int *available_timer_id)
01934 {
01935    struct sip_monitor_instance *monitor_instance = monitor->private_data;
01936    enum ast_cc_service_type service = monitor->service_offered;
01937    int when;
01938 
01939    if (!monitor_instance) {
01940       return -1;
01941    }
01942 
01943    if (!(monitor_instance->subscription_pvt = sip_alloc(NULL, NULL, 0, SIP_SUBSCRIBE, NULL))) {
01944       return -1;
01945    }
01946 
01947    when = service == AST_CC_CCBS ? ast_get_ccbs_available_timer(monitor->interface->config_params) :
01948       ast_get_ccnr_available_timer(monitor->interface->config_params);
01949 
01950    sip_pvt_lock(monitor_instance->subscription_pvt);
01951    ast_set_flag(&monitor_instance->subscription_pvt->flags[0], SIP_OUTGOING);
01952    create_addr(monitor_instance->subscription_pvt, monitor_instance->peername, 0, 1, NULL);
01953    ast_sip_ouraddrfor(&monitor_instance->subscription_pvt->sa, &monitor_instance->subscription_pvt->ourip, monitor_instance->subscription_pvt);
01954    monitor_instance->subscription_pvt->subscribed = CALL_COMPLETION;
01955    monitor_instance->subscription_pvt->expiry = when;
01956 
01957    transmit_invite(monitor_instance->subscription_pvt, SIP_SUBSCRIBE, FALSE, 2, monitor_instance->subscribe_uri);
01958    sip_pvt_unlock(monitor_instance->subscription_pvt);
01959 
01960    ao2_t_ref(monitor, +1, "Adding a ref to the monitor for the scheduler");
01961    *available_timer_id = ast_sched_add(sched, when * 1000, ast_cc_available_timer_expire, monitor);
01962    return 0;
01963 }
01964 
01965 static int construct_pidf_body(enum sip_cc_publish_state state, char *pidf_body, size_t size, const char *presentity)
01966 {
01967    struct ast_str *body = ast_str_alloca(size);
01968    char tuple_id[32];
01969 
01970    generate_random_string(tuple_id, sizeof(tuple_id));
01971 
01972    /* We'll make this a bare-bones pidf body. In state_notify_build_xml, the PIDF
01973     * body gets a lot more extra junk that isn't necessary, so we'll leave it out here.
01974     */
01975    ast_str_append(&body, 0, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
01976    /* XXX The entity attribute is currently set to the peer name associated with the
01977     * dialog. This is because we currently only call this function for call-completion
01978     * PUBLISH bodies. In such cases, the entity is completely disregarded. For other
01979     * event packages, it may be crucial to have a proper URI as the presentity so this
01980     * should be revisited as support is expanded.
01981     */
01982    ast_str_append(&body, 0, "<presence xmlns=\"urn:ietf:params:xml:ns:pidf\" entity=\"%s\">\n", presentity);
01983    ast_str_append(&body, 0, "<tuple id=\"%s\">\n", tuple_id);
01984    ast_str_append(&body, 0, "<status><basic>%s</basic></status>\n", state == CC_OPEN ? "open" : "closed");
01985    ast_str_append(&body, 0, "</tuple>\n");
01986    ast_str_append(&body, 0, "</presence>\n");
01987    ast_copy_string(pidf_body, ast_str_buffer(body), size);
01988    return 0;
01989 }
01990 
01991 static int sip_cc_monitor_suspend(struct ast_cc_monitor *monitor)
01992 {
01993    struct sip_monitor_instance *monitor_instance = monitor->private_data;
01994    enum sip_publish_type publish_type;
01995    struct cc_epa_entry *cc_entry;
01996 
01997    if (!monitor_instance) {
01998       return -1;
01999    }
02000 
02001    if (!monitor_instance->suspension_entry) {
02002       /* We haven't yet allocated the suspension entry, so let's give it a shot */
02003       if (!(monitor_instance->suspension_entry = create_epa_entry("call-completion", monitor_instance->peername))) {
02004          ast_log(LOG_WARNING, "Unable to allocate sip EPA entry for call-completion\n");
02005          ao2_ref(monitor_instance, -1);
02006          return -1;
02007       }
02008       if (!(cc_entry = ast_calloc(1, sizeof(*cc_entry)))) {
02009          ast_log(LOG_WARNING, "Unable to allocate space for instance data of EPA entry for call-completion\n");
02010          ao2_ref(monitor_instance, -1);
02011          return -1;
02012       }
02013       cc_entry->core_id = monitor->core_id;
02014       monitor_instance->suspension_entry->instance_data = cc_entry;
02015       publish_type = SIP_PUBLISH_INITIAL;
02016    } else {
02017       publish_type = SIP_PUBLISH_MODIFY;
02018       cc_entry = monitor_instance->suspension_entry->instance_data;
02019    }
02020 
02021    cc_entry->current_state = CC_CLOSED;
02022 
02023    if (ast_strlen_zero(monitor_instance->notify_uri)) {
02024       /* If we have no set notify_uri, then what this means is that we have
02025        * not received a NOTIFY from this destination stating that he is
02026        * currently available.
02027        *
02028        * This situation can arise when the core calls the suspend callbacks
02029        * of multiple destinations. If one of the other destinations aside
02030        * from this one notified Asterisk that he is available, then there
02031        * is no reason to take any suspension action on this device. Rather,
02032        * we should return now and if we receive a NOTIFY while monitoring
02033        * is still "suspended" then we can immediately respond with the
02034        * proper PUBLISH to let this endpoint know what is going on.
02035        */
02036       return 0;
02037    }
02038    construct_pidf_body(CC_CLOSED, monitor_instance->suspension_entry->body, sizeof(monitor_instance->suspension_entry->body), monitor_instance->peername);
02039    return transmit_publish(monitor_instance->suspension_entry, publish_type, monitor_instance->notify_uri);
02040 }
02041 
02042 static int sip_cc_monitor_unsuspend(struct ast_cc_monitor *monitor)
02043 {
02044    struct sip_monitor_instance *monitor_instance = monitor->private_data;
02045    struct cc_epa_entry *cc_entry;
02046 
02047    if (!monitor_instance) {
02048       return -1;
02049    }
02050 
02051    ast_assert(monitor_instance->suspension_entry != NULL);
02052 
02053    cc_entry = monitor_instance->suspension_entry->instance_data;
02054    cc_entry->current_state = CC_OPEN;
02055    if (ast_strlen_zero(monitor_instance->notify_uri)) {
02056       /* This means we are being asked to unsuspend a call leg we never
02057        * sent a PUBLISH on. As such, there is no reason to send another
02058        * PUBLISH at this point either. We can just return instead.
02059        */
02060       return 0;
02061    }
02062    construct_pidf_body(CC_OPEN, monitor_instance->suspension_entry->body, sizeof(monitor_instance->suspension_entry->body), monitor_instance->peername);
02063    return transmit_publish(monitor_instance->suspension_entry, SIP_PUBLISH_MODIFY, monitor_instance->notify_uri);
02064 }
02065 
02066 static int sip_cc_monitor_cancel_available_timer(struct ast_cc_monitor *monitor, int *sched_id)
02067 {
02068    if (*sched_id != -1) {
02069       AST_SCHED_DEL(sched, *sched_id);
02070       ao2_t_ref(monitor, -1, "Removing scheduler's reference to the monitor");
02071    }
02072    return 0;
02073 }
02074 
02075 static void sip_cc_monitor_destructor(void *private_data)
02076 {
02077    struct sip_monitor_instance *monitor_instance = private_data;
02078    ao2_unlink(sip_monitor_instances, monitor_instance);
02079    ast_module_unref(ast_module_info->self);
02080 }
02081 
02082 static int sip_get_cc_information(struct sip_request *req, char *subscribe_uri, size_t size, enum ast_cc_service_type *service)
02083 {
02084    char *call_info = ast_strdupa(sip_get_header(req, "Call-Info"));
02085    char *uri;
02086    char *purpose;
02087    char *service_str;
02088    static const char cc_purpose[] = "purpose=call-completion";
02089    static const int cc_purpose_len = sizeof(cc_purpose) - 1;
02090 
02091    if (ast_strlen_zero(call_info)) {
02092       /* No Call-Info present. Definitely no CC offer */
02093       return -1;
02094    }
02095 
02096    uri = strsep(&call_info, ";");
02097 
02098    while ((purpose = strsep(&call_info, ";"))) {
02099       if (!strncmp(purpose, cc_purpose, cc_purpose_len)) {
02100          break;
02101       }
02102    }
02103    if (!purpose) {
02104       /* We didn't find the appropriate purpose= parameter. Oh well */
02105       return -1;
02106    }
02107 
02108    /* Okay, call-completion has been offered. Let's figure out what type of service this is */
02109    while ((service_str = strsep(&call_info, ";"))) {
02110       if (!strncmp(service_str, "m=", 2)) {
02111          break;
02112       }
02113    }
02114    if (!service_str) {
02115       /* So they didn't offer a particular service, We'll just go with CCBS since it really
02116        * doesn't matter anyway
02117        */
02118       service_str = "BS";
02119    } else {
02120       /* We already determined that there is an "m=" so no need to check
02121        * the result of this strsep
02122        */
02123       strsep(&service_str, "=");
02124    }
02125 
02126    if ((*service = service_string_to_service_type(service_str)) == AST_CC_NONE) {
02127       /* Invalid service offered */
02128       return -1;
02129    }
02130 
02131    ast_copy_string(subscribe_uri, get_in_brackets(uri), size);
02132 
02133    return 0;
02134 }
02135 
02136 /*
02137  * \brief Determine what, if any, CC has been offered and queue a CC frame if possible
02138  *
02139  * After taking care of some formalities to be sure that this call is eligible for CC,
02140  * we first try to see if we can make use of native CC. We grab the information from
02141  * the passed-in sip_request (which is always a response to an INVITE). If we can
02142  * use native CC monitoring for the call, then so be it.
02143  *
02144  * If native cc monitoring is not possible or not supported, then we will instead attempt
02145  * to use generic monitoring. Falling back to generic from a failed attempt at using native
02146  * monitoring will only work if the monitor policy of the endpoint is "always"
02147  *
02148  * \param pvt The current dialog. Contains CC parameters for the endpoint
02149  * \param req The response to the INVITE we want to inspect
02150  * \param service The service to use if generic monitoring is to be used. For native
02151  * monitoring, we get the service from the SIP response itself
02152  */
02153 static void sip_handle_cc(struct sip_pvt *pvt, struct sip_request *req, enum ast_cc_service_type service)
02154 {
02155    enum ast_cc_monitor_policies monitor_policy = ast_get_cc_monitor_policy(pvt->cc_params);
02156    int core_id;
02157    char interface_name[AST_CHANNEL_NAME];
02158 
02159    if (monitor_policy == AST_CC_MONITOR_NEVER) {
02160       /* Don't bother, just return */
02161       return;
02162    }
02163 
02164    if ((core_id = ast_cc_get_current_core_id(pvt->owner)) == -1) {
02165       /* For some reason, CC is invalid, so don't try it! */
02166       return;
02167    }
02168 
02169    ast_channel_get_device_name(pvt->owner, interface_name, sizeof(interface_name));
02170 
02171    if (monitor_policy == AST_CC_MONITOR_ALWAYS || monitor_policy == AST_CC_MONITOR_NATIVE) {
02172       char subscribe_uri[SIPBUFSIZE];
02173       char device_name[AST_CHANNEL_NAME];
02174       enum ast_cc_service_type offered_service;
02175       struct sip_monitor_instance *monitor_instance;
02176       if (sip_get_cc_information(req, subscribe_uri, sizeof(subscribe_uri), &offered_service)) {
02177          /* If CC isn't being offered to us, or for some reason the CC offer is
02178           * not formatted correctly, then it may still be possible to use generic
02179           * call completion since the monitor policy may be "always"
02180           */
02181          goto generic;
02182       }
02183       ast_channel_get_device_name(pvt->owner, device_name, sizeof(device_name));
02184       if (!(monitor_instance = sip_monitor_instance_init(core_id, subscribe_uri, pvt->peername, device_name))) {
02185          /* Same deal. We can try using generic still */
02186          goto generic;
02187       }
02188       /* We bump the refcount of chan_sip because once we queue this frame, the CC core
02189        * will have a reference to callbacks in this module. We decrement the module
02190        * refcount once the monitor destructor is called
02191        */
02192       ast_module_ref(ast_module_info->self);
02193       ast_queue_cc_frame(pvt->owner, "SIP", pvt->dialstring, offered_service, monitor_instance);
02194       ao2_ref(monitor_instance, -1);
02195       return;
02196    }
02197 
02198 generic:
02199    if (monitor_policy == AST_CC_MONITOR_GENERIC || monitor_policy == AST_CC_MONITOR_ALWAYS) {
02200       ast_queue_cc_frame(pvt->owner, AST_CC_GENERIC_MONITOR_TYPE, interface_name, service, NULL);
02201    }
02202 }
02203 
02204 /*! \brief Working TLS connection configuration */
02205 static struct ast_tls_config sip_tls_cfg;
02206 
02207 /*! \brief Default TLS connection configuration */
02208 static struct ast_tls_config default_tls_cfg;
02209 
02210 /*! \brief The TCP server definition */
02211 static struct ast_tcptls_session_args sip_tcp_desc = {
02212    .accept_fd = -1,
02213    .master = AST_PTHREADT_NULL,
02214    .tls_cfg = NULL,
02215    .poll_timeout = -1,
02216    .name = "SIP TCP server",
02217    .accept_fn = ast_tcptls_server_root,
02218    .worker_fn = sip_tcp_worker_fn,
02219 };
02220 
02221 /*! \brief The TCP/TLS server definition */
02222 static struct ast_tcptls_session_args sip_tls_desc = {
02223    .accept_fd = -1,
02224    .master = AST_PTHREADT_NULL,
02225    .tls_cfg = &sip_tls_cfg,
02226    .poll_timeout = -1,
02227    .name = "SIP TLS server",
02228    .accept_fn = ast_tcptls_server_root,
02229    .worker_fn = sip_tcp_worker_fn,
02230 };
02231 
02232 /*! \brief Append to SIP dialog history
02233    \return Always returns 0 */
02234 #define append_history(p, event, fmt , args... )   append_history_full(p, "%-15s " fmt, event, ## args)
02235 
02236 struct sip_pvt *dialog_ref_debug(struct sip_pvt *p, const char *tag, char *file, int line, const char *func)
02237 {
02238    if (p)
02239 #ifdef REF_DEBUG
02240       __ao2_ref_debug(p, 1, tag, file, line, func);
02241 #else
02242       ao2_ref(p, 1);
02243 #endif
02244    else
02245       ast_log(LOG_ERROR, "Attempt to Ref a null pointer\n");
02246    return p;
02247 }
02248 
02249 struct sip_pvt *dialog_unref_debug(struct sip_pvt *p, const char *tag, char *file, int line, const char *func)
02250 {
02251    if (p)
02252 #ifdef REF_DEBUG
02253       __ao2_ref_debug(p, -1, tag, file, line, func);
02254 #else
02255       ao2_ref(p, -1);
02256 #endif
02257    return NULL;
02258 }
02259 
02260 /*! \brief map from an integer value to a string.
02261  * If no match is found, return errorstring
02262  */
02263 static const char *map_x_s(const struct _map_x_s *table, int x, const char *errorstring)
02264 {
02265    const struct _map_x_s *cur;
02266 
02267    for (cur = table; cur->s; cur++) {
02268       if (cur->x == x) {
02269          return cur->s;
02270       }
02271    }
02272    return errorstring;
02273 }
02274 
02275 /*! \brief map from a string to an integer value, case insensitive.
02276  * If no match is found, return errorvalue.
02277  */
02278 static int map_s_x(const struct _map_x_s *table, const char *s, int errorvalue)
02279 {
02280    const struct _map_x_s *cur;
02281 
02282    for (cur = table; cur->s; cur++) {
02283       if (!strcasecmp(cur->s, s)) {
02284          return cur->x;
02285       }
02286    }
02287    return errorvalue;
02288 }
02289 
02290 static enum AST_REDIRECTING_REASON sip_reason_str_to_code(const char *text)
02291 {
02292    enum AST_REDIRECTING_REASON ast = AST_REDIRECTING_REASON_UNKNOWN;
02293    int i;
02294 
02295    for (i = 0; i < ARRAY_LEN(sip_reason_table); ++i) {
02296       if (!strcasecmp(text, sip_reason_table[i].text)) {
02297          ast = sip_reason_table[i].code;
02298          break;
02299       }
02300    }
02301 
02302    return ast;
02303 }
02304 
02305 static const char *sip_reason_code_to_str(enum AST_REDIRECTING_REASON code)
02306 {
02307    if (code >= 0 && code < ARRAY_LEN(sip_reason_table)) {
02308       return sip_reason_table[code].text;
02309    }
02310 
02311    return "unknown";
02312 }
02313 
02314 /*!
02315  * \brief generic function for determining if a correct transport is being
02316  * used to contact a peer
02317  *
02318  * this is done as a macro so that the "tmpl" var can be passed either a
02319  * sip_request or a sip_peer
02320  */
02321 #define check_request_transport(peer, tmpl) ({ \
02322    int ret = 0; \
02323    if (peer->socket.type == tmpl->socket.type) \
02324       ; \
02325    else if (!(peer->transports & tmpl->socket.type)) {\
02326       ast_log(LOG_ERROR, \
02327          "'%s' is not a valid transport for '%s'. we only use '%s'! ending call.\n", \
02328          sip_get_transport(tmpl->socket.type), peer->name, get_transport_list(peer->transports) \
02329          ); \
02330       ret = 1; \
02331    } else if (peer->socket.type & SIP_TRANSPORT_TLS) { \
02332       ast_log(LOG_WARNING, \
02333          "peer '%s' HAS NOT USED (OR SWITCHED TO) TLS in favor of '%s' (but this was allowed in sip.conf)!\n", \
02334          peer->name, sip_get_transport(tmpl->socket.type) \
02335       ); \
02336    } else { \
02337       ast_debug(1, \
02338          "peer '%s' has contacted us over %s even though we prefer %s.\n", \
02339          peer->name, sip_get_transport(tmpl->socket.type), sip_get_transport(peer->socket.type) \
02340       ); \
02341    }\
02342    (ret); \
02343 })
02344 
02345 /*! \brief
02346  * duplicate a list of channel variables, \return the copy.
02347  */
02348 static struct ast_variable *copy_vars(struct ast_variable *src)
02349 {
02350    struct ast_variable *res = NULL, *tmp, *v = NULL;
02351 
02352    for (v = src ; v ; v = v->next) {
02353       if ((tmp = ast_variable_new(v->name, v->value, v->file))) {
02354          tmp->next = res;
02355          res = tmp;
02356       }
02357    }
02358    return res;
02359 }
02360 
02361 static void tcptls_packet_destructor(void *obj)
02362 {
02363    struct tcptls_packet *packet = obj;
02364 
02365    ast_free(packet->data);
02366 }
02367 
02368 static void sip_tcptls_client_args_destructor(void *obj)
02369 {
02370    struct ast_tcptls_session_args *args = obj;
02371    if (args->tls_cfg) {
02372       ast_free(args->tls_cfg->certfile);
02373       ast_free(args->tls_cfg->pvtfile);
02374       ast_free(args->tls_cfg->cipher);
02375       ast_free(args->tls_cfg->cafile);
02376       ast_free(args->tls_cfg->capath);
02377    }
02378    ast_free(args->tls_cfg);
02379    ast_free((char *) args->name);
02380 }
02381 
02382 static void sip_threadinfo_destructor(void *obj)
02383 {
02384    struct sip_threadinfo *th = obj;
02385    struct tcptls_packet *packet;
02386 
02387    if (th->alert_pipe[1] > -1) {
02388       close(th->alert_pipe[0]);
02389    }
02390    if (th->alert_pipe[1] > -1) {
02391       close(th->alert_pipe[1]);
02392    }
02393    th->alert_pipe[0] = th->alert_pipe[1] = -1;
02394 
02395    while ((packet = AST_LIST_REMOVE_HEAD(&th->packet_q, entry))) {
02396       ao2_t_ref(packet, -1, "thread destruction, removing packet from frame queue");
02397    }
02398 
02399    if (th->tcptls_session) {
02400       ao2_t_ref(th->tcptls_session, -1, "remove tcptls_session for sip_threadinfo object");
02401    }
02402 }
02403 
02404 /*! \brief creates a sip_threadinfo object and links it into the threadt table. */
02405 static struct sip_threadinfo *sip_threadinfo_create(struct ast_tcptls_session_instance *tcptls_session, int transport)
02406 {
02407    struct sip_threadinfo *th;
02408 
02409    if (!tcptls_session || !(th = ao2_alloc(sizeof(*th), sip_threadinfo_destructor))) {
02410       return NULL;
02411    }
02412 
02413    th->alert_pipe[0] = th->alert_pipe[1] = -1;
02414 
02415    if (pipe(th->alert_pipe) == -1) {
02416       ao2_t_ref(th, -1, "Failed to open alert pipe on sip_threadinfo");
02417       ast_log(LOG_ERROR, "Could not create sip alert pipe in tcptls thread, error %s\n", strerror(errno));
02418       return NULL;
02419    }
02420    ao2_t_ref(tcptls_session, +1, "tcptls_session ref for sip_threadinfo object");
02421    th->tcptls_session = tcptls_session;
02422    th->type = transport ? transport : (tcptls_session->ssl ? SIP_TRANSPORT_TLS: SIP_TRANSPORT_TCP);
02423    ao2_t_link(threadt, th, "Adding new tcptls helper thread");
02424    ao2_t_ref(th, -1, "Decrementing threadinfo ref from alloc, only table ref remains");
02425    return th;
02426 }
02427 
02428 /*! \brief used to indicate to a tcptls thread that data is ready to be written */
02429 static int sip_tcptls_write(struct ast_tcptls_session_instance *tcptls_session, const void *buf, size_t len)
02430 {
02431    int res = len;
02432    struct sip_threadinfo *th = NULL;
02433    struct tcptls_packet *packet = NULL;
02434    struct sip_threadinfo tmp = {
02435       .tcptls_session = tcptls_session,
02436    };
02437    enum sip_tcptls_alert alert = TCPTLS_ALERT_DATA;
02438 
02439    if (!tcptls_session) {
02440       return XMIT_ERROR;
02441    }
02442 
02443    ast_mutex_lock(&tcptls_session->lock);
02444 
02445    if ((tcptls_session->fd == -1) ||
02446       !(th = ao2_t_find(threadt, &tmp, OBJ_POINTER, "ao2_find, getting sip_threadinfo in tcp helper thread")) ||
02447       !(packet = ao2_alloc(sizeof(*packet), tcptls_packet_destructor)) ||
02448       !(packet->data = ast_str_create(len))) {
02449       goto tcptls_write_setup_error;
02450    }
02451 
02452    /* goto tcptls_write_error should _NOT_ be used beyond this point */
02453    ast_str_set(&packet->data, 0, "%s", (char *) buf);
02454    packet->len = len;
02455 
02456    /* alert tcptls thread handler that there is a packet to be sent.
02457     * must lock the thread info object to guarantee control of the
02458     * packet queue */
02459    ao2_lock(th);
02460    if (write(th->alert_pipe[1], &alert, sizeof(alert)) == -1) {
02461       ast_log(LOG_ERROR, "write() to alert pipe failed: %s\n", strerror(errno));
02462       ao2_t_ref(packet, -1, "could not write to alert pipe, remove packet");
02463       packet = NULL;
02464       res = XMIT_ERROR;
02465    } else { /* it is safe to queue the frame after issuing the alert when we hold the threadinfo lock */
02466       AST_LIST_INSERT_TAIL(&th->packet_q, packet, entry);
02467    }
02468    ao2_unlock(th);
02469 
02470    ast_mutex_unlock(&tcptls_session->lock);
02471    ao2_t_ref(th, -1, "In sip_tcptls_write, unref threadinfo object after finding it");
02472    return res;
02473 
02474 tcptls_write_setup_error:
02475    if (th) {
02476       ao2_t_ref(th, -1, "In sip_tcptls_write, unref threadinfo obj, could not create packet");
02477    }
02478    if (packet) {
02479       ao2_t_ref(packet, -1, "could not allocate packet's data");
02480    }
02481    ast_mutex_unlock(&tcptls_session->lock);
02482 
02483    return XMIT_ERROR;
02484 }
02485 
02486 /*! \brief SIP TCP connection handler */
02487 static void *sip_tcp_worker_fn(void *data)
02488 {
02489    struct ast_tcptls_session_instance *tcptls_session = data;
02490 
02491    return _sip_tcp_helper_thread(NULL, tcptls_session);
02492 }
02493 
02494 /*! \brief Check if the authtimeout has expired.
02495  * \param start the time when the session started
02496  *
02497  * \retval 0 the timeout has expired
02498  * \retval -1 error
02499  * \return the number of milliseconds until the timeout will expire
02500  */
02501 static int sip_check_authtimeout(time_t start)
02502 {
02503    int timeout;
02504    time_t now;
02505    if(time(&now) == -1) {
02506       ast_log(LOG_ERROR, "error executing time(): %s\n", strerror(errno));
02507       return -1;
02508    }
02509 
02510    timeout = (authtimeout - (now - start)) * 1000;
02511    if (timeout < 0) {
02512       /* we have timed out */
02513       return 0;
02514    }
02515 
02516    return timeout;
02517 }
02518 
02519 /*! \brief SIP TCP thread management function
02520    This function reads from the socket, parses the packet into a request
02521 */
02522 static void *_sip_tcp_helper_thread(struct sip_pvt *pvt, struct ast_tcptls_session_instance *tcptls_session)
02523 {
02524    int res, cl, timeout = -1, authenticated = 0, flags, after_poll = 0, need_poll = 1;
02525    time_t start;
02526    struct sip_request req = { 0, } , reqcpy = { 0, };
02527    struct sip_threadinfo *me = NULL;
02528    char buf[1024] = "";
02529    struct pollfd fds[2] = { { 0 }, { 0 }, };
02530    struct ast_tcptls_session_args *ca = NULL;
02531 
02532    /* If this is a server session, then the connection has already been
02533     * setup. Check if the authlimit has been reached and if not create the
02534     * threadinfo object so we can access this thread for writing.
02535     *
02536     * if this is a client connection more work must be done.
02537     * 1. We own the parent session args for a client connection.  This pointer needs
02538     *    to be held on to so we can decrement it's ref count on thread destruction.
02539     * 2. The threadinfo object was created before this thread was launched, however
02540     *    it must be found within the threadt table.
02541     * 3. Last, the tcptls_session must be started.
02542     */
02543    if (!tcptls_session->client) {
02544       if (ast_atomic_fetchadd_int(&unauth_sessions, +1) >= authlimit) {
02545          /* unauth_sessions is decremented in the cleanup code */
02546          goto cleanup;
02547       }
02548 
02549       if ((flags = fcntl(tcptls_session->fd, F_GETFL)) == -1) {
02550          ast_log(LOG_ERROR, "error setting socket to non blocking mode, fcntl() failed: %s\n", strerror(errno));
02551          goto cleanup;
02552       }
02553 
02554       flags |= O_NONBLOCK;
02555       if (fcntl(tcptls_session->fd, F_SETFL, flags) == -1) {
02556          ast_log(LOG_ERROR, "error setting socket to non blocking mode, fcntl() failed: %s\n", strerror(errno));
02557          goto cleanup;
02558       }
02559 
02560       if (!(me = sip_threadinfo_create(tcptls_session, tcptls_session->ssl ? SIP_TRANSPORT_TLS : SIP_TRANSPORT_TCP))) {
02561          goto cleanup;
02562       }
02563       ao2_t_ref(me, +1, "Adding threadinfo ref for tcp_helper_thread");
02564    } else {
02565       struct sip_threadinfo tmp = {
02566          .tcptls_session = tcptls_session,
02567       };
02568 
02569       if ((!(ca = tcptls_session->parent)) ||
02570          (!(me = ao2_t_find(threadt, &tmp, OBJ_POINTER, "ao2_find, getting sip_threadinfo in tcp helper thread"))) ||
02571          (!(tcptls_session = ast_tcptls_client_start(tcptls_session)))) {
02572          goto cleanup;
02573       }
02574    }
02575 
02576    flags = 1;
02577    if (setsockopt(tcptls_session->fd, SOL_SOCKET, SO_KEEPALIVE, &flags, sizeof(flags))) {
02578       ast_log(LOG_ERROR, "error enabling TCP keep-alives on sip socket: %s\n", strerror(errno));
02579       goto cleanup;
02580    }
02581 
02582    me->threadid = pthread_self();
02583    ast_debug(2, "Starting thread for %s server\n", tcptls_session->ssl ? "SSL" : "TCP");
02584 
02585    /* set up pollfd to watch for reads on both the socket and the alert_pipe */
02586    fds[0].fd = tcptls_session->fd;
02587    fds[1].fd = me->alert_pipe[0];
02588    fds[0].events = fds[1].events = POLLIN | POLLPRI;
02589 
02590    if (!(req.data = ast_str_create(SIP_MIN_PACKET))) {
02591       goto cleanup;
02592    }
02593    if (!(reqcpy.data = ast_str_create(SIP_MIN_PACKET))) {
02594       goto cleanup;
02595    }
02596 
02597    if(time(&start) == -1) {
02598       ast_log(LOG_ERROR, "error executing time(): %s\n", strerror(errno));
02599       goto cleanup;
02600    }
02601 
02602    for (;;) {
02603       struct ast_str *str_save;
02604 
02605       if (!tcptls_session->client && req.authenticated && !authenticated) {
02606          authenticated = 1;
02607          ast_atomic_fetchadd_int(&unauth_sessions, -1);
02608       }
02609 
02610       /* calculate the timeout for unauthenticated server sessions */
02611       if (!tcptls_session->client && !authenticated ) {
02612          if ((timeout = sip_check_authtimeout(start)) < 0) {
02613             goto cleanup;
02614          }
02615 
02616          if (timeout == 0) {
02617             ast_debug(2, "SIP %s server timed out\n", tcptls_session->ssl ? "SSL": "TCP");
02618             goto cleanup;
02619          }
02620       } else {
02621          timeout = -1;
02622       }
02623 
02624       res = ast_poll(fds, 2, timeout); /* polls for both socket and alert_pipe */
02625       if (res < 0) {
02626          ast_debug(2, "SIP %s server :: ast_wait_for_input returned %d\n", tcptls_session->ssl ? "SSL": "TCP", res);
02627          goto cleanup;
02628       } else if (res == 0) {
02629          /* timeout */
02630          ast_debug(2, "SIP %s server timed out\n", tcptls_session->ssl ? "SSL": "TCP");
02631          goto cleanup;
02632       }
02633 
02634       /* handle the socket event, check for both reads from the socket fd,
02635        * and writes from alert_pipe fd */
02636       if (fds[0].revents) { /* there is data on the socket to be read */
02637          after_poll = 1;
02638 
02639          fds[0].revents = 0;
02640 
02641          /* clear request structure */
02642          str_save = req.data;
02643          memset(&req, 0, sizeof(req));
02644          req.data = str_save;
02645          ast_str_reset(req.data);
02646 
02647          str_save = reqcpy.data;
02648          memset(&reqcpy, 0, sizeof(reqcpy));
02649          reqcpy.data = str_save;
02650          ast_str_reset(reqcpy.data);
02651 
02652          memset(buf, 0, sizeof(buf));
02653 
02654          if (tcptls_session->ssl) {
02655             set_socket_transport(&req.socket, SIP_TRANSPORT_TLS);
02656             req.socket.port = htons(ourport_tls);
02657          } else {
02658             set_socket_transport(&req.socket, SIP_TRANSPORT_TCP);
02659             req.socket.port = htons(ourport_tcp);
02660          }
02661          req.socket.fd = tcptls_session->fd;
02662 
02663          /* Read in headers one line at a time */
02664          while (ast_str_strlen(req.data) < 4 || strncmp(REQ_OFFSET_TO_STR(&req, data->used - 4), "\r\n\r\n", 4)) {
02665             if (!tcptls_session->client && !authenticated ) {
02666                if ((timeout = sip_check_authtimeout(start)) < 0) {
02667                   goto cleanup;
02668                }
02669 
02670                if (timeout == 0) {
02671                   ast_debug(2, "SIP %s server timed out\n", tcptls_session->ssl ? "SSL": "TCP");
02672                   goto cleanup;
02673                }
02674             } else {
02675                timeout = -1;
02676             }
02677 
02678             /* special polling behavior is required for TLS
02679              * sockets because of the buffering done in the
02680              * TLS layer */
02681             if (!tcptls_session->ssl || need_poll) {
02682                need_poll = 0;
02683                after_poll = 1;
02684                res = ast_wait_for_input(tcptls_session->fd, timeout);
02685                if (res < 0) {
02686                   ast_debug(2, "SIP TCP server :: ast_wait_for_input returned %d\n", res);
02687                   goto cleanup;
02688                } else if (res == 0) {
02689                   /* timeout */
02690                   ast_debug(2, "SIP TCP server timed out\n");
02691                   goto cleanup;
02692                }
02693             }
02694 
02695             ast_mutex_lock(&tcptls_session->lock);
02696             if (!fgets(buf, sizeof(buf), tcptls_session->f)) {
02697                ast_mutex_unlock(&tcptls_session->lock);
02698                if (after_poll) {
02699                   goto cleanup;
02700                } else {
02701                   need_poll = 1;
02702                   continue;
02703                }
02704             }
02705             ast_mutex_unlock(&tcptls_session->lock);
02706             after_poll = 0;
02707             if (me->stop) {
02708                 goto cleanup;
02709             }
02710             ast_str_append(&req.data, 0, "%s", buf);
02711          }
02712          copy_request(&reqcpy, &req);
02713          parse_request(&reqcpy);
02714          /* In order to know how much to read, we need the content-length header */
02715          if (sscanf(sip_get_header(&reqcpy, "Content-Length"), "%30d", &cl)) {
02716             while (cl > 0) {
02717                size_t bytes_read;
02718                if (!tcptls_session->client && !authenticated ) {
02719                   if ((timeout = sip_check_authtimeout(start)) < 0) {
02720                      goto cleanup;
02721                   }
02722 
02723                   if (timeout == 0) {
02724                      ast_debug(2, "SIP %s server timed out\n", tcptls_session->ssl ? "SSL": "TCP");
02725                      goto cleanup;
02726                   }
02727                } else {
02728                   timeout = -1;
02729                }
02730 
02731                if (!tcptls_session->ssl || need_poll) {
02732                   need_poll = 0;
02733                   after_poll = 1;
02734                   res = ast_wait_for_input(tcptls_session->fd, timeout);
02735                   if (res < 0) {
02736                      ast_debug(2, "SIP TCP server :: ast_wait_for_input returned %d\n", res);
02737                      goto cleanup;
02738                   } else if (res == 0) {
02739                      /* timeout */
02740                      ast_debug(2, "SIP TCP server timed out\n");
02741                      goto cleanup;
02742                   }
02743                }
02744 
02745                ast_mutex_lock(&tcptls_session->lock);
02746                if (!(bytes_read = fread(buf, 1, MIN(sizeof(buf) - 1, cl), tcptls_session->f))) {
02747                   ast_mutex_unlock(&tcptls_session->lock);
02748                   if (after_poll) {
02749                      goto cleanup;
02750                   } else {
02751                      need_poll = 1;
02752                      continue;
02753                   }
02754                }
02755                buf[bytes_read] = '\0';
02756                ast_mutex_unlock(&tcptls_session->lock);
02757                after_poll = 0;
02758                if (me->stop) {
02759                   goto cleanup;
02760                }
02761                cl -= strlen(buf);
02762                ast_str_append(&req.data, 0, "%s", buf);
02763             }
02764          }
02765          /*! \todo XXX If there's no Content-Length or if the content-length and what
02766                we receive is not the same - we should generate an error */
02767 
02768          req.socket.tcptls_session = tcptls_session;
02769          handle_request_do(&req, &tcptls_session->remote_address);
02770       }
02771 
02772       if (fds[1].revents) { /* alert_pipe indicates there is data in the send queue to be sent */
02773          enum sip_tcptls_alert alert;
02774          struct tcptls_packet *packet;
02775 
02776          fds[1].revents = 0;
02777 
02778          if (read(me->alert_pipe[0], &alert, sizeof(alert)) == -1) {
02779             ast_log(LOG_ERROR, "read() failed: %s\n", strerror(errno));
02780             continue;
02781          }
02782 
02783          switch (alert) {
02784          case TCPTLS_ALERT_STOP:
02785             goto cleanup;
02786          case TCPTLS_ALERT_DATA:
02787             ao2_lock(me);
02788             if (!(packet = AST_LIST_REMOVE_HEAD(&me->packet_q, entry))) {
02789                ast_log(LOG_WARNING, "TCPTLS thread alert_pipe indicated packet should be sent, but frame_q is empty");
02790             }
02791             ao2_unlock(me);
02792 
02793             if (packet) {
02794                if (ast_tcptls_server_write(tcptls_session, ast_str_buffer(packet->data), packet->len) == -1) {
02795                   ast_log(LOG_WARNING, "Failure to write to tcp/tls socket\n");
02796                }
02797                ao2_t_ref(packet, -1, "tcptls packet sent, this is no longer needed");
02798             }
02799             break;
02800          default:
02801             ast_log(LOG_ERROR, "Unknown tcptls thread alert '%d'\n", alert);
02802          }
02803       }
02804    }
02805 
02806    ast_debug(2, "Shutting down thread for %s server\n", tcptls_session->ssl ? "SSL" : "TCP");
02807 
02808 cleanup:
02809    if (tcptls_session && !tcptls_session->client && !authenticated) {
02810       ast_atomic_fetchadd_int(&unauth_sessions, -1);
02811    }
02812 
02813    if (me) {
02814       ao2_t_unlink(threadt, me, "Removing tcptls helper thread, thread is closing");
02815       ao2_t_ref(me, -1, "Removing tcp_helper_threads threadinfo ref");
02816    }
02817    deinit_req(&reqcpy);
02818    deinit_req(&req);
02819 
02820    /* if client, we own the parent session arguments and must decrement ref */
02821    if (ca) {
02822       ao2_t_ref(ca, -1, "closing tcptls thread, getting rid of client tcptls_session arguments");
02823    }
02824 
02825    if (tcptls_session) {
02826       ast_mutex_lock(&tcptls_session->lock);
02827       ast_tcptls_close_session_file(tcptls_session);
02828       tcptls_session->parent = NULL;
02829       ast_mutex_unlock(&tcptls_session->lock);
02830 
02831       ao2_ref(tcptls_session, -1);
02832       tcptls_session = NULL;
02833    }
02834    return NULL;
02835 }
02836 
02837 #ifdef REF_DEBUG
02838 #define sip_ref_peer(arg1,arg2) _ref_peer((arg1),(arg2), __FILE__, __LINE__, __PRETTY_FUNCTION__)
02839 #define sip_unref_peer(arg1,arg2) _unref_peer((arg1),(arg2), __FILE__, __LINE__, __PRETTY_FUNCTION__)
02840 static struct sip_peer *_ref_peer(struct sip_peer *peer, char *tag, char *file, int line, const char *func)
02841 {
02842    if (peer)
02843       __ao2_ref_debug(peer, 1, tag, file, line, func);
02844    else
02845       ast_log(LOG_ERROR, "Attempt to Ref a null peer pointer\n");
02846    return peer;
02847 }
02848 
02849 static struct sip_peer *_unref_peer(struct sip_peer *peer, char *tag, char *file, int line, const char *func)
02850 {
02851    if (peer)
02852       __ao2_ref_debug(peer, -1, tag, file, line, func);
02853    return NULL;
02854 }
02855 #else
02856 /*!
02857  * helper functions to unreference various types of objects.
02858  * By handling them this way, we don't have to declare the
02859  * destructor on each call, which removes the chance of errors.
02860  */
02861 void *sip_unref_peer(struct sip_peer *peer, char *tag)
02862 {
02863    ao2_t_ref(peer, -1, tag);
02864    return NULL;
02865 }
02866 
02867 struct sip_peer *sip_ref_peer(struct sip_peer *peer, char *tag)
02868 {
02869    ao2_t_ref(peer, 1, tag);
02870    return peer;
02871 }
02872 #endif /* REF_DEBUG */
02873 
02874 static void peer_sched_cleanup(struct sip_peer *peer)
02875 {
02876    if (peer->pokeexpire != -1) {
02877       AST_SCHED_DEL_UNREF(sched, peer->pokeexpire,
02878             sip_unref_peer(peer, "removing poke peer ref"));
02879    }
02880    if (peer->expire != -1) {
02881       AST_SCHED_DEL_UNREF(sched, peer->expire,
02882             sip_unref_peer(peer, "remove register expire ref"));
02883    }
02884 }
02885 
02886 typedef enum {
02887    SIP_PEERS_MARKED,
02888    SIP_PEERS_ALL,
02889 } peer_unlink_flag_t;
02890 
02891 /* this func is used with ao2_callback to unlink/delete all marked or linked
02892    peers, depending on arg */
02893 static int match_and_cleanup_peer_sched(void *peerobj, void *arg, int flags)
02894 {
02895    struct sip_peer *peer = peerobj;
02896    peer_unlink_flag_t which = *(peer_unlink_flag_t *)arg;
02897 
02898    if (which == SIP_PEERS_ALL || peer->the_mark) {
02899       peer_sched_cleanup(peer);
02900       if (peer->dnsmgr) {
02901          ast_dnsmgr_release(peer->dnsmgr);
02902          peer->dnsmgr = NULL;
02903          sip_unref_peer(peer, "Release peer from dnsmgr");
02904       }
02905       return CMP_MATCH;
02906    }
02907    return 0;
02908 }
02909 
02910 static void unlink_peers_from_tables(peer_unlink_flag_t flag)
02911 {
02912    ao2_t_callback(peers, OBJ_NODATA | OBJ_UNLINK | OBJ_MULTIPLE,
02913       match_and_cleanup_peer_sched, &flag, "initiating callback to remove marked peers");
02914    ao2_t_callback(peers_by_ip, OBJ_NODATA | OBJ_UNLINK | OBJ_MULTIPLE,
02915       match_and_cleanup_peer_sched, &flag, "initiating callback to remove marked peers");
02916 }
02917 
02918 /* \brief Unlink all marked peers from ao2 containers */
02919 static void unlink_marked_peers_from_tables(void)
02920 {
02921    unlink_peers_from_tables(SIP_PEERS_MARKED);
02922 }
02923 
02924 static void unlink_all_peers_from_tables(void)
02925 {
02926    unlink_peers_from_tables(SIP_PEERS_ALL);
02927 }
02928 
02929 /* \brief Unlink single peer from all ao2 containers */
02930 static void unlink_peer_from_tables(struct sip_peer *peer)
02931 {
02932    ao2_t_unlink(peers, peer, "ao2_unlink of peer from peers table");
02933    if (!ast_sockaddr_isnull(&peer->addr)) {
02934       ao2_t_unlink(peers_by_ip, peer, "ao2_unlink of peer from peers_by_ip table");
02935    }
02936 }
02937 
02938 /*! \brief maintain proper refcounts for a sip_pvt's outboundproxy
02939  *
02940  * This function sets pvt's outboundproxy pointer to the one referenced
02941  * by the proxy parameter. Because proxy may be a refcounted object, and
02942  * because pvt's old outboundproxy may also be a refcounted object, we need
02943  * to maintain the proper refcounts.
02944  *
02945  * \param pvt The sip_pvt for which we wish to set the outboundproxy
02946  * \param proxy The sip_proxy which we will point pvt towards.
02947  * \return Returns void
02948  */
02949 static void ref_proxy(struct sip_pvt *pvt, struct sip_proxy *proxy)
02950 {
02951    struct sip_proxy *old_obproxy = pvt->outboundproxy;
02952    /* The sip_cfg.outboundproxy is statically allocated, and so
02953     * we don't ever need to adjust refcounts for it
02954     */
02955    if (proxy && proxy != &sip_cfg.outboundproxy) {
02956       ao2_ref(proxy, +1);
02957    }
02958    pvt->outboundproxy = proxy;
02959    if (old_obproxy && old_obproxy != &sip_cfg.outboundproxy) {
02960       ao2_ref(old_obproxy, -1);
02961    }
02962 }
02963 
02964 /*!
02965  * \brief Unlink a dialog from the dialogs container, as well as any other places
02966  * that it may be currently stored.
02967  *
02968  * \note A reference to the dialog must be held before calling this function, and this
02969  * function does not release that reference.
02970  */
02971 void dialog_unlink_all(struct sip_pvt *dialog)
02972 {
02973    struct sip_pkt *cp;
02974    struct ast_channel *owner;
02975 
02976    dialog_ref(dialog, "Let's bump the count in the unlink so it doesn't accidentally become dead before we are done");
02977 
02978    ao2_t_unlink(dialogs, dialog, "unlinking dialog via ao2_unlink");
02979    ao2_t_unlink(dialogs_needdestroy, dialog, "unlinking dialog_needdestroy via ao2_unlink");
02980    ao2_t_unlink(dialogs_rtpcheck, dialog, "unlinking dialog_rtpcheck via ao2_unlink");
02981 
02982    /* Unlink us from the owner (channel) if we have one */
02983    owner = sip_pvt_lock_full(dialog);
02984    if (owner) {
02985       ast_debug(1, "Detaching from channel %s\n", ast_channel_name(owner));
02986       owner->tech_pvt = dialog_unref(owner->tech_pvt, "resetting channel dialog ptr in unlink_all");
02987       ast_channel_unlock(owner);
02988       ast_channel_unref(owner);
02989       dialog->owner = NULL;
02990    }
02991    sip_pvt_unlock(dialog);
02992 
02993    if (dialog->registry) {
02994       if (dialog->registry->call == dialog) {
02995          dialog->registry->call = dialog_unref(dialog->registry->call, "nulling out the registry's call dialog field in unlink_all");
02996       }
02997       dialog->registry = registry_unref(dialog->registry, "delete dialog->registry");
02998    }
02999    if (dialog->stateid != -1) {
03000       ast_extension_state_del(dialog->stateid, cb_extensionstate);
03001       dialog->stateid = -1;
03002    }
03003    /* Remove link from peer to subscription of MWI */
03004    if (dialog->relatedpeer && dialog->relatedpeer->mwipvt == dialog) {
03005       dialog->relatedpeer->mwipvt = dialog_unref(dialog->relatedpeer->mwipvt, "delete ->relatedpeer->mwipvt");
03006    }
03007    if (dialog->relatedpeer && dialog->relatedpeer->call == dialog) {
03008       dialog->relatedpeer->call = dialog_unref(dialog->relatedpeer->call, "unset the relatedpeer->call field in tandem with relatedpeer field itself");
03009    }
03010 
03011    /* remove all current packets in this dialog */
03012    while((cp = dialog->packets)) {
03013       dialog->packets = dialog->packets->next;
03014       AST_SCHED_DEL(sched, cp->retransid);
03015       dialog_unref(cp->owner, "remove all current packets in this dialog, and the pointer to the dialog too as part of __sip_destroy");
03016       if (cp->data) {
03017          ast_free(cp->data);
03018       }
03019       ast_free(cp);
03020    }
03021 
03022    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"));
03023 
03024    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"));
03025    
03026    if (dialog->autokillid > -1) {
03027       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"));
03028    }
03029 
03030    if (dialog->request_queue_sched_id > -1) {
03031       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"));
03032    }
03033 
03034    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"));
03035 
03036    if (dialog->t38id > -1) {
03037       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"));
03038    }
03039 
03040    if (dialog->stimer) {
03041       stop_session_timer(dialog);
03042    }
03043 
03044    dialog_unref(dialog, "Let's unbump the count in the unlink so the poor pvt can disappear if it is time");
03045 }
03046 
03047 void *registry_unref(struct sip_registry *reg, char *tag)
03048 {
03049    ast_debug(3, "SIP Registry %s: refcount now %d\n", reg->hostname, reg->refcount - 1);
03050    ASTOBJ_UNREF(reg, sip_registry_destroy);
03051    return NULL;
03052 }
03053 
03054 /*! \brief Add object reference to SIP registry */
03055 static struct sip_registry *registry_addref(struct sip_registry *reg, char *tag)
03056 {
03057    ast_debug(3, "SIP Registry %s: refcount now %d\n", reg->hostname, reg->refcount + 1);
03058    return ASTOBJ_REF(reg); /* Add pointer to registry in packet */
03059 }
03060 
03061 /*! \brief Interface structure with callbacks used to connect to UDPTL module*/
03062 static struct ast_udptl_protocol sip_udptl = {
03063    type: "SIP",
03064    get_udptl_info: sip_get_udptl_peer,
03065    set_udptl_peer: sip_set_udptl_peer,
03066 };
03067 
03068 static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
03069    __attribute__((format(printf, 2, 3)));
03070 
03071 
03072 /*! \brief Convert transfer status to string */
03073 static const char *referstatus2str(enum referstatus rstatus)
03074 {
03075    return map_x_s(referstatusstrings, rstatus, "");
03076 }
03077 
03078 static inline void pvt_set_needdestroy(struct sip_pvt *pvt, const char *reason)
03079 {
03080    if (pvt->final_destruction_scheduled) {
03081       return; /* This is already scheduled for final destruction, let the scheduler take care of it. */
03082    }
03083    append_history(pvt, "NeedDestroy", "Setting needdestroy because %s", reason);
03084    if (!pvt->needdestroy) {
03085       pvt->needdestroy = 1;
03086       ao2_t_link(dialogs_needdestroy, pvt, "link pvt into dialogs_needdestroy container");
03087    }
03088 }
03089 
03090 /*! \brief Initialize the initital request packet in the pvt structure.
03091    This packet is used for creating replies and future requests in
03092    a dialog */
03093 static void initialize_initreq(struct sip_pvt *p, struct sip_request *req)
03094 {
03095    if (p->initreq.headers) {
03096       ast_debug(1, "Initializing already initialized SIP dialog %s (presumably reinvite)\n", p->callid);
03097    } else {
03098       ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
03099    }
03100    /* Use this as the basis */
03101    copy_request(&p->initreq, req);
03102    parse_request(&p->initreq);
03103    if (req->debug) {
03104       ast_verbose("Initreq: %d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
03105    }
03106 }
03107 
03108 /*! \brief Encapsulate setting of SIP_ALREADYGONE to be able to trace it with debugging */
03109 static void sip_alreadygone(struct sip_pvt *dialog)
03110 {
03111    ast_debug(3, "Setting SIP_ALREADYGONE on dialog %s\n", dialog->callid);
03112    dialog->alreadygone = 1;
03113 }
03114 
03115 /*! Resolve DNS srv name or host name in a sip_proxy structure */
03116 static int proxy_update(struct sip_proxy *proxy)
03117 {
03118    /* if it's actually an IP address and not a name,
03119            there's no need for a managed lookup */
03120    if (!ast_sockaddr_parse(&proxy->ip, proxy->name, 0)) {
03121       /* Ok, not an IP address, then let's check if it's a domain or host */
03122       /* XXX Todo - if we have proxy port, don't do SRV */
03123       proxy->ip.ss.ss_family = get_address_family_filter(&bindaddr); /* Filter address family */
03124       if (ast_get_ip_or_srv(&proxy->ip, proxy->name, sip_cfg.srvlookup ? "_sip._udp" : NULL) < 0) {
03125             ast_log(LOG_WARNING, "Unable to locate host '%s'\n", proxy->name);
03126             return FALSE;
03127       }
03128 
03129    }
03130 
03131    ast_sockaddr_set_port(&proxy->ip, proxy->port);
03132 
03133    proxy->last_dnsupdate = time(NULL);
03134    return TRUE;
03135 }
03136 
03137 /*! \brief converts ascii port to int representation. If no
03138  *  pt buffer is provided or the pt has errors when being converted
03139  *  to an int value, the port provided as the standard is used.
03140  */
03141 unsigned int port_str2int(const char *pt, unsigned int standard)
03142 {
03143    int port = standard;
03144    if (ast_strlen_zero(pt) || (sscanf(pt, "%30d", &port) != 1) || (port < 1) || (port > 65535)) {
03145       port = standard;
03146    }
03147 
03148    return port;
03149 }
03150 
03151 /*! \brief Get default outbound proxy or global proxy */
03152 static struct sip_proxy *obproxy_get(struct sip_pvt *dialog, struct sip_peer *peer)
03153 {
03154    if (peer && peer->outboundproxy) {
03155       if (sipdebug) {
03156          ast_debug(1, "OBPROXY: Applying peer OBproxy to this call\n");
03157       }
03158       append_history(dialog, "OBproxy", "Using peer obproxy %s", peer->outboundproxy->name);
03159       return peer->outboundproxy;
03160    }
03161    if (sip_cfg.outboundproxy.name[0]) {
03162       if (sipdebug) {
03163          ast_debug(1, "OBPROXY: Applying global OBproxy to this call\n");
03164       }
03165       append_history(dialog, "OBproxy", "Using global obproxy %s", sip_cfg.outboundproxy.name);
03166       return &sip_cfg.outboundproxy;
03167    }
03168    if (sipdebug) {
03169       ast_debug(1, "OBPROXY: Not applying OBproxy to this call\n");
03170    }
03171    return NULL;
03172 }
03173 
03174 /*! \brief returns true if 'name' (with optional trailing whitespace)
03175  * matches the sip method 'id'.
03176  * Strictly speaking, SIP methods are case SENSITIVE, but we do
03177  * a case-insensitive comparison to be more tolerant.
03178  * following Jon Postel's rule: Be gentle in what you accept, strict with what you send
03179  */
03180 static int method_match(enum sipmethod id, const char *name)
03181 {
03182    int len = strlen(sip_methods[id].text);
03183    int l_name = name ? strlen(name) : 0;
03184    /* true if the string is long enough, and ends with whitespace, and matches */
03185    return (l_name >= len && name[len] < 33 &&
03186       !strncasecmp(sip_methods[id].text, name, len));
03187 }
03188 
03189 /*! \brief  find_sip_method: Find SIP method from header */
03190 static int find_sip_method(const char *msg)
03191 {
03192    int i, res = 0;
03193    
03194    if (ast_strlen_zero(msg)) {
03195       return 0;
03196    }
03197    for (i = 1; i < ARRAY_LEN(sip_methods) && !res; i++) {
03198       if (method_match(i, msg)) {
03199          res = sip_methods[i].id;
03200       }
03201    }
03202    return res;
03203 }
03204 
03205 /*! \brief See if we pass debug IP filter */
03206 static inline int sip_debug_test_addr(const struct ast_sockaddr *addr)
03207 {
03208    /* Can't debug if sipdebug is not enabled */
03209    if (!sipdebug) {
03210       return 0;
03211    }
03212 
03213    /* A null debug_addr means we'll debug any address */
03214    if (ast_sockaddr_isnull(&debugaddr)) {
03215       return 1;
03216    }
03217 
03218    /* If no port was specified for a debug address, just compare the
03219     * addresses, otherwise compare the address and port
03220     */
03221    if (ast_sockaddr_port(&debugaddr)) {
03222       return !ast_sockaddr_cmp(&debugaddr, addr);
03223    } else {
03224       return !ast_sockaddr_cmp_addr(&debugaddr, addr);
03225    }
03226 }
03227 
03228 /*! \brief The real destination address for a write */
03229 static const struct ast_sockaddr *sip_real_dst(const struct sip_pvt *p)
03230 {
03231    if (p->outboundproxy) {
03232       return &p->outboundproxy->ip;
03233    }
03234 
03235    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;
03236 }
03237 
03238 /*! \brief Display SIP nat mode */
03239 static const char *sip_nat_mode(const struct sip_pvt *p)
03240 {
03241    return ast_test_flag(&p->flags[0], SIP_NAT_FORCE_RPORT) ? "NAT" : "no NAT";
03242 }
03243 
03244 /*! \brief Test PVT for debugging output */
03245 static inline int sip_debug_test_pvt(struct sip_pvt *p)
03246 {
03247    if (!sipdebug) {
03248       return 0;
03249    }
03250    return sip_debug_test_addr(sip_real_dst(p));
03251 }
03252 
03253 /*! \brief Return int representing a bit field of transport types found in const char *transport */
03254 static int get_transport_str2enum(const char *transport)
03255 {
03256    int res = 0;
03257 
03258    if (ast_strlen_zero(transport)) {
03259       return res;
03260    }
03261 
03262    if (!strcasecmp(transport, "udp")) {
03263       res |= SIP_TRANSPORT_UDP;
03264    }
03265    if (!strcasecmp(transport, "tcp")) {
03266       res |= SIP_TRANSPORT_TCP;
03267    }
03268    if (!strcasecmp(transport, "tls")) {
03269       res |= SIP_TRANSPORT_TLS;
03270    }
03271 
03272    return res;
03273 }
03274 
03275 /*! \brief Return configuration of transports for a device */
03276 static inline const char *get_transport_list(unsigned int transports) {
03277    switch (transports) {
03278       case SIP_TRANSPORT_UDP:
03279          return "UDP";
03280       case SIP_TRANSPORT_TCP:
03281          return "TCP";
03282       case SIP_TRANSPORT_TLS:
03283          return "TLS";
03284       case SIP_TRANSPORT_UDP | SIP_TRANSPORT_TCP:
03285          return "TCP,UDP";
03286       case SIP_TRANSPORT_UDP | SIP_TRANSPORT_TLS:
03287          return "TLS,UDP";
03288       case SIP_TRANSPORT_TCP | SIP_TRANSPORT_TLS:
03289          return "TLS,TCP";
03290       default:
03291          return transports ?
03292             "TLS,TCP,UDP" : "UNKNOWN"; 
03293    }
03294 }
03295 
03296 /*! \brief Return transport as string */
03297 const char *sip_get_transport(enum sip_transport t)
03298 {
03299    switch (t) {
03300    case SIP_TRANSPORT_UDP:
03301       return "UDP";
03302    case SIP_TRANSPORT_TCP:
03303       return "TCP";
03304    case SIP_TRANSPORT_TLS:
03305       return "TLS";
03306    }
03307 
03308    return "UNKNOWN";
03309 }
03310 
03311 /*! \brief Return protocol string for srv dns query */
03312 static inline const char *get_srv_protocol(enum sip_transport t)
03313 {
03314    switch (t) {
03315    case SIP_TRANSPORT_UDP:
03316       return "udp";
03317    case SIP_TRANSPORT_TLS:
03318    case SIP_TRANSPORT_TCP:
03319       return "tcp";
03320    }
03321 
03322    return "udp";
03323 }
03324 
03325 /*! \brief Return service string for srv dns query */
03326 static inline const char *get_srv_service(enum sip_transport t)
03327 {
03328    switch (t) {
03329    case SIP_TRANSPORT_TCP:
03330    case SIP_TRANSPORT_UDP:
03331       return "sip";
03332    case SIP_TRANSPORT_TLS:
03333       return "sips";
03334    }
03335    return "sip";
03336 }
03337 
03338 /*! \brief Return transport of dialog.
03339    \note this is based on a false assumption. We don't always use the
03340    outbound proxy for all requests in a dialog. It depends on the
03341    "force" parameter. The FIRST request is always sent to the ob proxy.
03342    \todo Fix this function to work correctly
03343 */
03344 static inline const char *get_transport_pvt(struct sip_pvt *p)
03345 {
03346    if (p->outboundproxy && p->outboundproxy->transport) {
03347       set_socket_transport(&p->socket, p->outboundproxy->transport);
03348    }
03349 
03350    return sip_get_transport(p->socket.type);
03351 }
03352 
03353 /*!
03354  * \internal
03355  * \brief Transmit SIP message
03356  *
03357  * \details
03358  * Sends a SIP request or response on a given socket (in the pvt)
03359  * \note
03360  * Called by retrans_pkt, send_request, send_response and __sip_reliable_xmit
03361  *
03362  * \return length of transmitted message, XMIT_ERROR on known network failures -1 on other failures.
03363  */
03364 static int __sip_xmit(struct sip_pvt *p, struct ast_str *data)
03365 {
03366    int res = 0;
03367    const struct ast_sockaddr *dst = sip_real_dst(p);
03368 
03369    ast_debug(2, "Trying to put '%.11s' onto %s socket destined for %s\n", data->str, get_transport_pvt(p), ast_sockaddr_stringify(dst));
03370 
03371    if (sip_prepare_socket(p) < 0) {
03372       return XMIT_ERROR;
03373    }
03374 
03375    if (p->socket.type == SIP_TRANSPORT_UDP) {
03376       res = ast_sendto(p->socket.fd, data->str, ast_str_strlen(data), 0, dst);
03377    } else if (p->socket.tcptls_session) {
03378       res = sip_tcptls_write(p->socket.tcptls_session, data->str, ast_str_strlen(data));
03379    } else {
03380       ast_debug(2, "Socket type is TCP but no tcptls_session is present to write to\n");
03381       return XMIT_ERROR;
03382    }
03383 
03384    if (res == -1) {
03385       switch (errno) {
03386       case EBADF:    /* Bad file descriptor - seems like this is generated when the host exist, but doesn't accept the UDP packet */
03387       case EHOSTUNREACH:   /* Host can't be reached */
03388       case ENETDOWN:    /* Interface down */
03389       case ENETUNREACH: /* Network failure */
03390       case ECONNREFUSED:      /* ICMP port unreachable */
03391          res = XMIT_ERROR; /* Don't bother with trying to transmit again */
03392       }
03393    }
03394    if (res != ast_str_strlen(data)) {
03395       ast_log(LOG_WARNING, "sip_xmit of %p (len %zu) to %s returned %d: %s\n", data, ast_str_strlen(data), ast_sockaddr_stringify(dst), res, strerror(errno));
03396    }
03397 
03398    return res;
03399 }
03400 
03401 /*! \brief Build a Via header for a request */
03402 static void build_via(struct sip_pvt *p)
03403 {
03404    /* Work around buggy UNIDEN UIP200 firmware */
03405    const char *rport = (ast_test_flag(&p->flags[0], SIP_NAT_FORCE_RPORT) || ast_test_flag(&p->flags[0], SIP_NAT_RPORT_PRESENT)) ? ";rport" : "";
03406 
03407    /* z9hG4bK is a magic cookie.  See RFC 3261 section 8.1.1.7 */
03408    snprintf(p->via, sizeof(p->via), "SIP/2.0/%s %s;branch=z9hG4bK%08x%s",
03409        get_transport_pvt(p),
03410        ast_sockaddr_stringify_remote(&p->ourip),
03411        (int) p->branch, rport);
03412 }
03413 
03414 /*! \brief NAT fix - decide which IP address to use for Asterisk server?
03415  *
03416  * Using the localaddr structure built up with localnet statements in sip.conf
03417  * apply it to their address to see if we need to substitute our
03418  * externaddr or can get away with our internal bindaddr
03419  * 'us' is always overwritten.
03420  */
03421 static void ast_sip_ouraddrfor(const struct ast_sockaddr *them, struct ast_sockaddr *us, struct sip_pvt *p)
03422 {
03423    struct ast_sockaddr theirs;
03424 
03425    /* Set want_remap to non-zero if we want to remap 'us' to an externally
03426     * reachable IP address and port. This is done if:
03427     * 1. we have a localaddr list (containing 'internal' addresses marked
03428     *    as 'deny', so ast_apply_ha() will return AST_SENSE_DENY on them,
03429     *    and AST_SENSE_ALLOW on 'external' ones);
03430     * 2. externaddr is set, so we know what to use as the
03431     *    externally visible address;
03432     * 3. the remote address, 'them', is external;
03433     * 4. the address returned by ast_ouraddrfor() is 'internal' (AST_SENSE_DENY
03434     *    when passed to ast_apply_ha() so it does need to be remapped.
03435     *    This fourth condition is checked later.
03436     */
03437    int want_remap = 0;
03438 
03439    ast_sockaddr_copy(us, &internip); /* starting guess for the internal address */
03440    /* now ask the system what would it use to talk to 'them' */
03441    ast_ouraddrfor(them, us);
03442    ast_sockaddr_copy(&theirs, them);
03443 
03444    if (ast_sockaddr_is_ipv6(&theirs)) {
03445       if (localaddr && !ast_sockaddr_isnull(&externaddr)) {
03446          ast_log(LOG_WARNING, "Address remapping activated in sip.conf "
03447             "but we're using IPv6, which doesn't need it. Please "
03448             "remove \"localnet\" and/or \"externaddr\" settings.\n");
03449       }
03450    } else {
03451       want_remap = localaddr &&
03452          !ast_sockaddr_isnull(&externaddr) &&
03453          ast_apply_ha(localaddr, &theirs) == AST_SENSE_ALLOW ;
03454    }
03455 
03456    if (want_remap &&
03457        (!sip_cfg.matchexternaddrlocally || !ast_apply_ha(localaddr, us)) ) {
03458       /* if we used externhost, see if it is time to refresh the info */
03459       if (externexpire && time(NULL) >= externexpire) {
03460          if (ast_sockaddr_resolve_first(&externaddr, externhost, 0)) {
03461             ast_log(LOG_NOTICE, "Warning: Re-lookup of '%s' failed!\n", externhost);
03462          }
03463          externexpire = time(NULL) + externrefresh;
03464       }
03465       if (!ast_sockaddr_isnull(&externaddr)) {
03466          ast_sockaddr_copy(us, &externaddr);
03467          switch (p->socket.type) {
03468          case SIP_TRANSPORT_TCP:
03469             if (!externtcpport && ast_sockaddr_port(&externaddr)) {
03470                /* for consistency, default to the externaddr port */
03471                externtcpport = ast_sockaddr_port(&externaddr);
03472             }
03473             ast_sockaddr_set_port(us, externtcpport);
03474             break;
03475          case SIP_TRANSPORT_TLS:
03476             ast_sockaddr_set_port(us, externtlsport);
03477             break;
03478          case SIP_TRANSPORT_UDP:
03479             if (!ast_sockaddr_port(&externaddr)) {
03480                ast_sockaddr_set_port(us, ast_sockaddr_port(&bindaddr));
03481             }
03482             break;
03483          default:
03484             break;
03485          }
03486       }
03487       ast_debug(1, "Target address %s is not local, substituting externaddr\n",
03488            ast_sockaddr_stringify(them));
03489    } else if (p) {
03490       /* no remapping, but we bind to a specific address, so use it. */
03491       switch (p->socket.type) {
03492       case SIP_TRANSPORT_TCP:
03493          if (!ast_sockaddr_is_any(&sip_tcp_desc.local_address)) {
03494             ast_sockaddr_copy(us,
03495                     &sip_tcp_desc.local_address);
03496          } else {
03497             ast_sockaddr_set_port(us,
03498                         ast_sockaddr_port(&sip_tcp_desc.local_address));
03499          }
03500          break;
03501       case SIP_TRANSPORT_TLS:
03502          if (!ast_sockaddr_is_any(&sip_tls_desc.local_address)) {
03503             ast_sockaddr_copy(us,
03504                     &sip_tls_desc.local_address);
03505          } else {
03506             ast_sockaddr_set_port(us,
03507                         ast_sockaddr_port(&sip_tls_desc.local_address));
03508          }
03509          break;
03510       case SIP_TRANSPORT_UDP:
03511          /* fall through on purpose */
03512       default:
03513          if (!ast_sockaddr_is_any(&bindaddr)) {
03514             ast_sockaddr_copy(us, &bindaddr);
03515          }
03516          if (!ast_sockaddr_port(us)) {
03517             ast_sockaddr_set_port(us, ast_sockaddr_port(&bindaddr));
03518          }
03519       }
03520    } else if (!ast_sockaddr_is_any(&bindaddr)) {
03521       ast_sockaddr_copy(us, &bindaddr);
03522    }
03523    ast_debug(3, "Setting SIP_TRANSPORT_%s with address %s\n", sip_get_transport(p->socket.type), ast_sockaddr_stringify(us));
03524 }
03525 
03526 /*! \brief Append to SIP dialog history with arg list  */
03527 static __attribute__((format(printf, 2, 0))) void append_history_va(struct sip_pvt *p, const char *fmt, va_list ap)
03528 {
03529    char buf[80], *c = buf; /* max history length */
03530    struct sip_history *hist;
03531    int l;
03532 
03533    vsnprintf(buf, sizeof(buf), fmt, ap);
03534    strsep(&c, "\r\n"); /* Trim up everything after \r or \n */
03535    l = strlen(buf) + 1;
03536    if (!(hist = ast_calloc(1, sizeof(*hist) + l))) {
03537       return;
03538    }
03539    if (!p->history && !(p->history = ast_calloc(1, sizeof(*p->history)))) {
03540       ast_free(hist);
03541       return;
03542    }
03543    memcpy(hist->event, buf, l);
03544    if (p->history_entries == MAX_HISTORY_ENTRIES) {
03545       struct sip_history *oldest;
03546       oldest = AST_LIST_REMOVE_HEAD(p->history, list);
03547       p->history_entries--;
03548       ast_free(oldest);
03549    }
03550    AST_LIST_INSERT_TAIL(p->history, hist, list);
03551    p->history_entries++;
03552 }
03553 
03554 /*! \brief Append to SIP dialog history with arg list  */
03555 static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
03556 {
03557    va_list ap;
03558 
03559    if (!p) {
03560       return;
03561    }
03562 
03563    if (!p->do_history && !recordhistory && !dumphistory) {
03564       return;
03565    }
03566 
03567    va_start(ap, fmt);
03568    append_history_va(p, fmt, ap);
03569    va_end(ap);
03570 
03571    return;
03572 }
03573 
03574 /*! \brief Retransmit SIP message if no answer (Called from scheduler) */
03575 static int retrans_pkt(const void *data)
03576 {
03577    struct sip_pkt *pkt = (struct sip_pkt *)data, *prev, *cur = NULL;
03578    int reschedule = DEFAULT_RETRANS;
03579    int xmitres = 0;
03580    /* how many ms until retrans timeout is reached */
03581    int64_t diff = pkt->retrans_stop_time - ast_tvdiff_ms(ast_tvnow(), pkt->time_sent);
03582 
03583    /* Do not retransmit if time out is reached. This will be negative if the time between
03584     * the first transmission and now is larger than our timeout period. This is a fail safe
03585     * check in case the scheduler gets behind or the clock is changed. */
03586    if ((diff <= 0) || (diff > pkt->retrans_stop_time)) {
03587       pkt->retrans_stop = 1;
03588    }
03589 
03590    /* Lock channel PVT */
03591    sip_pvt_lock(pkt->owner);
03592 
03593    if (!pkt->retrans_stop) {
03594       pkt->retrans++;
03595       if (!pkt->timer_t1) {   /* Re-schedule using timer_a and timer_t1 */
03596          if (sipdebug) {
03597             ast_debug(4, "SIP TIMER: Not rescheduling id #%d:%s (Method %d) (No timer T1)\n",
03598                pkt->retransid,
03599                sip_methods[pkt->method].text,
03600                pkt->method);
03601          }
03602       } else {
03603          int siptimer_a;
03604 
03605          if (sipdebug) {
03606             ast_debug(4, "SIP TIMER: Rescheduling retransmission #%d (%d) %s - %d\n",
03607                pkt->retransid,
03608                pkt->retrans,
03609                sip_methods[pkt->method].text,
03610                pkt->method);
03611          }
03612          if (!pkt->timer_a) {
03613             pkt->timer_a = 2 ;
03614          } else {
03615             pkt->timer_a = 2 * pkt->timer_a;
03616          }
03617 
03618          /* For non-invites, a maximum of 4 secs */
03619          siptimer_a = pkt->timer_t1 * pkt->timer_a;   /* Double each time */
03620          if (pkt->method != SIP_INVITE && siptimer_a > 4000) {
03621             siptimer_a = 4000;
03622          }
03623 
03624          /* Reschedule re-transmit */
03625          reschedule = siptimer_a;
03626          ast_debug(4, "** SIP timers: Rescheduling retransmission %d to %d ms (t1 %d ms (Retrans id #%d)) \n",
03627             pkt->retrans + 1,
03628             siptimer_a,
03629             pkt->timer_t1,
03630             pkt->retransid);
03631       }
03632 
03633       if (sip_debug_test_pvt(pkt->owner)) {
03634          const struct ast_sockaddr *dst = sip_real_dst(pkt->owner);
03635          ast_verbose("Retransmitting #%d (%s) to %s:\n%s\n---\n",
03636             pkt->retrans, sip_nat_mode(pkt->owner),
03637             ast_sockaddr_stringify(dst),
03638             pkt->data->str);
03639       }
03640 
03641       append_history(pkt->owner, "ReTx", "%d %s", reschedule, pkt->data->str);
03642       xmitres = __sip_xmit(pkt->owner, pkt->data);
03643 
03644       /* If there was no error during the network transmission, schedule the next retransmission,
03645        * but if the next retransmission is going to be beyond our timeout period, mark the packet's
03646        * stop_retrans value and set the next retransmit to be the exact time of timeout.  This will
03647        * allow any responses to the packet to be processed before the packet is destroyed on the next
03648        * call to this function by the scheduler. */
03649       if (xmitres != XMIT_ERROR) {
03650          if (reschedule >= diff) {
03651             pkt->retrans_stop = 1;
03652             reschedule = diff;
03653          }
03654          sip_pvt_unlock(pkt->owner);
03655          return  reschedule;
03656       }
03657    }
03658 
03659    /* At this point, either the packet's retransmission timed out, or there was a
03660     * transmission error, either way destroy the scheduler item and this packet. */
03661 
03662    pkt->retransid = -1; /* Kill this scheduler item */
03663 
03664    if (pkt->owner && pkt->method != SIP_OPTIONS && xmitres == 0) {
03665       if (pkt->is_fatal || sipdebug) { /* Tell us if it's critical or if we're debugging */
03666          ast_log(LOG_WARNING, "Retransmission timeout reached on transmission %s for seqno %u (%s %s) -- See https://wiki.asterisk.org/wiki/display/AST/SIP+Retransmissions\n"
03667             "Packet timed out after %dms with no response\n",
03668             pkt->owner->callid,
03669             pkt->seqno,
03670             pkt->is_fatal ? "Critical" : "Non-critical",
03671             pkt->is_resp ? "Response" : "Request",
03672             (int) ast_tvdiff_ms(ast_tvnow(), pkt->time_sent));
03673       }
03674    } else if (pkt->method == SIP_OPTIONS && sipdebug) {
03675       ast_log(LOG_WARNING, "Cancelling retransmit of OPTIONs (call id %s)  -- See https://wiki.asterisk.org/wiki/display/AST/SIP+Retransmissions\n", pkt->owner->callid);
03676    }
03677 
03678    if (xmitres == XMIT_ERROR) {
03679       ast_log(LOG_WARNING, "Transmit error :: Cancelling transmission on Call ID %s\n", pkt->owner->callid);
03680       append_history(pkt->owner, "XmitErr", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
03681    } else {
03682       append_history(pkt->owner, "MaxRetries", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
03683    }
03684 
03685    if (pkt->is_fatal) {
03686       while(pkt->owner->owner && ast_channel_trylock(pkt->owner->owner)) {
03687          sip_pvt_unlock(pkt->owner);   /* SIP_PVT, not channel */
03688          usleep(1);
03689          sip_pvt_lock(pkt->owner);
03690       }
03691       if (pkt->owner->owner && !pkt->owner->owner->hangupcause) {
03692          pkt->owner->owner->hangupcause = AST_CAUSE_NO_USER_RESPONSE;
03693       }
03694       if (pkt->owner->owner) {
03695          ast_log(LOG_WARNING, "Hanging up call %s - no reply to our critical packet (see https://wiki.asterisk.org/wiki/display/AST/SIP+Retransmissions).\n", pkt->owner->callid);
03696 
03697          if (pkt->is_resp &&
03698             (pkt->response_code >= 200) &&
03699             (pkt->response_code < 300) &&
03700             pkt->owner->pendinginvite &&
03701             ast_test_flag(&pkt->owner->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED)) {
03702             /* This is a timeout of the 2XX response to a pending INVITE.  In this case terminate the INVITE
03703              * transaction just as if we received the ACK, but immediately hangup with a BYE (sip_hangup
03704              * will send the BYE as long as the dialog is not set as "alreadygone")
03705              * RFC 3261 section 13.3.1.4.
03706              * "If the server retransmits the 2xx response for 64*T1 seconds without receiving
03707              * an ACK, the dialog is confirmed, but the session SHOULD be terminated.  This is
03708              * accomplished with a BYE, as described in Section 15." */
03709             pkt->owner->invitestate = INV_TERMINATED;
03710             pkt->owner->pendinginvite = 0;
03711          } else {
03712             /* there is nothing left to do, mark the dialog as gone */
03713             sip_alreadygone(pkt->owner);
03714          }
03715          ast_queue_hangup_with_cause(pkt->owner->owner, AST_CAUSE_PROTOCOL_ERROR);
03716          ast_channel_unlock(pkt->owner->owner);
03717       } else {
03718          /* If no channel owner, destroy now */
03719 
03720          /* Let the peerpoke system expire packets when the timer expires for poke_noanswer */
03721          if (pkt->method != SIP_OPTIONS && pkt->method != SIP_REGISTER) {
03722             pvt_set_needdestroy(pkt->owner, "no response to critical packet");
03723             sip_alreadygone(pkt->owner);
03724             append_history(pkt->owner, "DialogKill", "Killing this failed dialog immediately");
03725          }
03726       }
03727    }
03728 
03729    if (pkt->method == SIP_BYE) {
03730       /* We're not getting answers on SIP BYE's.  Tear down the call anyway. */
03731       sip_alreadygone(pkt->owner);
03732       if (pkt->owner->owner) {
03733          ast_channel_unlock(pkt->owner->owner);
03734       }
03735       append_history(pkt->owner, "ByeFailure", "Remote peer doesn't respond to bye. Destroying call anyway.");
03736       pvt_set_needdestroy(pkt->owner, "no response to BYE");
03737    }
03738 
03739    /* Remove the packet */
03740    for (prev = NULL, cur = pkt->owner->packets; cur; prev = cur, cur = cur->next) {
03741       if (cur == pkt) {
03742          UNLINK(cur, pkt->owner->packets, prev);
03743          sip_pvt_unlock(pkt->owner);
03744          if (pkt->owner) {
03745             pkt->owner = dialog_unref(pkt->owner,"pkt is being freed, its dialog ref is dead now");
03746          }
03747          if (pkt->data) {
03748             ast_free(pkt->data);
03749          }
03750          pkt->data = NULL;
03751          ast_free(pkt);
03752          return 0;
03753       }
03754    }
03755    /* error case */
03756    ast_log(LOG_WARNING, "Weird, couldn't find packet owner!\n");
03757    sip_pvt_unlock(pkt->owner);
03758    return 0;
03759 }
03760 
03761 /*!
03762  * \internal
03763  * \brief Transmit packet with retransmits
03764  * \return 0 on success, -1 on failure to allocate packet
03765  */
03766 static enum sip_result __sip_reliable_xmit(struct sip_pvt *p, uint32_t seqno, int resp, struct ast_str *data, int fatal, int sipmethod)
03767 {
03768    struct sip_pkt *pkt = NULL;
03769    int siptimer_a = DEFAULT_RETRANS;
03770    int xmitres = 0;
03771    int respid;
03772 
03773    if (sipmethod == SIP_INVITE) {
03774       /* Note this is a pending invite */
03775       p->pendinginvite = seqno;
03776    }
03777 
03778    /* If the transport is something reliable (TCP or TLS) then don't really send this reliably */
03779    /* I removed the code from retrans_pkt that does the same thing so it doesn't get loaded into the scheduler */
03780    /*! \todo According to the RFC some packets need to be retransmitted even if its TCP, so this needs to get revisited */
03781    if (!(p->socket.type & SIP_TRANSPORT_UDP)) {
03782       xmitres = __sip_xmit(p, data);   /* Send packet */
03783       if (xmitres == XMIT_ERROR) {  /* Serious network trouble, no need to try again */
03784          append_history(p, "XmitErr", "%s", fatal ? "(Critical)" : "(Non-critical)");
03785          return AST_FAILURE;
03786       } else {
03787          return AST_SUCCESS;
03788       }
03789    }
03790 
03791    if (!(pkt = ast_calloc(1, sizeof(*pkt)))) {
03792       return AST_FAILURE;
03793    }
03794    /* copy data, add a terminator and save length */
03795    if (!(pkt->data = ast_str_create(ast_str_strlen(data)))) {
03796       ast_free(pkt);
03797       return AST_FAILURE;
03798    }
03799    ast_str_set(&pkt->data, 0, "%s%s", data->str, "\0");
03800    /* copy other parameters from the caller */
03801    pkt->method = sipmethod;
03802    pkt->seqno = seqno;
03803    pkt->is_resp = resp;
03804    pkt->is_fatal = fatal;
03805    pkt->owner = dialog_ref(p, "__sip_reliable_xmit: setting pkt->owner");
03806    pkt->next = p->packets;
03807    p->packets = pkt; /* Add it to the queue */
03808    if (resp) {
03809       /* Parse out the response code */
03810       if (sscanf(ast_str_buffer(pkt->data), "SIP/2.0 %30u", &respid) == 1) {
03811          pkt->response_code = respid;
03812       }
03813    }
03814    pkt->timer_t1 = p->timer_t1;  /* Set SIP timer T1 */
03815    pkt->retransid = -1;
03816    if (pkt->timer_t1) {
03817       siptimer_a = pkt->timer_t1;
03818    }
03819 
03820    pkt->time_sent = ast_tvnow(); /* time packet was sent */
03821    pkt->retrans_stop_time = 64 * (pkt->timer_t1 ? pkt->timer_t1 : DEFAULT_TIMER_T1); /* time in ms after pkt->time_sent to stop retransmission */
03822 
03823    /* Schedule retransmission */
03824    AST_SCHED_REPLACE_VARIABLE(pkt->retransid, sched, siptimer_a, retrans_pkt, pkt, 1);
03825    if (sipdebug) {
03826       ast_debug(4, "*** SIP TIMER: Initializing retransmit timer on packet: Id  #%d\n", pkt->retransid);
03827    }
03828 
03829    xmitres = __sip_xmit(pkt->owner, pkt->data); /* Send packet */
03830 
03831    if (xmitres == XMIT_ERROR) {  /* Serious network trouble, no need to try again */
03832       append_history(pkt->owner, "XmitErr", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
03833       ast_log(LOG_ERROR, "Serious Network Trouble; __sip_xmit returns error for pkt data\n");
03834       AST_SCHED_DEL(sched, pkt->retransid);
03835       p->packets = pkt->next;
03836       pkt->owner = dialog_unref(pkt->owner,"pkt is being freed, its dialog ref is dead now");
03837       ast_free(pkt->data);
03838       ast_free(pkt);
03839       return AST_FAILURE;
03840    } else {
03841       /* This is odd, but since the retrans timer starts at 500ms and the do_monitor thread
03842        * only wakes up every 1000ms by default, we have to poke the thread here to make
03843        * sure it successfully detects this must be retransmitted in less time than
03844        * it usually sleeps for. Otherwise it might not retransmit this packet for 1000ms. */
03845       if (monitor_thread != AST_PTHREADT_NULL) {
03846          pthread_kill(monitor_thread, SIGURG);
03847       }
03848       return AST_SUCCESS;
03849    }
03850 }
03851 
03852 /*! \brief Kill a SIP dialog (called only by the scheduler)
03853  * The scheduler has a reference to this dialog when p->autokillid != -1,
03854  * and we are called using that reference. So if the event is not
03855  * rescheduled, we need to call dialog_unref().
03856  */
03857 static int __sip_autodestruct(const void *data)
03858 {
03859    struct sip_pvt *p = (struct sip_pvt *)data;
03860    struct ast_channel *owner;
03861 
03862    /* If this is a subscription, tell the phone that we got a timeout */
03863    if (p->subscribed && p->subscribed != MWI_NOTIFICATION && p->subscribed != CALL_COMPLETION) {
03864       transmit_state_notify(p, AST_EXTENSION_DEACTIVATED, 1, TRUE);  /* Send last notification */
03865       p->subscribed = NONE;
03866       append_history(p, "Subscribestatus", "timeout");
03867       ast_debug(3, "Re-scheduled destruction of SIP subscription %s\n", p->callid ? p->callid : "<unknown>");
03868       return 10000;  /* Reschedule this destruction so that we know that it's gone */
03869    }
03870 
03871    /* If there are packets still waiting for delivery, delay the destruction */
03872    if (p->packets) {
03873       if (!p->needdestroy) {
03874          char method_str[31];
03875          ast_debug(3, "Re-scheduled destruction of SIP call %s\n", p->callid ? p->callid : "<unknown>");
03876          append_history(p, "ReliableXmit", "timeout");
03877          if (sscanf(p->lastmsg, "Tx: %30s", method_str) == 1 || sscanf(p->lastmsg, "Rx: %30s", method_str) == 1) {
03878             if (method_match(SIP_CANCEL, method_str) || method_match(SIP_BYE, method_str)) {
03879                pvt_set_needdestroy(p, "autodestruct");
03880             }
03881          }
03882          return 10000;
03883       } else {
03884          /* They've had their chance to respond. Time to bail */
03885          __sip_pretend_ack(p);
03886       }
03887    }
03888 
03889    /* Reset schedule ID */
03890    p->autokillid = -1;
03891 
03892 
03893    /*
03894     * Lock both the pvt and the channel safely so that we can queue up a frame.
03895     */
03896    owner = sip_pvt_lock_full(p);
03897    if (owner) {
03898       ast_log(LOG_WARNING, "Autodestruct on dialog '%s' with owner in place (Method: %s)\n", p->callid, sip_methods[p->method].text);
03899       ast_queue_hangup_with_cause(owner, AST_CAUSE_PROTOCOL_ERROR);
03900       ast_channel_unlock(owner);
03901       ast_channel_unref(owner);
03902    } else if (p->refer && !p->alreadygone) {
03903       ast_debug(3, "Finally hanging up channel after transfer: %s\n", p->callid);
03904       stop_media_flows(p);
03905       transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
03906       append_history(p, "ReferBYE", "Sending BYE on transferer call leg %s", p->callid);
03907       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
03908    } else {
03909       append_history(p, "AutoDestroy", "%s", p->callid);
03910       ast_debug(3, "Auto destroying SIP dialog '%s'\n", p->callid);
03911       sip_pvt_unlock(p);
03912       dialog_unlink_all(p); /* once it's unlinked and unrefd everywhere, it'll be freed automagically */
03913       sip_pvt_lock(p);
03914       /* dialog_unref(p, "unref dialog-- no other matching conditions"); -- unlink all now should finish off the dialog's references and free it. */
03915       /* sip_destroy(p); */      /* Go ahead and destroy dialog. All attempts to recover is done */
03916       /* sip_destroy also absorbs the reference */
03917    }
03918 
03919    sip_pvt_unlock(p);
03920 
03921    dialog_unref(p, "The ref to a dialog passed to this sched callback is going out of scope; unref it.");
03922 
03923    return 0;
03924 }
03925 
03926 /*! \brief Schedule final destruction of SIP dialog.  This can not be canceled.
03927  *  This function is used to keep a dialog around for a period of time in order
03928  *  to properly respond to any retransmits. */
03929 void sip_scheddestroy_final(struct sip_pvt *p, int ms)
03930 {
03931    if (p->final_destruction_scheduled) {
03932       return; /* already set final destruction */
03933    }
03934 
03935    sip_scheddestroy(p, ms);
03936    if (p->autokillid != -1) {
03937       p->final_destruction_scheduled = 1;
03938    }
03939 }
03940 
03941 /*! \brief Schedule destruction of SIP dialog */
03942 void sip_scheddestroy(struct sip_pvt *p, int ms)
03943 {
03944    if (p->final_destruction_scheduled) {
03945       return; /* already set final destruction */
03946    }
03947 
03948    if (ms < 0) {
03949       if (p->timer_t1 == 0) {
03950          p->timer_t1 = global_t1;   /* Set timer T1 if not set (RFC 3261) */
03951       }
03952       if (p->timer_b == 0) {
03953          p->timer_b = global_timer_b;  /* Set timer B if not set (RFC 3261) */
03954       }
03955       ms = p->timer_t1 * 64;
03956    }
03957    if (sip_debug_test_pvt(p)) {
03958       ast_verbose("Scheduling destruction of SIP dialog '%s' in %d ms (Method: %s)\n", p->callid, ms, sip_methods[p->method].text);
03959    }
03960    if (sip_cancel_destroy(p)) {
03961       ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
03962    }
03963 
03964    if (p->do_history) {
03965       append_history(p, "SchedDestroy", "%d ms", ms);
03966    }
03967    p->autokillid = ast_sched_add(sched, ms, __sip_autodestruct, dialog_ref(p, "setting ref as passing into ast_sched_add for __sip_autodestruct"));
03968 
03969    if (p->stimer && p->stimer->st_active == TRUE && p->stimer->st_schedid > 0) {
03970       stop_session_timer(p);
03971    }
03972 }
03973 
03974 /*! \brief Cancel destruction of SIP dialog.
03975  * Be careful as this also absorbs the reference - if you call it
03976  * from within the scheduler, this might be the last reference.
03977  */
03978 int sip_cancel_destroy(struct sip_pvt *p)
03979 {
03980    if (p->final_destruction_scheduled) {
03981       return 0;
03982    }
03983 
03984    if (p->autokillid > -1) {
03985       append_history(p, "CancelDestroy", "");
03986       AST_SCHED_DEL_UNREF(sched, p->autokillid, dialog_unref(p, "remove ref for autokillid"));
03987    }
03988    return 0;
03989 }
03990 
03991 /*! \brief Acknowledges receipt of a packet and stops retransmission
03992  * called with p locked*/
03993 int __sip_ack(struct sip_pvt *p, uint32_t seqno, int resp, int sipmethod)
03994 {
03995    struct sip_pkt *cur, *prev = NULL;
03996    const char *msg = "Not Found";   /* used only for debugging */
03997    int res = FALSE;
03998 
03999    /* If we have an outbound proxy for this dialog, then delete it now since
04000      the rest of the requests in this dialog needs to follow the routing.
04001      If obforcing is set, we will keep the outbound proxy during the whole
04002      dialog, regardless of what the SIP rfc says
04003    */
04004    if (p->outboundproxy && !p->outboundproxy->force){
04005       ref_proxy(p, NULL);
04006    }
04007 
04008    for (cur = p->packets; cur; prev = cur, cur = cur->next) {
04009       if (cur->seqno != seqno || cur->is_resp != resp) {
04010          continue;
04011       }
04012       if (cur->is_resp || cur->method == sipmethod) {
04013          res = TRUE;
04014          msg = "Found";
04015          if (!resp && (seqno == p->pendinginvite)) {
04016             ast_debug(1, "Acked pending invite %u\n", p->pendinginvite);
04017             p->pendinginvite = 0;
04018          }
04019          if (cur->retransid > -1) {
04020             if (sipdebug)
04021                ast_debug(4, "** SIP TIMER: Cancelling retransmit of packet (reply received) Retransid #%d\n", cur->retransid);
04022          }
04023          /* This odd section is designed to thwart a
04024           * race condition in the packet scheduler. There are
04025           * two conditions under which deleting the packet from the
04026           * scheduler can fail.
04027           *
04028           * 1. The packet has been removed from the scheduler because retransmission
04029           * is being attempted. The problem is that if the packet is currently attempting
04030           * retransmission and we are at this point in the code, then that MUST mean
04031           * that retrans_pkt is waiting on p's lock. Therefore we will relinquish the
04032           * lock temporarily to allow retransmission.
04033           *
04034           * 2. The packet has reached its maximum number of retransmissions and has
04035           * been permanently removed from the packet scheduler. If this is the case, then
04036           * the packet's retransid will be set to -1. The atomicity of the setting and checking
04037           * of the retransid to -1 is ensured since in both cases p's lock is held.
04038           */
04039          while (cur->retransid > -1 && ast_sched_del(sched, cur->retransid)) {
04040             sip_pvt_unlock(p);
04041             usleep(1);
04042             sip_pvt_lock(p);
04043          }
04044          UNLINK(cur, p->packets, prev);
04045          dialog_unref(cur->owner, "unref pkt cur->owner dialog from sip ack before freeing pkt");
04046          if (cur->data) {
04047             ast_free(cur->data);
04048          }
04049          ast_free(cur);
04050          break;
04051       }
04052    }
04053    ast_debug(1, "Stopping retransmission on '%s' of %s %u: Match %s\n",
04054       p->callid, resp ? "Response" : "Request", seqno, msg);
04055    return res;
04056 }
04057 
04058 /*! \brief Pretend to ack all packets
04059  * called with p locked */
04060 void __sip_pretend_ack(struct sip_pvt *p)
04061 {
04062    struct sip_pkt *cur = NULL;
04063 
04064    while (p->packets) {
04065       int method;
04066       if (cur == p->packets) {
04067          ast_log(LOG_WARNING, "Have a packet that doesn't want to give up! %s\n", sip_methods[cur->method].text);
04068          return;
04069       }
04070       cur = p->packets;
04071       method = (cur->method) ? cur->method : find_sip_method(cur->data->str);
04072       __sip_ack(p, cur->seqno, cur->is_resp, method);
04073    }
04074 }
04075 
04076 /*! \brief Acks receipt of packet, keep it around (used for provisional responses) */
04077 int __sip_semi_ack(struct sip_pvt *p, uint32_t seqno, int resp, int sipmethod)
04078 {
04079    struct sip_pkt *cur;
04080    int res = FALSE;
04081 
04082    for (cur = p->packets; cur; cur = cur->next) {
04083       if (cur->seqno == seqno && cur->is_resp == resp &&
04084          (cur->is_resp || method_match(sipmethod, cur->data->str))) {
04085          /* this is our baby */
04086          if (cur->retransid > -1) {
04087             if (sipdebug)
04088                ast_debug(4, "*** SIP TIMER: Cancelling retransmission #%d - %s (got response)\n", cur->retransid, sip_methods[sipmethod].text);
04089          }
04090          AST_SCHED_DEL(sched, cur->retransid);
04091          res = TRUE;
04092          break;
04093       }
04094    }
04095    ast_debug(1, "(Provisional) Stopping retransmission (but retaining packet) on '%s' %s %u: %s\n", p->callid, resp ? "Response" : "Request", seqno, res == -1 ? "Not Found" : "Found");
04096    return res;
04097 }
04098 
04099 
04100 /*! \brief Copy SIP request, parse it */
04101 static void parse_copy(struct sip_request *dst, const struct sip_request *src)
04102 {
04103    copy_request(dst, src);
04104    parse_request(dst);
04105 }
04106 
04107 /*! \brief add a blank line if no body */
04108 static void add_blank(struct sip_request *req)
04109 {
04110    if (!req->lines) {
04111       /* Add extra empty return. add_header() reserves 4 bytes so cannot be truncated */
04112       ast_str_append(&req->data, 0, "\r\n");
04113    }
04114 }
04115 
04116 static int send_provisional_keepalive_full(struct sip_pvt *pvt, int with_sdp)
04117 {
04118    const char *msg = NULL;
04119    struct ast_channel *chan;
04120    int res = 0;
04121 
04122    chan = sip_pvt_lock_full(pvt);
04123 
04124    if (!pvt->last_provisional || !strncasecmp(pvt->last_provisional, "100", 3)) {
04125       msg = "183 Session Progress";
04126    }
04127 
04128    if (pvt->invitestate < INV_COMPLETED) {
04129       if (with_sdp) {
04130          transmit_response_with_sdp(pvt, S_OR(msg, pvt->last_provisional), &pvt->initreq, XMIT_UNRELIABLE, FALSE, FALSE);
04131       } else {
04132          transmit_response(pvt, S_OR(msg, pvt->last_provisional), &pvt->initreq);
04133       }
04134       res = PROVIS_KEEPALIVE_TIMEOUT;
04135    }
04136 
04137    if (chan) {
04138       ast_channel_unlock(chan);
04139       chan = ast_channel_unref(chan);
04140    }
04141 
04142    if (!res) {
04143       pvt->provisional_keepalive_sched_id = -1;
04144    }
04145 
04146    sip_pvt_unlock(pvt);
04147 
04148 #if 0
04149    /*
04150     * XXX BUG TODO
04151     *
04152     * Without this code, it appears as if this function is leaking its
04153     * reference to the sip_pvt.  However, adding it introduces a crash.
04154     * This points to some sort of reference count imbalance elsewhere,
04155     * but I'm not sure where ...
04156     */
04157    if (!res) {
04158       dialog_unref(pvt, "dialog ref for provisional keepalive");
04159    }
04160 #endif
04161 
04162    return res;
04163 }
04164 
04165 static int send_provisional_keepalive(const void *data)
04166 {
04167    struct sip_pvt *pvt = (struct sip_pvt *) data;
04168 
04169    return send_provisional_keepalive_full(pvt, 0);
04170 }
04171 
04172 static int send_provisional_keepalive_with_sdp(const void *data)
04173 {
04174    struct sip_pvt *pvt = (void *) data;
04175 
04176    return send_provisional_keepalive_full(pvt, 1);
04177 }
04178 
04179 static void update_provisional_keepalive(struct sip_pvt *pvt, int with_sdp)
04180 {
04181    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"));
04182 
04183    pvt->provisional_keepalive_sched_id = ast_sched_add(sched, PROVIS_KEEPALIVE_TIMEOUT,
04184       with_sdp ? send_provisional_keepalive_with_sdp : send_provisional_keepalive, dialog_ref(pvt, "Increment refcount to pass dialog pointer to sched callback"));
04185 }
04186 
04187 /*! \brief Transmit response on SIP request*/
04188 static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, uint32_t seqno)
04189 {
04190    int res;
04191 
04192    finalize_content(req);
04193    add_blank(req);
04194    if (sip_debug_test_pvt(p)) {
04195       const struct ast_sockaddr *dst = sip_real_dst(p);
04196 
04197       ast_verbose("\n<--- %sTransmitting (%s) to %s --->\n%s\n<------------>\n",
04198          reliable ? "Reliably " : "", sip_nat_mode(p),
04199          ast_sockaddr_stringify(dst),
04200          req->data->str);
04201    }
04202    if (p->do_history) {
04203       struct sip_request tmp = { .rlPart1 = 0, };
04204       parse_copy(&tmp, req);
04205       append_history(p, reliable ? "TxRespRel" : "TxResp", "%s / %s - %s", tmp.data->str, sip_get_header(&tmp, "CSeq"),
04206          (tmp.method == SIP_RESPONSE || tmp.method == SIP_UNKNOWN) ? REQ_OFFSET_TO_STR(&tmp, rlPart2) : sip_methods[tmp.method].text);
04207       deinit_req(&tmp);
04208    }
04209 
04210    /* If we are sending a final response to an INVITE, stop retransmitting provisional responses */
04211    if (p->initreq.method == SIP_INVITE && reliable == XMIT_CRITICAL) {
04212       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"));
04213    }
04214 
04215    res = (reliable) ?
04216        __sip_reliable_xmit(p, seqno, 1, req->data, (reliable == XMIT_CRITICAL), req->method) :
04217       __sip_xmit(p, req->data);
04218    deinit_req(req);
04219    if (res > 0) {
04220       return 0;
04221    }
04222    return res;
04223 }
04224 
04225 /*!
04226  * \internal
04227  * \brief Send SIP Request to the other part of the dialogue
04228  * \return see \ref __sip_xmit
04229  */
04230 static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, uint32_t seqno)
04231 {
04232    int res;
04233 
04234    /* If we have an outbound proxy, reset peer address
04235       Only do this once.
04236    */
04237    if (p->outboundproxy) {
04238       p->sa = p->outboundproxy->ip;
04239    }
04240 
04241    finalize_content(req);
04242    add_blank(req);
04243    if (sip_debug_test_pvt(p)) {
04244       if (ast_test_flag(&p->flags[0], SIP_NAT_FORCE_RPORT)) {
04245          ast_verbose("%sTransmitting (NAT) to %s:\n%s\n---\n", reliable ? "Reliably " : "", ast_sockaddr_stringify(&p->recv), req->data->str);
04246       } else {
04247          ast_verbose("%sTransmitting (no NAT) to %s:\n%s\n---\n", reliable ? "Reliably " : "", ast_sockaddr_stringify(&p->sa), req->data->str);
04248       }
04249    }
04250    if (p->do_history) {
04251       struct sip_request tmp = { .rlPart1 = 0, };
04252       parse_copy(&tmp, req);
04253       append_history(p, reliable ? "TxReqRel" : "TxReq", "%s / %s - %s", tmp.data->str, sip_get_header(&tmp, "CSeq"), sip_methods[tmp.method].text);
04254       deinit_req(&tmp);
04255    }
04256    res = (reliable) ?
04257       __sip_reliable_xmit(p, seqno, 0, req->data, (reliable == XMIT_CRITICAL), req->method) :
04258       __sip_xmit(p, req->data);
04259    deinit_req(req);
04260    return res;
04261 }
04262 
04263 static void enable_dsp_detect(struct sip_pvt *p)
04264 {
04265    int features = 0;
04266 
04267    if (p->dsp) {
04268       return;
04269    }
04270 
04271    if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) ||
04272        (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO)) {
04273       if (p->rtp) {
04274          ast_rtp_instance_dtmf_mode_set(p->rtp, AST_RTP_DTMF_MODE_INBAND);
04275       }
04276       features |= DSP_FEATURE_DIGIT_DETECT;
04277    }
04278 
04279    if (ast_test_flag(&p->flags[1], SIP_PAGE2_FAX_DETECT_CNG)) {
04280       features |= DSP_FEATURE_FAX_DETECT;
04281    }
04282 
04283    if (!features) {
04284       return;
04285    }
04286 
04287    if (!(p->dsp = ast_dsp_new())) {
04288       return;
04289    }
04290 
04291    ast_dsp_set_features(p->dsp, features);
04292    if (global_relaxdtmf) {
04293       ast_dsp_set_digitmode(p->dsp, DSP_DIGITMODE_DTMF | DSP_DIGITMODE_RELAXDTMF);
04294    }
04295 }
04296 
04297 static void disable_dsp_detect(struct sip_pvt *p)
04298 {
04299    if (p->dsp) {
04300       ast_dsp_free(p->dsp);
04301       p->dsp = NULL;
04302    }
04303 }
04304 
04305 /*! \brief Set an option on a SIP dialog */
04306 static int sip_setoption(struct ast_channel *chan, int option, void *data, int datalen)
04307 {
04308    int res = -1;
04309    struct sip_pvt *p = chan->tech_pvt;
04310 
04311         if (!p) {
04312       ast_log(LOG_ERROR, "Attempt to Ref a null pointer.  sip private structure is gone!\n");
04313       return -1;
04314         }
04315 
04316    sip_pvt_lock(p);
04317 
04318    switch (option) {
04319    case AST_OPTION_FORMAT_READ:
04320       if (p->rtp) {
04321          res = ast_rtp_instance_set_read_format(p->rtp, (struct ast_format *) data);
04322       }
04323       break;
04324    case AST_OPTION_FORMAT_WRITE:
04325       if (p->rtp) {
04326          res = ast_rtp_instance_set_write_format(p->rtp, (struct ast_format *) data);
04327       }
04328       break;
04329    case AST_OPTION_MAKE_COMPATIBLE:
04330       if (p->rtp) {
04331          res = ast_rtp_instance_make_compatible(chan, p->rtp, (struct ast_channel *) data);
04332       }
04333       break;
04334    case AST_OPTION_DIGIT_DETECT:
04335       if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) ||
04336           (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO)) {
04337          char *cp = (char *) data;
04338 
04339          ast_debug(1, "%sabling digit detection on %s\n", *cp ? "En" : "Dis", ast_channel_name(chan));
04340          if (*cp) {
04341             enable_dsp_detect(p);
04342          } else {
04343             disable_dsp_detect(p);
04344          }
04345          res = 0;
04346       }
04347       break;
04348    case AST_OPTION_SECURE_SIGNALING:
04349       p->req_secure_signaling = *(unsigned int *) data;
04350       res = 0;
04351       break;
04352    case AST_OPTION_SECURE_MEDIA:
04353       ast_set2_flag(&p->flags[1], *(unsigned int *) data, SIP_PAGE2_USE_SRTP);
04354       res = 0;
04355       break;
04356    default:
04357       break;
04358    }
04359 
04360    sip_pvt_unlock(p);
04361 
04362    return res;
04363 }
04364 
04365 /*! \brief Query an option on a SIP dialog */
04366 static int sip_queryoption(struct ast_channel *chan, int option, void *data, int *datalen)
04367 {
04368    int res = -1;
04369    enum ast_t38_state state = T38_STATE_UNAVAILABLE;
04370    struct sip_pvt *p = (struct sip_pvt *) chan->tech_pvt;
04371    char *cp;
04372 
04373    sip_pvt_lock(p);
04374 
04375    switch (option) {
04376    case AST_OPTION_T38_STATE:
04377       /* Make sure we got an ast_t38_state enum passed in */
04378       if (*datalen != sizeof(enum ast_t38_state)) {
04379          ast_log(LOG_ERROR, "Invalid datalen for AST_OPTION_T38_STATE option. Expected %d, got %d\n", (int)sizeof(enum ast_t38_state), *datalen);
04380          break;
04381       }
04382 
04383       /* 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 */
04384       if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT)) {
04385          switch (p->t38.state) {
04386          case T38_LOCAL_REINVITE:
04387          case T38_PEER_REINVITE:
04388             state = T38_STATE_NEGOTIATING;
04389             break;
04390          case T38_ENABLED:
04391             state = T38_STATE_NEGOTIATED;
04392             break;
04393          case T38_REJECTED:
04394             state = T38_STATE_REJECTED;
04395             break;
04396          default:
04397             state = T38_STATE_UNKNOWN;
04398          }
04399       }
04400 
04401       *((enum ast_t38_state *) data) = state;
04402       res = 0;
04403 
04404       break;
04405    case AST_OPTION_DIGIT_DETECT:
04406       cp = (char *) data;
04407       *cp = p->dsp ? 1 : 0;
04408       ast_debug(1, "Reporting digit detection %sabled on %s\n", *cp ? "en" : "dis", ast_channel_name(chan));
04409       break;
04410    case AST_OPTION_SECURE_SIGNALING:
04411       *((unsigned int *) data) = p->req_secure_signaling;
04412       res = 0;
04413       break;
04414    case AST_OPTION_SECURE_MEDIA:
04415       *((unsigned int *) data) = ast_test_flag(&p->flags[1], SIP_PAGE2_USE_SRTP) ? 1 : 0;
04416       res = 0;
04417       break;
04418    case AST_OPTION_DEVICE_NAME:
04419       if (p && p->outgoing_call) {
04420          cp = (char *) data;
04421          ast_copy_string(cp, p->dialstring, *datalen);
04422          res = 0;
04423       }
04424       /* We purposely break with a return of -1 in the
04425        * implied else case here
04426        */
04427       break;
04428    default:
04429       break;
04430    }
04431 
04432    sip_pvt_unlock(p);
04433 
04434    return res;
04435 }
04436 
04437 /*! \brief Locate closing quote in a string, skipping escaped quotes.
04438  * optionally with a limit on the search.
04439  * start must be past the first quote.
04440  */
04441 const char *find_closing_quote(const char *start, const char *lim)
04442 {
04443    char last_char = '\0';
04444    const char *s;
04445    for (s = start; *s && s != lim; last_char = *s++) {
04446       if (*s == '"' && last_char != '\\')
04447          break;
04448    }
04449    return s;
04450 }
04451 
04452 /*! \brief Send message with Access-URL header, if this is an HTML URL only! */
04453 static int sip_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen)
04454 {
04455    struct sip_pvt *p = chan->tech_pvt;
04456 
04457    if (subclass != AST_HTML_URL)
04458       return -1;
04459 
04460    ast_string_field_build(p, url, "<%s>;mode=active", data);
04461 
04462    if (sip_debug_test_pvt(p))
04463       ast_debug(1, "Send URL %s, state = %d!\n", data, chan->_state);
04464 
04465    switch (chan->_state) {
04466    case AST_STATE_RING:
04467       transmit_response(p, "100 Trying", &p->initreq);
04468       break;
04469    case AST_STATE_RINGING:
04470       transmit_response(p, "180 Ringing", &p->initreq);
04471       break;
04472    case AST_STATE_UP:
04473       if (!p->pendinginvite) {      /* We are up, and have no outstanding invite */
04474          transmit_reinvite_with_sdp(p, FALSE, FALSE);
04475       } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
04476          ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
04477       }
04478       break;
04479    default:
04480       ast_log(LOG_WARNING, "Don't know how to send URI when state is %d!\n", chan->_state);
04481    }
04482 
04483    return 0;
04484 }
04485 
04486 /*! \brief Deliver SIP call ID for the call */
04487 static const char *sip_get_callid(struct ast_channel *chan)
04488 {
04489    return chan->tech_pvt ? ((struct sip_pvt *) chan->tech_pvt)->callid : "";
04490 }
04491 
04492 /*!
04493  * \internal
04494  * \brief Send SIP MESSAGE text within a call
04495  * \note Called from PBX core sendtext() application
04496  */
04497 static int sip_sendtext(struct ast_channel *ast, const char *text)
04498 {
04499    struct sip_pvt *dialog = ast->tech_pvt;
04500    int debug;
04501 
04502    if (!dialog) {
04503       return -1;
04504    }
04505    /* NOT ast_strlen_zero, because a zero-length message is specifically
04506     * allowed by RFC 3428 (See section 10, Examples) */
04507    if (!text) {
04508       return 0;
04509    }
04510    if(!is_method_allowed(&dialog->allowed_methods, SIP_MESSAGE)) {
04511       ast_debug(2, "Trying to send MESSAGE to device that does not support it.\n");
04512       return(0);
04513    }
04514 
04515    debug = sip_debug_test_pvt(dialog);
04516    if (debug) {
04517       ast_verbose("Sending text %s on %s\n", text, ast_channel_name(ast));
04518    }
04519 
04520    /* Setup to send text message */
04521    sip_pvt_lock(dialog);
04522    destroy_msg_headers(dialog);
04523    ast_string_field_set(dialog, msg_body, text);
04524    transmit_message(dialog, 0, 0);
04525    sip_pvt_unlock(dialog);
04526    return 0;
04527 }
04528 
04529 /*! \brief Update peer object in realtime storage
04530    If the Asterisk system name is set in asterisk.conf, we will use
04531    that name and store that in the "regserver" field in the sippeers
04532    table to facilitate multi-server setups.
04533 */
04534 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)
04535 {
04536    char port[10];
04537    char ipaddr[INET6_ADDRSTRLEN];
04538    char regseconds[20];
04539    char *tablename = NULL;
04540    char str_lastms[20];
04541 
04542    const char *sysname = ast_config_AST_SYSTEM_NAME;
04543    char *syslabel = NULL;
04544 
04545    time_t nowtime = time(NULL) + expirey;
04546    const char *fc = fullcontact ? "fullcontact" : NULL;
04547 
04548    int realtimeregs = ast_check_realtime("sipregs");
04549 
04550    tablename = realtimeregs ? "sipregs" : "sippeers";
04551 
04552    snprintf(str_lastms, sizeof(str_lastms), "%d", lastms);
04553    snprintf(regseconds, sizeof(regseconds), "%d", (int)nowtime);  /* Expiration time */
04554    ast_copy_string(ipaddr, ast_sockaddr_isnull(addr) ? "" : ast_sockaddr_stringify_addr(addr), sizeof(ipaddr));
04555    ast_copy_string(port, ast_sockaddr_port(addr) ? ast_sockaddr_stringify_port(addr) : "", sizeof(port));
04556 
04557    if (ast_strlen_zero(sysname)) /* No system name, disable this */
04558       sysname = NULL;
04559    else if (sip_cfg.rtsave_sysname)
04560       syslabel = "regserver";
04561 
04562    /* XXX IMPORTANT: Anytime you add a new parameter to be updated, you
04563          *  must also add it to contrib/scripts/asterisk.ldap-schema,
04564          *  contrib/scripts/asterisk.ldif,
04565          *  and to configs/res_ldap.conf.sample as described in
04566          *  bugs 15156 and 15895
04567          */
04568    if (fc) {
04569       ast_update_realtime(tablename, "name", peername, "ipaddr", ipaddr,
04570          "port", port, "regseconds", regseconds,
04571          deprecated_username ? "username" : "defaultuser", defaultuser,
04572          "useragent", useragent, "lastms", str_lastms,
04573          fc, fullcontact, syslabel, sysname, SENTINEL); /* note fc and syslabel _can_ be NULL */
04574    } else {
04575       ast_update_realtime(tablename, "name", peername, "ipaddr", ipaddr,
04576          "port", port, "regseconds", regseconds,
04577          "useragent", useragent, "lastms", str_lastms,
04578          deprecated_username ? "username" : "defaultuser", defaultuser,
04579          syslabel, sysname, SENTINEL); /* note syslabel _can_ be NULL */
04580    }
04581 }
04582 
04583 /*! \brief Automatically add peer extension to dial plan */
04584 static void register_peer_exten(struct sip_peer *peer, int onoff)
04585 {
04586    char multi[256];
04587    char *stringp, *ext, *context;
04588    struct pbx_find_info q = { .stacklen = 0 };
04589 
04590    /* XXX note that sip_cfg.regcontext is both a global 'enable' flag and
04591     * the name of the global regexten context, if not specified
04592     * individually.
04593     */
04594    if (ast_strlen_zero(sip_cfg.regcontext))
04595       return;
04596 
04597    ast_copy_string(multi, S_OR(peer->regexten, peer->name), sizeof(multi));
04598    stringp = multi;
04599    while ((ext = strsep(&stringp, "&"))) {
04600       if ((context = strchr(ext, '@'))) {
04601          *context++ = '\0';   /* split ext@context */
04602          if (!ast_context_find(context)) {
04603             ast_log(LOG_WARNING, "Context %s must exist in regcontext= in sip.conf!\n", context);
04604             continue;
04605          }
04606       } else {
04607          context = sip_cfg.regcontext;
04608       }
04609       if (onoff) {
04610          if (!ast_exists_extension(NULL, context, ext, 1, NULL)) {
04611             ast_add_extension(context, 1, ext, 1, NULL, NULL, "Noop",
04612                 ast_strdup(peer->name), ast_free_ptr, "SIP");
04613          }
04614       } else if (pbx_find_extension(NULL, NULL, &q, context, ext, 1, NULL, "", E_MATCH)) {
04615          ast_context_remove_extension(context, ext, 1, NULL);
04616       }
04617    }
04618 }
04619 
04620 /*! Destroy mailbox subscriptions */
04621 static void destroy_mailbox(struct sip_mailbox *mailbox)
04622 {
04623    if (mailbox->event_sub)
04624       ast_event_unsubscribe(mailbox->event_sub);
04625    ast_free(mailbox);
04626 }
04627 
04628 /*! Destroy all peer-related mailbox subscriptions */
04629 static void clear_peer_mailboxes(struct sip_peer *peer)
04630 {
04631    struct sip_mailbox *mailbox;
04632 
04633    while ((mailbox = AST_LIST_REMOVE_HEAD(&peer->mailboxes, entry)))
04634       destroy_mailbox(mailbox);
04635 }
04636 
04637 static void sip_destroy_peer_fn(void *peer)
04638 {
04639    sip_destroy_peer(peer);
04640 }
04641 
04642 /*! \brief Destroy peer object from memory */
04643 static void sip_destroy_peer(struct sip_peer *peer)
04644 {
04645    ast_debug(3, "Destroying SIP peer %s\n", peer->name);
04646 
04647    /*
04648     * Remove any mailbox event subscriptions for this peer before
04649     * we destroy anything.  An event subscription callback may be
04650     * happening right now.
04651     */
04652    clear_peer_mailboxes(peer);
04653 
04654    if (peer->outboundproxy) {
04655       ao2_ref(peer->outboundproxy, -1);
04656       peer->outboundproxy = NULL;
04657    }
04658 
04659    /* Delete it, it needs to disappear */
04660    if (peer->call) {
04661       dialog_unlink_all(peer->call);
04662       peer->call = dialog_unref(peer->call, "peer->call is being unset");
04663    }
04664 
04665    if (peer->mwipvt) {  /* We have an active subscription, delete it */
04666       dialog_unlink_all(peer->mwipvt);
04667       peer->mwipvt = dialog_unref(peer->mwipvt, "unreffing peer->mwipvt");
04668    }
04669 
04670    if (peer->chanvars) {
04671       ast_variables_destroy(peer->chanvars);
04672       peer->chanvars = NULL;
04673    }
04674 
04675    register_peer_exten(peer, FALSE);
04676    ast_free_ha(peer->ha);
04677    ast_free_ha(peer->directmediaha);
04678    if (peer->selfdestruct)
04679       ast_atomic_fetchadd_int(&apeerobjs, -1);
04680    else if (!ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) && peer->is_realtime) {
04681       ast_atomic_fetchadd_int(&rpeerobjs, -1);
04682       ast_debug(3, "-REALTIME- peer Destroyed. Name: %s. Realtime Peer objects: %d\n", peer->name, rpeerobjs);
04683    } else
04684       ast_atomic_fetchadd_int(&speerobjs, -1);
04685    if (peer->auth) {
04686       ao2_t_ref(peer->auth, -1, "Removing peer authentication");
04687       peer->auth = NULL;
04688    }
04689 
04690    if (peer->socket.tcptls_session) {
04691       ao2_ref(peer->socket.tcptls_session, -1);
04692       peer->socket.tcptls_session = NULL;
04693    }
04694 
04695    ast_cc_config_params_destroy(peer->cc_params);
04696 
04697    ast_string_field_free_memory(peer);
04698 
04699    peer->caps = ast_format_cap_destroy(peer->caps);
04700 }
04701 
04702 /*! \brief Update peer data in database (if used) */
04703 static void update_peer(struct sip_peer *p, int expire)
04704 {
04705    int rtcachefriends = ast_test_flag(&p->flags[1], SIP_PAGE2_RTCACHEFRIENDS);
04706    if (sip_cfg.peer_rtupdate &&
04707        (p->is_realtime || rtcachefriends)) {
04708       realtime_update_peer(p->name, &p->addr, p->username, p->fullcontact, p->useragent, expire, p->deprecated_username, p->lastms);
04709    }
04710 }
04711 
04712 static struct ast_variable *get_insecure_variable_from_config(struct ast_config *cfg)
04713 {
04714    struct ast_variable *var = NULL;
04715    struct ast_flags flags = {0};
04716    char *cat = NULL;
04717    const char *insecure;
04718    while ((cat = ast_category_browse(cfg, cat))) {
04719       insecure = ast_variable_retrieve(cfg, cat, "insecure");
04720       set_insecure_flags(&flags, insecure, -1);
04721       if (ast_test_flag(&flags, SIP_INSECURE_PORT)) {
04722          var = ast_category_root(cfg, cat);
04723          break;
04724       }
04725    }
04726    return var;
04727 }
04728 
04729 static struct ast_variable *get_insecure_variable_from_sippeers(const char *column, const char *value)
04730 {
04731    struct ast_config *peerlist;
04732    struct ast_variable *var = NULL;
04733    if ((peerlist = ast_load_realtime_multientry("sippeers", column, value, "insecure LIKE", "%port%", SENTINEL))) {
04734       if ((var = get_insecure_variable_from_config(peerlist))) {
04735          /* Must clone, because var will get freed along with
04736           * peerlist. */
04737          var = ast_variables_dup(var);
04738       }
04739       ast_config_destroy(peerlist);
04740    }
04741    return var;
04742 }
04743 
04744 /* Yes.. the only column that makes sense to pass is "ipaddr", but for
04745  * consistency's sake, we require the column name to be passed. As extra
04746  * argument, we take a pointer to var. We already got the info, so we better
04747  * return it and save the caller a query. If return value is nonzero, then *var
04748  * is nonzero too (and the other way around). */
04749 static struct ast_variable *get_insecure_variable_from_sipregs(const char *column, const char *value, struct ast_variable **var)
04750 {
04751    struct ast_variable *varregs = NULL;
04752    struct ast_config *regs, *peers;
04753    char *regscat;
04754    const char *regname;
04755 
04756    if (!(regs = ast_load_realtime_multientry("sipregs", column, value, SENTINEL))) {
04757       return NULL;
04758    }
04759 
04760    /* Load *all* peers that are probably insecure=port */
04761    if (!(peers = ast_load_realtime_multientry("sippeers", "insecure LIKE", "%port%", SENTINEL))) {
04762       ast_config_destroy(regs);
04763       return NULL;
04764    }
04765 
04766    /* Loop over the sipregs that match IP address and attempt to find an
04767     * insecure=port match to it in sippeers. */
04768    regscat = NULL;
04769    while ((regscat = ast_category_browse(regs, regscat)) && (regname = ast_variable_retrieve(regs, regscat, "name"))) {
04770       char *peerscat;
04771       const char *peername;
04772 
04773       peerscat = NULL;
04774       while ((peerscat = ast_category_browse(peers, peerscat)) && (peername = ast_variable_retrieve(peers, peerscat, "name"))) {
04775          if (!strcasecmp(regname, peername)) {
04776             /* Ensure that it really is insecure=port and
04777              * not something else. */
04778             const char *insecure = ast_variable_retrieve(peers, peerscat, "insecure");
04779             struct ast_flags flags = {0};
04780             set_insecure_flags(&flags, insecure, -1);
04781             if (ast_test_flag(&flags, SIP_INSECURE_PORT)) {
04782                /* ENOMEM checks till the bitter end. */
04783                if ((varregs = ast_variables_dup(ast_category_root(regs, regscat)))) {
04784                   if (!(*var = ast_variables_dup(ast_category_root(peers, peerscat)))) {
04785                      ast_variables_destroy(varregs);
04786                      varregs = NULL;
04787                   }
04788                }
04789                goto done;
04790             }
04791          }
04792       }
04793    }
04794 
04795 done:
04796    ast_config_destroy(regs);
04797    ast_config_destroy(peers);
04798    return varregs;
04799 }
04800 
04801 static const char *get_name_from_variable(const struct ast_variable *var)
04802 {
04803    /* Don't expect this to return non-NULL. Both NULL and empty
04804     * values can cause the option to get removed from the variable
04805     * list. This is called on ast_variables gotten from both
04806     * ast_load_realtime and ast_load_realtime_multientry.
04807     * - ast_load_realtime removes options with empty values
04808     * - ast_load_realtime_multientry does not!
04809     * For consistent behaviour, we check for the empty name and
04810     * return NULL instead. */
04811    const struct ast_variable *tmp;
04812    for (tmp = var; tmp; tmp = tmp->next) {
04813       if (!strcasecmp(tmp->name, "name")) {
04814          if (!ast_strlen_zero(tmp->value)) {
04815             return tmp->value;
04816          }
04817          break;
04818       }
04819    }
04820    return NULL;
04821 }
04822 
04823 /* If varregs is NULL, we don't use sipregs.
04824  * Using empty if-bodies instead of goto's while avoiding unnecessary indents */
04825 static int realtime_peer_by_name(const char *const *name, struct ast_sockaddr *addr, const char *ipaddr, struct ast_variable **var, struct ast_variable **varregs)
04826 {
04827    /* Peer by name and host=dynamic */
04828    if ((*var = ast_load_realtime("sippeers", "name", *name, "host", "dynamic", SENTINEL))) {
04829       ;
04830    /* Peer by name and host=IP */
04831    } else if (addr && !(*var = ast_load_realtime("sippeers", "name", *name, "host", ipaddr, SENTINEL))) {
04832       ;
04833    /* Peer by name and host=HOSTNAME */
04834    } else if ((*var = ast_load_realtime("sippeers", "name", *name, SENTINEL))) {
04835       /*!\note
04836        * If this one loaded something, then we need to ensure that the host
04837        * field matched.  The only reason why we can't have this as a criteria
04838        * is because we only have the IP address and the host field might be
04839        * set as a name (and the reverse PTR might not match).
04840        */
04841       if (addr) {
04842          struct ast_variable *tmp;
04843          for (tmp = *var; tmp; tmp = tmp->next) {
04844             if (!strcasecmp(tmp->name, "host")) {
04845                struct ast_sockaddr *addrs = NULL;
04846 
04847                if (ast_sockaddr_resolve(&addrs,
04848                          tmp->value,
04849                          PARSE_PORT_FORBID,
04850                          get_address_family_filter(&bindaddr)) <= 0 ||
04851                          ast_sockaddr_cmp(&addrs[0], addr)) {
04852                   /* No match */
04853                   ast_variables_destroy(*var);
04854                   *var = NULL;
04855                }
04856                ast_free(addrs);
04857                break;
04858             }
04859          }
04860       }
04861    }
04862 
04863    /* Did we find anything? */
04864    if (*var) {
04865       if (varregs) {
04866          *varregs = ast_load_realtime("sipregs", "name", *name, SENTINEL);
04867       }
04868       return 1;
04869    }
04870    return 0;
04871 }
04872 
04873 /* Another little helper function for backwards compatibility: this
04874  * checks/fetches the sippeer that belongs to the sipreg. If none is
04875  * found, we free the sipreg and return false. This way we can do the
04876  * check inside the if-condition below. In the old code, not finding
04877  * the sippeer also had it continue look for another match, so we do
04878  * the same. */
04879 static struct ast_variable *realtime_peer_get_sippeer_helper(const char **name, struct ast_variable **varregs) {
04880    struct ast_variable *var = NULL;
04881    const char *old_name = *name;
04882    *name = get_name_from_variable(*varregs);
04883    if (!*name || !(var = ast_load_realtime("sippeers", "name", *name, SENTINEL))) {
04884       if (!*name) {
04885          ast_log(LOG_WARNING, "Found sipreg but it has no name\n");
04886       }
04887       ast_variables_destroy(*varregs);
04888       *varregs = NULL;
04889       *name = old_name;
04890    }
04891    return var;
04892 }
04893 
04894 /* If varregs is NULL, we don't use sipregs. If we return true, then *name is
04895  * set. Using empty if-bodies instead of goto's while avoiding unnecessary
04896  * indents. */
04897 static int realtime_peer_by_addr(const char **name, struct ast_sockaddr *addr, const char *ipaddr, const char *callbackexten, struct ast_variable **var, struct ast_variable **varregs)
04898 {
04899    char portstring[6]; /* up to 5 digits plus null terminator */
04900    ast_copy_string(portstring, ast_sockaddr_stringify_port(addr), sizeof(portstring));
04901 
04902    /* We're not finding this peer by this name anymore. Reset it. */
04903    *name = NULL;
04904 
04905    /* First check for fixed IP hosts with matching callbackextensions, if specified */
04906    if (!ast_strlen_zero(callbackexten) && (*var = ast_load_realtime("sippeers", "host", ipaddr, "port", portstring, "callbackextension", callbackexten, SENTINEL))) {
04907       ;
04908    /* Check for fixed IP hosts */
04909    } else if ((*var = ast_load_realtime("sippeers", "host", ipaddr, "port", portstring, SENTINEL))) {
04910       ;
04911    /* Check for registered hosts (in sipregs) */
04912    } else if (varregs && (*varregs = ast_load_realtime("sipregs", "ipaddr", ipaddr, "port", portstring, SENTINEL)) &&
04913          (*var = realtime_peer_get_sippeer_helper(name, varregs))) {
04914       ;
04915    /* Check for registered hosts (in sippeers) */
04916    } else if (!varregs && (*var = ast_load_realtime("sippeers", "ipaddr", ipaddr, "port", portstring, SENTINEL))) {
04917       ;
04918    /* We couldn't match on ipaddress and port, so we need to check if port is insecure */
04919    } else if ((*var = get_insecure_variable_from_sippeers("host", ipaddr))) {
04920       ;
04921    /* Same as above, but try the IP address field (in sipregs)
04922     * Observe that it fetches the name/var at the same time, without the
04923     * realtime_peer_get_sippeer_helper. Also note that it is quite inefficient.
04924     * Avoid sipregs if possible. */
04925    } else if (varregs && (*varregs = get_insecure_variable_from_sipregs("ipaddr", ipaddr, var))) {
04926       ;
04927    /* Same as above, but try the IP address field (in sippeers) */
04928    } else if (!varregs && (*var = get_insecure_variable_from_sippeers("ipaddr", ipaddr))) {
04929       ;
04930    }
04931 
04932    /* Nothing found? */
04933    if (!*var) {
04934       return 0;
04935    }
04936 
04937    /* Check peer name. It must not be empty. There may exist a
04938     * different match that does have a name, but it's too late for
04939     * that now. */
04940    if (!*name && !(*name = get_name_from_variable(*var))) {
04941       ast_log(LOG_WARNING, "Found peer for IP %s but it has no name\n", ipaddr);
04942       ast_variables_destroy(*var);
04943       *var = NULL;
04944       if (varregs && *varregs) {
04945          ast_variables_destroy(*varregs);
04946          *varregs = NULL;
04947       }
04948       return 0;
04949    }
04950 
04951    /* Make sure varregs is populated if var is. The inverse,
04952     * ensuring that var is set when varregs is, is taken
04953     * care of by realtime_peer_get_sippeer_helper(). */
04954    if (varregs && !*varregs) {
04955       *varregs = ast_load_realtime("sipregs", "name", *name, SENTINEL);
04956    }
04957    return 1;
04958 }
04959 
04960 static int register_realtime_peers_with_callbackextens(void)
04961 {
04962    struct ast_config *cfg;
04963    char *cat = NULL;
04964 
04965    if (!(ast_check_realtime("sippeers"))) {
04966       return 0;
04967    }
04968 
04969    /* This is hacky. We want name to be the cat, so it is the first property */
04970    if (!(cfg = ast_load_realtime_multientry("sippeers", "name LIKE", "%", "callbackextension LIKE", "%", SENTINEL))) {
04971       return -1;
04972    }
04973 
04974    while ((cat = ast_category_browse(cfg, cat))) {
04975       struct sip_peer *peer;
04976       struct ast_variable *var = ast_category_root(cfg, cat);
04977 
04978       if (!(peer = build_peer(cat, var, NULL, TRUE, FALSE))) {
04979          continue;
04980       }
04981       ast_log(LOG_NOTICE, "Created realtime peer '%s' for registration\n", peer->name);
04982 
04983       peer->is_realtime = 1;
04984       sip_unref_peer(peer, "register_realtime_peers: Done registering releasing");
04985    }
04986 
04987    ast_config_destroy(cfg);
04988 
04989    return 0;
04990 }
04991 
04992 /*! \brief  realtime_peer: Get peer from realtime storage
04993  * Checks the "sippeers" realtime family from extconfig.conf
04994  * Checks the "sipregs" realtime family from extconfig.conf if it's configured.
04995  * This returns a pointer to a peer and because we use build_peer, we can rest
04996  * assured that the refcount is bumped.
04997  * 
04998  * \note This is never called with both newpeername and addr at the same time.
04999  * If you do, be prepared to get a peer with a different name than newpeername.
05000  */
05001 static struct sip_peer *realtime_peer(const char *newpeername, struct ast_sockaddr *addr, char *callbackexten, int devstate_only, int which_objects)
05002 {
05003    struct sip_peer *peer = NULL;
05004    struct ast_variable *var = NULL;
05005    struct ast_variable *varregs = NULL;
05006    char ipaddr[INET6_ADDRSTRLEN];
05007    int realtimeregs = ast_check_realtime("sipregs");
05008 
05009    if (addr) {
05010       ast_copy_string(ipaddr, ast_sockaddr_stringify_addr(addr), sizeof(ipaddr));
05011    } else {
05012       ipaddr[0] = '\0';
05013    }
05014 
05015    if (newpeername && realtime_peer_by_name(&newpeername, addr, ipaddr, &var, realtimeregs ? &varregs : NULL)) {
05016       ;
05017    } else if (addr && realtime_peer_by_addr(&newpeername, addr, ipaddr, callbackexten, &var, realtimeregs ? &varregs : NULL)) {
05018       ;
05019    } else {
05020       return NULL;
05021    }
05022 
05023    /* If we're looking for users, don't return peers (although this check
05024     * should probably be done in realtime_peer_by_* instead...) */
05025    if (which_objects == FINDUSERS) {
05026       struct ast_variable *tmp;
05027       for (tmp = var; tmp; tmp = tmp->next) {
05028          if (!strcasecmp(tmp->name, "type") && (!strcasecmp(tmp->value, "peer"))) {
05029             goto cleanup;
05030          }
05031       }
05032    }
05033 
05034    /* Peer found in realtime, now build it in memory */
05035    peer = build_peer(newpeername, var, varregs, TRUE, devstate_only);
05036    if (!peer) {
05037       goto cleanup;
05038    }
05039 
05040    ast_debug(3, "-REALTIME- loading peer from database to memory. Name: %s. Peer objects: %d\n", peer->name, rpeerobjs);
05041 
05042    if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) && !devstate_only) {
05043       /* Cache peer */
05044       ast_copy_flags(&peer->flags[1], &global_flags[1], SIP_PAGE2_RTAUTOCLEAR|SIP_PAGE2_RTCACHEFRIENDS);
05045       if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTAUTOCLEAR)) {
05046          AST_SCHED_REPLACE_UNREF(peer->expire, sched, sip_cfg.rtautoclear * 1000, expire_register, peer,
05047                sip_unref_peer(_data, "remove registration ref"),
05048                sip_unref_peer(peer, "remove registration ref"),
05049                sip_ref_peer(peer, "add registration ref"));
05050       }
05051       ao2_t_link(peers, peer, "link peer into peers table");
05052       if (!ast_sockaddr_isnull(&peer->addr)) {
05053          ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
05054       }
05055    }
05056    peer->is_realtime = 1;
05057 
05058 cleanup:
05059    ast_variables_destroy(var);
05060    ast_variables_destroy(varregs);
05061    return peer;
05062 }
05063 
05064 /* Function to assist finding peers by name only */
05065 static int find_by_name(void *obj, void *arg, void *data, int flags)
05066 {
05067    struct sip_peer *search = obj, *match = arg;
05068    int *which_objects = data;
05069 
05070    /* Usernames in SIP uri's are case sensitive. Domains are not */
05071    if (strcmp(search->name, match->name)) {
05072       return 0;
05073    }
05074 
05075    switch (*which_objects) {
05076    case FINDUSERS:
05077       if (!(search->type & SIP_TYPE_USER)) {
05078          return 0;
05079       }
05080       break;
05081    case FINDPEERS:
05082       if (!(search->type & SIP_TYPE_PEER)) {
05083          return 0;
05084       }
05085       break;
05086    case FINDALLDEVICES:
05087       break;
05088    }
05089 
05090    return CMP_MATCH | CMP_STOP;
05091 }
05092 
05093 static struct sip_peer *sip_find_peer_full(const char *peer, struct ast_sockaddr *addr, char *callbackexten, int realtime, int which_objects, int devstate_only, int transport)
05094 {
05095    struct sip_peer *p = NULL;
05096    struct sip_peer tmp_peer;
05097 
05098    if (peer) {
05099       ast_copy_string(tmp_peer.name, peer, sizeof(tmp_peer.name));
05100       p = ao2_t_callback_data(peers, OBJ_POINTER, find_by_name, &tmp_peer, &which_objects, "ao2_find in peers table");
05101    } else if (addr) { /* search by addr? */
05102       ast_sockaddr_copy(&tmp_peer.addr, addr);
05103       tmp_peer.flags[0].flags = 0;
05104       tmp_peer.transports = transport;
05105       p = ao2_t_callback_data(peers_by_ip, OBJ_POINTER, peer_ipcmp_cb_full, &tmp_peer, callbackexten, "ao2_find in peers_by_ip table");
05106       if (!p) {
05107          ast_set_flag(&tmp_peer.flags[0], SIP_INSECURE_PORT);
05108          p = ao2_t_callback_data(peers_by_ip, OBJ_POINTER, peer_ipcmp_cb_full, &tmp_peer, callbackexten, "ao2_find in peers_by_ip table 2");
05109          if (p) {
05110             return p;
05111          }
05112       }
05113    }
05114 
05115    if (!p && (realtime || devstate_only)) {
05116       /* realtime_peer will return a peer with matching callbackexten if possible, otherwise one matching
05117        * without the callbackexten */
05118       p = realtime_peer(peer, addr, callbackexten, devstate_only, which_objects);
05119       if (p) {
05120          switch (which_objects) {
05121          case FINDUSERS:
05122             if (!(p->type & SIP_TYPE_USER)) {
05123                sip_unref_peer(p, "Wrong type of realtime SIP endpoint");
05124                return NULL;
05125             }
05126             break;
05127          case FINDPEERS:
05128             if (!(p->type & SIP_TYPE_PEER)) {
05129                sip_unref_peer(p, "Wrong type of realtime SIP endpoint");
05130                return NULL;
05131             }
05132             break;
05133          case FINDALLDEVICES:
05134             break;
05135          }
05136       }
05137    }
05138 
05139    return p;
05140 }
05141 
05142 /*!
05143  * \brief Locate device by name or ip address
05144  * \param peer, sin, realtime, devstate_only, transport
05145  * \param which_objects Define which objects should be matched when doing a lookup
05146  *        by name.  Valid options are FINDUSERS, FINDPEERS, or FINDALLDEVICES.
05147  *        Note that this option is not used at all when doing a lookup by IP.
05148  *
05149  * This is used on find matching device on name or ip/port.
05150  * If the device was declared as type=peer, we don't match on peer name on incoming INVITEs.
05151  *
05152  * \note Avoid using this function in new functions if there is a way to avoid it,
05153  * since it might cause a database lookup.
05154  */
05155 struct sip_peer *sip_find_peer(const char *peer, struct ast_sockaddr *addr, int realtime, int which_objects, int devstate_only, int transport)
05156 {
05157    return sip_find_peer_full(peer, addr, NULL, realtime, which_objects, devstate_only, transport);
05158 }
05159 
05160 static struct sip_peer *sip_find_peer_by_ip_and_exten(struct ast_sockaddr *addr, char *callbackexten, int transport)
05161 {
05162    return sip_find_peer_full(NULL, addr, callbackexten, TRUE, FINDPEERS, FALSE, transport);
05163 }
05164 
05165 /*! \brief Set nat mode on the various data sockets */
05166 static void do_setnat(struct sip_pvt *p)
05167 {
05168    const char *mode;
05169    int natflags;
05170 
05171    natflags = ast_test_flag(&p->flags[1], SIP_PAGE2_SYMMETRICRTP);
05172    mode = natflags ? "On" : "Off";
05173 
05174    if (p->rtp) {
05175       ast_debug(1, "Setting NAT on RTP to %s\n", mode);
05176       ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_NAT, natflags);
05177    }
05178    if (p->vrtp) {
05179       ast_debug(1, "Setting NAT on VRTP to %s\n", mode);
05180       ast_rtp_instance_set_prop(p->vrtp, AST_RTP_PROPERTY_NAT, natflags);
05181    }
05182    if (p->udptl) {
05183       ast_debug(1, "Setting NAT on UDPTL to %s\n", mode);
05184       ast_udptl_setnat(p->udptl, natflags);
05185    }
05186    if (p->trtp) {
05187       ast_debug(1, "Setting NAT on TRTP to %s\n", mode);
05188       ast_rtp_instance_set_prop(p->trtp, AST_RTP_PROPERTY_NAT, natflags);
05189    }
05190 }
05191 
05192 /*! \brief Change the T38 state on a SIP dialog */
05193 static void change_t38_state(struct sip_pvt *p, int state)
05194 {
05195    int old = p->t38.state;
05196    struct ast_channel *chan = p->owner;
05197    struct ast_control_t38_parameters parameters = { .request_response = 0 };
05198 
05199    /* Don't bother changing if we are already in the state wanted */
05200    if (old == state)
05201       return;
05202 
05203    p->t38.state = state;
05204    ast_debug(2, "T38 state changed to %d on channel %s\n", p->t38.state, chan ? ast_channel_name(chan) : "<none>");
05205 
05206    /* If no channel was provided we can't send off a control frame */
05207    if (!chan)
05208       return;
05209 
05210    /* Given the state requested and old state determine what control frame we want to queue up */
05211    switch (state) {
05212    case T38_PEER_REINVITE:
05213       parameters = p->t38.their_parms;
05214       parameters.max_ifp = ast_udptl_get_far_max_ifp(p->udptl);
05215       parameters.request_response = AST_T38_REQUEST_NEGOTIATE;
05216       ast_udptl_set_tag(p->udptl, "%s", ast_channel_name(chan));
05217       break;
05218    case T38_ENABLED:
05219       parameters = p->t38.their_parms;
05220       parameters.max_ifp = ast_udptl_get_far_max_ifp(p->udptl);
05221       parameters.request_response = AST_T38_NEGOTIATED;
05222       ast_udptl_set_tag(p->udptl, "%s", ast_channel_name(chan));
05223       break;
05224    case T38_REJECTED:
05225    case T38_DISABLED:
05226       if (old == T38_ENABLED) {
05227          parameters.request_response = AST_T38_TERMINATED;
05228       } else if (old == T38_LOCAL_REINVITE) {
05229          parameters.request_response = AST_T38_REFUSED;
05230       }
05231       break;
05232    case T38_LOCAL_REINVITE:
05233       /* wait until we get a peer response before responding to local reinvite */
05234       break;
05235    }
05236 
05237    /* Woot we got a message, create a control frame and send it on! */
05238    if (parameters.request_response)
05239       ast_queue_control_data(chan, AST_CONTROL_T38_PARAMETERS, &parameters, sizeof(parameters));
05240 }
05241 
05242 /*! \brief Set the global T38 capabilities on a SIP dialog structure */
05243 static void set_t38_capabilities(struct sip_pvt *p)
05244 {
05245    if (p->udptl) {
05246       if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) == SIP_PAGE2_T38SUPPORT_UDPTL_REDUNDANCY) {
05247                         ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_REDUNDANCY);
05248       } else if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) == SIP_PAGE2_T38SUPPORT_UDPTL_FEC) {
05249          ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_FEC);
05250       } else if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) == SIP_PAGE2_T38SUPPORT_UDPTL) {
05251          ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_NONE);
05252       }
05253    }
05254 }
05255 
05256 static void copy_socket_data(struct sip_socket *to_sock, const struct sip_socket *from_sock)
05257 {
05258    if (to_sock->tcptls_session) {
05259       ao2_ref(to_sock->tcptls_session, -1);
05260       to_sock->tcptls_session = NULL;
05261    }
05262 
05263    if (from_sock->tcptls_session) {
05264       ao2_ref(from_sock->tcptls_session, +1);
05265    }
05266 
05267    *to_sock = *from_sock;
05268 }
05269 
05270 /*! \brief Initialize RTP portion of a dialog
05271  * \return -1 on failure, 0 on success
05272  */
05273 static int dialog_initialize_rtp(struct sip_pvt *dialog)
05274 {
05275    struct ast_sockaddr bindaddr_tmp;
05276 
05277    if (!sip_methods[dialog->method].need_rtp) {
05278       return 0;
05279    }
05280 
05281    ast_sockaddr_copy(&bindaddr_tmp, &bindaddr);
05282    if (!(dialog->rtp = ast_rtp_instance_new(dialog->engine, sched, &bindaddr_tmp, NULL))) {
05283       return -1;
05284    }
05285 
05286    if (ast_test_flag(&dialog->flags[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS) ||
05287          (ast_test_flag(&dialog->flags[1], SIP_PAGE2_VIDEOSUPPORT) && (ast_format_cap_has_type(dialog->caps, AST_FORMAT_TYPE_VIDEO)))) {
05288       if (!(dialog->vrtp = ast_rtp_instance_new(dialog->engine, sched, &bindaddr_tmp, NULL))) {
05289          return -1;
05290       }
05291       ast_rtp_instance_set_timeout(dialog->vrtp, dialog->rtptimeout);
05292       ast_rtp_instance_set_hold_timeout(dialog->vrtp, dialog->rtpholdtimeout);
05293       ast_rtp_instance_set_keepalive(dialog->vrtp, dialog->rtpkeepalive);
05294 
05295       ast_rtp_instance_set_prop(dialog->vrtp, AST_RTP_PROPERTY_RTCP, 1);
05296    }
05297 
05298    if (ast_test_flag(&dialog->flags[1], SIP_PAGE2_TEXTSUPPORT)) {
05299       if (!(dialog->trtp = ast_rtp_instance_new(dialog->engine, sched, &bindaddr_tmp, NULL))) {
05300          return -1;
05301       }
05302       /* Do not timeout text as its not constant*/
05303       ast_rtp_instance_set_keepalive(dialog->trtp, dialog->rtpkeepalive);
05304 
05305       ast_rtp_instance_set_prop(dialog->trtp, AST_RTP_PROPERTY_RTCP, 1);
05306    }
05307 
05308    ast_rtp_instance_set_timeout(dialog->rtp, dialog->rtptimeout);
05309    ast_rtp_instance_set_hold_timeout(dialog->rtp, dialog->rtpholdtimeout);
05310    ast_rtp_instance_set_keepalive(dialog->rtp, dialog->rtpkeepalive);
05311 
05312    ast_rtp_instance_set_prop(dialog->rtp, AST_RTP_PROPERTY_RTCP, 1);
05313    ast_rtp_instance_set_prop(dialog->rtp, AST_RTP_PROPERTY_DTMF, ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
05314    ast_rtp_instance_set_prop(dialog->rtp, AST_RTP_PROPERTY_DTMF_COMPENSATE, ast_test_flag(&dialog->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
05315 
05316    ast_rtp_instance_set_qos(dialog->rtp, global_tos_audio, global_cos_audio, "SIP RTP");
05317 
05318    do_setnat(dialog);
05319 
05320    return 0;
05321 }
05322 
05323 /*! \brief Create address structure from peer reference.
05324  * This function copies data from peer to the dialog, so we don't have to look up the peer
05325  * again from memory or database during the life time of the dialog.
05326  *
05327  * \return -1 on error, 0 on success.
05328  *
05329  */
05330 static int create_addr_from_peer(struct sip_pvt *dialog, struct sip_peer *peer)
05331 {
05332    struct sip_auth_container *credentials;
05333 
05334    /* this checks that the dialog is contacting the peer on a valid
05335     * transport type based on the peers transport configuration,
05336     * otherwise, this function bails out */
05337    if (dialog->socket.type && check_request_transport(peer, dialog))
05338       return -1;
05339    copy_socket_data(&dialog->socket, &peer->socket);
05340 
05341    if (!(ast_sockaddr_isnull(&peer->addr) && ast_sockaddr_isnull(&peer->defaddr)) &&
05342        (!peer->maxms || ((peer->lastms >= 0)  && (peer->lastms <= peer->maxms)))) {
05343       dialog->sa = ast_sockaddr_isnull(&peer->addr) ? peer->defaddr : peer->addr;
05344       dialog->recv = dialog->sa;
05345    } else
05346       return -1;
05347 
05348    /* XXX TODO: get flags directly from peer only as they are needed using dialog->relatedpeer */
05349    ast_copy_flags(&dialog->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
05350    ast_copy_flags(&dialog->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
05351    ast_copy_flags(&dialog->flags[2], &peer->flags[2], SIP_PAGE3_FLAGS_TO_COPY);
05352    ast_format_cap_copy(dialog->caps, peer->caps);
05353    dialog->prefs = peer->prefs;
05354    dialog->amaflags = peer->amaflags;
05355 
05356    ast_string_field_set(dialog, engine, peer->engine);
05357 
05358    dialog->rtptimeout = peer->rtptimeout;
05359    dialog->rtpholdtimeout = peer->rtpholdtimeout;
05360    dialog->rtpkeepalive = peer->rtpkeepalive;
05361    if (dialog_initialize_rtp(dialog)) {
05362       return -1;
05363    }
05364 
05365    if (dialog->rtp) { /* Audio */
05366       ast_rtp_instance_set_prop(dialog->rtp, AST_RTP_PROPERTY_DTMF, ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
05367       ast_rtp_instance_set_prop(dialog->rtp, AST_RTP_PROPERTY_DTMF_COMPENSATE, ast_test_flag(&dialog->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
05368       /* Set Frame packetization */
05369       ast_rtp_codecs_packetization_set(ast_rtp_instance_get_codecs(dialog->rtp), dialog->rtp, &dialog->prefs);
05370       dialog->autoframing = peer->autoframing;
05371    }
05372 
05373    /* XXX TODO: get fields directly from peer only as they are needed using dialog->relatedpeer */
05374    ast_string_field_set(dialog, peername, peer->name);
05375    ast_string_field_set(dialog, authname, peer->username);
05376    ast_string_field_set(dialog, username, peer->username);
05377    ast_string_field_set(dialog, peersecret, peer->secret);
05378    ast_string_field_set(dialog, peermd5secret, peer->md5secret);
05379    ast_string_field_set(dialog, mohsuggest, peer->mohsuggest);
05380    ast_string_field_set(dialog, mohinterpret, peer->mohinterpret);
05381    ast_string_field_set(dialog, tohost, peer->tohost);
05382    ast_string_field_set(dialog, fullcontact, peer->fullcontact);
05383    ast_string_field_set(dialog, accountcode, peer->accountcode);
05384    ast_string_field_set(dialog, context, peer->context);
05385    ast_string_field_set(dialog, cid_num, peer->cid_num);
05386    ast_string_field_set(dialog, cid_name, peer->cid_name);
05387    ast_string_field_set(dialog, cid_tag, peer->cid_tag);
05388    ast_string_field_set(dialog, mwi_from, peer->mwi_from);
05389    if (!ast_strlen_zero(peer->parkinglot)) {
05390       ast_string_field_set(dialog, parkinglot, peer->parkinglot);
05391    }
05392    ast_string_field_set(dialog, engine, peer->engine);
05393    ref_proxy(dialog, obproxy_get(dialog, peer));
05394    dialog->callgroup = peer->callgroup;
05395    dialog->pickupgroup = peer->pickupgroup;
05396    ast_copy_string(dialog->zone, peer->zone, sizeof(dialog->zone));
05397    dialog->allowtransfer = peer->allowtransfer;
05398    dialog->jointnoncodeccapability = dialog->noncodeccapability;
05399 
05400    /* Update dialog authorization credentials */
05401    ao2_lock(peer);
05402    credentials = peer->auth;
05403    if (credentials) {
05404       ao2_t_ref(credentials, +1, "Ref peer auth for dialog");
05405    }
05406    ao2_unlock(peer);
05407    ao2_lock(dialog);
05408    if (dialog->peerauth) {
05409       ao2_t_ref(dialog->peerauth, -1, "Unref old dialog peer auth");
05410    }
05411    dialog->peerauth = credentials;
05412    ao2_unlock(dialog);
05413 
05414    dialog->maxcallbitrate = peer->maxcallbitrate;
05415    dialog->disallowed_methods = peer->disallowed_methods;
05416    ast_cc_copy_config_params(dialog->cc_params, peer->cc_params);
05417    if (ast_strlen_zero(dialog->tohost))
05418       ast_string_field_set(dialog, tohost, ast_sockaddr_stringify_host_remote(&dialog->sa));
05419    if (!ast_strlen_zero(peer->fromdomain)) {
05420       ast_string_field_set(dialog, fromdomain, peer->fromdomain);
05421       if (!dialog->initreq.headers) {
05422          char *new_callid;
05423          char *tmpcall = ast_strdupa(dialog->callid);
05424          /* this sure looks to me like we are going to change the callid on this dialog!! */
05425          new_callid = strchr(tmpcall, '@');
05426          if (new_callid) {
05427             int callid_size;
05428 
05429             *new_callid = '\0';
05430 
05431             /* Change the dialog callid. */
05432             callid_size = strlen(tmpcall) + strlen(peer->fromdomain) + 2;
05433             new_callid = alloca(callid_size);
05434             snprintf(new_callid, callid_size, "%s@%s", tmpcall, peer->fromdomain);
05435             change_callid_pvt(dialog, new_callid);
05436          }
05437       }
05438    }
05439    if (!ast_strlen_zero(peer->fromuser))
05440       ast_string_field_set(dialog, fromuser, peer->fromuser);
05441    if (!ast_strlen_zero(peer->language))
05442       ast_string_field_set(dialog, language, peer->language);
05443    /* Set timer T1 to RTT for this peer (if known by qualify=) */
05444    /* Minimum is settable or default to 100 ms */
05445    /* If there is a maxms and lastms from a qualify use that over a manual T1
05446       value. Otherwise, use the peer's T1 value. */
05447    if (peer->maxms && peer->lastms)
05448       dialog->timer_t1 = peer->lastms < global_t1min ? global_t1min : peer->lastms;
05449    else
05450       dialog->timer_t1 = peer->timer_t1;
05451 
05452    /* Set timer B to control transaction timeouts, the peer setting is the default and overrides
05453       the known timer */
05454    if (peer->timer_b)
05455       dialog->timer_b = peer->timer_b;
05456    else
05457       dialog->timer_b = 64 * dialog->timer_t1;
05458 
05459    if ((ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
05460        (ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
05461       dialog->noncodeccapability |= AST_RTP_DTMF;
05462    else
05463       dialog->noncodeccapability &= ~AST_RTP_DTMF;
05464    dialog->directmediaha = ast_duplicate_ha_list(peer->directmediaha);
05465    if (peer->call_limit)
05466       ast_set_flag(&dialog->flags[0], SIP_CALL_LIMIT);
05467    if (!dialog->portinuri)
05468       dialog->portinuri = peer->portinuri;
05469    dialog->chanvars = copy_vars(peer->chanvars);
05470    if (peer->fromdomainport)
05471       dialog->fromdomainport = peer->fromdomainport;
05472 
05473    return 0;
05474 }
05475 
05476 /*! \brief The default sip port for the given transport */
05477 static inline int default_sip_port(enum sip_transport type)
05478 {
05479    return type == SIP_TRANSPORT_TLS ? STANDARD_TLS_PORT : STANDARD_SIP_PORT;
05480 }
05481 
05482 /*! \brief create address structure from device name
05483  *      Or, if peer not found, find it in the global DNS
05484  *      returns TRUE (-1) on failure, FALSE on success */
05485 static int create_addr(struct sip_pvt *dialog, const char *opeer, struct ast_sockaddr *addr, int newdialog, struct ast_sockaddr *remote_address)
05486 {
05487    struct sip_peer *peer;
05488    char *peername, *peername2, *hostn;
05489    char host[MAXHOSTNAMELEN];
05490    char service[MAXHOSTNAMELEN];
05491    int srv_ret = 0;
05492    int tportno;
05493 
05494    AST_DECLARE_APP_ARGS(hostport,
05495       AST_APP_ARG(host);
05496       AST_APP_ARG(port);
05497    );
05498 
05499    peername = ast_strdupa(opeer);
05500    peername2 = ast_strdupa(opeer);
05501    AST_NONSTANDARD_RAW_ARGS(hostport, peername2, ':');
05502 
05503    if (hostport.port)
05504       dialog->portinuri = 1;
05505 
05506    dialog->timer_t1 = global_t1; /* Default SIP retransmission timer T1 (RFC 3261) */
05507    dialog->timer_b = global_timer_b; /* Default SIP transaction timer B (RFC 3261) */
05508    peer = sip_find_peer(peername, NULL, TRUE, FINDPEERS, FALSE, 0);
05509 
05510    if (peer) {
05511       int res;
05512       if (newdialog) {
05513          set_socket_transport(&dialog->socket, 0);
05514       }
05515       res = create_addr_from_peer(dialog, peer);
05516       if (!ast_sockaddr_isnull(remote_address)) {
05517          ast_sockaddr_copy(&dialog->sa, remote_address);
05518       }
05519       dialog->relatedpeer = sip_ref_peer(peer, "create_addr: setting dialog's relatedpeer pointer");
05520       sip_unref_peer(peer, "create_addr: unref peer from sip_find_peer hashtab lookup");
05521       return res;
05522    } else if (ast_check_digits(peername)) {
05523       /* Although an IPv4 hostname *could* be represented as a 32-bit integer, it is uncommon and
05524        * it makes dialing SIP/${EXTEN} for a peer that isn't defined resolve to an IP that is
05525        * almost certainly not intended. It is much better to just reject purely numeric hostnames */
05526       ast_log(LOG_WARNING, "Purely numeric hostname (%s), and not a peer--rejecting!\n", peername);
05527       return -1;
05528    } else {
05529       dialog->rtptimeout = global_rtptimeout;
05530       dialog->rtpholdtimeout = global_rtpholdtimeout;
05531       dialog->rtpkeepalive = global_rtpkeepalive;
05532       if (dialog_initialize_rtp(dialog)) {
05533          return -1;
05534       }
05535    }
05536 
05537    ast_string_field_set(dialog, tohost, hostport.host);
05538    dialog->allowed_methods &= ~sip_cfg.disallowed_methods;
05539 
05540    /* Get the outbound proxy information */
05541    ref_proxy(dialog, obproxy_get(dialog, NULL));
05542 
05543    if (addr) {
05544       /* This address should be updated using dnsmgr */
05545       ast_sockaddr_copy(&dialog->sa, addr);
05546    } else {
05547 
05548       /* Let's see if we can find the host in DNS. First try DNS SRV records,
05549          then hostname lookup */
05550       /*! \todo Fix this function. When we ask for SRV, we should check all transports
05551            In the future, we should first check NAPTR to find out transport preference
05552        */
05553       hostn = peername;
05554       /* Section 4.2 of RFC 3263 specifies that if a port number is specified, then
05555        * an A record lookup should be used instead of SRV.
05556        */
05557       if (!hostport.port && sip_cfg.srvlookup) {
05558          snprintf(service, sizeof(service), "_%s._%s.%s", 
05559              get_srv_service(dialog->socket.type),
05560              get_srv_protocol(dialog->socket.type), peername);
05561          if ((srv_ret = ast_get_srv(NULL, host, sizeof(host), &tportno,
05562                      service)) > 0) {
05563             hostn = host;
05564          }
05565       }
05566 
05567       if (ast_sockaddr_resolve_first(&dialog->sa, hostn, 0)) {
05568          ast_log(LOG_WARNING, "No such host: %s\n", peername);
05569          return -1;
05570       }
05571 
05572       if (srv_ret > 0) {
05573          ast_sockaddr_set_port(&dialog->sa, tportno);
05574       }
05575    }
05576 
05577    if (!dialog->socket.type)
05578       set_socket_transport(&dialog->socket, SIP_TRANSPORT_UDP);
05579    if (!dialog->socket.port) {
05580       dialog->socket.port = htons(ast_sockaddr_port(&bindaddr));
05581    }
05582 
05583    if (!ast_sockaddr_port(&dialog->sa)) {
05584       ast_sockaddr_set_port(&dialog->sa, default_sip_port(dialog->socket.type));
05585    }
05586    ast_sockaddr_copy(&dialog->recv, &dialog->sa);
05587    return 0;
05588 }
05589 
05590 /*! \brief Scheduled congestion on a call.
05591  * Only called by the scheduler, must return the reference when done.
05592  */
05593 static int auto_congest(const void *arg)
05594 {
05595    struct sip_pvt *p = (struct sip_pvt *)arg;
05596 
05597    sip_pvt_lock(p);
05598    p->initid = -1;   /* event gone, will not be rescheduled */
05599    if (p->owner) {
05600       /* XXX fails on possible deadlock */
05601       if (!ast_channel_trylock(p->owner)) {
05602          append_history(p, "Cong", "Auto-congesting (timer)");
05603          ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
05604          ast_channel_unlock(p->owner);
05605       }
05606 
05607       /* Give the channel a chance to act before we proceed with destruction */
05608       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
05609    }
05610    sip_pvt_unlock(p);
05611    dialog_unref(p, "unreffing arg passed into auto_congest callback (p->initid)");
05612    return 0;
05613 }
05614 
05615 
05616 /*! \brief Initiate SIP call from PBX
05617  *      used from the dial() application      */
05618 static int sip_call(struct ast_channel *ast, const char *dest, int timeout)
05619 {
05620    int res;
05621    struct sip_pvt *p = ast->tech_pvt;  /* chan is locked, so the reference cannot go away */
05622    struct varshead *headp;
05623    struct ast_var_t *current;
05624    const char *referer = NULL;   /* SIP referrer */
05625    int cc_core_id;
05626    char uri[SIPBUFSIZE] = "";
05627 
05628    if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
05629       ast_log(LOG_WARNING, "sip_call called on %s, neither down nor reserved\n", ast_channel_name(ast));
05630       return -1;
05631    }
05632 
05633    if (ast_cc_is_recall(ast, &cc_core_id, "SIP")) {
05634       char device_name[AST_CHANNEL_NAME];
05635       struct ast_cc_monitor *recall_monitor;
05636       struct sip_monitor_instance *monitor_instance;
05637       ast_channel_get_device_name(ast, device_name, sizeof(device_name));
05638       if ((recall_monitor = ast_cc_get_monitor_by_recall_core_id(cc_core_id, device_name))) {
05639          monitor_instance = recall_monitor->private_data;
05640          ast_copy_string(uri, monitor_instance->notify_uri, sizeof(uri));
05641          ao2_t_ref(recall_monitor, -1, "Got the URI we need so unreffing monitor");
05642       }
05643    }
05644 
05645    /* Check whether there is vxml_url, distinctive ring variables */
05646    headp=&ast->varshead;
05647    AST_LIST_TRAVERSE(headp, current, entries) {
05648       /* Check whether there is a VXML_URL variable */
05649       if (!p->options->vxml_url && !strcasecmp(ast_var_name(current), "VXML_URL")) {
05650          p->options->vxml_url = ast_var_value(current);
05651       } else if (!p->options->uri_options && !strcasecmp(ast_var_name(current), "SIP_URI_OPTIONS")) {
05652          p->options->uri_options = ast_var_value(current);
05653       } else if (!p->options->addsipheaders && !strncasecmp(ast_var_name(current), "SIPADDHEADER", strlen("SIPADDHEADER"))) {
05654          /* Check whether there is a variable with a name starting with SIPADDHEADER */
05655          p->options->addsipheaders = 1;
05656       } else if (!strcasecmp(ast_var_name(current), "SIPFROMDOMAIN")) {
05657          ast_string_field_set(p, fromdomain, ast_var_value(current));
05658       } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER")) {
05659          /* This is a transfered call */
05660          p->options->transfer = 1;
05661       } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER_REFERER")) {
05662          /* This is the referrer */
05663          referer = ast_var_value(current);
05664       } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER_REPLACES")) {
05665          /* We're replacing a call. */
05666          p->options->replaces = ast_var_value(current);
05667       } else if (!strcasecmp(ast_var_name(current), "SIP_MAX_FORWARDS")) {
05668          if (sscanf(ast_var_value(current), "%30d", &(p->maxforwards)) != 1) {
05669             ast_log(LOG_WARNING, "The SIP_MAX_FORWARDS channel variable is not a valid integer.");
05670          }
05671       }
05672    }
05673 
05674    /* Check to see if we should try to force encryption */
05675    if (p->req_secure_signaling && p->socket.type != SIP_TRANSPORT_TLS) {
05676       ast_log(LOG_WARNING, "Encrypted signaling is required\n");
05677       ast->hangupcause = AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
05678       return -1;
05679    }
05680 
05681    if (ast_test_flag(&p->flags[1], SIP_PAGE2_USE_SRTP)) {
05682       if (ast_test_flag(&p->flags[0], SIP_REINVITE)) {
05683          ast_debug(1, "Direct media not possible when using SRTP, ignoring canreinvite setting\n");
05684          ast_clear_flag(&p->flags[0], SIP_REINVITE);
05685       }
05686 
05687       if (p->rtp && !p->srtp && setup_srtp(&p->srtp) < 0) {
05688          ast_log(LOG_WARNING, "SRTP audio setup failed\n");
05689          return -1;
05690       }
05691 
05692       if (p->vrtp && !p->vsrtp && setup_srtp(&p->vsrtp) < 0) {
05693          ast_log(LOG_WARNING, "SRTP video setup failed\n");
05694          return -1;
05695       }
05696 
05697       if (p->trtp && !p->tsrtp && setup_srtp(&p->tsrtp) < 0) {
05698          ast_log(LOG_WARNING, "SRTP text setup failed\n");
05699          return -1;
05700       }
05701    }
05702 
05703    res = 0;
05704    ast_set_flag(&p->flags[0], SIP_OUTGOING);
05705 
05706    /* T.38 re-INVITE FAX detection should never be done for outgoing calls,
05707     * so ensure it is disabled.
05708     */
05709    ast_clear_flag(&p->flags[1], SIP_PAGE2_FAX_DETECT_T38);
05710 
05711    if (p->options->transfer) {
05712       char buf[SIPBUFSIZE/2];
05713 
05714       if (referer) {
05715          if (sipdebug)
05716             ast_debug(3, "Call for %s transfered by %s\n", p->username, referer);
05717          snprintf(buf, sizeof(buf)-1, "-> %s (via %s)", p->cid_name, referer);
05718       } else
05719          snprintf(buf, sizeof(buf)-1, "-> %s", p->cid_name);
05720       ast_string_field_set(p, cid_name, buf);
05721    }
05722    ast_debug(1, "Outgoing Call for %s\n", p->username);
05723 
05724    res = update_call_counter(p, INC_CALL_RINGING);
05725 
05726    if (res == -1) {
05727       ast->hangupcause = AST_CAUSE_USER_BUSY;
05728       return res;
05729    }
05730    p->callingpres = ast_party_id_presentation(&ast->caller.id);
05731    ast_rtp_instance_available_formats(p->rtp, p->caps, p->prefcaps, p->jointcaps);
05732    p->jointnoncodeccapability = p->noncodeccapability;
05733 
05734    /* If there are no audio formats left to offer, punt */
05735    if (!(ast_format_cap_has_type(p->jointcaps, AST_FORMAT_TYPE_AUDIO))) {
05736       ast_log(LOG_WARNING, "No audio format found to offer. Cancelling call to %s\n", p->username);
05737       res = -1;
05738    } else {
05739       int xmitres;
05740       struct ast_party_connected_line connected;
05741       struct ast_set_party_connected_line update_connected;
05742 
05743       sip_pvt_lock(p);
05744 
05745       /* Supply initial connected line information if available. */
05746       memset(&update_connected, 0, sizeof(update_connected));
05747       ast_party_connected_line_init(&connected);
05748       if (!ast_strlen_zero(p->cid_num)
05749          || (p->callingpres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED) {
05750          update_connected.id.number = 1;
05751          connected.id.number.valid = 1;
05752          connected.id.number.str = (char *) p->cid_num;
05753          connected.id.number.presentation = p->callingpres;
05754       }
05755       if (!ast_strlen_zero(p->cid_name)
05756          || (p->callingpres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED) {
05757          update_connected.id.name = 1;
05758          connected.id.name.valid = 1;
05759          connected.id.name.str = (char *) p->cid_name;
05760          connected.id.name.presentation = p->callingpres;
05761       }
05762       if (update_connected.id.number || update_connected.id.name) {
05763          connected.id.tag = (char *) p->cid_tag;
05764          connected.source = AST_CONNECTED_LINE_UPDATE_SOURCE_ANSWER;
05765          ast_channel_queue_connected_line_update(ast, &connected, &update_connected);
05766       }
05767 
05768       xmitres = transmit_invite(p, SIP_INVITE, 1, 2, uri);
05769       sip_pvt_unlock(p);
05770       if (xmitres == XMIT_ERROR)
05771          return -1;
05772       p->invitestate = INV_CALLING;
05773 
05774       /* Initialize auto-congest time */
05775       AST_SCHED_REPLACE_UNREF(p->initid, sched, p->timer_b, auto_congest, p,
05776                         dialog_unref(_data, "dialog ptr dec when SCHED_REPLACE del op succeeded"),
05777                         dialog_unref(p, "dialog ptr dec when SCHED_REPLACE add failed"),
05778                         dialog_ref(p, "dialog ptr inc when SCHED_REPLACE add succeeded") );
05779    }
05780    return res;
05781 }
05782 
05783 /*! \brief Destroy registry object
05784    Objects created with the register= statement in static configuration */
05785 static void sip_registry_destroy(struct sip_registry *reg)
05786 {
05787    /* Really delete */
05788    ast_debug(3, "Destroying registry entry for %s@%s\n", reg->username, reg->hostname);
05789 
05790    if (reg->call) {
05791       /* Clear registry before destroying to ensure
05792          we don't get reentered trying to grab the registry lock */
05793       reg->call->registry = registry_unref(reg->call->registry, "destroy reg->call->registry");
05794       ast_debug(3, "Destroying active SIP dialog for registry %s@%s\n", reg->username, reg->hostname);
05795       dialog_unlink_all(reg->call);
05796       reg->call = dialog_unref(reg->call, "unref reg->call");
05797       /* reg->call = sip_destroy(reg->call); */
05798    }
05799    AST_SCHED_DEL(sched, reg->expire);
05800    AST_SCHED_DEL(sched, reg->timeout);
05801 
05802    ast_string_field_free_memory(reg);
05803    ast_atomic_fetchadd_int(&regobjs, -1);
05804    ast_free(reg);
05805 }
05806 
05807 /*! \brief Destroy MWI subscription object */
05808 static void sip_subscribe_mwi_destroy(struct sip_subscription_mwi *mwi)
05809 {
05810    if (mwi->call) {
05811       mwi->call->mwi = NULL;
05812       sip_destroy(mwi->call);
05813    }
05814    
05815    AST_SCHED_DEL(sched, mwi->resub);
05816    ast_string_field_free_memory(mwi);
05817    ast_free(mwi);
05818 }
05819 
05820 /*! \brief Execute destruction of SIP dialog structure, release memory */
05821 void __sip_destroy(struct sip_pvt *p, int lockowner, int lockdialoglist)
05822 {
05823    struct sip_request *req;
05824 
05825    /* Destroy Session-Timers if allocated */
05826    if (p->stimer) {
05827       p->stimer->quit_flag = 1;
05828       stop_session_timer(p);
05829       ast_free(p->stimer);
05830       p->stimer = NULL;
05831    }
05832 
05833    if (sip_debug_test_pvt(p))
05834       ast_verbose("Really destroying SIP dialog '%s' Method: %s\n", p->callid, sip_methods[p->method].text);
05835 
05836    if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
05837       update_call_counter(p, DEC_CALL_LIMIT);
05838       ast_debug(2, "This call did not properly clean up call limits. Call ID %s\n", p->callid);
05839    }
05840 
05841    /* Unlink us from the owner if we have one */
05842    if (p->owner) {
05843       if (lockowner)
05844          ast_channel_lock(p->owner);
05845       ast_debug(1, "Detaching from %s\n", ast_channel_name(p->owner));
05846       p->owner->tech_pvt = NULL;
05847       /* Make sure that the channel knows its backend is going away */
05848       p->owner->_softhangup |= AST_SOFTHANGUP_DEV;
05849       if (lockowner)
05850          ast_channel_unlock(p->owner);
05851       /* Give the channel a chance to react before deallocation */
05852       usleep(1);
05853    }
05854 
05855    /* Remove link from peer to subscription of MWI */
05856    if (p->relatedpeer && p->relatedpeer->mwipvt)
05857       p->relatedpeer->mwipvt = dialog_unref(p->relatedpeer->mwipvt, "delete ->relatedpeer->mwipvt");
05858    if (p->relatedpeer && p->relatedpeer->call == p)
05859       p->relatedpeer->call = dialog_unref(p->relatedpeer->call, "unset the relatedpeer->call field in tandem with relatedpeer field itself");
05860    
05861    if (p->relatedpeer)
05862       p->relatedpeer = sip_unref_peer(p->relatedpeer,"unsetting a dialog relatedpeer field in sip_destroy");
05863    
05864    if (p->registry) {
05865       if (p->registry->call == p)
05866          p->registry->call = dialog_unref(p->registry->call, "nulling out the registry's call dialog field in unlink_all");
05867       p->registry = registry_unref(p->registry, "delete p->registry");
05868    }
05869    
05870    if (p->mwi) {
05871       p->mwi->call = NULL;
05872    }
05873 
05874    if (dumphistory)
05875       sip_dump_history(p);
05876 
05877    if (p->options)
05878       ast_free(p->options);
05879 
05880    if (p->notify) {
05881       ast_variables_destroy(p->notify->headers);
05882       ast_free(p->notify->content);
05883       ast_free(p->notify);
05884    }
05885    if (p->rtp) {
05886       ast_rtp_instance_destroy(p->rtp);
05887    }
05888    if (p->vrtp) {
05889       ast_rtp_instance_destroy(p->vrtp);
05890    }
05891    if (p->trtp) {
05892       ast_rtp_instance_destroy(p->trtp);
05893    }
05894    if (p->udptl)
05895       ast_udptl_destroy(p->udptl);
05896    if (p->refer)
05897       ast_free(p->refer);
05898    if (p->route) {
05899       free_old_route(p->route);
05900       p->route = NULL;
05901    }
05902    deinit_req(&p->initreq);
05903 
05904    /* Clear history */
05905    if (p->history) {
05906       struct sip_history *hist;
05907       while ( (hist = AST_LIST_REMOVE_HEAD(p->history, list)) ) {
05908          ast_free(hist);
05909          p->history_entries--;
05910       }
05911       ast_free(p->history);
05912       p->history = NULL;
05913    }
05914 
05915    while ((req = AST_LIST_REMOVE_HEAD(&p->request_queue, next))) {
05916       ast_free(req);
05917    }
05918 
05919    if (p->chanvars) {
05920       ast_variables_destroy(p->chanvars);
05921       p->chanvars = NULL;
05922    }
05923 
05924    destroy_msg_headers(p);
05925 
05926    if (p->srtp) {
05927       sip_srtp_destroy(p->srtp);
05928       p->srtp = NULL;
05929    }
05930 
05931    if (p->vsrtp) {
05932       sip_srtp_destroy(p->vsrtp);
05933       p->vsrtp = NULL;
05934    }
05935 
05936    if (p->tsrtp) {
05937       sip_srtp_destroy(p->tsrtp);
05938       p->tsrtp = NULL;
05939    }
05940 
05941    if (p->directmediaha) {
05942       ast_free_ha(p->directmediaha);
05943       p->directmediaha = NULL;
05944    }
05945 
05946    ast_string_field_free_memory(p);
05947 
05948    ast_cc_config_params_destroy(p->cc_params);
05949 
05950    if (p->epa_entry) {
05951       ao2_ref(p->epa_entry, -1);
05952       p->epa_entry = NULL;
05953    }
05954 
05955    if (p->socket.tcptls_session) {
05956       ao2_ref(p->socket.tcptls_session, -1);
05957       p->socket.tcptls_session = NULL;
05958    }
05959 
05960    if (p->peerauth) {
05961       ao2_t_ref(p->peerauth, -1, "Removing active peer authentication");
05962       p->peerauth = NULL;
05963    }
05964 
05965    p->caps = ast_format_cap_destroy(p->caps);
05966    p->jointcaps = ast_format_cap_destroy(p->jointcaps);
05967    p->peercaps = ast_format_cap_destroy(p->peercaps);
05968    p->redircaps = ast_format_cap_destroy(p->redircaps);
05969    p->prefcaps = ast_format_cap_destroy(p->prefcaps);
05970 }
05971 
05972 /*! \brief  update_call_counter: Handle call_limit for SIP devices
05973  * Setting a call-limit will cause calls above the limit not to be accepted.
05974  *
05975  * Remember that for a type=friend, there's one limit for the user and
05976  * another for the peer, not a combined call limit.
05977  * This will cause unexpected behaviour in subscriptions, since a "friend"
05978  * is *two* devices in Asterisk, not one.
05979  *
05980  * Thought: For realtime, we should probably update storage with inuse counter...
05981  *
05982  * \return 0 if call is ok (no call limit, below threshold)
05983  * -1 on rejection of call
05984  *
05985  */
05986 static int update_call_counter(struct sip_pvt *fup, int event)
05987 {
05988    char name[256];
05989    int *inuse = NULL, *call_limit = NULL, *inringing = NULL;
05990    int outgoing = fup->outgoing_call;
05991    struct sip_peer *p = NULL;
05992 
05993    ast_debug(3, "Updating call counter for %s call\n", outgoing ? "outgoing" : "incoming");
05994 
05995 
05996    /* Test if we need to check call limits, in order to avoid
05997       realtime lookups if we do not need it */
05998    if (!ast_test_flag(&fup->flags[0], SIP_CALL_LIMIT) && !ast_test_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD))
05999       return 0;
06000 
06001    ast_copy_string(name, fup->username, sizeof(name));
06002 
06003    /* Check the list of devices */
06004    if (fup->relatedpeer) {
06005       p = sip_ref_peer(fup->relatedpeer, "ref related peer for update_call_counter");
06006       inuse = &p->inUse;
06007       call_limit = &p->call_limit;
06008       inringing = &p->inRinging;
06009       ast_copy_string(name, fup->peername, sizeof(name));
06010    }
06011    if (!p) {
06012       ast_debug(2, "%s is not a local device, no call limit\n", name);
06013       return 0;
06014    }
06015 
06016    switch(event) {
06017    /* incoming and outgoing affects the inUse counter */
06018    case DEC_CALL_LIMIT:
06019       /* Decrement inuse count if applicable */
06020       if (inuse) {
06021          sip_pvt_lock(fup);
06022          ao2_lock(p);
06023          if (*inuse > 0) {
06024             if (ast_test_flag(&fup->flags[0], SIP_INC_COUNT)) {
06025                (*inuse)--;
06026                ast_clear_flag(&fup->flags[0], SIP_INC_COUNT);
06027             }
06028          } else {
06029             *inuse = 0;
06030          }
06031          ao2_unlock(p);
06032          sip_pvt_unlock(fup);
06033       }
06034 
06035       /* Decrement ringing count if applicable */
06036       if (inringing) {
06037          sip_pvt_lock(fup);
06038          ao2_lock(p);
06039          if (*inringing > 0) {
06040             if (ast_test_flag(&fup->flags[0], SIP_INC_RINGING)) {
06041                (*inringing)--;
06042                ast_clear_flag(&fup->flags[0], SIP_INC_RINGING);
06043             }
06044          } else {
06045             *inringing = 0;
06046          }
06047          ao2_unlock(p);
06048          sip_pvt_unlock(fup);
06049       }
06050 
06051       /* Decrement onhold count if applicable */
06052       sip_pvt_lock(fup);
06053       ao2_lock(p);
06054       if (ast_test_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD) && sip_cfg.notifyhold) {
06055          ast_clear_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD);
06056          ao2_unlock(p);
06057          sip_pvt_unlock(fup);
06058          sip_peer_hold(fup, FALSE);
06059       } else {
06060          ao2_unlock(p);
06061          sip_pvt_unlock(fup);
06062       }
06063       if (sipdebug)
06064          ast_debug(2, "Call %s %s '%s' removed from call limit %d\n", outgoing ? "to" : "from", "peer", name, *call_limit);
06065       break;
06066 
06067    case INC_CALL_RINGING:
06068    case INC_CALL_LIMIT:
06069       /* If call limit is active and we have reached the limit, reject the call */
06070       if (*call_limit > 0 ) {
06071          if (*inuse >= *call_limit) {
06072             ast_log(LOG_NOTICE, "Call %s %s '%s' rejected due to usage limit of %d\n", outgoing ? "to" : "from", "peer", name, *call_limit);
06073             sip_unref_peer(p, "update_call_counter: unref peer p, call limit exceeded");
06074             return -1;
06075          }
06076       }
06077       if (inringing && (event == INC_CALL_RINGING)) {
06078          sip_pvt_lock(fup);
06079          ao2_lock(p);
06080          if (!ast_test_flag(&fup->flags[0], SIP_INC_RINGING)) {
06081             (*inringing)++;
06082             ast_set_flag(&fup->flags[0], SIP_INC_RINGING);
06083          }
06084          ao2_unlock(p);
06085          sip_pvt_unlock(fup);
06086       }
06087       if (inuse) {
06088          sip_pvt_lock(fup);
06089          ao2_lock(p);
06090          if (!ast_test_flag(&fup->flags[0], SIP_INC_COUNT)) {
06091             (*inuse)++;
06092             ast_set_flag(&fup->flags[0], SIP_INC_COUNT);
06093          }
06094          ao2_unlock(p);
06095          sip_pvt_unlock(fup);
06096       }
06097       if (sipdebug) {
06098          ast_debug(2, "Call %s %s '%s' is %d out of %d\n", outgoing ? "to" : "from", "peer", name, *inuse, *call_limit);
06099       }
06100       break;
06101 
06102    case DEC_CALL_RINGING:
06103       if (inringing) {
06104          sip_pvt_lock(fup);
06105          ao2_lock(p);
06106          if (ast_test_flag(&fup->flags[0], SIP_INC_RINGING)) {
06107             if (*inringing > 0) {
06108                (*inringing)--;
06109             }
06110             ast_clear_flag(&fup->flags[0], SIP_INC_RINGING);
06111          }
06112          ao2_unlock(p);
06113          sip_pvt_unlock(fup);
06114       }
06115       break;
06116 
06117    default:
06118       ast_log(LOG_ERROR, "update_call_counter(%s, %d) called with no event!\n", name, event);
06119    }
06120 
06121    if (p) {
06122       ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", p->name);
06123       sip_unref_peer(p, "update_call_counter: sip_unref_peer from call counter");
06124    }
06125    return 0;
06126 }
06127 
06128 
06129 static void sip_destroy_fn(void *p)
06130 {
06131    sip_destroy(p);
06132 }
06133 
06134 /*! \brief Destroy SIP call structure.
06135  * Make it return NULL so the caller can do things like
06136  * foo = sip_destroy(foo);
06137  * and reduce the chance of bugs due to dangling pointers.
06138  */
06139 struct sip_pvt *sip_destroy(struct sip_pvt *p)
06140 {
06141    ast_debug(3, "Destroying SIP dialog %s\n", p->callid);
06142    __sip_destroy(p, TRUE, TRUE);
06143    return NULL;
06144 }
06145 
06146 /*! \brief Convert SIP hangup causes to Asterisk hangup causes */
06147 int hangup_sip2cause(int cause)
06148 {
06149    /* Possible values taken from causes.h */
06150 
06151    switch(cause) {
06152       case 401:   /* Unauthorized */
06153          return AST_CAUSE_CALL_REJECTED;
06154       case 403:   /* Not found */
06155          return AST_CAUSE_CALL_REJECTED;
06156       case 404:   /* Not found */
06157          return AST_CAUSE_UNALLOCATED;
06158       case 405:   /* Method not allowed */
06159          return AST_CAUSE_INTERWORKING;
06160       case 407:   /* Proxy authentication required */
06161          return AST_CAUSE_CALL_REJECTED;
06162       case 408:   /* No reaction */
06163          return AST_CAUSE_NO_USER_RESPONSE;
06164       case 409:   /* Conflict */
06165          return AST_CAUSE_NORMAL_TEMPORARY_FAILURE;
06166       case 410:   /* Gone */
06167          return AST_CAUSE_NUMBER_CHANGED;
06168       case 411:   /* Length required */
06169          return AST_CAUSE_INTERWORKING;
06170       case 413:   /* Request entity too large */
06171          return AST_CAUSE_INTERWORKING;
06172       case 414:   /* Request URI too large */
06173          return AST_CAUSE_INTERWORKING;
06174       case 415:   /* Unsupported media type */
06175          return AST_CAUSE_INTERWORKING;
06176       case 420:   /* Bad extension */
06177          return AST_CAUSE_NO_ROUTE_DESTINATION;
06178       case 480:   /* No answer */
06179          return AST_CAUSE_NO_ANSWER;
06180       case 481:   /* No answer */
06181          return AST_CAUSE_INTERWORKING;
06182       case 482:   /* Loop detected */
06183          return AST_CAUSE_INTERWORKING;
06184       case 483:   /* Too many hops */
06185          return AST_CAUSE_NO_ANSWER;
06186       case 484:   /* Address incomplete */
06187          return AST_CAUSE_INVALID_NUMBER_FORMAT;
06188       case 485:   /* Ambiguous */
06189          return AST_CAUSE_UNALLOCATED;
06190       case 486:   /* Busy everywhere */
06191          return AST_CAUSE_BUSY;
06192       case 487:   /* Request terminated */
06193          return AST_CAUSE_INTERWORKING;
06194       case 488:   /* No codecs approved */
06195          return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
06196       case 491:   /* Request pending */
06197          return AST_CAUSE_INTERWORKING;
06198       case 493:   /* Undecipherable */
06199          return AST_CAUSE_INTERWORKING;
06200       case 500:   /* Server internal failure */
06201          return AST_CAUSE_FAILURE;
06202       case 501:   /* Call rejected */
06203          return AST_CAUSE_FACILITY_REJECTED;
06204       case 502:
06205          return AST_CAUSE_DESTINATION_OUT_OF_ORDER;
06206       case 503:   /* Service unavailable */
06207          return AST_CAUSE_CONGESTION;
06208       case 504:   /* Gateway timeout */
06209          return AST_CAUSE_RECOVERY_ON_TIMER_EXPIRE;
06210       case 505:   /* SIP version not supported */
06211          return AST_CAUSE_INTERWORKING;
06212       case 600:   /* Busy everywhere */
06213          return AST_CAUSE_USER_BUSY;
06214       case 603:   /* Decline */
06215          return AST_CAUSE_CALL_REJECTED;
06216       case 604:   /* Does not exist anywhere */
06217          return AST_CAUSE_UNALLOCATED;
06218       case 606:   /* Not acceptable */
06219          return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
06220       default:
06221          if (cause < 500 && cause >= 400) {
06222             /* 4xx class error that is unknown - someting wrong with our request */
06223             return AST_CAUSE_INTERWORKING;
06224          } else if (cause < 600 && cause >= 500) {
06225             /* 5xx class error - problem in the remote end */
06226             return AST_CAUSE_CONGESTION;
06227          } else if (cause < 700 && cause >= 600) {
06228             /* 6xx - global errors in the 4xx class */
06229             return AST_CAUSE_INTERWORKING;
06230          }
06231          return AST_CAUSE_NORMAL;
06232    }
06233    /* Never reached */
06234    return 0;
06235 }
06236 
06237 /*! \brief Convert Asterisk hangup causes to SIP codes
06238 \verbatim
06239  Possible values from causes.h
06240         AST_CAUSE_NOTDEFINED    AST_CAUSE_NORMAL        AST_CAUSE_BUSY
06241         AST_CAUSE_FAILURE       AST_CAUSE_CONGESTION    AST_CAUSE_UNALLOCATED
06242 
06243    In addition to these, a lot of PRI codes is defined in causes.h
06244    ...should we take care of them too ?
06245 
06246    Quote RFC 3398
06247 
06248    ISUP Cause value                        SIP response
06249    ----------------                        ------------
06250    1  unallocated number                   404 Not Found
06251    2  no route to network                  404 Not found
06252    3  no route to destination              404 Not found
06253    16 normal call clearing                 --- (*)
06254    17 user busy                            486 Busy here
06255    18 no user responding                   408 Request Timeout
06256    19 no answer from the user              480 Temporarily unavailable
06257    20 subscriber absent                    480 Temporarily unavailable
06258    21 call rejected                        403 Forbidden (+)
06259    22 number changed (w/o diagnostic)      410 Gone
06260    22 number changed (w/ diagnostic)       301 Moved Permanently
06261    23 redirection to new destination       410 Gone
06262    26 non-selected user clearing           404 Not Found (=)
06263    27 destination out of order             502 Bad Gateway
06264    28 address incomplete                   484 Address incomplete
06265    29 facility rejected                    501 Not implemented
06266    31 normal unspecified                   480 Temporarily unavailable
06267 \endverbatim
06268 */
06269 const char *hangup_cause2sip(int cause)
06270 {
06271    switch (cause) {
06272       case AST_CAUSE_UNALLOCATED:      /* 1 */
06273       case AST_CAUSE_NO_ROUTE_DESTINATION:   /* 3 IAX2: Can't find extension in context */
06274       case AST_CAUSE_NO_ROUTE_TRANSIT_NET:   /* 2 */
06275          return "404 Not Found";
06276       case AST_CAUSE_CONGESTION:    /* 34 */
06277       case AST_CAUSE_SWITCH_CONGESTION:   /* 42 */
06278          return "503 Service Unavailable";
06279       case AST_CAUSE_NO_USER_RESPONSE: /* 18 */
06280          return "408 Request Timeout";
06281       case AST_CAUSE_NO_ANSWER:     /* 19 */
06282       case AST_CAUSE_UNREGISTERED:        /* 20 */
06283          return "480 Temporarily unavailable";
06284       case AST_CAUSE_CALL_REJECTED:    /* 21 */
06285          return "403 Forbidden";
06286       case AST_CAUSE_NUMBER_CHANGED:      /* 22 */
06287          return "410 Gone";
06288       case AST_CAUSE_NORMAL_UNSPECIFIED:  /* 31 */
06289          return "480 Temporarily unavailable";
06290       case AST_CAUSE_INVALID_NUMBER_FORMAT:
06291          return "484 Address incomplete";
06292       case AST_CAUSE_USER_BUSY:
06293          return "486 Busy here";
06294       case AST_CAUSE_FAILURE:
06295          return "500 Server internal failure";
06296       case AST_CAUSE_FACILITY_REJECTED:   /* 29 */
06297          return "501 Not Implemented";
06298       case AST_CAUSE_CHAN_NOT_IMPLEMENTED:
06299          return "503 Service Unavailable";
06300       /* Used in chan_iax2 */
06301       case AST_CAUSE_DESTINATION_OUT_OF_ORDER:
06302          return "502 Bad Gateway";
06303       case AST_CAUSE_BEARERCAPABILITY_NOTAVAIL: /* Can't find codec to connect to host */
06304          return "488 Not Acceptable Here";
06305       case AST_CAUSE_INTERWORKING:  /* Unspecified Interworking issues */
06306          return "500 Network error";
06307 
06308       case AST_CAUSE_NOTDEFINED:
06309       default:
06310          ast_debug(1, "AST hangup cause %d (no match found in SIP)\n", cause);
06311          return NULL;
06312    }
06313 
06314    /* Never reached */
06315    return 0;
06316 }
06317 
06318 /*! \brief  sip_hangup: Hangup SIP call
06319  * Part of PBX interface, called from ast_hangup */
06320 static int sip_hangup(struct ast_channel *ast)
06321 {
06322    struct sip_pvt *p = ast->tech_pvt;
06323    int needcancel = FALSE;
06324    int needdestroy = 0;
06325    struct ast_channel *oldowner = ast;
06326 
06327    if (!p) {
06328       ast_debug(1, "Asked to hangup channel that was not connected\n");
06329       return 0;
06330    }
06331    if (ast_test_flag(ast, AST_FLAG_ANSWERED_ELSEWHERE) || ast->hangupcause == AST_CAUSE_ANSWERED_ELSEWHERE) {
06332       ast_debug(1, "This call was answered elsewhere");
06333       if (ast->hangupcause == AST_CAUSE_ANSWERED_ELSEWHERE) {
06334          ast_debug(1, "####### It's the cause code, buddy. The cause code!!!\n");
06335       }
06336       append_history(p, "Cancel", "Call answered elsewhere");
06337       p->answered_elsewhere = TRUE;
06338    }
06339 
06340    /* Store hangupcause locally in PVT so we still have it before disconnect */
06341    if (p->owner)
06342       p->hangupcause = p->owner->hangupcause;
06343 
06344    if (ast_test_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER)) {
06345       if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
06346          if (sipdebug)
06347             ast_debug(1, "update_call_counter(%s) - decrement call limit counter on hangup\n", p->username);
06348          update_call_counter(p, DEC_CALL_LIMIT);
06349       }
06350       ast_debug(4, "SIP Transfer: Not hanging up right now... Rescheduling hangup for %s.\n", p->callid);
06351       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
06352       ast_clear_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER); /* Really hang up next time */
06353       p->owner->tech_pvt = dialog_unref(p->owner->tech_pvt, "unref p->owner->tech_pvt");
06354       sip_pvt_lock(p);
06355       p->owner = NULL;  /* Owner will be gone after we return, so take it away */
06356       sip_pvt_unlock(p);
06357       ast_module_unref(ast_module_info->self);
06358       return 0;
06359    }
06360 
06361    if (ast_test_flag(ast, AST_FLAG_ZOMBIE)) {
06362       if (p->refer)
06363          ast_debug(1, "SIP Transfer: Hanging up Zombie channel %s after transfer ... Call-ID: %s\n", ast_channel_name(ast), p->callid);
06364       else
06365          ast_debug(1, "Hanging up zombie call. Be scared.\n");
06366    } else
06367       ast_debug(1, "Hangup call %s, SIP callid %s\n", ast_channel_name(ast), p->callid);
06368 
06369    sip_pvt_lock(p);
06370    if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
06371       if (sipdebug)
06372          ast_debug(1, "update_call_counter(%s) - decrement call limit counter on hangup\n", p->username);
06373       update_call_counter(p, DEC_CALL_LIMIT);
06374    }
06375 
06376    /* Determine how to disconnect */
06377    if (p->owner != ast) {
06378       ast_log(LOG_WARNING, "Huh?  We aren't the owner? Can't hangup call.\n");
06379       sip_pvt_unlock(p);
06380       return 0;
06381    }
06382    /* If the call is not UP, we need to send CANCEL instead of BYE */
06383    /* In case of re-invites, the call might be UP even though we have an incomplete invite transaction */
06384    if (p->invitestate < INV_COMPLETED && p->owner->_state != AST_STATE_UP) {
06385       needcancel = TRUE;
06386       ast_debug(4, "Hanging up channel in state %s (not UP)\n", ast_state2str(ast->_state));
06387    }
06388 
06389    stop_media_flows(p); /* Immediately stop RTP, VRTP and UDPTL as applicable */
06390 
06391    append_history(p, needcancel ? "Cancel" : "Hangup", "Cause %s", p->owner ? ast_cause2str(p->hangupcause) : "Unknown");
06392 
06393    /* Disconnect */
06394    disable_dsp_detect(p);
06395 
06396    p->owner = NULL;
06397    ast->tech_pvt = dialog_unref(ast->tech_pvt, "unref ast->tech_pvt");
06398 
06399    ast_module_unref(ast_module_info->self);
06400    /* Do not destroy this pvt until we have timeout or
06401       get an answer to the BYE or INVITE/CANCEL
06402       If we get no answer during retransmit period, drop the call anyway.
06403       (Sorry, mother-in-law, you can't deny a hangup by sending
06404       603 declined to BYE...)
06405    */
06406    if (p->alreadygone)
06407       needdestroy = 1;  /* Set destroy flag at end of this function */
06408    else if (p->invitestate != INV_CALLING)
06409       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
06410 
06411    /* Start the process if it's not already started */
06412    if (!p->alreadygone && p->initreq.data && !ast_strlen_zero(p->initreq.data->str)) {
06413       if (needcancel) { /* Outgoing call, not up */
06414          if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06415             /* if we can't send right now, mark it pending */
06416             if (p->invitestate == INV_CALLING) {
06417                /* We can't send anything in CALLING state */
06418                ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
06419                /* 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. */
06420                sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
06421                append_history(p, "DELAY", "Not sending cancel, waiting for timeout");
06422             } else {
06423                struct sip_pkt *cur;
06424 
06425                for (cur = p->packets; cur; cur = cur->next) {
06426                   __sip_semi_ack(p, cur->seqno, cur->is_resp, cur->method ? cur->method : find_sip_method(cur->data->str));
06427                }
06428                p->invitestate = INV_CANCELLED;
06429                /* Send a new request: CANCEL */
06430                transmit_request(p, SIP_CANCEL, p->lastinvite, XMIT_RELIABLE, FALSE);
06431                /* Actually don't destroy us yet, wait for the 487 on our original
06432                   INVITE, but do set an autodestruct just in case we never get it. */
06433                needdestroy = 0;
06434                sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
06435             }
06436          } else { /* Incoming call, not up */
06437             const char *res;
06438             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"));
06439             if (p->hangupcause && (res = hangup_cause2sip(p->hangupcause)))
06440                transmit_response_reliable(p, res, &p->initreq);
06441             else
06442                transmit_response_reliable(p, "603 Declined", &p->initreq);
06443             p->invitestate = INV_TERMINATED;
06444          }
06445       } else { /* Call is in UP state, send BYE */
06446          if (p->stimer->st_active == TRUE) {
06447             stop_session_timer(p);
06448          }
06449 
06450          if (!p->pendinginvite) {
06451             struct ast_channel *bridge = ast_bridged_channel(oldowner);
06452             char quality_buf[AST_MAX_USER_FIELD], *quality;
06453 
06454             /* We need to get the lock on bridge because ast_rtp_instance_set_stats_vars will attempt
06455              * to lock the bridge. This may get hairy...
06456              */
06457             while (bridge && ast_channel_trylock(bridge)) {
06458                sip_pvt_unlock(p);
06459                do {
06460                   CHANNEL_DEADLOCK_AVOIDANCE(oldowner);
06461                } while (sip_pvt_trylock(p));
06462                bridge = ast_bridged_channel(oldowner);
06463             }
06464 
06465             if (p->rtp) {
06466                ast_rtp_instance_set_stats_vars(oldowner, p->rtp);
06467             }
06468 
06469             if (bridge) {
06470                struct sip_pvt *q = bridge->tech_pvt;
06471 
06472                if (IS_SIP_TECH(bridge->tech) && q && q->rtp) {
06473                   ast_rtp_instance_set_stats_vars(bridge, q->rtp);
06474                }
06475                ast_channel_unlock(bridge);
06476             }
06477 
06478             if (p->do_history || oldowner) {
06479                if (p->rtp && (quality = ast_rtp_instance_get_quality(p->rtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY, quality_buf, sizeof(quality_buf)))) {
06480                   if (p->do_history) {
06481                      append_history(p, "RTCPaudio", "Quality:%s", quality);
06482                   }
06483                   if (oldowner) {
06484                      pbx_builtin_setvar_helper(oldowner, "RTPAUDIOQOS", quality);
06485                   }
06486                }
06487                if (p->vrtp && (quality = ast_rtp_instance_get_quality(p->vrtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY, quality_buf, sizeof(quality_buf)))) {
06488                   if (p->do_history) {
06489                      append_history(p, "RTCPvideo", "Quality:%s", quality);
06490                   }
06491                   if (oldowner) {
06492                      pbx_builtin_setvar_helper(oldowner, "RTPVIDEOQOS", quality);
06493                   }
06494                }
06495                if (p->trtp && (quality = ast_rtp_instance_get_quality(p->trtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY, quality_buf, sizeof(quality_buf)))) {
06496                   if (p->do_history) {
06497                      append_history(p, "RTCPtext", "Quality:%s", quality);
06498                   }
06499                   if (oldowner) {
06500                      pbx_builtin_setvar_helper(oldowner, "RTPTEXTQOS", quality);
06501                   }
06502                }
06503             }
06504 
06505             /* Send a hangup */
06506             if (oldowner->_state == AST_STATE_UP) {
06507                transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
06508             }
06509 
06510          } else {
06511             /* Note we will need a BYE when this all settles out
06512                but we can't send one while we have "INVITE" outstanding. */
06513             ast_set_flag(&p->flags[0], SIP_PENDINGBYE);  
06514             ast_clear_flag(&p->flags[0], SIP_NEEDREINVITE); 
06515             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"));
06516             if (sip_cancel_destroy(p))
06517                ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
06518          }
06519       }
06520    }
06521    if (needdestroy) {
06522       pvt_set_needdestroy(p, "hangup");
06523    }
06524    sip_pvt_unlock(p);
06525    return 0;
06526 }
06527 
06528 /*! \brief Try setting codec suggested by the SIP_CODEC channel variable */
06529 static void try_suggested_sip_codec(struct sip_pvt *p)
06530 {
06531    struct ast_format fmt;
06532    const char *codec;
06533 
06534    ast_format_clear(&fmt);
06535 
06536    if (p->outgoing_call) {
06537       codec = pbx_builtin_getvar_helper(p->owner, "SIP_CODEC_OUTBOUND");
06538    } else if (!(codec = pbx_builtin_getvar_helper(p->owner, "SIP_CODEC_INBOUND"))) {
06539       codec = pbx_builtin_getvar_helper(p->owner, "SIP_CODEC");
06540    }
06541 
06542    if (!codec) 
06543       return;
06544 
06545    ast_getformatbyname(codec, &fmt);
06546    if (fmt.id) {
06547       ast_log(LOG_NOTICE, "Changing codec to '%s' for this call because of ${SIP_CODEC} variable\n", codec);
06548       if (ast_format_cap_iscompatible(p->jointcaps, &fmt)) {
06549          ast_format_cap_set(p->jointcaps, &fmt);
06550          ast_format_cap_set(p->caps, &fmt);
06551       } else
06552          ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because it is not shared by both ends.\n");
06553    } else
06554       ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because of unrecognized/not configured codec (check allow/disallow in sip.conf): %s\n", codec);
06555    return;
06556 }
06557 
06558 /*! \brief  sip_answer: Answer SIP call , send 200 OK on Invite
06559  * Part of PBX interface */
06560 static int sip_answer(struct ast_channel *ast)
06561 {
06562    int res = 0;
06563    struct sip_pvt *p = ast->tech_pvt;
06564 
06565    sip_pvt_lock(p);
06566    if (ast->_state != AST_STATE_UP) {
06567       try_suggested_sip_codec(p);
06568 
06569       ast_setstate(ast, AST_STATE_UP);
06570       ast_debug(1, "SIP answering channel: %s\n", ast_channel_name(ast));
06571       ast_rtp_instance_update_source(p->rtp);
06572       res = transmit_response_with_sdp(p, "200 OK", &p->initreq, XMIT_CRITICAL, FALSE, TRUE);
06573       ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
06574    }
06575    sip_pvt_unlock(p);
06576    return res;
06577 }
06578 
06579 /*! \brief Send frame to media channel (rtp) */
06580 static int sip_write(struct ast_channel *ast, struct ast_frame *frame)
06581 {
06582    struct sip_pvt *p = ast->tech_pvt;
06583    int res = 0;
06584 
06585    switch (frame->frametype) {
06586    case AST_FRAME_VOICE:
06587       if (!(ast_format_cap_iscompatible(ast->nativeformats, &frame->subclass.format))) {
06588          char s1[512];
06589          ast_log(LOG_WARNING, "Asked to transmit frame type %s, while native formats is %s read/write = %s/%s\n",
06590             ast_getformatname(&frame->subclass.format),
06591             ast_getformatname_multiple(s1, sizeof(s1), ast->nativeformats),
06592             ast_getformatname(&ast->readformat),
06593             ast_getformatname(&ast->writeformat));
06594          return 0;
06595       }
06596       if (p) {
06597          sip_pvt_lock(p);
06598          if (p->t38.state == T38_ENABLED) {
06599             /* drop frame, can't sent VOICE frames while in T.38 mode */
06600             sip_pvt_unlock(p);
06601             break;
06602          } else if (p->rtp) {
06603             /* If channel is not up, activate early media session */
06604             if ((ast->_state != AST_STATE_UP) &&
06605                 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
06606                 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06607                ast_rtp_instance_update_source(p->rtp);
06608                if (!global_prematuremediafilter) {
06609                   p->invitestate = INV_EARLY_MEDIA;
06610                   transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
06611                   ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
06612                }
06613             }
06614             p->lastrtptx = time(NULL);
06615             res = ast_rtp_instance_write(p->rtp, frame);
06616          }
06617          sip_pvt_unlock(p);
06618       }
06619       break;
06620    case AST_FRAME_VIDEO:
06621       if (p) {
06622          sip_pvt_lock(p);
06623          if (p->vrtp) {
06624             /* Activate video early media */
06625             if ((ast->_state != AST_STATE_UP) &&
06626                 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
06627                 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06628                p->invitestate = INV_EARLY_MEDIA;
06629                transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
06630                ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
06631             }
06632             p->lastrtptx = time(NULL);
06633             res = ast_rtp_instance_write(p->vrtp, frame);
06634          }
06635          sip_pvt_unlock(p);
06636       }
06637       break;
06638    case AST_FRAME_TEXT:
06639       if (p) {
06640          sip_pvt_lock(p);
06641          if (p->red) {
06642             ast_rtp_red_buffer(p->trtp, frame);
06643          } else {
06644             if (p->trtp) {
06645                /* Activate text early media */
06646                if ((ast->_state != AST_STATE_UP) &&
06647                    !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
06648                    !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06649                   p->invitestate = INV_EARLY_MEDIA;
06650                   transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
06651                   ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
06652                }
06653                p->lastrtptx = time(NULL);
06654                res = ast_rtp_instance_write(p->trtp, frame);
06655             }
06656          }
06657          sip_pvt_unlock(p);
06658       }
06659       break;
06660    case AST_FRAME_IMAGE:
06661       return 0;
06662       break;
06663    case AST_FRAME_MODEM:
06664       if (p) {
06665          sip_pvt_lock(p);
06666          /* UDPTL requires two-way communication, so early media is not needed here.
06667             we simply forget the frames if we get modem frames before the bridge is up.
06668             Fax will re-transmit.
06669          */
06670          if ((ast->_state == AST_STATE_UP) &&
06671              p->udptl &&
06672              (p->t38.state == T38_ENABLED)) {
06673             res = ast_udptl_write(p->udptl, frame);
06674          }
06675          sip_pvt_unlock(p);
06676       }
06677       break;
06678    default:
06679       ast_log(LOG_WARNING, "Can't send %d type frames with SIP write\n", frame->frametype);
06680       return 0;
06681    }
06682 
06683    return res;
06684 }
06685 
06686 /*! \brief  sip_fixup: Fix up a channel:  If a channel is consumed, this is called.
06687         Basically update any ->owner links */
06688 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
06689 {
06690    int ret = -1;
06691    struct sip_pvt *p;
06692 
06693    if (newchan && ast_test_flag(newchan, AST_FLAG_ZOMBIE))
06694       ast_debug(1, "New channel is zombie\n");
06695    if (oldchan && ast_test_flag(oldchan, AST_FLAG_ZOMBIE))
06696       ast_debug(1, "Old channel is zombie\n");
06697 
06698    if (!newchan || !newchan->tech_pvt) {
06699       if (!newchan)
06700          ast_log(LOG_WARNING, "No new channel! Fixup of %s failed.\n", ast_channel_name(oldchan));
06701       else
06702          ast_log(LOG_WARNING, "No SIP tech_pvt! Fixup of %s failed.\n", ast_channel_name(oldchan));
06703       return -1;
06704    }
06705    p = newchan->tech_pvt;
06706 
06707    sip_pvt_lock(p);
06708    append_history(p, "Masq", "Old channel: %s\n", ast_channel_name(oldchan));
06709    append_history(p, "Masq (cont)", "...new owner: %s\n", ast_channel_name(newchan));
06710    if (p->owner != oldchan)
06711       ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, p->owner);
06712    else {
06713       p->owner = newchan;
06714       /* Re-invite RTP back to Asterisk. Needed if channel is masqueraded out of a native
06715          RTP bridge (i.e., RTP not going through Asterisk): RTP bridge code might not be
06716          able to do this if the masquerade happens before the bridge breaks (e.g., AMI
06717          redirect of both channels). Note that a channel can not be masqueraded *into*
06718          a native bridge. So there is no danger that this breaks a native bridge that
06719          should stay up. */
06720       sip_set_rtp_peer(newchan, NULL, NULL, 0, 0, 0);
06721       ret = 0;
06722    }
06723    ast_debug(3, "SIP Fixup: New owner for dialogue %s: %s (Old parent: %s)\n", p->callid, ast_channel_name(p->owner), ast_channel_name(oldchan));
06724 
06725    sip_pvt_unlock(p);
06726    return ret;
06727 }
06728 
06729 static int sip_senddigit_begin(struct ast_channel *ast, char digit)
06730 {
06731    struct sip_pvt *p = ast->tech_pvt;
06732    int res = 0;
06733 
06734    sip_pvt_lock(p);
06735    switch (ast_test_flag(&p->flags[0], SIP_DTMF)) {
06736    case SIP_DTMF_INBAND:
06737       res = -1; /* Tell Asterisk to generate inband indications */
06738       break;
06739    case SIP_DTMF_RFC2833:
06740       if (p->rtp)
06741          ast_rtp_instance_dtmf_begin(p->rtp, digit);
06742       break;
06743    default:
06744       break;
06745    }
06746    sip_pvt_unlock(p);
06747 
06748    return res;
06749 }
06750 
06751 /*! \brief Send DTMF character on SIP channel
06752    within one call, we're able to transmit in many methods simultaneously */
06753 static int sip_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration)
06754 {
06755    struct sip_pvt *p = ast->tech_pvt;
06756    int res = 0;
06757 
06758    sip_pvt_lock(p);
06759    switch (ast_test_flag(&p->flags[0], SIP_DTMF)) {
06760    case SIP_DTMF_INFO:
06761    case SIP_DTMF_SHORTINFO:
06762       transmit_info_with_digit(p, digit, duration);
06763       break;
06764    case SIP_DTMF_RFC2833:
06765       if (p->rtp)
06766          ast_rtp_instance_dtmf_end_with_duration(p->rtp, digit, duration);
06767       break;
06768    case SIP_DTMF_INBAND:
06769       res = -1; /* Tell Asterisk to stop inband indications */
06770       break;
06771    }
06772    sip_pvt_unlock(p);
06773 
06774    return res;
06775 }
06776 
06777 /*! \brief Transfer SIP call */
06778 static int sip_transfer(struct ast_channel *ast, const char *dest)
06779 {
06780    struct sip_pvt *p = ast->tech_pvt;
06781    int res;
06782 
06783    if (dest == NULL) /* functions below do not take a NULL */
06784       dest = "";
06785    sip_pvt_lock(p);
06786    if (ast->_state == AST_STATE_RING)
06787       res = sip_sipredirect(p, dest);
06788    else
06789       res = transmit_refer(p, dest);
06790    sip_pvt_unlock(p);
06791    return res;
06792 }
06793 
06794 /*! \brief Helper function which updates T.38 capability information and triggers a reinvite */
06795 static int interpret_t38_parameters(struct sip_pvt *p, const struct ast_control_t38_parameters *parameters)
06796 {
06797    int res = 0;
06798 
06799    if (!ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) || !p->udptl) {
06800       return -1;
06801    }
06802    switch (parameters->request_response) {
06803    case AST_T38_NEGOTIATED:
06804    case AST_T38_REQUEST_NEGOTIATE:         /* Request T38 */
06805       /* Negotiation can not take place without a valid max_ifp value. */
06806       if (!parameters->max_ifp) {
06807          if (p->t38.state == T38_PEER_REINVITE) {
06808             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"));
06809             transmit_response_reliable(p, "488 Not acceptable here", &p->initreq);
06810          }
06811          change_t38_state(p, T38_REJECTED);
06812          break;
06813       } else if (p->t38.state == T38_PEER_REINVITE) {
06814          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"));
06815          p->t38.our_parms = *parameters;
06816          /* modify our parameters to conform to the peer's parameters,
06817           * based on the rules in the ITU T.38 recommendation
06818           */
06819          if (!p->t38.their_parms.fill_bit_removal) {
06820             p->t38.our_parms.fill_bit_removal = FALSE;
06821          }
06822          if (!p->t38.their_parms.transcoding_mmr) {
06823             p->t38.our_parms.transcoding_mmr = FALSE;
06824          }
06825          if (!p->t38.their_parms.transcoding_jbig) {
06826             p->t38.our_parms.transcoding_jbig = FALSE;
06827          }
06828          p->t38.our_parms.version = MIN(p->t38.our_parms.version, p->t38.their_parms.version);
06829          p->t38.our_parms.rate_management = p->t38.their_parms.rate_management;
06830          ast_udptl_set_local_max_ifp(p->udptl, p->t38.our_parms.max_ifp);
06831          change_t38_state(p, T38_ENABLED);
06832          transmit_response_with_t38_sdp(p, "200 OK", &p->initreq, XMIT_CRITICAL);
06833       } else if (p->t38.state != T38_ENABLED) {
06834          p->t38.our_parms = *parameters;
06835          ast_udptl_set_local_max_ifp(p->udptl, p->t38.our_parms.max_ifp);
06836          change_t38_state(p, T38_LOCAL_REINVITE);
06837          if (!p->pendinginvite) {
06838             transmit_reinvite_with_sdp(p, TRUE, FALSE);
06839          } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
06840             ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
06841          }
06842       }
06843       break;
06844    case AST_T38_TERMINATED:
06845    case AST_T38_REFUSED:
06846    case AST_T38_REQUEST_TERMINATE:         /* Shutdown T38 */
06847       if (p->t38.state == T38_PEER_REINVITE) {
06848          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"));
06849          change_t38_state(p, T38_REJECTED);
06850          transmit_response_reliable(p, "488 Not acceptable here", &p->initreq);
06851       } else if (p->t38.state == T38_ENABLED)
06852          transmit_reinvite_with_sdp(p, FALSE, FALSE);
06853       break;
06854    case AST_T38_REQUEST_PARMS: {    /* Application wants remote's parameters re-sent */
06855       struct ast_control_t38_parameters parameters = p->t38.their_parms;
06856 
06857       if (p->t38.state == T38_PEER_REINVITE) {
06858          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"));
06859          parameters.max_ifp = ast_udptl_get_far_max_ifp(p->udptl);
06860          parameters.request_response = AST_T38_REQUEST_NEGOTIATE;
06861          ast_queue_control_data(p->owner, AST_CONTROL_T38_PARAMETERS, &parameters, sizeof(parameters));
06862          /* we need to return a positive value here, so that applications that
06863           * send this request can determine conclusively whether it was accepted or not...
06864           * older versions of chan_sip would just silently accept it and return zero.
06865           */
06866          res = AST_T38_REQUEST_PARMS;
06867       }
06868       break;
06869    }
06870    default:
06871       res = -1;
06872       break;
06873    }
06874 
06875    return res;
06876 }
06877 
06878 /*! \internal \brief Create and initialize UDPTL for the specified dialog
06879  * \param p SIP private structure to create UDPTL object for
06880  * \pre p is locked
06881  * \pre p->owner is locked
06882  *
06883  * \note In the case of failure, SIP_PAGE2_T38SUPPORT is cleared on p
06884  *
06885  * \return 0 on success, any other value on failure
06886  */
06887 static int initialize_udptl(struct sip_pvt *p)
06888 {
06889    int natflags = ast_test_flag(&p->flags[1], SIP_PAGE2_SYMMETRICRTP);
06890 
06891    if (!ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT)) {
06892       return 1;
06893    }
06894 
06895    /* If we've already initialized T38, don't take any further action */
06896    if (p->udptl) {
06897       return 0;
06898    }
06899 
06900    /* T38 can be supported by this dialog, create it and set the derived properties */
06901    if ((p->udptl = ast_udptl_new_with_bindaddr(sched, io, 0, &bindaddr))) {
06902       if (p->owner) {
06903          ast_channel_set_fd(p->owner, 5, ast_udptl_fd(p->udptl));
06904       }
06905 
06906       ast_udptl_setqos(p->udptl, global_tos_audio, global_cos_audio);
06907       p->t38_maxdatagram = p->relatedpeer ? p->relatedpeer->t38_maxdatagram : global_t38_maxdatagram;
06908       set_t38_capabilities(p);
06909 
06910       ast_debug(1, "Setting NAT on UDPTL to %s\n", natflags ? "On" : "Off");
06911       ast_udptl_setnat(p->udptl, natflags);
06912    } else {
06913       ast_log(AST_LOG_WARNING, "UDPTL creation failed - disabling T38 for this dialog\n");
06914       ast_clear_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT);
06915       return 1;
06916    }
06917 
06918    return 0;
06919 }
06920 
06921 /*! \brief Play indication to user
06922  * With SIP a lot of indications is sent as messages, letting the device play
06923    the indication - busy signal, congestion etc
06924    \return -1 to force ast_indicate to send indication in audio, 0 if SIP can handle the indication by sending a message
06925 */
06926 static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen)
06927 {
06928    struct sip_pvt *p = ast->tech_pvt;
06929    int res = 0;
06930 
06931    sip_pvt_lock(p);
06932    switch(condition) {
06933    case AST_CONTROL_RINGING:
06934       if (ast->_state == AST_STATE_RING) {
06935          p->invitestate = INV_EARLY_MEDIA;
06936          if (!ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) ||
06937              (ast_test_flag(&p->flags[0], SIP_PROG_INBAND) == SIP_PROG_INBAND_NEVER)) {            
06938             /* Send 180 ringing if out-of-band seems reasonable */
06939             transmit_provisional_response(p, "180 Ringing", &p->initreq, 0);
06940             ast_set_flag(&p->flags[0], SIP_RINGING);
06941             if (ast_test_flag(&p->flags[0], SIP_PROG_INBAND) != SIP_PROG_INBAND_YES)
06942                break;
06943          } else {
06944             /* Well, if it's not reasonable, just send in-band */
06945          }
06946       }
06947       res = -1;
06948       break;
06949    case AST_CONTROL_BUSY:
06950       if (ast->_state != AST_STATE_UP) {
06951          transmit_response_reliable(p, "486 Busy Here", &p->initreq);
06952          p->invitestate = INV_COMPLETED;
06953          sip_alreadygone(p);
06954          ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
06955          break;
06956       }
06957       res = -1;
06958       break;
06959    case AST_CONTROL_CONGESTION:
06960       if (ast->_state != AST_STATE_UP) {
06961          transmit_response_reliable(p, "503 Service Unavailable", &p->initreq);
06962          p->invitestate = INV_COMPLETED;
06963          sip_alreadygone(p);
06964          ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
06965          break;
06966       }
06967       res = -1;
06968       break;
06969    case AST_CONTROL_INCOMPLETE:
06970       if (ast->_state != AST_STATE_UP) {
06971          switch (ast_test_flag(&p->flags[1], SIP_PAGE2_ALLOWOVERLAP)) {
06972          case SIP_PAGE2_ALLOWOVERLAP_YES:
06973             transmit_response_reliable(p, "484 Address Incomplete", &p->initreq);
06974             p->invitestate = INV_COMPLETED;
06975             sip_alreadygone(p);
06976             ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
06977             break;
06978          case SIP_PAGE2_ALLOWOVERLAP_DTMF:
06979             /* Just wait for inband DTMF digits */
06980             break;
06981          default:
06982             /* it actually means no support for overlap */
06983             transmit_response_reliable(p, "404 Not Found", &p->initreq);
06984             p->invitestate = INV_COMPLETED;
06985             sip_alreadygone(p);
06986             ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
06987             break;
06988          }
06989       }
06990       break;
06991    case AST_CONTROL_PROCEEDING:
06992       if ((ast->_state != AST_STATE_UP) &&
06993           !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
06994           !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06995          transmit_response(p, "100 Trying", &p->initreq);
06996          p->invitestate = INV_PROCEEDING;
06997          break;
06998       }
06999       res = -1;
07000       break;
07001    case AST_CONTROL_PROGRESS:
07002       if ((ast->_state != AST_STATE_UP) &&
07003           !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
07004           !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
07005          p->invitestate = INV_EARLY_MEDIA;
07006          transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
07007          ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
07008          break;
07009       }
07010       res = -1;
07011       break;
07012    case AST_CONTROL_HOLD:
07013       ast_rtp_instance_update_source(p->rtp);
07014       ast_moh_start(ast, data, p->mohinterpret);
07015       break;
07016    case AST_CONTROL_UNHOLD:
07017       ast_rtp_instance_update_source(p->rtp);
07018       ast_moh_stop(ast);
07019       break;
07020    case AST_CONTROL_VIDUPDATE:   /* Request a video frame update */
07021       if (p->vrtp && !p->novideo) {
07022          transmit_info_with_vidupdate(p);
07023          /* ast_rtcp_send_h261fur(p->vrtp); */
07024       } else
07025          res = -1;
07026       break;
07027    case AST_CONTROL_T38_PARAMETERS:
07028       res = -1;
07029       if (datalen != sizeof(struct ast_control_t38_parameters)) {
07030          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);
07031       } else {
07032          const struct ast_control_t38_parameters *parameters = data;
07033          if (!initialize_udptl(p)) {
07034             res = interpret_t38_parameters(p, parameters);
07035          }
07036       }
07037       break;
07038    case AST_CONTROL_SRCUPDATE:
07039       ast_rtp_instance_update_source(p->rtp);
07040       break;
07041    case AST_CONTROL_SRCCHANGE:
07042       ast_rtp_instance_change_source(p->rtp);
07043       break;
07044    case AST_CONTROL_CONNECTED_LINE:
07045       update_connectedline(p, data, datalen);
07046       break;
07047    case AST_CONTROL_REDIRECTING:
07048       update_redirecting(p, data, datalen);
07049       break;
07050    case AST_CONTROL_AOC:
07051       {
07052          struct ast_aoc_decoded *decoded = ast_aoc_decode((struct ast_aoc_encoded *) data, datalen, ast);
07053          if (!decoded) {
07054             ast_log(LOG_ERROR, "Error decoding indicated AOC data\n");
07055             res = -1;
07056             break;
07057          }
07058          switch (ast_aoc_get_msg_type(decoded)) {
07059          case AST_AOC_REQUEST:
07060             if (ast_aoc_get_termination_request(decoded)) {
07061                /* TODO, once there is a way to get AOC-E on hangup, attempt that here
07062                 * before hanging up the channel.*/
07063 
07064                /* The other side has already initiated the hangup. This frame
07065                 * just says they are waiting to get AOC-E before completely tearing
07066                 * the call down.  Since SIP does not support this at the moment go
07067                 * ahead and terminate the call here to avoid an unnecessary timeout. */
07068                ast_debug(1, "AOC-E termination request received on %s. This is not yet supported on sip. Continue with hangup \n", ast_channel_name(p->owner));
07069                ast_softhangup_nolock(p->owner, AST_SOFTHANGUP_DEV);
07070             }
07071             break;
07072          case AST_AOC_D:
07073          case AST_AOC_E:
07074             if (ast_test_flag(&p->flags[2], SIP_PAGE3_SNOM_AOC)) {
07075                transmit_info_with_aoc(p, decoded);
07076             }
07077             break;
07078          case AST_AOC_S: /* S not supported yet */
07079          default:
07080             break;
07081          }
07082          ast_aoc_destroy_decoded(decoded);
07083       }
07084       break;
07085    case AST_CONTROL_UPDATE_RTP_PEER: /* Absorb this since it is handled by the bridge */
07086       break;
07087    case -1:
07088       res = -1;
07089       break;
07090    default:
07091       ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", condition);
07092       res = -1;
07093       break;
07094    }
07095    sip_pvt_unlock(p);
07096    return res;
07097 }
07098 
07099 /*!
07100  * \brief Initiate a call in the SIP channel
07101  *
07102  * \note called from sip_request_call (calls from the pbx ) for
07103  * outbound channels and from handle_request_invite for inbound
07104  * channels
07105  *
07106  * \pre i is locked
07107  *
07108  * \return New ast_channel locked.
07109  */
07110 static struct ast_channel *sip_new(struct sip_pvt *i, int state, const char *title, const char *linkedid)
07111 {
07112    struct ast_channel *tmp;
07113    struct ast_variable *v = NULL;
07114    struct ast_format fmt;
07115    struct ast_format_cap *what = NULL; /* SHALLOW COPY DO NOT DESTROY! */
07116    int needvideo = 0;
07117    int needtext = 0;
07118    char buf[SIPBUFSIZE];
07119    char *exten;
07120 
07121    {
07122       const char *my_name; /* pick a good name */
07123    
07124       if (title) {
07125          my_name = title;
07126       } else {
07127          my_name = ast_strdupa(i->fromdomain);
07128       }
07129 
07130       sip_pvt_unlock(i);
07131       /* Don't hold a sip pvt lock while we allocate a channel */
07132       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));
07133    }
07134    if (!tmp) {
07135       ast_log(LOG_WARNING, "Unable to allocate AST channel structure for SIP channel\n");
07136       sip_pvt_lock(i);
07137       return NULL;
07138    }
07139    ast_channel_lock(tmp);
07140    sip_pvt_lock(i);
07141    ast_channel_cc_params_init(tmp, i->cc_params);
07142    tmp->caller.id.tag = ast_strdup(i->cid_tag);
07143 
07144    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;
07145 
07146    /* Select our native format based on codec preference until we receive
07147       something from another device to the contrary. */
07148    if (!(ast_format_cap_is_empty(i->jointcaps))) { /* The joint capabilities of us and peer */
07149       what = i->jointcaps;
07150    } else if (!(ast_format_cap_is_empty(i->caps))) {     /* Our configured capability for this peer */
07151       what = i->caps;
07152    } else {
07153       what = sip_cfg.caps;
07154    }
07155 
07156    /* Set the native formats */
07157    ast_format_cap_copy(tmp->nativeformats, what);
07158    /* choose and use only the best audio format for our native formats */
07159    ast_codec_choose(&i->prefs, tmp->nativeformats, 1, &fmt); /* get the best audio format */
07160    ast_format_cap_remove_bytype(tmp->nativeformats, AST_FORMAT_TYPE_AUDIO); /* remove only the other audio formats */
07161    ast_format_cap_add(tmp->nativeformats, &fmt); /* add our best choice back */
07162 
07163    ast_debug(3, "*** Our native formats are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, tmp->nativeformats));
07164    ast_debug(3, "*** Joint capabilities are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, i->jointcaps));
07165    ast_debug(3, "*** Our capabilities are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, i->caps));
07166    ast_debug(3, "*** AST_CODEC_CHOOSE formats are %s \n", ast_getformatname(&fmt));
07167    if (!ast_format_cap_is_empty(i->prefcaps)) {
07168       ast_debug(3, "*** Our preferred formats from the incoming channel are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, i->prefcaps));
07169    }
07170 
07171    /* If we have a prefcodec setting, we have an inbound channel that set a
07172       preferred format for this call. Otherwise, we check the jointcapability
07173       We also check for vrtp. If it's not there, we are not allowed do any video anyway.
07174     */
07175    if (i->vrtp) {
07176       if (ast_test_flag(&i->flags[1], SIP_PAGE2_VIDEOSUPPORT))
07177          needvideo = 1;
07178       else if (!ast_format_cap_is_empty(i->prefcaps))
07179          needvideo = ast_format_cap_has_type(i->prefcaps, AST_FORMAT_TYPE_VIDEO);   /* Outbound call */
07180       else
07181          needvideo = ast_format_cap_has_type(i->jointcaps, AST_FORMAT_TYPE_VIDEO);  /* Inbound call */
07182    }
07183 
07184    if (i->trtp) {
07185       if (!ast_format_cap_is_empty(i->prefcaps))
07186          needtext = ast_format_cap_has_type(i->prefcaps, AST_FORMAT_TYPE_TEXT);  /* Outbound call */
07187       else
07188          needtext = ast_format_cap_has_type(i->jointcaps, AST_FORMAT_TYPE_TEXT); /* Inbound call */
07189    }
07190 
07191    if (needvideo) {
07192       ast_debug(3, "This channel can handle video! HOLLYWOOD next!\n");
07193    } else {
07194       ast_debug(3, "This channel will not be able to handle video.\n");
07195    }
07196 
07197    enable_dsp_detect(i);
07198 
07199    if ((ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) ||
07200        (ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_AUTO)) {
07201       if (i->rtp) {
07202          ast_rtp_instance_dtmf_mode_set(i->rtp, AST_RTP_DTMF_MODE_INBAND);
07203       }
07204    } else if (ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) {
07205       if (i->rtp) {
07206          ast_rtp_instance_dtmf_mode_set(i->rtp, AST_RTP_DTMF_MODE_RFC2833);
07207       }
07208    }
07209 
07210    /* Set file descriptors for audio, video, and realtime text.  Since
07211     * UDPTL is created as needed in the lifetime of a dialog, its file
07212     * descriptor is set in initialize_udptl */
07213    if (i->rtp) {
07214       ast_channel_set_fd(tmp, 0, ast_rtp_instance_fd(i->rtp, 0));
07215       ast_channel_set_fd(tmp, 1, ast_rtp_instance_fd(i->rtp, 1));
07216    }
07217    if (needvideo && i->vrtp) {
07218       ast_channel_set_fd(tmp, 2, ast_rtp_instance_fd(i->vrtp, 0));
07219       ast_channel_set_fd(tmp, 3, ast_rtp_instance_fd(i->vrtp, 1));
07220    }
07221    if (needtext && i->trtp) {
07222       ast_channel_set_fd(tmp, 4, ast_rtp_instance_fd(i->trtp, 0));
07223    }
07224    if (i->udptl) {
07225       ast_channel_set_fd(tmp, 5, ast_udptl_fd(i->udptl));
07226    }
07227 
07228    if (state == AST_STATE_RING) {
07229       tmp->rings = 1;
07230    }
07231    tmp->adsicpe = AST_ADSI_UNAVAILABLE;
07232 
07233    ast_format_copy(&tmp->writeformat, &fmt);
07234    ast_format_copy(&tmp->rawwriteformat, &fmt);
07235    ast_rtp_instance_set_write_format(i->rtp, &fmt);
07236 
07237    ast_format_copy(&tmp->readformat, &fmt);
07238    ast_format_copy(&tmp->rawreadformat, &fmt);
07239    ast_rtp_instance_set_read_format(i->rtp, &fmt);
07240 
07241    tmp->tech_pvt = dialog_ref(i, "sip_new: set chan->tech_pvt to i");
07242 
07243    tmp->callgroup = i->callgroup;
07244    tmp->pickupgroup = i->pickupgroup;
07245    tmp->caller.id.name.presentation = i->callingpres;
07246    tmp->caller.id.number.presentation = i->callingpres;
07247    if (!ast_strlen_zero(i->parkinglot)) {
07248       ast_channel_parkinglot_set(tmp, i->parkinglot);
07249    }
07250    if (!ast_strlen_zero(i->accountcode)) {
07251       ast_channel_accountcode_set(tmp, i->accountcode);
07252    }
07253    if (i->amaflags) {
07254       tmp->amaflags = i->amaflags;
07255    }
07256    if (!ast_strlen_zero(i->language)) {
07257       ast_channel_language_set(tmp, i->language);
07258    }
07259    if (!ast_strlen_zero(i->zone)) {
07260       if (!(tmp->zone = ast_get_indication_zone(i->zone))) {
07261          ast_log(LOG_ERROR, "Unknown country code '%s' for tonezone. Check indications.conf for available country codes.\n", i->zone);
07262       } 
07263    }
07264    i->owner = tmp;
07265    ast_module_ref(ast_module_info->self);
07266    ast_copy_string(tmp->context, i->context, sizeof(tmp->context));
07267    /*Since it is valid to have extensions in the dialplan that have unescaped characters in them
07268     * we should decode the uri before storing it in the channel, but leave it encoded in the sip_pvt
07269     * structure so that there aren't issues when forming URI's
07270     */
07271    exten = ast_strdupa(i->exten);
07272    sip_pvt_unlock(i);
07273    ast_channel_unlock(tmp);
07274    if (!ast_exists_extension(NULL, i->context, i->exten, 1, i->cid_num)) {
07275       ast_uri_decode(exten, ast_uri_sip_user);
07276    }
07277    ast_channel_lock(tmp);
07278    sip_pvt_lock(i);
07279    ast_copy_string(tmp->exten, exten, sizeof(tmp->exten));
07280 
07281    /* Don't use ast_set_callerid() here because it will
07282     * generate an unnecessary NewCallerID event  */
07283    if (!ast_strlen_zero(i->cid_num)) {
07284       tmp->caller.ani.number.valid = 1;
07285       tmp->caller.ani.number.str = ast_strdup(i->cid_num);
07286    }
07287    if (!ast_strlen_zero(i->rdnis)) {
07288       tmp->redirecting.from.number.valid = 1;
07289       tmp->redirecting.from.number.str = ast_strdup(i->rdnis);
07290    }
07291 
07292    if (!ast_strlen_zero(i->exten) && strcmp(i->exten, "s")) {
07293       tmp->dialed.number.str = ast_strdup(i->exten);
07294    }
07295 
07296    tmp->priority = 1;
07297    if (!ast_strlen_zero(i->uri)) {
07298       pbx_builtin_setvar_helper(tmp, "SIPURI", i->uri);
07299    }
07300    if (!ast_strlen_zero(i->domain)) {
07301       pbx_builtin_setvar_helper(tmp, "SIPDOMAIN", i->domain);
07302    }
07303    if (!ast_strlen_zero(i->callid)) {
07304       pbx_builtin_setvar_helper(tmp, "SIPCALLID", i->callid);
07305    }
07306    if (i->rtp) {
07307       ast_jb_configure(tmp, &global_jbconf);
07308    }
07309 
07310    /* Set channel variables for this call from configuration */
07311    for (v = i->chanvars ; v ; v = v->next) {
07312       char valuebuf[1024];
07313       pbx_builtin_setvar_helper(tmp, v->name, ast_get_encoded_str(v->value, valuebuf, sizeof(valuebuf)));
07314    }
07315 
07316    if (i->do_history) {
07317       append_history(i, "NewChan", "Channel %s - from %s", ast_channel_name(tmp), i->callid);
07318    }
07319 
07320    /* Inform manager user about new channel and their SIP call ID */
07321    if (sip_cfg.callevents) {
07322       manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
07323          "Channel: %s\r\nUniqueid: %s\r\nChanneltype: %s\r\nSIPcallid: %s\r\nSIPfullcontact: %s\r\n",
07324          ast_channel_name(tmp), ast_channel_uniqueid(tmp), "SIP", i->callid, i->fullcontact);
07325    }
07326 
07327    return tmp;
07328 }
07329 
07330 /*! \brief Reads one line of SIP message body */
07331 static char *get_body_by_line(const char *line, const char *name, int nameLen, char delimiter)
07332 {
07333    if (!strncasecmp(line, name, nameLen) && line[nameLen] == delimiter) {
07334       return ast_skip_blanks(line + nameLen + 1);
07335    }
07336 
07337    return "";
07338 }
07339 
07340 /*! \brief Lookup 'name' in the SDP starting
07341  * at the 'start' line. Returns the matching line, and 'start'
07342  * is updated with the next line number.
07343  */
07344 static const char *get_sdp_iterate(int *start, struct sip_request *req, const char *name)
07345 {
07346    int len = strlen(name);
07347 
07348    while (*start < (req->sdp_start + req->sdp_count)) {
07349       const char *r = get_body_by_line(REQ_OFFSET_TO_STR(req, line[(*start)++]), name, len, '=');
07350       if (r[0] != '\0')
07351          return r;
07352    }
07353 
07354    /* if the line was not found, ensure that *start points past the SDP */
07355    (*start)++;
07356 
07357    return "";
07358 }
07359 
07360 /*! \brief Fetches the next valid SDP line between the 'start' line
07361  * (inclusive) and the 'stop' line (exclusive). Returns the type
07362  * ('a', 'c', ...) and matching line in reference 'start' is updated
07363  * with the next line number.
07364  */
07365 static char get_sdp_line(int *start, int stop, struct sip_request *req, const char **value)
07366 {
07367    char type = '\0';
07368    const char *line = NULL;
07369 
07370    if (stop > (req->sdp_start + req->sdp_count)) {
07371       stop = req->sdp_start + req->sdp_count;
07372    }
07373 
07374    while (*start < stop) {
07375       line = REQ_OFFSET_TO_STR(req, line[(*start)++]);
07376       if (line[1] == '=') {
07377          type = line[0];
07378          *value = ast_skip_blanks(line + 2);
07379          break;
07380       }
07381    }
07382 
07383    return type;
07384 }
07385 
07386 /*! \brief Get a specific line from the message body */
07387 static char *get_body(struct sip_request *req, char *name, char delimiter)
07388 {
07389    int x;
07390    int len = strlen(name);
07391    char *r;
07392 
07393    for (x = 0; x < req->lines; x++) {
07394       r = get_body_by_line(REQ_OFFSET_TO_STR(req, line[x]), name, len, delimiter);
07395       if (r[0] != '\0') {
07396          return r;
07397       }
07398    }
07399 
07400    return "";
07401 }
07402 
07403 /*! \brief Structure for conversion between compressed SIP and "normal" SIP headers */
07404 struct cfalias {
07405    const char *fullname;
07406    const char *shortname;
07407 };
07408 static const struct cfalias aliases[] = {
07409    { "Content-Type",           "c" },
07410    { "Content-Encoding",       "e" },
07411    { "From",                   "f" },
07412    { "Call-ID",                "i" },
07413    { "Contact",                "m" },
07414    { "Content-Length",         "l" },
07415    { "Subject",                "s" },
07416    { "To",                     "t" },
07417    { "Supported",              "k" },
07418    { "Refer-To",               "r" },
07419    { "Referred-By",            "b" },
07420    { "Allow-Events",           "u" },
07421    { "Event",                  "o" },
07422    { "Via",                    "v" },
07423    { "Accept-Contact",         "a" },
07424    { "Reject-Contact",         "j" },
07425    { "Request-Disposition",    "d" },
07426    { "Session-Expires",        "x" },
07427    { "Identity",               "y" },
07428    { "Identity-Info",          "n" },
07429 };
07430 
07431 /*! \brief Find compressed SIP alias */
07432 static const char *find_alias(const char *name, const char *_default)
07433 {
07434    int x;
07435 
07436    for (x = 0; x < ARRAY_LEN(aliases); x++) {
07437       if (!strcasecmp(aliases[x].fullname, name))
07438          return aliases[x].shortname;
07439    }
07440 
07441    return _default;
07442 }
07443 
07444 /*! \brief Find full SIP alias */
07445 static const char *find_full_alias(const char *name, const char *_default)
07446 {
07447    int x;
07448 
07449    if (strlen(name) == 1) {
07450       /* We have a short header name to convert. */
07451       for (x = 0; x < ARRAY_LEN(aliases); ++x) {
07452          if (!strcasecmp(aliases[x].shortname, name))
07453             return aliases[x].fullname;
07454       }
07455    }
07456 
07457    return _default;
07458 }
07459 
07460 static const char *__get_header(const struct sip_request *req, const char *name, int *start)
07461 {
07462    /*
07463     * Technically you can place arbitrary whitespace both before and after the ':' in
07464     * a header, although RFC3261 clearly says you shouldn't before, and place just
07465     * one afterwards.  If you shouldn't do it, what absolute idiot decided it was
07466     * a good idea to say you can do it, and if you can do it, why in the hell would.
07467     * you say you shouldn't.
07468     * Anyways, pedanticsipchecking controls whether we allow spaces before ':',
07469     * and we always allow spaces after that for compatibility.
07470     */
07471    const char *sname = find_alias(name, NULL);
07472    int x, len = strlen(name), slen = (sname ? 1 : 0);
07473    for (x = *start; x < req->headers; x++) {
07474       const char *header = REQ_OFFSET_TO_STR(req, header[x]);
07475       int smatch = 0, match = !strncasecmp(header, name, len);
07476       if (slen) {
07477          smatch = !strncasecmp(header, sname, slen);
07478       }
07479       if (match || smatch) {
07480          /* skip name */
07481          const char *r = header + (match ? len : slen );
07482          if (sip_cfg.pedanticsipchecking) {
07483             r = ast_skip_blanks(r);
07484          }
07485 
07486          if (*r == ':') {
07487             *start = x+1;
07488             return ast_skip_blanks(r+1);
07489          }
07490       }
07491    }
07492 
07493    /* Don't return NULL, so sip_get_header is always a valid pointer */
07494    return "";
07495 }
07496 
07497 /*! \brief Get header from SIP request
07498    \return Always return something, so don't check for NULL because it won't happen :-)
07499 */
07500 const char *sip_get_header(const struct sip_request *req, const char *name)
07501 {
07502    int start = 0;
07503    return __get_header(req, name, &start);
07504 }
07505 
07506 /*! \brief Read RTP from network */
07507 static struct ast_frame *sip_rtp_read(struct ast_channel *ast, struct sip_pvt *p, int *faxdetect)
07508 {
07509    /* Retrieve audio/etc from channel.  Assumes p->lock is already held. */
07510    struct ast_frame *f;
07511    
07512    if (!p->rtp) {
07513       /* We have no RTP allocated for this channel */
07514       return &ast_null_frame;
07515    }
07516 
07517    switch(ast->fdno) {
07518    case 0:
07519       f = ast_rtp_instance_read(p->rtp, 0);  /* RTP Audio */
07520       break;
07521    case 1:
07522       f = ast_rtp_instance_read(p->rtp, 1);  /* RTCP Control Channel */
07523       break;
07524    case 2:
07525       f = ast_rtp_instance_read(p->vrtp, 0); /* RTP Video */
07526       break;
07527    case 3:
07528       f = ast_rtp_instance_read(p->vrtp, 1); /* RTCP Control Channel for video */
07529       break;
07530    case 4:
07531       f = ast_rtp_instance_read(p->trtp, 0); /* RTP Text */
07532       if (sipdebug_text) {
07533          struct ast_str *out = ast_str_create(f->datalen * 4 + 6);
07534          int i;
07535          unsigned char* arr = f->data.ptr;
07536          do {
07537             if (!out) {
07538                break;
07539             }
07540             for (i = 0; i < f->datalen; i++) {
07541                ast_str_append(&out, 0, "%c", (arr[i] > ' ' && arr[i] < '}') ? arr[i] : '.');
07542             }
07543             ast_str_append(&out, 0, " -> ");
07544             for (i = 0; i < f->datalen; i++) {
07545                ast_str_append(&out, 0, "%02X ", arr[i]);
07546             }
07547             ast_verb(0, "%s\n", ast_str_buffer(out));
07548             ast_free(out);
07549          } while (0);
07550       }
07551       break;
07552    case 5:
07553       f = ast_udptl_read(p->udptl); /* UDPTL for T.38 */
07554       break;
07555    default:
07556       f = &ast_null_frame;
07557    }
07558    /* Don't forward RFC2833 if we're not supposed to */
07559    if (f && (f->frametype == AST_FRAME_DTMF_BEGIN || f->frametype == AST_FRAME_DTMF_END) &&
07560        (ast_test_flag(&p->flags[0], SIP_DTMF) != SIP_DTMF_RFC2833)) {
07561       ast_debug(1, "Ignoring DTMF (%c) RTP frame because dtmfmode is not RFC2833\n", f->subclass.integer);
07562       return &ast_null_frame;
07563    }
07564 
07565    /* We already hold the channel lock */
07566    if (!p->owner || (f && f->frametype != AST_FRAME_VOICE)) {
07567       return f;
07568    }
07569 
07570    if (f && !ast_format_cap_iscompatible(p->owner->nativeformats, &f->subclass.format)) {
07571       if (!ast_format_cap_iscompatible(p->jointcaps, &f->subclass.format)) {
07572          ast_debug(1, "Bogus frame of format '%s' received from '%s'!\n",
07573             ast_getformatname(&f->subclass.format), ast_channel_name(p->owner));
07574          return &ast_null_frame;
07575       }
07576       ast_debug(1, "Oooh, format changed to %s\n",
07577          ast_getformatname(&f->subclass.format));
07578       ast_format_cap_remove_bytype(p->owner->nativeformats, AST_FORMAT_TYPE_AUDIO);
07579       ast_format_cap_add(p->owner->nativeformats, &f->subclass.format);
07580       ast_set_read_format(p->owner, &p->owner->readformat);
07581       ast_set_write_format(p->owner, &p->owner->writeformat);
07582    }
07583 
07584    if (f && p->dsp) {
07585       f = ast_dsp_process(p->owner, p->dsp, f);
07586       if (f && f->frametype == AST_FRAME_DTMF) {
07587          if (f->subclass.integer == 'f') {
07588             ast_debug(1, "Fax CNG detected on %s\n", ast_channel_name(ast));
07589             *faxdetect = 1;
07590             /* If we only needed this DSP for fax detection purposes we can just drop it now */
07591             if (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) {
07592                ast_dsp_set_features(p->dsp, DSP_FEATURE_DIGIT_DETECT);
07593             } else {
07594                ast_dsp_free(p->dsp);
07595                p->dsp = NULL;
07596             }
07597          } else {
07598             ast_debug(1, "* Detected inband DTMF '%c'\n", f->subclass.integer);
07599          }
07600       }
07601    }
07602 
07603    return f;
07604 }
07605 
07606 /*! \brief Read SIP RTP from channel */
07607 static struct ast_frame *sip_read(struct ast_channel *ast)
07608 {
07609    struct ast_frame *fr;
07610    struct sip_pvt *p = ast->tech_pvt;
07611    int faxdetected = FALSE;
07612 
07613    sip_pvt_lock(p);
07614    fr = sip_rtp_read(ast, p, &faxdetected);
07615    p->lastrtprx = time(NULL);
07616 
07617    /* If we detect a CNG tone and fax detection is enabled then send us off to the fax extension */
07618    if (faxdetected && ast_test_flag(&p->flags[1], SIP_PAGE2_FAX_DETECT_CNG)) {
07619       if (strcmp(ast->exten, "fax")) {
07620          const char *target_context = S_OR(ast->macrocontext, ast->context);
07621          /* We need to unlock 'ast' here because
07622           * ast_exists_extension has the potential to start and
07623           * stop an autoservice on the channel. Such action is
07624           * prone to deadlock if the channel is locked.
07625           */
07626          sip_pvt_unlock(p);
07627          ast_channel_unlock(ast);
07628          if (ast_exists_extension(ast, target_context, "fax", 1,
07629             S_COR(ast->caller.id.number.valid, ast->caller.id.number.str, NULL))) {
07630             ast_channel_lock(ast);
07631             sip_pvt_lock(p);
07632             ast_verb(2, "Redirecting '%s' to fax extension due to CNG detection\n", ast_channel_name(ast));
07633             pbx_builtin_setvar_helper(ast, "FAXEXTEN", ast->exten);
07634             if (ast_async_goto(ast, target_context, "fax", 1)) {
07635                ast_log(LOG_NOTICE, "Failed to async goto '%s' into fax of '%s'\n", ast_channel_name(ast), target_context);
07636             }
07637             fr = &ast_null_frame;
07638          } else {
07639             ast_channel_lock(ast);
07640             sip_pvt_lock(p);
07641             ast_log(LOG_NOTICE, "FAX CNG detected but no fax extension\n");
07642          }
07643       }
07644    }
07645 
07646    /* Only allow audio through if they sent progress with SDP, or if the channel is actually answered */
07647    if (fr && fr->frametype == AST_FRAME_VOICE && p->invitestate != INV_EARLY_MEDIA && ast->_state != AST_STATE_UP) {
07648       fr = &ast_null_frame;
07649    }
07650 
07651    sip_pvt_unlock(p);
07652 
07653    return fr;
07654 }
07655 
07656 
07657 /*! \brief Generate 32 byte random string for callid's etc */
07658 static char *generate_random_string(char *buf, size_t size)
07659 {
07660    long val[4];
07661    int x;
07662 
07663    for (x=0; x<4; x++)
07664       val[x] = ast_random();
07665    snprintf(buf, size, "%08lx%08lx%08lx%08lx", val[0], val[1], val[2], val[3]);
07666 
07667    return buf;
07668 }
07669 
07670 static char *generate_uri(struct sip_pvt *pvt, char *buf, size_t size)
07671 {
07672    struct ast_str *uri = ast_str_alloca(size);
07673    ast_str_set(&uri, 0, "%s", pvt->socket.type == SIP_TRANSPORT_TLS ? "sips:" : "sip:");
07674    /* Here would be a great place to generate a UUID, but for now we'll
07675     * use the handy random string generation function we already have
07676     */
07677    ast_str_append(&uri, 0, "%s", generate_random_string(buf, size));
07678    ast_str_append(&uri, 0, "@%s", ast_sockaddr_stringify_remote(&pvt->ourip));
07679    ast_copy_string(buf, ast_str_buffer(uri), size);
07680    return buf;
07681 }
07682 
07683 /*!
07684  * \brief Build SIP Call-ID value for a non-REGISTER transaction
07685  *
07686  * \note The passed in pvt must not be in a dialogs container
07687  * since this function changes the hash key used by the
07688  * container.
07689  */
07690 static void build_callid_pvt(struct sip_pvt *pvt)
07691 {
07692    char buf[33];
07693    const char *host = S_OR(pvt->fromdomain, ast_sockaddr_stringify_remote(&pvt->ourip));
07694 
07695    ast_string_field_build(pvt, callid, "%s@%s", generate_random_string(buf, sizeof(buf)), host);
07696 }
07697 
07698 /*! \brief Unlink the given object from the container and return TRUE if it was in the container. */
07699 #define CONTAINER_UNLINK(container, obj, tag)                        \
07700    ({                                                    \
07701       int found = 0;                                        \
07702       typeof((obj)) __removed_obj;                             \
07703       __removed_obj = ao2_t_callback((container),                    \
07704          OBJ_UNLINK | OBJ_POINTER, ao2_match_by_addr, (obj), (tag));    \
07705       if (__removed_obj) {                                  \
07706          ao2_ref(__removed_obj, -1);                              \
07707          found = 1;                                         \
07708       }                                                  \
07709       found;                                                \
07710    })
07711 
07712 /*!
07713  * \internal
07714  * \brief Safely change the callid of the given SIP dialog.
07715  *
07716  * \param pvt SIP private structure to change callid
07717  * \param callid Specified new callid to use.  NULL if generate new callid.
07718  *
07719  * \return Nothing
07720  */
07721 static void change_callid_pvt(struct sip_pvt *pvt, const char *callid)
07722 {
07723    int in_dialog_container;
07724    int in_rtp_container;
07725 
07726    ao2_lock(dialogs);
07727    ao2_lock(dialogs_rtpcheck);
07728    in_dialog_container = CONTAINER_UNLINK(dialogs, pvt,
07729       "About to change the callid -- remove the old name");
07730    in_rtp_container = CONTAINER_UNLINK(dialogs_rtpcheck, pvt,
07731       "About to change the callid -- remove the old name");
07732    if (callid) {
07733       ast_string_field_set(pvt, callid, callid);
07734    } else {
07735       build_callid_pvt(pvt);
07736    }
07737    if (in_dialog_container) {
07738       ao2_t_link(dialogs, pvt, "New dialog callid -- inserted back into table");
07739    }
07740    if (in_rtp_container) {
07741       ao2_t_link(dialogs_rtpcheck, pvt, "New dialog callid -- inserted back into table");
07742    }
07743    ao2_unlock(dialogs_rtpcheck);
07744    ao2_unlock(dialogs);
07745 }
07746 
07747 /*! \brief Build SIP Call-ID value for a REGISTER transaction */
07748 static void build_callid_registry(struct sip_registry *reg, const struct ast_sockaddr *ourip, const char *fromdomain)
07749 {
07750    char buf[33];
07751 
07752    const char *host = S_OR(fromdomain, ast_sockaddr_stringify_host_remote(ourip));
07753 
07754    ast_string_field_build(reg, callid, "%s@%s", generate_random_string(buf, sizeof(buf)), host);
07755 }
07756 
07757 /*! \brief Make our SIP dialog tag */
07758 static void make_our_tag(char *tagbuf, size_t len)
07759 {
07760    snprintf(tagbuf, len, "as%08lx", ast_random());
07761 }
07762 
07763 /*! \brief Allocate Session-Timers struct w/in dialog */
07764 static struct sip_st_dlg* sip_st_alloc(struct sip_pvt *const p)
07765 {
07766    struct sip_st_dlg *stp;
07767 
07768    if (p->stimer) {
07769       ast_log(LOG_ERROR, "Session-Timer struct already allocated\n");
07770       return p->stimer;
07771    }
07772 
07773    if (!(stp = ast_calloc(1, sizeof(struct sip_st_dlg))))
07774       return NULL;
07775 
07776    p->stimer = stp;
07777 
07778    stp->st_schedid = -1;           /* Session-Timers ast_sched scheduler id */
07779 
07780    return p->stimer;
07781 }
07782 
07783 /*! \brief Allocate sip_pvt structure, set defaults and link in the container.
07784  * Returns a reference to the object so whoever uses it later must
07785  * remember to release the reference.
07786  */
07787 struct sip_pvt *sip_alloc(ast_string_field callid, struct ast_sockaddr *addr,
07788              int useglobal_nat, const int intended_method, struct sip_request *req)
07789 {
07790    struct sip_pvt *p;
07791 
07792    if (!(p = ao2_t_alloc(sizeof(*p), sip_destroy_fn, "allocate a dialog(pvt) struct")))
07793       return NULL;
07794 
07795    if (ast_string_field_init(p, 512)) {
07796       ao2_t_ref(p, -1, "failed to string_field_init, drop p");
07797       return NULL;
07798    }
07799 
07800    if (!(p->cc_params = ast_cc_config_params_init())) {
07801       ao2_t_ref(p, -1, "Yuck, couldn't allocate cc_params struct. Get rid o' p");
07802       return NULL;
07803    }
07804    p->caps = ast_format_cap_alloc_nolock();
07805    p->jointcaps = ast_format_cap_alloc_nolock();
07806    p->peercaps = ast_format_cap_alloc_nolock();
07807    p->redircaps = ast_format_cap_alloc_nolock();
07808    p->prefcaps = ast_format_cap_alloc_nolock();
07809 
07810    if (!p->caps|| !p->jointcaps || !p->peercaps || !p->redircaps) {
07811       p->caps = ast_format_cap_destroy(p->caps);
07812       p->jointcaps = ast_format_cap_destroy(p->jointcaps);
07813       p->peercaps = ast_format_cap_destroy(p->peercaps);
07814       p->redircaps = ast_format_cap_destroy(p->redircaps);
07815       p->prefcaps = ast_format_cap_destroy(p->prefcaps);
07816       ao2_t_ref(p, -1, "Yuck, couldn't allocate format capabilities. Get rid o' p");
07817       return NULL;
07818    }
07819 
07820 
07821    /* If this dialog is created as a result of a request or response, lets store
07822     * some information about it in the dialog. */
07823    if (req) {
07824       struct sip_via *via;
07825       const char *cseq = sip_get_header(req, "Cseq");
07826       uint32_t seqno;
07827 
07828       /* get branch parameter from initial Request that started this dialog */
07829       via = parse_via(sip_get_header(req, "Via"));
07830       if (via) {
07831          /* only store the branch if it begins with the magic prefix "z9hG4bK", otherwise
07832           * it is not useful to us to have it */
07833          if (!ast_strlen_zero(via->branch) && !strncasecmp(via->branch, "z9hG4bK", 7)) {
07834             ast_string_field_set(p, initviabranch, via->branch);
07835             ast_string_field_set(p, initviasentby, via->sent_by);
07836          }
07837          free_via(via);
07838       }
07839 
07840       /* Store initial incoming cseq. An error in sscanf here is ignored.  There is no approperiate
07841        * except not storing the number.  CSeq validation must take place before dialog creation in find_call */
07842       if (!ast_strlen_zero(cseq) && (sscanf(cseq, "%30u", &seqno) == 1)) {
07843          p->init_icseq = seqno;
07844       }
07845       /* Later in ast_sip_ouraddrfor we need this to choose the right ip and port for the specific transport */
07846       set_socket_transport(&p->socket, req->socket.type);
07847    } else {
07848       set_socket_transport(&p->socket, SIP_TRANSPORT_UDP);
07849    }
07850 
07851    p->socket.fd = -1;
07852    p->method = intended_method;
07853    p->initid = -1;
07854    p->waitid = -1;
07855    p->autokillid = -1;
07856    p->request_queue_sched_id = -1;
07857    p->provisional_keepalive_sched_id = -1;
07858    p->t38id = -1;
07859    p->subscribed = NONE;
07860    p->stateid = -1;
07861    p->sessionversion_remote = -1;
07862    p->session_modify = TRUE;
07863    p->stimer = NULL;
07864    p->prefs = default_prefs;     /* Set default codecs for this call */
07865    ast_copy_string(p->zone, default_zone, sizeof(p->zone));
07866    p->maxforwards = sip_cfg.default_max_forwards;
07867 
07868    if (intended_method != SIP_OPTIONS) {  /* Peerpoke has it's own system */
07869       p->timer_t1 = global_t1;   /* Default SIP retransmission timer T1 (RFC 3261) */
07870       p->timer_b = global_timer_b;  /* Default SIP transaction timer B (RFC 3261) */
07871    }
07872 
07873    if (!addr) {
07874       p->ourip = internip;
07875    } else {
07876       ast_sockaddr_copy(&p->sa, addr);
07877       ast_sip_ouraddrfor(&p->sa, &p->ourip, p);
07878    }
07879 
07880    /* Copy global flags to this PVT at setup. */
07881    ast_copy_flags(&p->flags[0], &global_flags[0], SIP_FLAGS_TO_COPY);
07882    ast_copy_flags(&p->flags[1], &global_flags[1], SIP_PAGE2_FLAGS_TO_COPY);
07883    ast_copy_flags(&p->flags[2], &global_flags[2], SIP_PAGE3_FLAGS_TO_COPY);
07884 
07885    p->do_history = recordhistory;
07886 
07887    p->branch = ast_random();  
07888    make_our_tag(p->tag, sizeof(p->tag));
07889    p->ocseq = INITIAL_CSEQ;
07890    p->allowed_methods = UINT_MAX;
07891 
07892    if (sip_methods[intended_method].need_rtp) {
07893       p->maxcallbitrate = default_maxcallbitrate;
07894       p->autoframing = global_autoframing;
07895    }
07896 
07897    if (useglobal_nat && addr) {
07898       /* Setup NAT structure according to global settings if we have an address */
07899       ast_copy_flags(&p->flags[0], &global_flags[0], SIP_NAT_FORCE_RPORT);
07900       ast_sockaddr_copy(&p->recv, addr);
07901 
07902       do_setnat(p);
07903    }
07904 
07905    if (p->method != SIP_REGISTER) {
07906       ast_string_field_set(p, fromdomain, default_fromdomain);
07907       p->fromdomainport = default_fromdomainport;
07908    }
07909    build_via(p);
07910    if (!callid)
07911       build_callid_pvt(p);
07912    else
07913       ast_string_field_set(p, callid, callid);
07914    /* Assign default music on hold class */
07915    ast_string_field_set(p, mohinterpret, default_mohinterpret);
07916    ast_string_field_set(p, mohsuggest, default_mohsuggest);
07917    ast_format_cap_copy(p->caps, sip_cfg.caps);
07918    p->allowtransfer = sip_cfg.allowtransfer;
07919    if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
07920        (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO)) {
07921       p->noncodeccapability |= AST_RTP_DTMF;
07922    }
07923    ast_string_field_set(p, context, sip_cfg.default_context);
07924    ast_string_field_set(p, parkinglot, default_parkinglot);
07925    ast_string_field_set(p, engine, default_engine);
07926 
07927    AST_LIST_HEAD_INIT_NOLOCK(&p->request_queue);
07928 
07929    /* Add to active dialog list */
07930 
07931    ao2_t_link(dialogs, p, "link pvt into dialogs table");
07932 
07933    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");
07934    return p;
07935 }
07936 
07937 /*!
07938  * \brief Process the Via header according to RFC 3261 section 18.2.2.
07939  * \param p a sip_pvt structure that will be modified according to the received
07940  * header
07941  * \param req a sip request with a Via header to process
07942  *
07943  * This function will update the destination of the response according to the
07944  * Via header in the request and RFC 3261 section 18.2.2. We do not have a
07945  * transport layer so we ignore certain values like the 'received' param (we
07946  * set the destination address to the addres the request came from in the
07947  * respprep() function).
07948  *
07949  * \retval -1 error
07950  * \retval 0 success
07951  */
07952 static int process_via(struct sip_pvt *p, const struct sip_request *req)
07953 {
07954    struct sip_via *via = parse_via(sip_get_header(req, "Via"));
07955 
07956    if (!via) {
07957       ast_log(LOG_ERROR, "error processing via header\n");
07958       return -1;
07959    }
07960 
07961    if (via->maddr) {
07962       if (ast_sockaddr_resolve_first(&p->sa, via->maddr, PARSE_PORT_FORBID)) {
07963          ast_log(LOG_WARNING, "Can't find address for maddr '%s'\n", via->maddr);
07964          ast_log(LOG_ERROR, "error processing via header\n");
07965          free_via(via);
07966          return -1;
07967       }
07968 
07969       if (ast_sockaddr_is_ipv4_multicast(&p->sa)) {
07970          setsockopt(sipsock, IPPROTO_IP, IP_MULTICAST_TTL, &via->ttl, sizeof(via->ttl));
07971       }
07972    }
07973 
07974    ast_sockaddr_set_port(&p->sa, via->port ? via->port : STANDARD_SIP_PORT);
07975 
07976    free_via(via);
07977    return 0;
07978 }
07979 
07980 /* \brief arguments used for Request/Response to matching */
07981 struct match_req_args {
07982    int method;
07983    const char *callid;
07984    const char *totag;
07985    const char *fromtag;
07986    uint32_t seqno;
07987 
07988    /* Set if this method is a Response */
07989    int respid;
07990 
07991    /* Set if the method is a Request */
07992    const char *ruri;
07993    const char *viabranch;
07994    const char *viasentby;
07995 
07996    /* Set this if the Authentication header is present in the Request. */
07997    int authentication_present;
07998 };
07999 
08000 enum match_req_res {
08001    SIP_REQ_MATCH,
08002    SIP_REQ_NOT_MATCH,
08003    SIP_REQ_LOOP_DETECTED, /* multiple incoming requests with same call-id but different branch parameters have been detected */
08004    SIP_REQ_FORKED, /* An outgoing request has been forked as result of receiving two differing 200ok responses. */
08005 };
08006 
08007 /*
08008  * \brief Match a incoming Request/Response to a dialog
08009  *
08010  * \retval enum match_req_res indicating if the dialog matches the arg
08011  */
08012 static enum match_req_res match_req_to_dialog(struct sip_pvt *sip_pvt_ptr, struct match_req_args *arg)
08013 {
08014    const char *init_ruri = NULL;
08015    if (sip_pvt_ptr->initreq.headers) {
08016       init_ruri = REQ_OFFSET_TO_STR(&sip_pvt_ptr->initreq, rlPart2);
08017    }
08018 
08019    /*
08020     * Match Tags and call-id to Dialog
08021     */
08022    if (!ast_strlen_zero(arg->callid) && strcmp(sip_pvt_ptr->callid, arg->callid)) {
08023       /* call-id does not match. */
08024       return SIP_REQ_NOT_MATCH;
08025    }
08026    if (arg->method == SIP_RESPONSE) {
08027       /* Verify fromtag of response matches the tag we gave them. */
08028       if (strcmp(arg->fromtag, sip_pvt_ptr->tag)) {
08029          /* fromtag from response does not match our tag */
08030          return SIP_REQ_NOT_MATCH;
08031       }
08032 
08033       /* Verify totag if we have one stored for this dialog, but never be strict about this for
08034        * a response until the dialog is established */
08035       if (!ast_strlen_zero(sip_pvt_ptr->theirtag) && ast_test_flag(&sip_pvt_ptr->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED)) {
08036          if (ast_strlen_zero(arg->totag)) {
08037             /* missing totag when they already gave us one earlier */
08038             return SIP_REQ_NOT_MATCH;
08039          }
08040          /* compare the totag of response with the tag we have stored for them */
08041          if (strcmp(arg->totag, sip_pvt_ptr->theirtag)) {
08042             /* totag did not match what we had stored for them. */
08043             char invite_branch[32] = { 0, };
08044             if (sip_pvt_ptr->invite_branch) {
08045                snprintf(invite_branch, sizeof(invite_branch), "z9hG4bK%08x", (int) sip_pvt_ptr->invite_branch);
08046             }
08047             /* Forked Request Detection
08048              *
08049              * If this is a 200ok response and the totags do not match, this
08050              * might be a forked response to an outgoing Request. Detection of
08051              * a forked response must meet the criteria below.
08052              *
08053              * 1. must be a 2xx Response
08054              * 2. call-d equal to call-id of Request. this is done earlier
08055              * 3. from-tag equal to from-tag of Request. this is done earlier
08056              * 4. branch parameter equal to branch of inital Request
08057              * 5. to-tag _NOT_ equal to previous 2xx response that already established the dialog.
08058              */
08059             if ((arg->respid == 200) &&
08060                !ast_strlen_zero(invite_branch) &&
08061                !ast_strlen_zero(arg->viabranch) &&
08062                !strcmp(invite_branch, arg->viabranch)) {
08063                return SIP_REQ_FORKED;
08064             }
08065 
08066             /* The totag did not match the one we had stored, and this is not a Forked Request. */
08067             return SIP_REQ_NOT_MATCH;
08068          }
08069       }
08070    } else {
08071       /* Verify the fromtag of Request matches the tag they provided earlier.
08072        * If this is a Request with authentication credentials, forget their old
08073        * tag as it is not valid after the 401 or 407 response. */
08074       if (!arg->authentication_present && strcmp(arg->fromtag, sip_pvt_ptr->theirtag)) {
08075          /* their tag does not match the one was have stored for them */
08076          return SIP_REQ_NOT_MATCH;
08077       }
08078       /* Verify if totag is present in Request, that it matches what we gave them as our tag earlier */
08079       if (!ast_strlen_zero(arg->totag) && (strcmp(arg->totag, sip_pvt_ptr->tag))) {
08080          /* totag from Request does not match our tag */
08081          return SIP_REQ_NOT_MATCH;
08082       }
08083    }
08084 
08085    /*
08086     * Compare incoming request against initial transaction.
08087     * 
08088     * This is a best effort attempt at distinguishing forked requests from
08089     * our initial transaction.  If all the elements are NOT in place to evaluate
08090     * this, this block is ignored and the dialog match is made regardless.
08091     * Once the totag is established after the dialog is confirmed, this is not necessary.
08092     *
08093     * CRITERIA required for initial transaction matching.
08094     * 
08095     * 1. Is a Request
08096     * 2. Callid and theirtag match (this is done in the dialog matching block)
08097     * 3. totag is NOT present
08098     * 4. CSeq matchs our initial transaction's cseq number
08099     * 5. pvt has init via branch parameter stored
08100     */
08101    if ((arg->method != SIP_RESPONSE) &&                 /* must be a Request */
08102       ast_strlen_zero(arg->totag) &&                   /* must not have a totag */
08103       (sip_pvt_ptr->init_icseq == arg->seqno) &&       /* the cseq must be the same as this dialogs initial cseq */
08104       !ast_strlen_zero(sip_pvt_ptr->initviabranch) &&  /* The dialog must have started with a RFC3261 compliant branch tag */
08105       init_ruri) {                                     /* the dialog must have an initial request uri associated with it */
08106       /* This Request matches all the criteria required for Loop/Merge detection.
08107        * Now we must go down the path of comparing VIA's and RURIs. */
08108       if (ast_strlen_zero(arg->viabranch) ||
08109          strcmp(arg->viabranch, sip_pvt_ptr->initviabranch) ||
08110          ast_strlen_zero(arg->viasentby) ||
08111          strcmp(arg->viasentby, sip_pvt_ptr->initviasentby)) {
08112          /* At this point, this request does not match this Dialog.*/
08113 
08114          /* if methods are different this is just a mismatch */
08115          if ((sip_pvt_ptr->method != arg->method)) {
08116             return SIP_REQ_NOT_MATCH;
08117          }
08118 
08119          /* If RUIs are different, this is a forked request to a separate URI.
08120           * Returning a mismatch allows this Request to be processed separately. */
08121          if (sip_uri_cmp(init_ruri, arg->ruri)) {
08122             /* not a match, request uris are different */
08123             return SIP_REQ_NOT_MATCH;
08124          }
08125 
08126          /* Loop/Merge Detected
08127           *
08128           * ---Current Matches to Initial Request---
08129           * request uri
08130           * Call-id
08131           * their-tag
08132           * no totag present
08133           * method
08134           * cseq
08135           *
08136           * --- Does not Match Initial Request ---
08137           * Top Via
08138           *
08139           * Without the same Via, this can not match our initial transaction for this dialog,
08140           * but given that this Request matches everything else associated with that initial
08141           * Request this is most certainly a Forked request in which we have already received
08142           * part of the fork.
08143           */
08144          return SIP_REQ_LOOP_DETECTED;
08145       }
08146    } /* end of Request Via check */
08147 
08148    /* Match Authentication Request.
08149     *
08150     * A Request with an Authentication header must come back with the
08151     * same Request URI.  Otherwise it is not a match.
08152     */
08153    if ((arg->method != SIP_RESPONSE) &&      /* Must be a Request type to even begin checking this */
08154       ast_strlen_zero(arg->totag) &&        /* no totag is present to match */
08155       arg->authentication_present &&        /* Authentication header is present in Request */
08156       sip_uri_cmp(init_ruri, arg->ruri)) {  /* Compare the Request URI of both the last Request and this new one */
08157 
08158       /* Authentication was provided, but the Request URI did not match the last one on this dialog. */
08159       return SIP_REQ_NOT_MATCH;
08160    }
08161 
08162    return SIP_REQ_MATCH;
08163 }
08164 
08165 /*! \brief This function creates a dialog to handle a forked request.  This dialog
08166  * exists only to properly terminiate the the forked request immediately.
08167  */
08168 static void forked_invite_init(struct sip_request *req, const char *new_theirtag, struct sip_pvt *original, struct ast_sockaddr *addr)
08169 {
08170    struct sip_pvt *p;
08171 
08172    if (!(p = sip_alloc(original->callid, addr, 1, SIP_INVITE, req)))  {
08173       return; /* alloc error */
08174    }
08175    p->invitestate = INV_TERMINATED;
08176    p->ocseq = original->ocseq;
08177    p->branch = original->branch;
08178 
08179    memcpy(&p->flags, &original->flags, sizeof(p->flags));
08180    copy_request(&p->initreq, &original->initreq);
08181    ast_string_field_set(p, theirtag, new_theirtag);
08182    ast_copy_string(p->tag, original->tag, sizeof(p->tag));
08183    ast_string_field_set(p, uri, original->uri);
08184    ast_string_field_set(p, our_contact, original->our_contact);
08185    ast_string_field_set(p, fullcontact, original->fullcontact);
08186    parse_ok_contact(p, req);
08187    build_route(p, req, 1);
08188 
08189    transmit_request(p, SIP_ACK, p->ocseq, XMIT_UNRELIABLE, TRUE);
08190    transmit_request(p, SIP_BYE, 0, XMIT_RELIABLE, TRUE);
08191 
08192    pvt_set_needdestroy(p, "forked request"); /* this dialog will terminate once the BYE is responed to or times out. */
08193    dialog_unref(p, "setup forked invite termination");
08194 }
08195 
08196 /*! \internal
08197  *
08198  * \brief Locks both pvt and pvt owner if owner is present.
08199  *
08200  * \note This function gives a ref to pvt->owner if it is present and locked.
08201  *       This reference must be decremented after pvt->owner is unlocked.
08202  *
08203  * \note This function will never give you up,
08204  * \note This function will never let you down.
08205  * \note This function will run around and desert you.
08206  *
08207  * \pre pvt is not locked
08208  * \post pvt is locked
08209  * \post pvt->owner is locked and its reference count is increased (if pvt->owner is not NULL)
08210  *
08211  * \returns a pointer to the locked and reffed pvt->owner channel if it exists.
08212  */
08213 static struct ast_channel *sip_pvt_lock_full(struct sip_pvt *pvt)
08214 {
08215    struct ast_channel *chan;
08216 
08217    /* Locking is simple when it is done right.  If you see a deadlock resulting
08218     * in this function, it is not this function's fault, Your problem exists elsewhere.
08219     * This function is perfect... seriously. */
08220    for (;;) {
08221       /* First, get the channel and grab a reference to it */
08222       sip_pvt_lock(pvt);
08223       chan = pvt->owner;
08224       if (chan) {
08225          /* The channel can not go away while we hold the pvt lock.
08226           * Give the channel a ref so it will not go away after we let
08227           * the pvt lock go. */
08228          ast_channel_ref(chan);
08229       } else {
08230          /* no channel, return pvt locked */
08231          return NULL;
08232       }
08233 
08234       /* We had to hold the pvt lock while getting a ref to the owner channel
08235        * but now we have to let this lock go in order to preserve proper
08236        * locking order when grabbing the channel lock */
08237       sip_pvt_unlock(pvt);
08238 
08239       /* Look, no deadlock avoidance, hooray! */
08240       ast_channel_lock(chan);
08241       sip_pvt_lock(pvt);
08242 
08243       if (pvt->owner == chan) {
08244          /* done */
08245          break;
08246       }
08247 
08248       /* If the owner changed while everything was unlocked, no problem,
08249        * just start over and everthing will work.  This is rare, do not be
08250        * confused by this loop and think this it is an expensive operation.
08251        * The majority of the calls to this function will never involve multiple
08252        * executions of this loop. */
08253       ast_channel_unlock(chan);
08254       ast_channel_unref(chan);
08255       sip_pvt_unlock(pvt);
08256    }
08257 
08258    /* If owner exists, it is locked and reffed */
08259    return pvt->owner;
08260 }
08261 
08262 /*! \brief find or create a dialog structure for an incoming SIP message.
08263  * Connect incoming SIP message to current dialog or create new dialog structure
08264  * Returns a reference to the sip_pvt object, remember to give it back once done.
08265  *     Called by handle_request_do
08266  */
08267 static struct sip_pvt *find_call(struct sip_request *req, struct ast_sockaddr *addr, const int intended_method)
08268 {
08269    char totag[128];
08270    char fromtag[128];
08271    const char *callid = sip_get_header(req, "Call-ID");
08272    const char *from = sip_get_header(req, "From");
08273    const char *to = sip_get_header(req, "To");
08274    const char *cseq = sip_get_header(req, "Cseq");
08275    struct sip_pvt *sip_pvt_ptr;
08276    uint32_t seqno;
08277    /* Call-ID, to, from and Cseq are required by RFC 3261. (Max-forwards and via too - ignored now) */
08278    /* sip_get_header always returns non-NULL so we must use ast_strlen_zero() */
08279    if (ast_strlen_zero(callid) || ast_strlen_zero(to) ||
08280          ast_strlen_zero(from) || ast_strlen_zero(cseq) ||
08281          (sscanf(cseq, "%30u", &seqno) != 1)) {
08282 
08283       /* RFC 3261 section 24.4.1.   Send a 400 Bad Request if the request is malformed. */
08284       if (intended_method != SIP_RESPONSE && intended_method != SIP_ACK) {
08285          transmit_response_using_temp(callid, addr, 1, intended_method,
08286                        req, "400 Bad Request");
08287       }
08288       return NULL;   /* Invalid packet */
08289    }
08290 
08291    if (sip_cfg.pedanticsipchecking) {
08292       /* In principle Call-ID's uniquely identify a call, but with a forking SIP proxy
08293          we need more to identify a branch - so we have to check branch, from
08294          and to tags to identify a call leg.
08295          For Asterisk to behave correctly, you need to turn on pedanticsipchecking
08296          in sip.conf
08297          */
08298       if (gettag(req, "To", totag, sizeof(totag)))
08299          req->has_to_tag = 1; /* Used in handle_request/response */
08300       gettag(req, "From", fromtag, sizeof(fromtag));
08301 
08302       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);
08303 
08304       /* All messages must always have From: tag */
08305       if (ast_strlen_zero(fromtag)) {
08306          ast_debug(5, "%s request has no from tag, dropping callid: %s from: %s\n", sip_methods[req->method].text , callid, from );
08307          return NULL;
08308       }
08309       /* reject requests that must always have a To: tag */
08310       if (ast_strlen_zero(totag) && (req->method == SIP_ACK || req->method == SIP_BYE || req->method == SIP_INFO )) {
08311          if (req->method != SIP_ACK) {
08312             transmit_response_using_temp(callid, addr, 1, intended_method, req, "481 Call leg/transaction does not exist");
08313          }
08314          ast_debug(5, "%s must have a to tag. dropping callid: %s from: %s\n", sip_methods[req->method].text , callid, from );
08315          return NULL;
08316       }
08317    }
08318 
08319    if (!sip_cfg.pedanticsipchecking) {
08320       struct sip_pvt tmp_dialog = {
08321          .callid = callid,
08322       };
08323       sip_pvt_ptr = ao2_t_find(dialogs, &tmp_dialog, OBJ_POINTER, "ao2_find in dialogs");
08324       if (sip_pvt_ptr) {  /* well, if we don't find it-- what IS in there? */
08325          /* Found the call */
08326          return sip_pvt_ptr;
08327       }
08328    } else { /* in pedantic mode! -- do the fancy search */
08329       struct sip_pvt tmp_dialog = {
08330          .callid = callid,
08331       };
08332       /* if a Outbound forked Request is detected, this pvt will point
08333        * to the dialog the Request is forking off of. */
08334       struct sip_pvt *fork_pvt = NULL;
08335       struct match_req_args args = { 0, };
08336       int found;
08337       struct ao2_iterator *iterator = ao2_t_callback(dialogs,
08338          OBJ_POINTER | OBJ_MULTIPLE,
08339          dialog_find_multiple,
08340          &tmp_dialog,
08341          "pedantic ao2_find in dialogs");
08342       struct sip_via *via = NULL;
08343 
08344       args.method = req->method;
08345       args.callid = NULL; /* we already matched this. */
08346       args.totag = totag;
08347       args.fromtag = fromtag;
08348       args.seqno = seqno;
08349       /* get via header information. */
08350       args.ruri = REQ_OFFSET_TO_STR(req, rlPart2);
08351       via = parse_via(sip_get_header(req, "Via"));
08352       if (via) {
08353          args.viasentby = via->sent_by;
08354          args.viabranch = via->branch;
08355       }
08356       /* determine if this is a Request with authentication credentials. */
08357       if (!ast_strlen_zero(sip_get_header(req, "Authorization")) ||
08358          !ast_strlen_zero(sip_get_header(req, "Proxy-Authorization"))) {
08359          args.authentication_present = 1;
08360       }
08361       /* if it is a response, get the response code */
08362       if (req->method == SIP_RESPONSE) {
08363          const char* e = ast_skip_blanks(REQ_OFFSET_TO_STR(req, rlPart2));
08364          int respid;
08365          if (!ast_strlen_zero(e) && (sscanf(e, "%30d", &respid) == 1)) {
08366             args.respid = respid;
08367          }
08368       }
08369 
08370       /* Iterate a list of dialogs already matched by Call-id */
08371       while (iterator && (sip_pvt_ptr = ao2_iterator_next(iterator))) {
08372          found = match_req_to_dialog(sip_pvt_ptr, &args);
08373 
08374          switch (found) {
08375          case SIP_REQ_MATCH:
08376             ao2_iterator_destroy(iterator);
08377             dialog_unref(fork_pvt, "unref fork_pvt");
08378             free_via(via);
08379             return sip_pvt_ptr; /* return pvt with ref */
08380          case SIP_REQ_LOOP_DETECTED:
08381             /* This is likely a forked Request that somehow resulted in us receiving multiple parts of the fork.
08382             * RFC 3261 section 8.2.2.2, Indicate that we want to merge requests by sending a 482 response. */
08383             transmit_response_using_temp(callid, addr, 1, intended_method, req, "482 (Loop Detected)");
08384             dialog_unref(sip_pvt_ptr, "pvt did not match incoming SIP msg, unref from search.");
08385             ao2_iterator_destroy(iterator);
08386             dialog_unref(fork_pvt, "unref fork_pvt");
08387             free_via(via);
08388             return NULL;
08389          case SIP_REQ_FORKED:
08390             dialog_unref(fork_pvt, "throwing way pvt to fork off of.");
08391             fork_pvt = dialog_ref(sip_pvt_ptr, "this pvt has a forked request, save this off to copy information into new dialog\n");
08392             /* fall through */
08393          case SIP_REQ_NOT_MATCH:
08394          default:
08395             dialog_unref(sip_pvt_ptr, "pvt did not match incoming SIP msg, unref from search");
08396          }
08397       }
08398       if (iterator) {
08399          ao2_iterator_destroy(iterator);
08400       }
08401 
08402       /* Handle any possible forked requests. This must be done only after transaction matching is complete. */
08403       if (fork_pvt) {
08404          /* XXX right now we only support handling forked INVITE Requests. Any other
08405           * forked request type must be added here. */
08406          if (fork_pvt->method == SIP_INVITE) {
08407             forked_invite_init(req, args.totag, fork_pvt, addr);
08408             dialog_unref(fork_pvt, "throwing way old forked pvt");
08409             free_via(via);
08410             return NULL;
08411          }
08412          fork_pvt = dialog_unref(fork_pvt, "throwing way pvt to fork off of");
08413       }
08414 
08415       free_via(via);
08416    } /* end of pedantic mode Request/Reponse to Dialog matching */
08417 
08418    /* See if the method is capable of creating a dialog */
08419    if (sip_methods[intended_method].can_create == CAN_CREATE_DIALOG) {
08420       struct sip_pvt *p = NULL;
08421 
08422       if (intended_method == SIP_REFER) {
08423          /* We do support REFER, but not outside of a dialog yet */
08424          transmit_response_using_temp(callid, addr, 1, intended_method, req, "603 Declined (no dialog)");
08425    
08426       /* Ok, time to create a new SIP dialog object, a pvt */
08427       } else if (!(p = sip_alloc(callid, addr, 1, intended_method, req)))  {
08428          /* We have a memory or file/socket error (can't allocate RTP sockets or something) so we're not
08429             getting a dialog from sip_alloc.
08430 
08431             Without a dialog we can't retransmit and handle ACKs and all that, but at least
08432             send an error message.
08433 
08434             Sorry, we apologize for the inconvienience
08435          */
08436          transmit_response_using_temp(callid, addr, 1, intended_method, req, "500 Server internal error");
08437          ast_debug(4, "Failed allocating SIP dialog, sending 500 Server internal error and giving up\n");
08438       }
08439       return p; /* can be NULL */
08440    } else if( sip_methods[intended_method].can_create == CAN_CREATE_DIALOG_UNSUPPORTED_METHOD) {
08441       /* A method we do not support, let's take it on the volley */
08442       transmit_response_using_temp(callid, addr, 1, intended_method, req, "501 Method Not Implemented");
08443       ast_debug(2, "Got a request with unsupported SIP method.\n");
08444    } else if (intended_method != SIP_RESPONSE && intended_method != SIP_ACK) {
08445       /* This is a request outside of a dialog that we don't know about */
08446       transmit_response_using_temp(callid, addr, 1, intended_method, req, "481 Call leg/transaction does not exist");
08447       ast_debug(2, "That's odd...  Got a request in unknown dialog. Callid %s\n", callid ? callid : "<unknown>");
08448    }
08449    /* We do not respond to responses for dialogs that we don't know about, we just drop
08450       the session quickly */
08451    if (intended_method == SIP_RESPONSE)
08452       ast_debug(2, "That's odd...  Got a response on a call we don't know about. Callid %s\n", callid ? callid : "<unknown>");
08453 
08454    return NULL;
08455 }
08456 
08457 /*! \brief create sip_registry object from register=> line in sip.conf and link into reg container */
08458 static int sip_register(const char *value, int lineno)
08459 {
08460    struct sip_registry *reg, *tmp;
08461 
08462    if (!(reg = ast_calloc_with_stringfields(1, struct sip_registry, 256))) {
08463       ast_log(LOG_ERROR, "Out of memory. Can't allocate SIP registry entry\n");
08464       return -1;
08465    }
08466 
08467    ASTOBJ_INIT(reg);
08468 
08469    ast_copy_string(reg->name, value, sizeof(reg->name));
08470    if (sip_parse_register_line(reg, default_expiry, value, lineno)) {
08471       registry_unref(reg, "failure to parse, unref the reg pointer");
08472       return -1;
08473    }
08474 
08475    /* set default expiry if necessary */
08476    if (reg->refresh && !reg->expiry && !reg->configured_expiry) {
08477       reg->refresh = reg->expiry = reg->configured_expiry = default_expiry;
08478    }
08479 
08480    /* Add the new registry entry to the list, but only if it isn't already there */
08481    if ((tmp = ASTOBJ_CONTAINER_FIND(&regl, reg->name))) {
08482       registry_unref(tmp, "throw away found registry");
08483    } else {
08484       ast_atomic_fetchadd_int(&regobjs, 1);
08485       ASTOBJ_CONTAINER_LINK(&regl, reg);
08486    }
08487 
08488    /* release the reference given by ASTOBJ_INIT. The container has another reference */
08489    registry_unref(reg, "unref the reg pointer");
08490 
08491    return 0;
08492 }
08493 
08494 /*! \brief Parse mwi=> line in sip.conf and add to list */
08495 static int sip_subscribe_mwi(const char *value, int lineno)
08496 {
08497    struct sip_subscription_mwi *mwi;
08498    int portnum = 0;
08499    enum sip_transport transport = SIP_TRANSPORT_UDP;
08500    char buf[256] = "";
08501    char *username = NULL, *hostname = NULL, *secret = NULL, *authuser = NULL, *porta = NULL, *mailbox = NULL, *at = NULL;
08502 
08503    if (!value) {
08504       return -1;
08505    }
08506 
08507    ast_copy_string(buf, value, sizeof(buf));
08508 
08509    if (!(at = strstr(buf, "@"))) {
08510       return -1;
08511    }
08512 
08513    if ((hostname = strrchr(buf, '@'))) {
08514       *hostname++ = '\0';
08515       username = buf;
08516    }
08517 
08518    if ((secret = strchr(username, ':'))) {
08519       *secret++ = '\0';
08520       if ((authuser = strchr(secret, ':'))) {
08521          *authuser++ = '\0';
08522       }
08523    }
08524 
08525    if ((mailbox = strchr(hostname, '/'))) {
08526       *mailbox++ = '\0';
08527    }
08528 
08529    if (ast_strlen_zero(username) || ast_strlen_zero(hostname) || ast_strlen_zero(mailbox)) {
08530       ast_log(LOG_WARNING, "Format for MWI subscription is user[:secret[:authuser]]@host[:port]/mailbox at line %d\n", lineno);
08531       return -1;
08532    }
08533 
08534    if ((porta = strchr(hostname, ':'))) {
08535       *porta++ = '\0';
08536       if (!(portnum = atoi(porta))) {
08537          ast_log(LOG_WARNING, "%s is not a valid port number at line %d\n", porta, lineno);
08538          return -1;
08539       }
08540    }
08541 
08542    if (!(mwi = ast_calloc_with_stringfields(1, struct sip_subscription_mwi, 256))) {
08543       return -1;
08544    }
08545 
08546    ASTOBJ_INIT(mwi);
08547    ast_string_field_set(mwi, username, username);
08548    if (secret) {
08549       ast_string_field_set(mwi, secret, secret);
08550    }
08551    if (authuser) {
08552       ast_string_field_set(mwi, authuser, authuser);
08553    }
08554    ast_string_field_set(mwi, hostname, hostname);
08555    ast_string_field_set(mwi, mailbox, mailbox);
08556    mwi->resub = -1;
08557    mwi->portno = portnum;
08558    mwi->transport = transport;
08559 
08560    ASTOBJ_CONTAINER_LINK(&submwil, mwi);
08561    ASTOBJ_UNREF(mwi, sip_subscribe_mwi_destroy);
08562 
08563    return 0;
08564 }
08565 
08566 static void mark_method_allowed(unsigned int *allowed_methods, enum sipmethod method)
08567 {
08568    (*allowed_methods) |= (1 << method);
08569 }
08570 
08571 static void mark_method_unallowed(unsigned int *allowed_methods, enum sipmethod method)
08572 {
08573    (*allowed_methods) &= ~(1 << method);
08574 }
08575 
08576 /*! \brief Check if method is allowed for a device or a dialog */
08577 static int is_method_allowed(unsigned int *allowed_methods, enum sipmethod method)
08578 {
08579    return ((*allowed_methods) >> method) & 1;
08580 }
08581 
08582 static void mark_parsed_methods(unsigned int *methods, char *methods_str)
08583 {
08584    char *method;
08585    for (method = strsep(&methods_str, ","); !ast_strlen_zero(method); method = strsep(&methods_str, ",")) {
08586       int id = find_sip_method(ast_skip_blanks(method));
08587       if (id == SIP_UNKNOWN) {
08588          continue;
08589       }
08590       mark_method_allowed(methods, id);
08591    }
08592 }
08593 /*!
08594  * \brief parse the Allow header to see what methods the endpoint we
08595  * are communicating with allows.
08596  *
08597  * We parse the allow header on incoming Registrations and save the
08598  * result to the SIP peer that is registering. When the registration
08599  * expires, we clear what we know about the peer's allowed methods.
08600  * When the peer re-registers, we once again parse to see if the
08601  * list of allowed methods has changed.
08602  *
08603  * For peers that do not register, we parse the first message we receive
08604  * during a call to see what is allowed, and save the information
08605  * for the duration of the call.
08606  * \param req The SIP request we are parsing
08607  * \retval The methods allowed
08608  */
08609 static unsigned int parse_allowed_methods(struct sip_request *req)
08610 {
08611    char *allow = ast_strdupa(sip_get_header(req, "Allow"));
08612    unsigned int allowed_methods = SIP_UNKNOWN;
08613 
08614    if (ast_strlen_zero(allow)) {
08615       /* I have witnessed that REGISTER requests from Polycom phones do not
08616        * place the phone's allowed methods in an Allow header. Instead, they place the
08617        * allowed methods in a methods= parameter in the Contact header.
08618        */
08619       char *contact = ast_strdupa(sip_get_header(req, "Contact"));
08620       char *methods = strstr(contact, ";methods=");
08621 
08622       if (ast_strlen_zero(methods)) {
08623          /* RFC 3261 states:
08624           *
08625           * "The absence of an Allow header field MUST NOT be
08626           * interpreted to mean that the UA sending the message supports no
08627           * methods.   Rather, it implies that the UA is not providing any
08628           * information on what methods it supports."
08629           *
08630           * For simplicity, we'll assume that the peer allows all known
08631           * SIP methods if they have no Allow header. We can then clear out the necessary
08632           * bits if the peer lets us know that we have sent an unsupported method.
08633           */
08634          return UINT_MAX;
08635       }
08636       allow = ast_strip_quoted(methods + 9, "\"", "\"");
08637    }
08638    mark_parsed_methods(&allowed_methods, allow);
08639    return allowed_methods;
08640 }
08641 
08642 /*! A wrapper for parse_allowed_methods geared toward sip_pvts
08643  *
08644  * This function, in addition to setting the allowed methods for a sip_pvt
08645  * also will take into account the setting of the SIP_PAGE2_RPID_UPDATE flag.
08646  *
08647  * \param pvt The sip_pvt we are setting the allowed_methods for
08648  * \param req The request which we are parsing
08649  * \retval The methods alloweded by the sip_pvt
08650  */
08651 static unsigned int set_pvt_allowed_methods(struct sip_pvt *pvt, struct sip_request *req)
08652 {
08653    pvt->allowed_methods = parse_allowed_methods(req);
08654    
08655    if (ast_test_flag(&pvt->flags[1], SIP_PAGE2_RPID_UPDATE)) {
08656       mark_method_allowed(&pvt->allowed_methods, SIP_UPDATE);
08657    }
08658    pvt->allowed_methods &= ~(pvt->disallowed_methods);
08659 
08660    return pvt->allowed_methods;
08661 }
08662 
08663 /*! \brief  Parse multiline SIP headers into one header
08664    This is enabled if pedanticsipchecking is enabled */
08665 static void lws2sws(struct ast_str *data)
08666 {
08667    char *msgbuf = data->str;
08668    int len = ast_str_strlen(data);
08669    int h = 0, t = 0;
08670    int lws = 0;
08671 
08672    for (; h < len;) {
08673       /* Eliminate all CRs */
08674       if (msgbuf[h] == '\r') {
08675          h++;
08676          continue;
08677       }
08678       /* Check for end-of-line */
08679       if (msgbuf[h] == '\n') {
08680          /* Check for end-of-message */
08681          if (h + 1 == len)
08682             break;
08683          /* Check for a continuation line */
08684          if (msgbuf[h + 1] == ' ' || msgbuf[h + 1] == '\t') {
08685             /* Merge continuation line */
08686             h++;
08687             continue;
08688          }
08689          /* Propagate LF and start new line */
08690          msgbuf[t++] = msgbuf[h++];
08691          lws = 0;
08692          continue;
08693       }
08694       if (msgbuf[h] == ' ' || msgbuf[h] == '\t') {
08695          if (lws) {
08696             h++;
08697             continue;
08698          }
08699          msgbuf[t++] = msgbuf[h++];
08700          lws = 1;
08701          continue;
08702       }
08703       msgbuf[t++] = msgbuf[h++];
08704       if (lws)
08705          lws = 0;
08706    }
08707    msgbuf[t] = '\0';
08708    data->used = t;
08709 }
08710 
08711 /*! \brief Parse a SIP message
08712    \note this function is used both on incoming and outgoing packets
08713 */
08714 static int parse_request(struct sip_request *req)
08715 {
08716    char *c = req->data->str;
08717    ptrdiff_t *dst = req->header;
08718    int i = 0, lim = SIP_MAX_HEADERS - 1;
08719    unsigned int skipping_headers = 0;
08720    ptrdiff_t current_header_offset = 0;
08721    char *previous_header = "";
08722 
08723    req->header[0] = 0;
08724    req->headers = -1;   /* mark that we are working on the header */
08725    for (; *c; c++) {
08726       if (*c == '\r') {    /* remove \r */
08727          *c = '\0';
08728       } else if (*c == '\n') {   /* end of this line */
08729          *c = '\0';
08730          current_header_offset = (c + 1) - req->data->str;
08731          previous_header = req->data->str + dst[i];
08732          if (skipping_headers) {
08733             /* check to see if this line is blank; if so, turn off
08734                the skipping flag, so the next line will be processed
08735                as a body line */
08736             if (ast_strlen_zero(previous_header)) {
08737                skipping_headers = 0;
08738             }
08739             dst[i] = current_header_offset; /* record start of next line */
08740             continue;
08741          }
08742          if (sipdebug) {
08743             ast_debug(4, "%7s %2d [%3d]: %s\n",
08744                  req->headers < 0 ? "Header" : "Body",
08745                  i, (int) strlen(previous_header), previous_header);
08746          }
08747          if (ast_strlen_zero(previous_header) && req->headers < 0) {
08748             req->headers = i; /* record number of header lines */
08749             dst = req->line;  /* start working on the body */
08750             i = 0;
08751             lim = SIP_MAX_LINES - 1;
08752          } else { /* move to next line, check for overflows */
08753             if (i++ == lim) {
08754                /* if we're processing headers, then skip any remaining
08755                   headers and move on to processing the body, otherwise
08756                   we're done */
08757                if (req->headers != -1) {
08758                   break;
08759                } else {
08760                   req->headers = i;
08761                   dst = req->line;
08762                   i = 0;
08763                   lim = SIP_MAX_LINES - 1;
08764                   skipping_headers = 1;
08765                }
08766             }
08767          }
08768          dst[i] = current_header_offset; /* record start of next line */
08769       }
08770    }
08771 
08772    /* Check for last header or body line without CRLF. The RFC for SDP requires CRLF,
08773       but since some devices send without, we'll be generous in what we accept. However,
08774       if we've already reached the maximum number of lines for portion of the message
08775       we were parsing, we can't accept any more, so just ignore it.
08776    */
08777    previous_header = req->data->str + dst[i];
08778    if ((i < lim) && !ast_strlen_zero(previous_header)) {
08779       if (sipdebug) {
08780          ast_debug(4, "%7s %2d [%3d]: %s\n",
08781               req->headers < 0 ? "Header" : "Body",
08782               i, (int) strlen(previous_header), previous_header );
08783       }
08784       i++;
08785    }
08786 
08787    /* update count of header or body lines */
08788    if (req->headers >= 0) {   /* we are in the body */
08789       req->lines = i;
08790    } else {       /* no body */
08791       req->headers = i;
08792       req->lines = 0;
08793       /* req->data->used will be a NULL byte */
08794       req->line[0] = ast_str_strlen(req->data);
08795    }
08796 
08797    if (*c) {
08798       ast_log(LOG_WARNING, "Too many lines, skipping <%s>\n", c);
08799    }
08800 
08801    /* Split up the first line parts */
08802    return determine_firstline_parts(req);
08803 }
08804 
08805 /*!
08806   \brief Determine whether a SIP message contains an SDP in its body
08807   \param req the SIP request to process
08808   \return 1 if SDP found, 0 if not found
08809 
08810   Also updates req->sdp_start and req->sdp_count to indicate where the SDP
08811   lives in the message body.
08812 */
08813 static int find_sdp(struct sip_request *req)
08814 {
08815    const char *content_type;
08816    const char *content_length;
08817    const char *search;
08818    char *boundary;
08819    unsigned int x;
08820    int boundaryisquoted = FALSE;
08821    int found_application_sdp = FALSE;
08822    int found_end_of_headers = FALSE;
08823 
08824    content_length = sip_get_header(req, "Content-Length");
08825 
08826    if (!ast_strlen_zero(content_length)) {
08827       if (sscanf(content_length, "%30u", &x) != 1) {
08828          ast_log(LOG_WARNING, "Invalid Content-Length: %s\n", content_length);
08829          return 0;
08830       }
08831 
08832       /* Content-Length of zero means there can't possibly be an
08833          SDP here, even if the Content-Type says there is */
08834       if (x == 0)
08835          return 0;
08836    }
08837 
08838    content_type = sip_get_header(req, "Content-Type");
08839 
08840    /* if the body contains only SDP, this is easy */
08841    if (!strncasecmp(content_type, "application/sdp", 15)) {
08842       req->sdp_start = 0;
08843       req->sdp_count = req->lines;
08844       return req->lines ? 1 : 0;
08845    }
08846 
08847    /* if it's not multipart/mixed, there cannot be an SDP */
08848    if (strncasecmp(content_type, "multipart/mixed", 15))
08849       return 0;
08850 
08851    /* if there is no boundary marker, it's invalid */
08852    if ((search = strcasestr(content_type, ";boundary=")))
08853       search += 10;
08854    else if ((search = strcasestr(content_type, "; boundary=")))
08855       search += 11;
08856    else
08857       return 0;
08858 
08859    if (ast_strlen_zero(search))
08860       return 0;
08861 
08862    /* If the boundary is quoted with ", remove quote */
08863    if (*search == '\"')  {
08864       search++;
08865       boundaryisquoted = TRUE;
08866    }
08867 
08868    /* make a duplicate of the string, with two extra characters
08869       at the beginning */
08870    boundary = ast_strdupa(search - 2);
08871    boundary[0] = boundary[1] = '-';
08872    /* Remove final quote */
08873    if (boundaryisquoted)
08874       boundary[strlen(boundary) - 1] = '\0';
08875 
08876    /* search for the boundary marker, the empty line delimiting headers from
08877       sdp part and the end boundry if it exists */
08878 
08879    for (x = 0; x < (req->lines); x++) {
08880       const char *line = REQ_OFFSET_TO_STR(req, line[x]);
08881       if (!strncasecmp(line, boundary, strlen(boundary))){
08882          if (found_application_sdp && found_end_of_headers) {
08883             req->sdp_count = (x - 1) - req->sdp_start;
08884             return 1;
08885          }
08886          found_application_sdp = FALSE;
08887       }
08888       if (!strcasecmp(line, "Content-Type: application/sdp"))
08889          found_application_sdp = TRUE;
08890       
08891       if (ast_strlen_zero(line)) {
08892          if (found_application_sdp && !found_end_of_headers){
08893             req->sdp_start = x;
08894             found_end_of_headers = TRUE;
08895          }
08896       }
08897    }
08898    if (found_application_sdp && found_end_of_headers) {
08899       req->sdp_count = x - req->sdp_start;
08900       return TRUE;
08901    }
08902    return FALSE;
08903 }
08904 
08905 /*! \brief Change hold state for a call */
08906 static void change_hold_state(struct sip_pvt *dialog, struct sip_request *req, int holdstate, int sendonly)
08907 {
08908    if (sip_cfg.notifyhold && (!holdstate || !ast_test_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD)))
08909       sip_peer_hold(dialog, holdstate);
08910    if (sip_cfg.callevents)
08911       manager_event(EVENT_FLAG_CALL, "Hold",
08912                "Status: %s\r\n"
08913                "Channel: %s\r\n"
08914                "Uniqueid: %s\r\n",
08915                holdstate ? "On" : "Off",
08916                ast_channel_name(dialog->owner),
08917                ast_channel_uniqueid(dialog->owner));
08918    append_history(dialog, holdstate ? "Hold" : "Unhold", "%s", req->data->str);
08919    if (!holdstate) { /* Put off remote hold */
08920       ast_clear_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD);   /* Clear both flags */
08921       return;
08922    }
08923    /* No address for RTP, we're on hold */
08924 
08925    if (sendonly == 1)   /* One directional hold (sendonly/recvonly) */
08926       ast_set_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD_ONEDIR);
08927    else if (sendonly == 2) /* Inactive stream */
08928       ast_set_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD_INACTIVE);
08929    else
08930       ast_set_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD_ACTIVE);
08931    return;
08932 }
08933 
08934 
08935 static int get_ip_and_port_from_sdp(struct sip_request *req, const enum media_type media, struct ast_sockaddr *addr)
08936 {
08937    const char *m;
08938    const char *c;
08939    int miterator = req->sdp_start;
08940    int citerator = req->sdp_start;
08941    int x = 0;
08942    int numberofports;
08943    int len;
08944    int af;
08945    char proto[4], host[258] = ""; /*Initialize to empty so we will know if we have any input */
08946 
08947    c = get_sdp_iterate(&citerator, req, "c");
08948    if (sscanf(c, "IN %3s %256s", proto, host) != 2) {
08949          ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
08950          /* Continue since there may be a valid host in a c= line specific to the audio stream */
08951    }
08952    /* We only want the m and c lines for audio */
08953    for (m = get_sdp_iterate(&miterator, req, "m"); !ast_strlen_zero(m); m = get_sdp_iterate(&miterator, req, "m")) {
08954       if ((media == SDP_AUDIO && ((sscanf(m, "audio %30u/%30u RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
08955           (sscanf(m, "audio %30u RTP/AVP %n", &x, &len) == 1 && len > 0))) ||
08956          (media == SDP_VIDEO && ((sscanf(m, "video %30u/%30u RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
08957           (sscanf(m, "video %30u RTP/AVP %n", &x, &len) == 1 && len > 0)))) {
08958          /* See if there's a c= line for this media stream.
08959           * XXX There is no guarantee that we'll be grabbing the c= line for this
08960           * particular media stream here. However, this is the same logic used in process_sdp.
08961           */
08962          c = get_sdp_iterate(&citerator, req, "c");
08963          if (!ast_strlen_zero(c)) {
08964             sscanf(c, "IN %3s %256s", proto, host);
08965          }
08966          break;
08967       }
08968    }
08969 
08970    if (!strcmp("IP4", proto)) {
08971       af = AF_INET;
08972    } else if (!strcmp("IP6", proto)) {
08973       af = AF_INET6;
08974    } else {
08975       ast_log(LOG_WARNING, "Unknown protocol '%s'.\n", proto);
08976       return -1;
08977    }
08978 
08979    if (ast_strlen_zero(host) || x == 0) {
08980       ast_log(LOG_WARNING, "Failed to read an alternate host or port in SDP. Expect %s problems\n", media == SDP_AUDIO ? "audio" : "video");
08981       return -1;
08982    }
08983 
08984    if (ast_sockaddr_resolve_first_af(addr, host, 0, af)) {
08985       ast_log(LOG_WARNING, "Could not look up IP address of alternate hostname. Expect %s problems\n", media == SDP_AUDIO? "audio" : "video");
08986       return -1;
08987    }
08988 
08989    return 0;
08990 }
08991 
08992 /*! \internal
08993  * \brief Returns whether or not the address is null or ANY / unspecified (0.0.0.0 or ::)
08994  * \retval TRUE if the address is null or any
08995  * \retval FALSE if the address it not null or any
08996  * \note In some circumstances, calls should be placed on hold if either of these conditions exist.
08997  */
08998 static int sockaddr_is_null_or_any(const struct ast_sockaddr *addr)
08999 {
09000    return ast_sockaddr_isnull(addr) || ast_sockaddr_is_any(addr);
09001 }
09002 
09003 /*! \brief Process SIP SDP offer, select formats and activate RTP channels
09004    If offer is rejected, we will not change any properties of the call
09005    Return 0 on success, a negative value on errors.
09006    Must be called after find_sdp().
09007 */
09008 static int process_sdp(struct sip_pvt *p, struct sip_request *req, int t38action)
09009 {
09010    int res = 0;
09011 
09012    /* Iterators for SDP parsing */
09013    int start = req->sdp_start;
09014    int next = start;
09015    int iterator = start;
09016 
09017    /* Temporary vars for SDP parsing */
09018    char type = '\0';
09019    const char *value = NULL;
09020    const char *m = NULL;           /* SDP media offer */
09021    const char *nextm = NULL;
09022    int len = -1;
09023 
09024    /* Host information */
09025    struct ast_sockaddr sessionsa;
09026    struct ast_sockaddr audiosa;
09027    struct ast_sockaddr videosa;
09028    struct ast_sockaddr textsa;
09029    struct ast_sockaddr imagesa;
09030    struct ast_sockaddr *sa = NULL;  /*!< RTP Audio host IP */
09031    struct ast_sockaddr *vsa = NULL; /*!< RTP video host IP */
09032    struct ast_sockaddr *tsa = NULL; /*!< RTP text host IP */
09033    struct ast_sockaddr *isa = NULL;     /*!< UDPTL host ip */
09034    int portno = -1;     /*!< RTP Audio port number */
09035    int vportno = -1;    /*!< RTP Video port number */
09036    int tportno = -1;    /*!< RTP Text port number */
09037    int udptlportno = -1;      /*!< UDPTL Image port number */
09038 
09039    /* Peer capability is the capability in the SDP, non codec is RFC2833 DTMF (101) */ 
09040    struct ast_format_cap *peercapability = ast_format_cap_alloc_nolock();
09041    struct ast_format_cap *vpeercapability = ast_format_cap_alloc_nolock();
09042    struct ast_format_cap *tpeercapability = ast_format_cap_alloc_nolock();
09043 
09044    int peernoncodeccapability = 0, vpeernoncodeccapability = 0, tpeernoncodeccapability = 0;
09045 
09046    struct ast_rtp_codecs newaudiortp, newvideortp, newtextrtp;
09047    struct ast_format_cap *newjointcapability = ast_format_cap_alloc_nolock(); /* Negotiated capability */
09048    struct ast_format_cap *newpeercapability = ast_format_cap_alloc_nolock();
09049    int newnoncodeccapability;
09050 
09051    const char *codecs;
09052    int codec;
09053 
09054    /* SRTP */
09055    int secure_audio = FALSE;
09056    int secure_video = FALSE;
09057 
09058    /* Others */
09059    int sendonly = -1;
09060    int vsendonly = -1;
09061    int numberofports;
09062    int numberofmediastreams = 0;
09063    int last_rtpmap_codec = 0;
09064    int red_data_pt[10];    /* For T.140 red */
09065    int red_num_gen = 0;    /* For T.140 red */
09066    char red_fmtp[100] = "empty"; /* For T.140 red */
09067    int debug = sip_debug_test_pvt(p);
09068 
09069    /* START UNKNOWN */
09070    char buf[SIPBUFSIZE];
09071    struct ast_format tmp_fmt;
09072    /* END UNKNOWN */
09073 
09074    /* Initial check */
09075    if (!p->rtp) {
09076       ast_log(LOG_ERROR, "Got SDP but have no RTP session allocated.\n");
09077       res = -1;
09078       goto process_sdp_cleanup;
09079    }
09080    if (!peercapability || !vpeercapability || !tpeercapability || !newpeercapability || !newjointcapability) {
09081       res = -1;
09082       goto process_sdp_cleanup;
09083    }
09084 
09085    /* Make sure that the codec structures are all cleared out */
09086    ast_rtp_codecs_payloads_clear(&newaudiortp, NULL);
09087    ast_rtp_codecs_payloads_clear(&newvideortp, NULL);
09088    ast_rtp_codecs_payloads_clear(&newtextrtp, NULL);
09089 
09090    /* Update our last rtprx when we receive an SDP, too */
09091    p->lastrtprx = p->lastrtptx = time(NULL); /* XXX why both ? */
09092 
09093    memset(p->offered_media, 0, sizeof(p->offered_media));
09094 
09095    if (p->vrtp) {
09096       ast_rtp_codecs_payloads_clear(&newvideortp, NULL);
09097    }
09098 
09099    if (p->trtp) {
09100       ast_rtp_codecs_payloads_clear(&newtextrtp, NULL);
09101    }
09102 
09103    /* Scan for the first media stream (m=) line to limit scanning of globals */
09104    nextm = get_sdp_iterate(&next, req, "m");
09105    if (ast_strlen_zero(nextm)) {
09106       ast_log(LOG_WARNING, "Insufficient information for SDP (m= not found)\n");
09107       res = -1;
09108       goto process_sdp_cleanup;
09109    }
09110 
09111    /* Scan session level SDP parameters (lines before first media stream) */
09112    while ((type = get_sdp_line(&iterator, next - 1, req, &value)) != '\0') {
09113       int processed = FALSE;
09114       switch (type) {
09115       case 'o':
09116          /* If we end up receiving SDP that doesn't actually modify the session we don't want to treat this as a fatal
09117           * error. We just want to ignore the SDP and let the rest of the packet be handled as normal.
09118           */
09119          if (!process_sdp_o(value, p)) {
09120             res = (p->session_modify == FALSE) ? 0 : -1;
09121             goto process_sdp_cleanup;
09122          }
09123          break;
09124       case 'c':
09125          if (process_sdp_c(value, &sessionsa)) {
09126             processed = TRUE;
09127             sa = &sessionsa;
09128             vsa = sa;
09129             tsa = sa;
09130             isa = sa;
09131          }
09132          break;
09133       case 'a':
09134          if (process_sdp_a_sendonly(value, &sendonly)) {
09135             processed = TRUE;
09136             vsendonly = sendonly;
09137          }
09138          else if (process_sdp_a_audio(value, p, &newaudiortp, &last_rtpmap_codec))
09139             processed = TRUE;
09140          else if (process_sdp_a_video(value, p, &newvideortp, &last_rtpmap_codec))
09141             processed = TRUE;
09142          else if (process_sdp_a_text(value, p, &newtextrtp, red_fmtp, &red_num_gen, red_data_pt, &last_rtpmap_codec))
09143             processed = TRUE;
09144          else if (process_sdp_a_image(value, p))
09145             processed = TRUE;
09146          break;
09147       }
09148 
09149       ast_debug(3, "Processing session-level SDP %c=%s... %s\n", type, value, (processed == TRUE)? "OK." : "UNSUPPORTED.");
09150    }
09151 
09152    /* default: novideo and notext set */
09153    p->novideo = TRUE;
09154    p->notext = TRUE;
09155 
09156    /* Scan media stream (m=) specific parameters loop */
09157    while (!ast_strlen_zero(nextm)) {
09158       int audio = FALSE;
09159       int video = FALSE;
09160       int image = FALSE;
09161       int text = FALSE;
09162       char protocol[5] = {0,};
09163       int x;
09164 
09165       numberofports = 1;
09166       len = -1;
09167       start = next;
09168       m = nextm;
09169       iterator = next;
09170       nextm = get_sdp_iterate(&next, req, "m");
09171 
09172       /* Search for audio media definition */
09173       if ((sscanf(m, "audio %30u/%30u RTP/%4s %n", &x, &numberofports, protocol, &len) == 3 && len > 0) ||
09174           (sscanf(m, "audio %30u RTP/%4s %n", &x, protocol, &len) == 2 && len > 0)) {
09175          if (x == 0) {
09176             ast_log(LOG_WARNING, "ignoring 'audio' media offer because port number is zero");
09177             continue;
09178          }
09179          if (!strcmp(protocol, "SAVP")) {
09180             secure_audio = 1;
09181          } else if (strcmp(protocol, "AVP")) {
09182             ast_log(LOG_WARNING, "unknown SDP media protocol in offer: %s\n", protocol);
09183             continue;
09184          }
09185          if (p->offered_media[SDP_AUDIO].order_offered) {
09186             ast_log(LOG_WARNING, "Multiple audio streams are not supported\n");
09187             res = -3;
09188             goto process_sdp_cleanup;
09189          }
09190          audio = TRUE;
09191          p->offered_media[SDP_AUDIO].order_offered = ++numberofmediastreams;
09192          portno = x;
09193 
09194          /* Scan through the RTP payload types specified in a "m=" line: */
09195          codecs = m + len;
09196          ast_copy_string(p->offered_media[SDP_AUDIO].codecs, codecs, sizeof(p->offered_media[SDP_AUDIO].codecs));
09197          for (; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
09198             if (sscanf(codecs, "%30u%n", &codec, &len) != 1) {
09199                ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
09200                res = -1;
09201                goto process_sdp_cleanup;
09202             }
09203             if (debug)
09204                ast_verbose("Found RTP audio format %d\n", codec);
09205 
09206             ast_rtp_codecs_payloads_set_m_type(&newaudiortp, NULL, codec);
09207          }
09208       /* Search for video media definition */
09209       } else if ((sscanf(m, "video %30u/%30u RTP/%4s %n", &x, &numberofports, protocol, &len) == 3 && len > 0) ||
09210             (sscanf(m, "video %30u RTP/%4s %n", &x, protocol, &len) == 2 && len > 0)) {
09211          if (x == 0) {
09212             ast_log(LOG_WARNING, "ignoring 'video' media offer because port number is zero");
09213             continue;
09214          }
09215          if (!strcmp(protocol, "SAVP")) {
09216             secure_video = 1;
09217          } else if (strcmp(protocol, "AVP")) {
09218             ast_log(LOG_WARNING, "unknown SDP media protocol in offer: %s\n", protocol);
09219             continue;
09220          }
09221          if (p->offered_media[SDP_VIDEO].order_offered) {
09222             ast_log(LOG_WARNING, "Multiple video streams are not supported\n");
09223             res = -3;
09224             goto process_sdp_cleanup;
09225          }
09226          video = TRUE;
09227          p->novideo = FALSE;
09228          p->offered_media[SDP_VIDEO].order_offered = ++numberofmediastreams;
09229          vportno = x;
09230 
09231          /* Scan through the RTP payload types specified in a "m=" line: */
09232          codecs = m + len;
09233          ast_copy_string(p->offered_media[SDP_VIDEO].codecs, codecs, sizeof(p->offered_media[SDP_VIDEO].codecs));
09234          for (; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
09235             if (sscanf(codecs, "%30u%n", &codec, &len) != 1) {
09236                ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
09237                res = -1;
09238                goto process_sdp_cleanup;
09239             }
09240             if (debug)
09241                ast_verbose("Found RTP video format %d\n", codec);
09242             ast_rtp_codecs_payloads_set_m_type(&newvideortp, NULL, codec);
09243          }
09244       /* Search for text media definition */
09245       } else if ((sscanf(m, "text %30u/%30u RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
09246             (sscanf(m, "text %30u RTP/AVP %n", &x, &len) == 1 && len > 0)) {
09247          if (x == 0) {
09248             ast_log(LOG_WARNING, "ignoring 'text' media offer because port number is zero");
09249             continue;
09250          }
09251          if (p->offered_media[SDP_TEXT].order_offered) {
09252             ast_log(LOG_WARNING, "Multiple text streams are not supported\n");
09253             res = -3;
09254             goto process_sdp_cleanup;
09255          }
09256          text = TRUE;
09257          p->notext = FALSE;
09258          p->offered_media[SDP_TEXT].order_offered = ++numberofmediastreams;
09259          tportno = x;
09260 
09261          /* Scan through the RTP payload types specified in a "m=" line: */
09262          codecs = m + len;
09263          ast_copy_string(p->offered_media[SDP_TEXT].codecs, codecs, sizeof(p->offered_media[SDP_TEXT].codecs));
09264          for (; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
09265             if (sscanf(codecs, "%30u%n", &codec, &len) != 1) {
09266                ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
09267                res = -1;
09268                goto process_sdp_cleanup;
09269             }
09270             if (debug)
09271                ast_verbose("Found RTP text format %d\n", codec);
09272             ast_rtp_codecs_payloads_set_m_type(&newtextrtp, NULL, codec);
09273          }
09274       /* Search for image media definition */
09275       } else if (((sscanf(m, "image %30u udptl t38%n", &x, &len) == 1 && len > 0) ||
09276              (sscanf(m, "image %30u UDPTL t38%n", &x, &len) == 1 && len > 0))) {
09277          if (x == 0) {
09278             ast_log(LOG_WARNING, "ignoring 'image' media offer because port number is zero");
09279             continue;
09280          }
09281          if (initialize_udptl(p)) {
09282             continue;
09283          }
09284 
09285          if (p->offered_media[SDP_IMAGE].order_offered) {
09286             ast_log(LOG_WARNING, "Multiple T.38 streams are not supported\n");
09287             res = -3;
09288             goto process_sdp_cleanup;
09289          }
09290          image = TRUE;
09291          if (debug)
09292             ast_verbose("Got T.38 offer in SDP in dialog %s\n", p->callid);
09293          p->offered_media[SDP_IMAGE].order_offered = ++numberofmediastreams;
09294          udptlportno = x;
09295 
09296          if (p->t38.state != T38_ENABLED) {
09297             memset(&p->t38.their_parms, 0, sizeof(p->t38.their_parms));
09298 
09299             /* default EC to none, the remote end should
09300              * respond with the EC they want to use */
09301             ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_NONE);
09302          }
09303       } else {
09304          ast_log(LOG_WARNING, "Unsupported SDP media type in offer: %s\n", m);
09305          continue;
09306       }
09307 
09308       /* Check for number of ports */
09309       if (numberofports > 1)
09310          ast_log(LOG_WARNING, "SDP offered %d ports for media, not supported by Asterisk. Will try anyway...\n", numberofports);
09311       
09312       /* Media stream specific parameters */
09313       while ((type = get_sdp_line(&iterator, next - 1, req, &value)) != '\0') {
09314          int processed = FALSE;
09315 
09316          switch (type) {
09317          case 'c':
09318             if (audio) {
09319                if (process_sdp_c(value, &audiosa)) {
09320                   processed = TRUE;
09321                   sa = &audiosa;
09322                }
09323             } else if (video) {
09324                if (process_sdp_c(value, &videosa)) {
09325                   processed = TRUE;
09326                   vsa = &videosa;
09327                }
09328             } else if (text) {
09329                if (process_sdp_c(value, &textsa)) {
09330                   processed = TRUE;
09331                   tsa = &textsa;
09332                }
09333             } else if (image) {
09334                if (process_sdp_c(value, &imagesa)) {
09335                   processed = TRUE;
09336                   isa = &imagesa;
09337                }
09338             }
09339             break;
09340          case 'a':
09341             /* Audio specific scanning */
09342             if (audio) {
09343                if (process_sdp_a_sendonly(value, &sendonly))
09344                   processed = TRUE;
09345                else if (process_crypto(p, p->rtp, &p->srtp, value))
09346                   processed = TRUE;
09347                else if (process_sdp_a_audio(value, p, &newaudiortp, &last_rtpmap_codec))
09348                   processed = TRUE;
09349             }
09350             /* Video specific scanning */
09351             else if (video) {
09352                if (process_sdp_a_sendonly(value, &vsendonly))
09353                   processed = TRUE;
09354                else if (process_crypto(p, p->vrtp, &p->vsrtp, value))
09355                   processed = TRUE;
09356                else if (process_sdp_a_video(value, p, &newvideortp, &last_rtpmap_codec))
09357                   processed = TRUE;
09358             }
09359             /* Text (T.140) specific scanning */
09360             else if (text) {
09361                if (process_sdp_a_text(value, p, &newtextrtp, red_fmtp, &red_num_gen, red_data_pt, &last_rtpmap_codec))
09362                   processed = TRUE;
09363                else if (process_crypto(p, p->trtp, &p->tsrtp, value))
09364                   processed = TRUE;
09365             }
09366             /* Image (T.38 FAX) specific scanning */
09367             else if (image) {
09368                if (process_sdp_a_image(value, p))
09369                   processed = TRUE;
09370             }
09371             break;
09372          }
09373 
09374          ast_debug(3, "Processing media-level (%s) SDP %c=%s... %s\n",
09375                (audio == TRUE)? "audio" : (video == TRUE)? "video" : "image",
09376                type, value,
09377                (processed == TRUE)? "OK." : "UNSUPPORTED.");
09378       }
09379    }
09380 
09381 
09382    /* Sanity checks */
09383    if (!sa && !vsa && !tsa && !isa) {
09384       ast_log(LOG_WARNING, "Insufficient information in SDP (c=)...\n");
09385       res = -1;
09386       goto process_sdp_cleanup;
09387    }
09388 
09389    if (portno == -1 && vportno == -1 && udptlportno == -1  && tportno == -1) {
09390       /* No acceptable offer found in SDP  - we have no ports */
09391       /* Do not change RTP or VRTP if this is a re-invite */
09392       ast_log(LOG_WARNING, "Failing due to no acceptable offer found\n");
09393       res = -2;
09394       goto process_sdp_cleanup;
09395    }
09396 
09397    if (secure_audio && !(p->srtp && (ast_test_flag(p->srtp, SRTP_CRYPTO_OFFER_OK)))) {
09398       ast_log(LOG_WARNING, "Can't provide secure audio requested in SDP offer\n");
09399       res = -4;
09400       goto process_sdp_cleanup;
09401    }
09402 
09403    if (!secure_audio && p->srtp) {
09404       ast_log(LOG_WARNING, "We are requesting SRTP, but they responded without it!\n");
09405       res = -4;
09406       goto process_sdp_cleanup;
09407    }
09408 
09409    if (secure_video && !(p->vsrtp && (ast_test_flag(p->vsrtp, SRTP_CRYPTO_OFFER_OK)))) {
09410       ast_log(LOG_WARNING, "Can't provide secure video requested in SDP offer\n");
09411       res = -4;
09412       goto process_sdp_cleanup;
09413    }
09414 
09415    if (!p->novideo && !secure_video && p->vsrtp) {
09416       ast_log(LOG_WARNING, "We are requesting SRTP, but they responded without it!\n");
09417       res = -4;
09418       goto process_sdp_cleanup;
09419    }
09420 
09421    if (!(secure_audio || secure_video) && ast_test_flag(&p->flags[1], SIP_PAGE2_USE_SRTP)) {
09422       ast_log(LOG_WARNING, "Matched device setup to use SRTP, but request was not!\n");
09423       res = -4;
09424       goto process_sdp_cleanup;
09425    }
09426 
09427    if (udptlportno == -1) {
09428       change_t38_state(p, T38_DISABLED);
09429    }
09430 
09431    /* Now gather all of the codecs that we are asked for: */
09432    ast_rtp_codecs_payload_formats(&newaudiortp, peercapability, &peernoncodeccapability);
09433    ast_rtp_codecs_payload_formats(&newvideortp, vpeercapability, &vpeernoncodeccapability);
09434    ast_rtp_codecs_payload_formats(&newtextrtp, tpeercapability, &tpeernoncodeccapability);
09435 
09436    ast_format_cap_append(newpeercapability, peercapability);
09437    ast_format_cap_append(newpeercapability, vpeercapability);
09438    ast_format_cap_append(newpeercapability, tpeercapability);
09439 
09440    ast_format_cap_joint_copy(p->caps, newpeercapability, newjointcapability);
09441    if (ast_format_cap_is_empty(newjointcapability) && udptlportno == -1) {
09442       ast_log(LOG_NOTICE, "No compatible codecs, not accepting this offer!\n");
09443       /* Do NOT Change current setting */
09444       res = -1;
09445       goto process_sdp_cleanup;
09446    }
09447 
09448    newnoncodeccapability = p->noncodeccapability & peernoncodeccapability;
09449 
09450    if (debug) {
09451       /* shame on whoever coded this.... */
09452       char s1[SIPBUFSIZE], s2[SIPBUFSIZE], s3[SIPBUFSIZE], s4[SIPBUFSIZE], s5[SIPBUFSIZE];
09453 
09454       ast_verbose("Capabilities: us - %s, peer - audio=%s/video=%s/text=%s, combined - %s\n",
09455              ast_getformatname_multiple(s1, SIPBUFSIZE, p->caps),
09456              ast_getformatname_multiple(s2, SIPBUFSIZE, peercapability),
09457              ast_getformatname_multiple(s3, SIPBUFSIZE, vpeercapability),
09458              ast_getformatname_multiple(s4, SIPBUFSIZE, tpeercapability),
09459              ast_getformatname_multiple(s5, SIPBUFSIZE, newjointcapability));
09460    }
09461    if (debug) {
09462       struct ast_str *s1 = ast_str_alloca(SIPBUFSIZE);
09463       struct ast_str *s2 = ast_str_alloca(SIPBUFSIZE);
09464       struct ast_str *s3 = ast_str_alloca(SIPBUFSIZE);
09465 
09466       ast_verbose("Non-codec capabilities (dtmf): us - %s, peer - %s, combined - %s\n",
09467              ast_rtp_lookup_mime_multiple2(s1, NULL, p->noncodeccapability, 0, 0),
09468              ast_rtp_lookup_mime_multiple2(s2, NULL, peernoncodeccapability, 0, 0),
09469              ast_rtp_lookup_mime_multiple2(s3, NULL, newnoncodeccapability, 0, 0));
09470    }
09471 
09472    if (portno != -1 || vportno != -1 || tportno != -1) {
09473       /* We are now ready to change the sip session and p->rtp and p->vrtp with the offered codecs, since
09474          they are acceptable */
09475       ast_format_cap_copy(p->jointcaps, newjointcapability);                /* Our joint codec profile for this call */
09476       ast_format_cap_copy(p->peercaps, newpeercapability);                  /* The other sides capability in latest offer */
09477       p->jointnoncodeccapability = newnoncodeccapability;     /* DTMF capabilities */
09478    
09479       /* respond with single most preferred joint codec, limiting the other side's choice */
09480       if (ast_test_flag(&p->flags[1], SIP_PAGE2_PREFERRED_CODEC)) {
09481          ast_codec_choose(&p->prefs, p->jointcaps, 1, &tmp_fmt);
09482          ast_format_cap_set(p->jointcaps, &tmp_fmt);
09483       }
09484    }
09485 
09486    /* Setup audio address and port */
09487    if (p->rtp) {
09488       if (portno > 0) {
09489          ast_sockaddr_set_port(sa, portno);
09490          ast_rtp_instance_set_remote_address(p->rtp, sa);
09491          if (debug) {
09492             ast_verbose("Peer audio RTP is at port %s\n",
09493                    ast_sockaddr_stringify(sa));
09494          }
09495 
09496          ast_rtp_codecs_payloads_copy(&newaudiortp, ast_rtp_instance_get_codecs(p->rtp), p->rtp);
09497          /* Ensure RTCP is enabled since it may be inactive
09498             if we're coming back from a T.38 session */
09499          ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_RTCP, 1);
09500          /* Ensure audio RTCP reads are enabled */
09501          if (p->owner) {
09502             ast_channel_set_fd(p->owner, 1, ast_rtp_instance_fd(p->rtp, 1));
09503          }
09504 
09505          if (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO) {
09506             ast_clear_flag(&p->flags[0], SIP_DTMF);
09507             if (newnoncodeccapability & AST_RTP_DTMF) {
09508                /* XXX Would it be reasonable to drop the DSP at this point? XXX */
09509                ast_set_flag(&p->flags[0], SIP_DTMF_RFC2833);
09510                /* Since RFC2833 is now negotiated we need to change some properties of the RTP stream */
09511                ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_DTMF, 1);
09512                ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_DTMF_COMPENSATE, ast_test_flag(&p->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
09513             } else {
09514                ast_set_flag(&p->flags[0], SIP_DTMF_INBAND);
09515             }
09516          }
09517       } else if (udptlportno > 0) {
09518          if (debug)
09519             ast_verbose("Got T.38 Re-invite without audio. Keeping RTP active during T.38 session.\n");
09520          /* Prevent audio RTCP reads */
09521          if (p->owner) {
09522             ast_channel_set_fd(p->owner, 1, -1);
09523          }
09524          /* Silence RTCP while audio RTP is inactive */
09525          ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_RTCP, 0);
09526       } else {
09527          ast_rtp_instance_stop(p->rtp);
09528          if (debug)
09529             ast_verbose("Peer doesn't provide audio\n");
09530       }
09531    }
09532 
09533    /* Setup video address and port */
09534    if (p->vrtp) {
09535       if (vportno > 0) {
09536          ast_sockaddr_set_port(vsa, vportno);
09537          ast_rtp_instance_set_remote_address(p->vrtp, vsa);
09538          if (debug) {
09539             ast_verbose("Peer video RTP is at port %s\n",
09540                    ast_sockaddr_stringify(vsa));
09541          }
09542          ast_rtp_codecs_payloads_copy(&newvideortp, ast_rtp_instance_get_codecs(p->vrtp), p->vrtp);
09543       } else {
09544          ast_rtp_instance_stop(p->vrtp);
09545          if (debug)
09546             ast_verbose("Peer doesn't provide video\n");
09547       }
09548    }
09549 
09550    /* Setup text address and port */
09551    if (p->trtp) {
09552       if (tportno > 0) {
09553          ast_sockaddr_set_port(tsa, tportno);
09554          ast_rtp_instance_set_remote_address(p->trtp, tsa);
09555          if (debug) {
09556             ast_verbose("Peer T.140 RTP is at port %s\n",
09557                    ast_sockaddr_stringify(tsa));
09558          }
09559          if (ast_format_cap_iscompatible(p->jointcaps, ast_format_set(&tmp_fmt, AST_FORMAT_T140RED, 0))) {
09560             p->red = 1;
09561             ast_rtp_red_init(p->trtp, 300, red_data_pt, 2);
09562          } else {
09563             p->red = 0;
09564          }
09565          ast_rtp_codecs_payloads_copy(&newtextrtp, ast_rtp_instance_get_codecs(p->trtp), p->trtp);
09566       } else {
09567          ast_rtp_instance_stop(p->trtp);
09568          if (debug)
09569             ast_verbose("Peer doesn't provide T.140\n");
09570       }
09571    }
09572    /* Setup image address and port */
09573    if (p->udptl) {
09574       if (udptlportno > 0) {
09575          if (ast_test_flag(&p->flags[1], SIP_PAGE2_SYMMETRICRTP) && ast_test_flag(&p->flags[1], SIP_PAGE2_UDPTL_DESTINATION)) {
09576             ast_rtp_instance_get_remote_address(p->rtp, isa);
09577             if (!ast_sockaddr_isnull(isa) && debug) {
09578                ast_debug(1, "Peer T.38 UDPTL is set behind NAT and with destination, destination address now %s\n", ast_sockaddr_stringify(isa));
09579             }
09580          }
09581          ast_sockaddr_set_port(isa, udptlportno);
09582          ast_udptl_set_peer(p->udptl, isa);
09583          if (debug)
09584             ast_debug(1,"Peer T.38 UDPTL is at port %s\n", ast_sockaddr_stringify(isa));
09585 
09586          /* verify the far max ifp can be calculated. this requires far max datagram to be set. */
09587          if (!ast_udptl_get_far_max_datagram(p->udptl)) {
09588             /* setting to zero will force a default if none was provided by the SDP */
09589             ast_udptl_set_far_max_datagram(p->udptl, 0);
09590          }
09591 
09592          /* Remote party offers T38, we need to update state */
09593          if ((t38action == SDP_T38_ACCEPT) &&
09594              (p->t38.state == T38_LOCAL_REINVITE)) {
09595             change_t38_state(p, T38_ENABLED);
09596          } else if ((t38action == SDP_T38_INITIATE) &&
09597                p->owner && p->lastinvite) {
09598             change_t38_state(p, T38_PEER_REINVITE); /* T38 Offered in re-invite from remote party */
09599             /* If fax detection is enabled then send us off to the fax extension */
09600             if (ast_test_flag(&p->flags[1], SIP_PAGE2_FAX_DETECT_T38)) {
09601                ast_channel_lock(p->owner);
09602                if (strcmp(p->owner->exten, "fax")) {
09603                   const char *target_context = S_OR(p->owner->macrocontext, p->owner->context);
09604                   ast_channel_unlock(p->owner);
09605                   if (ast_exists_extension(p->owner, target_context, "fax", 1,
09606                      S_COR(p->owner->caller.id.number.valid, p->owner->caller.id.number.str, NULL))) {
09607                      ast_verb(2, "Redirecting '%s' to fax extension due to peer T.38 re-INVITE\n", ast_channel_name(p->owner));
09608                      pbx_builtin_setvar_helper(p->owner, "FAXEXTEN", p->owner->exten);
09609                      if (ast_async_goto(p->owner, target_context, "fax", 1)) {
09610                         ast_log(LOG_NOTICE, "Failed to async goto '%s' into fax of '%s'\n", ast_channel_name(p->owner), target_context);
09611                      }
09612                   } else {
09613                      ast_log(LOG_NOTICE, "T.38 re-INVITE detected but no fax extension\n");
09614                   }
09615                } else {
09616                   ast_channel_unlock(p->owner);
09617                }
09618             }
09619          }
09620       } else {
09621          change_t38_state(p, T38_DISABLED);
09622          ast_udptl_stop(p->udptl);
09623          if (debug)
09624             ast_debug(1, "Peer doesn't provide T.38 UDPTL\n");
09625       }
09626    }
09627 
09628    if ((portno == -1) && (p->t38.state != T38_DISABLED) && (p->t38.state != T38_REJECTED)) {
09629       ast_debug(3, "Have T.38 but no audio, accepting offer anyway\n");
09630       res = 0;
09631       goto process_sdp_cleanup;
09632    }
09633 
09634    /* Ok, we're going with this offer */
09635    ast_debug(2, "We're settling with these formats: %s\n", ast_getformatname_multiple(buf, SIPBUFSIZE, p->jointcaps));
09636 
09637    if (!p->owner) { /* There's no open channel owning us so we can return here. For a re-invite or so, we proceed */
09638       res = 0;
09639       goto process_sdp_cleanup;
09640    }
09641 
09642    ast_debug(4, "We have an owner, now see if we need to change this call\n");
09643    if (ast_format_cap_has_type(p->jointcaps, AST_FORMAT_TYPE_AUDIO)) {
09644       if (debug) {
09645          char s1[SIPBUFSIZE], s2[SIPBUFSIZE];
09646          ast_debug(1, "Setting native formats after processing SDP. peer joint formats %s, old nativeformats %s\n",
09647             ast_getformatname_multiple(s1, SIPBUFSIZE, p->jointcaps),
09648             ast_getformatname_multiple(s2, SIPBUFSIZE, p->owner->nativeformats));
09649       }
09650 
09651       ast_codec_choose(&p->prefs, p->jointcaps, 1, &tmp_fmt);
09652 
09653       ast_format_cap_set(p->owner->nativeformats, &tmp_fmt);
09654       ast_format_cap_joint_append(p->caps, vpeercapability, p->owner->nativeformats);
09655       ast_format_cap_joint_append(p->caps, tpeercapability, p->owner->nativeformats);
09656 
09657       ast_set_read_format(p->owner, &p->owner->readformat);
09658       ast_set_write_format(p->owner, &p->owner->writeformat);
09659    }
09660 
09661    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)) {
09662       ast_queue_control(p->owner, AST_CONTROL_UNHOLD);
09663       /* Activate a re-invite */
09664       ast_queue_frame(p->owner, &ast_null_frame);
09665       change_hold_state(p, req, FALSE, sendonly);
09666    } else if ((sockaddr_is_null_or_any(sa) && sockaddr_is_null_or_any(vsa) && sockaddr_is_null_or_any(tsa) && sockaddr_is_null_or_any(isa)) || (sendonly && sendonly != -1)) {
09667       ast_queue_control_data(p->owner, AST_CONTROL_HOLD,
09668                    S_OR(p->mohsuggest, NULL),
09669                    !ast_strlen_zero(p->mohsuggest) ? strlen(p->mohsuggest) + 1 : 0);
09670       if (sendonly)
09671          ast_rtp_instance_stop(p->rtp);
09672       /* RTCP needs to go ahead, even if we're on hold!!! */
09673       /* Activate a re-invite */
09674       ast_queue_frame(p->owner, &ast_null_frame);
09675       change_hold_state(p, req, TRUE, sendonly);
09676    }
09677 
09678 process_sdp_cleanup:
09679    ast_format_cap_destroy(peercapability);
09680    ast_format_cap_destroy(vpeercapability);
09681    ast_format_cap_destroy(tpeercapability);
09682    ast_format_cap_destroy(newjointcapability);
09683    ast_format_cap_destroy(newpeercapability);
09684    return res;
09685 }
09686 
09687 static int process_sdp_o(const char *o, struct sip_pvt *p)
09688 {
09689    char *o_copy;
09690    char *token;
09691    int64_t rua_version;
09692 
09693    /* Store the SDP version number of remote UA. This will allow us to
09694    distinguish between session modifications and session refreshes. If
09695    the remote UA does not send an incremented SDP version number in a
09696    subsequent RE-INVITE then that means its not changing media session.
09697    The RE-INVITE may have been sent to update connected party, remote
09698    target or to refresh the session (Session-Timers).  Asterisk must not
09699    change media session and increment its own version number in answer
09700    SDP in this case. */
09701 
09702    p->session_modify = TRUE;
09703 
09704    if (ast_strlen_zero(o)) {
09705       ast_log(LOG_WARNING, "SDP syntax error. SDP without an o= line\n");
09706       return FALSE;
09707    }
09708 
09709    o_copy = ast_strdupa(o);
09710    token = strsep(&o_copy, " ");  /* Skip username   */
09711    if (!o_copy) {
09712       ast_log(LOG_WARNING, "SDP syntax error in o= line username\n");
09713       return FALSE;
09714    }
09715    token = strsep(&o_copy, " ");  /* Skip session-id */
09716    if (!o_copy) {
09717       ast_log(LOG_WARNING, "SDP syntax error in o= line session-id\n");
09718       return FALSE;
09719    }
09720    token = strsep(&o_copy, " ");  /* Version         */
09721    if (!o_copy) {
09722       ast_log(LOG_WARNING, "SDP syntax error in o= line\n");
09723       return FALSE;
09724    }
09725    if (!sscanf(token, "%30" SCNd64, &rua_version)) {
09726       ast_log(LOG_WARNING, "SDP syntax error in o= line version\n");
09727       return FALSE;
09728    }
09729 
09730    /* we need to check the SDP version number the other end sent us;
09731     * our rules for deciding what to accept are a bit complex.
09732     *
09733     * 1) if 'ignoresdpversion' has been set for this dialog, then
09734     *    we will just accept whatever they sent and assume it is
09735     *    a modification of the session, even if it is not
09736     * 2) otherwise, if this is the first SDP we've seen from them
09737     *    we accept it
09738     * 3) otherwise, if the new SDP version number is higher than the
09739     *    old one, we accept it
09740     * 4) otherwise, if this SDP is in response to us requesting a switch
09741     *    to T.38, we accept the SDP, but also generate a warning message
09742     *    that this peer should have the 'ignoresdpversion' option set,
09743     *    because it is not following the SDP offer/answer RFC; if we did
09744     *    not request a switch to T.38, then we stop parsing the SDP, as it
09745     *    has not changed from the previous version
09746     */
09747 
09748    if (ast_test_flag(&p->flags[1], SIP_PAGE2_IGNORESDPVERSION) ||
09749        (p->sessionversion_remote < 0) ||
09750        (p->sessionversion_remote < rua_version)) {
09751       p->sessionversion_remote = rua_version;
09752    } else {
09753       if (p->t38.state == T38_LOCAL_REINVITE) {
09754          p->sessionversion_remote = rua_version;
09755          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);
09756       } else {
09757          p->session_modify = FALSE;
09758          ast_debug(2, "Call %s responded to our reinvite without changing SDP version; ignoring SDP.\n", p->callid);
09759          return FALSE;
09760       }
09761    }
09762 
09763    return TRUE;
09764 }
09765 
09766 static int process_sdp_c(const char *c, struct ast_sockaddr *addr)
09767 {
09768    char proto[4], host[258];
09769    int af;
09770 
09771    /* Check for Media-description-level-address */
09772    if (sscanf(c, "IN %3s %255s", proto, host) == 2) {
09773       if (!strcmp("IP4", proto)) {
09774          af = AF_INET;
09775       } else if (!strcmp("IP6", proto)) {
09776          af = AF_INET6;
09777       } else {
09778          ast_log(LOG_WARNING, "Unknown protocol '%s'.\n", proto);
09779          return FALSE;
09780       }
09781       if (ast_sockaddr_resolve_first_af(addr, host, 0, af)) {
09782          ast_log(LOG_WARNING, "Unable to lookup RTP Audio host in c= line, '%s'\n", c);
09783          return FALSE;
09784       }
09785       return TRUE;
09786    } else {
09787       ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
09788       return FALSE;
09789    }
09790    return FALSE;
09791 }
09792 
09793 static int process_sdp_a_sendonly(const char *a, int *sendonly)
09794 {
09795    int found = FALSE;
09796 
09797    if (!strcasecmp(a, "sendonly")) {
09798       if (*sendonly == -1)
09799          *sendonly = 1;
09800       found = TRUE;
09801    } else if (!strcasecmp(a, "inactive")) {
09802       if (*sendonly == -1)
09803          *sendonly = 2;
09804       found = TRUE;
09805    }  else if (!strcasecmp(a, "sendrecv")) {
09806       if (*sendonly == -1)
09807          *sendonly = 0;
09808       found = TRUE;
09809    }
09810    return found;
09811 }
09812 
09813 static int process_sdp_a_audio(const char *a, struct sip_pvt *p, struct ast_rtp_codecs *newaudiortp, int *last_rtpmap_codec)
09814 {
09815    int found = FALSE;
09816    int codec;
09817    char mimeSubtype[128];
09818    char fmtp_string[64];
09819    unsigned int sample_rate;
09820    int debug = sip_debug_test_pvt(p);
09821 
09822    if (!strncasecmp(a, "ptime", 5)) {
09823       char *tmp = strrchr(a, ':');
09824       long int framing = 0;
09825       if (tmp) {
09826          tmp++;
09827          framing = strtol(tmp, NULL, 10);
09828          if (framing == LONG_MIN || framing == LONG_MAX) {
09829             framing = 0;
09830             ast_debug(1, "Can't read framing from SDP: %s\n", a);
09831          }
09832       }
09833       if (framing && p->autoframing) {
09834          struct ast_codec_pref *pref = &ast_rtp_instance_get_codecs(p->rtp)->pref;
09835          int codec_n;
09836          for (codec_n = 0; codec_n < AST_RTP_MAX_PT; codec_n++) {
09837             struct ast_rtp_payload_type format = ast_rtp_codecs_payload_lookup(ast_rtp_instance_get_codecs(p->rtp), codec_n);
09838             if (!format.asterisk_format)  /* non-codec or not found */
09839                continue;
09840             ast_debug(1, "Setting framing for %s to %ld\n", ast_getformatname(&format.format), framing);
09841             ast_codec_pref_setsize(pref, &format.format, framing);
09842          }
09843          ast_rtp_codecs_packetization_set(ast_rtp_instance_get_codecs(p->rtp), p->rtp, pref);
09844       }
09845       found = TRUE;
09846    } else if (sscanf(a, "rtpmap: %30u %127[^/]/%30u", &codec, mimeSubtype, &sample_rate) == 3) {
09847       /* We have a rtpmap to handle */
09848       if (*last_rtpmap_codec < SDP_MAX_RTPMAP_CODECS) {
09849          if (!(ast_rtp_codecs_payloads_set_rtpmap_type_rate(newaudiortp, NULL, codec, "audio", mimeSubtype,
09850              ast_test_flag(&p->flags[0], SIP_G726_NONSTANDARD) ? AST_RTP_OPT_G726_NONSTANDARD : 0, sample_rate))) {
09851             if (debug)
09852                ast_verbose("Found audio description format %s for ID %d\n", mimeSubtype, codec);
09853             //found_rtpmap_codecs[last_rtpmap_codec] = codec;
09854             (*last_rtpmap_codec)++;
09855             found = TRUE;
09856          } else {
09857             ast_rtp_codecs_payloads_unset(newaudiortp, NULL, codec);
09858             if (debug)
09859                ast_verbose("Found unknown media description format %s for ID %d\n", mimeSubtype, codec);
09860          }
09861       } else {
09862          if (debug)
09863             ast_verbose("Discarded description format %s for ID %d\n", mimeSubtype, codec);
09864       }
09865    } else if (sscanf(a, "fmtp: %30u %63s", &codec, fmtp_string) == 2) {
09866       struct ast_format *format;
09867 
09868       if ((format = ast_rtp_codecs_get_payload_format(newaudiortp, codec))) {
09869          unsigned int bit_rate;
09870          int val = 0;
09871 
09872          switch ((int) format->id) {
09873          case AST_FORMAT_SIREN7:
09874             if (sscanf(fmtp_string, "bitrate=%30u", &bit_rate) == 1) {
09875                if (bit_rate != 32000) {
09876                   ast_log(LOG_WARNING, "Got Siren7 offer at %d bps, but only 32000 bps supported; ignoring.\n", bit_rate);
09877                   ast_rtp_codecs_payloads_unset(newaudiortp, NULL, codec);
09878                } else {
09879                   found = TRUE;
09880                }
09881             }
09882             break;
09883          case AST_FORMAT_SIREN14:
09884             if (sscanf(fmtp_string, "bitrate=%30u", &bit_rate) == 1) {
09885                if (bit_rate != 48000) {
09886                   ast_log(LOG_WARNING, "Got Siren14 offer at %d bps, but only 48000 bps supported; ignoring.\n", bit_rate);
09887                   ast_rtp_codecs_payloads_unset(newaudiortp, NULL, codec);
09888                } else {
09889                   found = TRUE;
09890                }
09891             }
09892             break;
09893          case AST_FORMAT_G719:
09894             if (sscanf(fmtp_string, "bitrate=%30u", &bit_rate) == 1) {
09895                if (bit_rate != 64000) {
09896                   ast_log(LOG_WARNING, "Got G.719 offer at %d bps, but only 64000 bps supported; ignoring.\n", bit_rate);
09897                   ast_rtp_codecs_payloads_unset(newaudiortp, NULL, codec);
09898                } else {
09899                   found = TRUE;
09900                }
09901             }
09902             break;
09903          case AST_FORMAT_CELT:
09904             if (sscanf(fmtp_string, "framesize=%30u", &val) == 1) {
09905                ast_format_append(format, CELT_ATTR_KEY_FRAME_SIZE, val, AST_FORMAT_ATTR_END);
09906             }
09907          case AST_FORMAT_SILK:
09908             if (sscanf(fmtp_string, "maxaveragebitrate=%30u", &val) == 1) {
09909                ast_format_append(format, SILK_ATTR_KEY_MAX_BITRATE, val, AST_FORMAT_ATTR_END);
09910             }
09911             if (sscanf(fmtp_string, "usedtx=%30u", &val) == 1) {
09912                ast_format_append(format, SILK_ATTR_KEY_DTX, val ? 1 : 0, AST_FORMAT_ATTR_END);
09913             }
09914             if (sscanf(fmtp_string, "useinbandfec=%30u", &val) == 1) {
09915                ast_format_append(format, SILK_ATTR_KEY_FEC, val ? 1 : 0, AST_FORMAT_ATTR_END);
09916             }
09917             break;
09918          }
09919       }
09920    }
09921 
09922    return found;
09923 }
09924 
09925 static int process_sdp_a_video(const char *a, struct sip_pvt *p, struct ast_rtp_codecs *newvideortp, int *last_rtpmap_codec)
09926 {
09927    int found = FALSE;
09928    int codec;
09929    char mimeSubtype[128];
09930    unsigned int sample_rate;
09931    int debug = sip_debug_test_pvt(p);
09932 
09933    if (sscanf(a, "rtpmap: %30u %127[^/]/%30u", &codec, mimeSubtype, &sample_rate) == 3) {
09934       /* We have a rtpmap to handle */
09935       if (*last_rtpmap_codec < SDP_MAX_RTPMAP_CODECS) {
09936          /* Note: should really look at the '#chans' params too */
09937          if (!strncasecmp(mimeSubtype, "H26", 3) || !strncasecmp(mimeSubtype, "MP4", 3)) {
09938             if (!(ast_rtp_codecs_payloads_set_rtpmap_type_rate(newvideortp, NULL, codec, "video", mimeSubtype, 0, sample_rate))) {
09939                if (debug)
09940                   ast_verbose("Found video description format %s for ID %d\n", mimeSubtype, codec);
09941                //found_rtpmap_codecs[last_rtpmap_codec] = codec;
09942                (*last_rtpmap_codec)++;
09943                found = TRUE;
09944             } else {
09945                ast_rtp_codecs_payloads_unset(newvideortp, NULL, codec);
09946                if (debug)
09947                   ast_verbose("Found unknown media description format %s for ID %d\n", mimeSubtype, codec);
09948             }
09949          }
09950       } else {
09951          if (debug)
09952             ast_verbose("Discarded description format %s for ID %d\n", mimeSubtype, codec);
09953       }
09954    }
09955 
09956    return found;
09957 }
09958 
09959 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)
09960 {
09961    int found = FALSE;
09962    int codec;
09963    char mimeSubtype[128];
09964    unsigned int sample_rate;
09965    char *red_cp;
09966    int debug = sip_debug_test_pvt(p);
09967 
09968    if (sscanf(a, "rtpmap: %30u %127[^/]/%30u", &codec, mimeSubtype, &sample_rate) == 3) {
09969       /* We have a rtpmap to handle */
09970       if (*last_rtpmap_codec < SDP_MAX_RTPMAP_CODECS) {
09971          if (!strncasecmp(mimeSubtype, "T140", 4)) { /* Text */
09972             if (p->trtp) {
09973                /* ast_verbose("Adding t140 mimeSubtype to textrtp struct\n"); */
09974                ast_rtp_codecs_payloads_set_rtpmap_type_rate(newtextrtp, NULL, codec, "text", mimeSubtype, 0, sample_rate);
09975                found = TRUE;
09976             }
09977          } else if (!strncasecmp(mimeSubtype, "RED", 3)) { /* Text with Redudancy */
09978             if (p->trtp) {
09979                ast_rtp_codecs_payloads_set_rtpmap_type_rate(newtextrtp, NULL, codec, "text", mimeSubtype, 0, sample_rate);
09980                sprintf(red_fmtp, "fmtp:%d ", codec);
09981                if (debug)
09982                   ast_verbose("RED submimetype has payload type: %d\n", codec);
09983                found = TRUE;
09984             }
09985          }
09986       } else {
09987          if (debug)
09988             ast_verbose("Discarded description format %s for ID %d\n", mimeSubtype, codec);
09989       }
09990    } else if (!strncmp(a, red_fmtp, strlen(red_fmtp))) {
09991       /* count numbers of generations in fmtp */
09992       red_cp = &red_fmtp[strlen(red_fmtp)];
09993       strncpy(red_fmtp, a, 100);
09994 
09995       sscanf(red_cp, "%30u", &red_data_pt[*red_num_gen]);
09996       red_cp = strtok(red_cp, "/");
09997       while (red_cp && (*red_num_gen)++ < AST_RED_MAX_GENERATION) {
09998          sscanf(red_cp, "%30u", &red_data_pt[*red_num_gen]);
09999          red_cp = strtok(NULL, "/");
10000       }
10001       red_cp = red_fmtp;
10002       found = TRUE;
10003    }
10004 
10005    return found;
10006 }
10007 
10008 static int process_sdp_a_image(const char *a, struct sip_pvt *p)
10009 {
10010    int found = FALSE;
10011    char s[256];
10012    unsigned int x;
10013 
10014    if (initialize_udptl(p)) {
10015       return found;
10016    }
10017 
10018    if ((sscanf(a, "T38FaxMaxBuffer:%30u", &x) == 1)) {
10019       ast_debug(3, "MaxBufferSize:%d\n", x);
10020       found = TRUE;
10021    } else if ((sscanf(a, "T38MaxBitRate:%30u", &x) == 1) || (sscanf(a, "T38FaxMaxRate:%30u", &x) == 1)) {
10022       ast_debug(3, "T38MaxBitRate: %d\n", x);
10023       switch (x) {
10024       case 14400:
10025          p->t38.their_parms.rate = AST_T38_RATE_14400;
10026          break;
10027       case 12000:
10028          p->t38.their_parms.rate = AST_T38_RATE_12000;
10029          break;
10030       case 9600:
10031          p->t38.their_parms.rate = AST_T38_RATE_9600;
10032          break;
10033       case 7200:
10034          p->t38.their_parms.rate = AST_T38_RATE_7200;
10035          break;
10036       case 4800:
10037          p->t38.their_parms.rate = AST_T38_RATE_4800;
10038          break;
10039       case 2400:
10040          p->t38.their_parms.rate = AST_T38_RATE_2400;
10041          break;
10042       }
10043       found = TRUE;
10044    } else if ((sscanf(a, "T38FaxVersion:%30u", &x) == 1)) {
10045       ast_debug(3, "FaxVersion: %u\n", x);
10046       p->t38.their_parms.version = x;
10047       found = TRUE;
10048    } else if ((sscanf(a, "T38FaxMaxDatagram:%30u", &x) == 1) || (sscanf(a, "T38MaxDatagram:%30u", &x) == 1)) {
10049       /* override the supplied value if the configuration requests it */
10050       if (((signed int) p->t38_maxdatagram >= 0) && ((unsigned int) p->t38_maxdatagram > x)) {
10051          ast_debug(1, "Overriding T38FaxMaxDatagram '%d' with '%d'\n", x, p->t38_maxdatagram);
10052          x = p->t38_maxdatagram;
10053       }
10054       ast_debug(3, "FaxMaxDatagram: %u\n", x);
10055       ast_udptl_set_far_max_datagram(p->udptl, x);
10056       found = TRUE;
10057    } else if ((strncmp(a, "T38FaxFillBitRemoval", 20) == 0)) {
10058       if (sscanf(a, "T38FaxFillBitRemoval:%30u", &x) == 1) {
10059          ast_debug(3, "FillBitRemoval: %d\n", x);
10060          if (x == 1) {
10061             p->t38.their_parms.fill_bit_removal = TRUE;
10062          }
10063       } else {
10064          ast_debug(3, "FillBitRemoval\n");
10065          p->t38.their_parms.fill_bit_removal = TRUE;
10066       }
10067       found = TRUE;
10068    } else if ((strncmp(a, "T38FaxTranscodingMMR", 20) == 0)) {
10069       if (sscanf(a, "T38FaxTranscodingMMR:%30u", &x) == 1) {
10070          ast_debug(3, "Transcoding MMR: %d\n", x);
10071          if (x == 1) {
10072             p->t38.their_parms.transcoding_mmr = TRUE;
10073          }
10074       } else {
10075          ast_debug(3, "Transcoding MMR\n");
10076          p->t38.their_parms.transcoding_mmr = TRUE;
10077       }
10078       found = TRUE;
10079    } else if ((strncmp(a, "T38FaxTranscodingJBIG", 21) == 0)) {
10080       if (sscanf(a, "T38FaxTranscodingJBIG:%30u", &x) == 1) {
10081          ast_debug(3, "Transcoding JBIG: %d\n", x);
10082          if (x == 1) {
10083             p->t38.their_parms.transcoding_jbig = TRUE;
10084          }
10085       } else {
10086          ast_debug(3, "Transcoding JBIG\n");
10087          p->t38.their_parms.transcoding_jbig = TRUE;
10088       }
10089       found = TRUE;
10090    } else if ((sscanf(a, "T38FaxRateManagement:%255s", s) == 1)) {
10091       ast_debug(3, "RateManagement: %s\n", s);
10092       if (!strcasecmp(s, "localTCF"))
10093          p->t38.their_parms.rate_management = AST_T38_RATE_MANAGEMENT_LOCAL_TCF;
10094       else if (!strcasecmp(s, "transferredTCF"))
10095          p->t38.their_parms.rate_management = AST_T38_RATE_MANAGEMENT_TRANSFERRED_TCF;
10096       found = TRUE;
10097    } else if ((sscanf(a, "T38FaxUdpEC:%255s", s) == 1)) {
10098       ast_debug(3, "UDP EC: %s\n", s);
10099       if (!strcasecmp(s, "t38UDPRedundancy")) {
10100          ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_REDUNDANCY);
10101       } else if (!strcasecmp(s, "t38UDPFEC")) {
10102          ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_FEC);
10103       } else {
10104          ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_NONE);
10105       }
10106       found = TRUE;
10107    }
10108 
10109    return found;
10110 }
10111 
10112 /*! \brief Add "Supported" header to sip message.  Since some options may
10113  *  be disabled in the config, the sip_pvt must be inspected to determine what
10114  *  is supported for this dialog. */
10115 static int add_supported_header(struct sip_pvt *pvt, struct sip_request *req)
10116 {
10117    int res;
10118    if (st_get_mode(pvt, 0) != SESSION_TIMER_MODE_REFUSE) {
10119       res = add_header(req, "Supported", "replaces, timer");
10120    } else {
10121       res = add_header(req, "Supported", "replaces");
10122    }
10123    return res;
10124 }
10125 
10126 /*! \brief Add header to SIP message */
10127 static int add_header(struct sip_request *req, const char *var, const char *value)
10128 {
10129    if (req->headers == SIP_MAX_HEADERS) {
10130       ast_log(LOG_WARNING, "Out of SIP header space\n");
10131       return -1;
10132    }
10133 
10134    if (req->lines) {
10135       ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
10136       return -1;
10137    }
10138 
10139    if (sip_cfg.compactheaders) {
10140       var = find_alias(var, var);
10141    }
10142 
10143    ast_str_append(&req->data, 0, "%s: %s\r\n", var, value);
10144    req->header[req->headers] = ast_str_strlen(req->data);
10145 
10146    req->headers++;
10147 
10148    return 0;   
10149 }
10150 
10151 /*! 
10152  * \pre dialog is assumed to be locked while calling this function
10153  * \brief Add 'Max-Forwards' header to SIP message 
10154  */
10155 static int add_header_max_forwards(struct sip_pvt *dialog, struct sip_request *req)
10156 {
10157    char clen[10];
10158 
10159    snprintf(clen, sizeof(clen), "%d", dialog->maxforwards);
10160 
10161    return add_header(req, "Max-Forwards", clen);
10162 }
10163 
10164 /*! \brief Add 'Content-Length' header and content to SIP message */
10165 static int finalize_content(struct sip_request *req)
10166 {
10167    char clen[10];
10168 
10169    if (req->lines) {
10170       ast_log(LOG_WARNING, "finalize_content() called on a message that has already been finalized\n");
10171       return -1;
10172    }
10173 
10174    snprintf(clen, sizeof(clen), "%zd", ast_str_strlen(req->content));
10175    add_header(req, "Content-Length", clen);
10176 
10177    if (ast_str_strlen(req->content)) {
10178       ast_str_append(&req->data, 0, "\r\n%s", ast_str_buffer(req->content));
10179    }
10180    req->lines = ast_str_strlen(req->content) ? 1 : 0;
10181    return 0;
10182 }
10183 
10184 /*! \brief Add content (not header) to SIP message */
10185 static int add_content(struct sip_request *req, const char *line)
10186 {
10187    if (req->lines) {
10188       ast_log(LOG_WARNING, "Can't add more content when the content has been finalized\n");
10189       return -1;
10190    }
10191 
10192    ast_str_append(&req->content, 0, "%s", line);
10193    return 0;
10194 }
10195 
10196 /*! \brief Copy one header field from one request to another */
10197 static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field)
10198 {
10199    const char *tmp = sip_get_header(orig, field);
10200 
10201    if (!ast_strlen_zero(tmp)) /* Add what we're responding to */
10202       return add_header(req, field, tmp);
10203    ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
10204    return -1;
10205 }
10206 
10207 /*! \brief Copy all headers from one request to another */
10208 static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field)
10209 {
10210    int start = 0;
10211    int copied = 0;
10212    for (;;) {
10213       const char *tmp = __get_header(orig, field, &start);
10214 
10215       if (ast_strlen_zero(tmp))
10216          break;
10217       /* Add what we're responding to */
10218       add_header(req, field, tmp);
10219       copied++;
10220    }
10221    return copied ? 0 : -1;
10222 }
10223 
10224 /*! \brief Copy SIP VIA Headers from the request to the response
10225 \note If the client indicates that it wishes to know the port we received from,
10226    it adds ;rport without an argument to the topmost via header. We need to
10227    add the port number (from our point of view) to that parameter.
10228 \verbatim
10229    We always add ;received=<ip address> to the topmost via header.
10230 \endverbatim
10231    Received: RFC 3261, rport RFC 3581 */
10232 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field)
10233 {
10234    int copied = 0;
10235    int start = 0;
10236 
10237    for (;;) {
10238       char new[512];
10239       const char *oh = __get_header(orig, field, &start);
10240 
10241       if (ast_strlen_zero(oh))
10242          break;
10243 
10244       if (!copied) { /* Only check for empty rport in topmost via header */
10245          char leftmost[512], *others, *rport;
10246 
10247          /* Only work on leftmost value */
10248          ast_copy_string(leftmost, oh, sizeof(leftmost));
10249          others = strchr(leftmost, ',');
10250          if (others)
10251              *others++ = '\0';
10252 
10253          /* Find ;rport;  (empty request) */
10254          rport = strstr(leftmost, ";rport");
10255          if (rport && *(rport+6) == '=')
10256             rport = NULL;     /* We already have a parameter to rport */
10257 
10258          if (((ast_test_flag(&p->flags[0], SIP_NAT_FORCE_RPORT)) || (rport && ast_test_flag(&p->flags[0], SIP_NAT_RPORT_PRESENT)))) {
10259             /* We need to add received port - rport */
10260             char *end;
10261 
10262             rport = strstr(leftmost, ";rport");
10263 
10264             if (rport) {
10265                end = strchr(rport + 1, ';');
10266                if (end)
10267                   memmove(rport, end, strlen(end) + 1);
10268                else
10269                   *rport = '\0';
10270             }
10271 
10272             /* Add rport to first VIA header if requested */
10273             snprintf(new, sizeof(new), "%s;received=%s;rport=%d%s%s",
10274                leftmost, ast_sockaddr_stringify_addr_remote(&p->recv),
10275                ast_sockaddr_port(&p->recv),
10276                others ? "," : "", others ? others : "");
10277          } else {
10278             /* We should *always* add a received to the topmost via */
10279             snprintf(new, sizeof(new), "%s;received=%s%s%s",
10280                leftmost, ast_sockaddr_stringify_addr_remote(&p->recv),
10281                others ? "," : "", others ? others : "");
10282          }
10283          oh = new;   /* the header to copy */
10284       }  /* else add the following via headers untouched */
10285       add_header(req, field, oh);
10286       copied++;
10287    }
10288    if (!copied) {
10289       ast_log(LOG_NOTICE, "No header field '%s' present to copy\n", field);
10290       return -1;
10291    }
10292    return 0;
10293 }
10294 
10295 /*! \brief Add route header into request per learned route */
10296 static void add_route(struct sip_request *req, struct sip_route *route)
10297 {
10298    char r[SIPBUFSIZE*2], *p;
10299    int n, rem = sizeof(r);
10300 
10301    if (!route)
10302       return;
10303 
10304    p = r;
10305    for (;route ; route = route->next) {
10306       n = strlen(route->hop);
10307       if (rem < n+3) /* we need room for ",<route>" */
10308          break;
10309       if (p != r) {  /* add a separator after fist route */
10310          *p++ = ',';
10311          --rem;
10312       }
10313       *p++ = '<';
10314       ast_copy_string(p, route->hop, rem); /* cannot fail */
10315       p += n;
10316       *p++ = '>';
10317       rem -= (n+2);
10318    }
10319    *p = '\0';
10320    add_header(req, "Route", r);
10321 }
10322 
10323 /*! \brief Set destination from SIP URI
10324  *
10325  * Parse uri to h (host) and port - uri is already just the part inside the <>
10326  * general form we are expecting is sip[s]:username[:password][;parameter]@host[:port][;...]
10327  * If there's a port given, turn NAPTR/SRV off. NAPTR might indicate SIPS preference even
10328  * for SIP: uri's
10329  *
10330  * If there's a sips: uri scheme, TLS will be required.
10331  */
10332 static void set_destination(struct sip_pvt *p, char *uri)
10333 {
10334    char *h, *maddr, hostname[256];
10335    int hn;
10336    int debug=sip_debug_test_pvt(p);
10337    int tls_on = FALSE;
10338 
10339    if (debug)
10340       ast_verbose("set_destination: Parsing <%s> for address/port to send to\n", uri);
10341 
10342    /* Find and parse hostname */
10343    h = strchr(uri, '@');
10344    if (h)
10345       ++h;
10346    else {
10347       h = uri;
10348       if (!strncasecmp(h, "sip:", 4)) {
10349          h += 4;
10350       } else if (!strncasecmp(h, "sips:", 5)) {
10351          h += 5;
10352          tls_on = TRUE;
10353       }
10354    }
10355    hn = strcspn(h, ";>") + 1;
10356    if (hn > sizeof(hostname))
10357       hn = sizeof(hostname);
10358    ast_copy_string(hostname, h, hn);
10359    /* XXX bug here if string has been trimmed to sizeof(hostname) */
10360    h += hn - 1;
10361 
10362    /*! \todo XXX If we have sip_cfg.srvlookup on, then look for NAPTR/SRV,
10363     * otherwise, just look for A records */
10364    if (ast_sockaddr_resolve_first(&p->sa, hostname, 0)) {
10365       ast_log(LOG_WARNING, "Can't find address for host '%s'\n", hostname);
10366       return;
10367    }
10368 
10369    /* Got the hostname - but maybe there's a "maddr=" to override address? */
10370    maddr = strstr(h, "maddr=");
10371    if (maddr) {
10372       int port;
10373 
10374       maddr += 6;
10375       hn = strspn(maddr, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
10376                     "0123456789-.:[]") + 1;
10377       if (hn > sizeof(hostname))
10378          hn = sizeof(hostname);
10379       ast_copy_string(hostname, maddr, hn);
10380 
10381       port = ast_sockaddr_port(&p->sa);
10382 
10383       /*! \todo XXX If we have sip_cfg.srvlookup on, then look for
10384        * NAPTR/SRV, otherwise, just look for A records */
10385       if (ast_sockaddr_resolve_first(&p->sa, hostname, PARSE_PORT_FORBID)) {
10386          ast_log(LOG_WARNING, "Can't find address for host '%s'\n", hostname);
10387          return;
10388       }
10389 
10390       ast_sockaddr_set_port(&p->sa, port);
10391    }
10392 
10393    if (!ast_sockaddr_port(&p->sa)) {
10394       ast_sockaddr_set_port(&p->sa, tls_on ?
10395                   STANDARD_TLS_PORT : STANDARD_SIP_PORT);
10396    }
10397 
10398    if (debug) {
10399       ast_verbose("set_destination: set destination to %s\n",
10400              ast_sockaddr_stringify(&p->sa));
10401    }
10402 }
10403 
10404 /*! \brief Initialize SIP response, based on SIP request */
10405 static int init_resp(struct sip_request *resp, const char *msg)
10406 {
10407    /* Initialize a response */
10408    memset(resp, 0, sizeof(*resp));
10409    resp->method = SIP_RESPONSE;
10410    if (!(resp->data = ast_str_create(SIP_MIN_PACKET)))
10411       goto e_return;
10412    if (!(resp->content = ast_str_create(SIP_MIN_PACKET)))
10413       goto e_free_data;
10414    resp->header[0] = 0;
10415    ast_str_set(&resp->data, 0, "SIP/2.0 %s\r\n", msg);
10416    resp->headers++;
10417    return 0;
10418 
10419 e_free_data:
10420    ast_free(resp->data);
10421    resp->data = NULL;
10422 e_return:
10423    return -1;
10424 }
10425 
10426 /*! \brief Initialize SIP request */
10427 static int init_req(struct sip_request *req, int sipmethod, const char *recip)
10428 {
10429    /* Initialize a request */
10430    memset(req, 0, sizeof(*req));
10431    if (!(req->data = ast_str_create(SIP_MIN_PACKET)))
10432       goto e_return;
10433    if (!(req->content = ast_str_create(SIP_MIN_PACKET)))
10434       goto e_free_data;
10435    req->method = sipmethod;
10436    req->header[0] = 0;
10437    ast_str_set(&req->data, 0, "%s %s SIP/2.0\r\n", sip_methods[sipmethod].text, recip);
10438    req->headers++;
10439    return 0;
10440 
10441 e_free_data:
10442    ast_free(req->data);
10443    req->data = NULL;
10444 e_return:
10445    return -1;
10446 }
10447 
10448 /*! \brief Deinitialize SIP response/request */
10449 static void deinit_req(struct sip_request *req)
10450 {
10451    if (req->data) {
10452       ast_free(req->data);
10453       req->data = NULL;
10454    }
10455    if (req->content) {
10456       ast_free(req->content);
10457       req->content = NULL;
10458    }
10459 }
10460 
10461 
10462 /*! \brief Test if this response needs a contact header */
10463 static inline int resp_needs_contact(const char *msg, enum sipmethod method) {
10464    /* Requirements for Contact header inclusion in responses generated
10465     * from the header tables found in the following RFCs.  Where the
10466     * Contact header was marked mandatory (m) or optional (o) this
10467     * function returns 1.
10468     *
10469     * - RFC 3261 (ACK, BYE, CANCEL, INVITE, OPTIONS, REGISTER)
10470     * - RFC 2976 (INFO)
10471     * - RFC 3262 (PRACK)
10472     * - RFC 3265 (SUBSCRIBE, NOTIFY)
10473     * - RFC 3311 (UPDATE)
10474     * - RFC 3428 (MESSAGE)
10475     * - RFC 3515 (REFER)
10476     * - RFC 3903 (PUBLISH)
10477     */
10478 
10479    switch (method) {
10480       /* 1xx, 2xx, 3xx, 485 */
10481       case SIP_INVITE:
10482       case SIP_UPDATE:
10483       case SIP_SUBSCRIBE:
10484       case SIP_NOTIFY:
10485          if ((msg[0] >= '1' && msg[0] <= '3') || !strncmp(msg, "485", 3))
10486             return 1;
10487          break;
10488 
10489       /* 2xx, 3xx, 485 */
10490       case SIP_REGISTER:
10491       case SIP_OPTIONS:
10492          if (msg[0] == '2' || msg[0] == '3' || !strncmp(msg, "485", 3))
10493             return 1;
10494          break;
10495 
10496       /* 3xx, 485 */
10497       case SIP_BYE:
10498       case SIP_PRACK:
10499       case SIP_MESSAGE:
10500       case SIP_PUBLISH:
10501          if (msg[0] == '3' || !strncmp(msg, "485", 3))
10502             return 1;
10503          break;
10504 
10505       /* 2xx, 3xx, 4xx, 5xx, 6xx */
10506       case SIP_REFER:
10507          if (msg[0] >= '2' && msg[0] <= '6')
10508             return 1;
10509          break;
10510 
10511       /* contact will not be included for everything else */
10512       case SIP_ACK:
10513       case SIP_CANCEL:
10514       case SIP_INFO:
10515       case SIP_PING:
10516       default:
10517          return 0;
10518    }
10519    return 0;
10520 }
10521 
10522 /*! \brief Prepare SIP response packet */
10523 static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req)
10524 {
10525    char newto[256];
10526    const char *ot;
10527 
10528    init_resp(resp, msg);
10529    copy_via_headers(p, resp, req, "Via");
10530    if (msg[0] == '1' || msg[0] == '2')
10531       copy_all_header(resp, req, "Record-Route");
10532    copy_header(resp, req, "From");
10533    ot = sip_get_header(req, "To");
10534    if (!strcasestr(ot, "tag=") && strncmp(msg, "100", 3)) {
10535       /* Add the proper tag if we don't have it already.  If they have specified
10536          their tag, use it.  Otherwise, use our own tag */
10537       if (!ast_strlen_zero(p->theirtag) && ast_test_flag(&p->flags[0], SIP_OUTGOING))
10538          snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
10539       else if (p->tag && !ast_test_flag(&p->flags[0], SIP_OUTGOING))
10540          snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->tag);
10541       else
10542          ast_copy_string(newto, ot, sizeof(newto));
10543       ot = newto;
10544    }
10545    add_header(resp, "To", ot);
10546    copy_header(resp, req, "Call-ID");
10547    copy_header(resp, req, "CSeq");
10548    if (!ast_strlen_zero(global_useragent))
10549       add_header(resp, "Server", global_useragent);
10550    add_header(resp, "Allow", ALLOWED_METHODS);
10551    add_supported_header(p, resp);
10552 
10553    /* If this is an invite, add Session-Timers related headers if the feature is active for this session */
10554    if (p->method == SIP_INVITE && p->stimer && p->stimer->st_active == TRUE && p->stimer->st_active_peer_ua == TRUE) {
10555       char se_hdr[256];
10556       snprintf(se_hdr, sizeof(se_hdr), "%d;refresher=%s", p->stimer->st_interval,
10557          strefresher2str(p->stimer->st_ref));
10558       add_header(resp, "Session-Expires", se_hdr);
10559    }
10560 
10561    if (msg[0] == '2' && (p->method == SIP_SUBSCRIBE || p->method == SIP_REGISTER)) {
10562       /* For registration responses, we also need expiry and
10563          contact info */
10564       char tmp[256];
10565 
10566       snprintf(tmp, sizeof(tmp), "%d", p->expiry);
10567       add_header(resp, "Expires", tmp);
10568       if (p->expiry) {  /* Only add contact if we have an expiry time */
10569          char contact[SIPBUFSIZE];
10570          const char *contact_uri = p->method == SIP_SUBSCRIBE ? p->our_contact : p->fullcontact;
10571          char *brackets = strchr(contact_uri, '<');
10572          snprintf(contact, sizeof(contact), "%s%s%s;expires=%d", brackets ? "" : "<", contact_uri, brackets ? "" : ">", p->expiry);
10573          add_header(resp, "Contact", contact);  /* Not when we unregister */
10574       }
10575    } else if (!ast_strlen_zero(p->our_contact) && resp_needs_contact(msg, p->method)) {
10576       add_header(resp, "Contact", p->our_contact);
10577    }
10578 
10579    if (!ast_strlen_zero(p->url)) {
10580       add_header(resp, "Access-URL", p->url);
10581       ast_string_field_set(p, url, NULL);
10582    }
10583 
10584    /* default to routing the response to the address where the request
10585     * came from.  Since we don't have a transport layer, we do this here.
10586     * The process_via() function will update the port to either the port
10587     * specified in the via header or the default port later on (per RFC
10588     * 3261 section 18.2.2).
10589     */
10590    p->sa = p->recv;
10591 
10592    if (process_via(p, req)) {
10593       ast_log(LOG_WARNING, "error processing via header, will send response to originating address\n");
10594    }
10595 
10596    return 0;
10597 }
10598 
10599 /*! \brief Initialize a SIP request message (not the initial one in a dialog) */
10600 static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, uint32_t seqno, int newbranch)
10601 {
10602    struct sip_request *orig = &p->initreq;
10603    char stripped[80];
10604    char tmp[80];
10605    char newto[256];
10606    const char *c;
10607    const char *ot, *of;
10608    int is_strict = FALSE;     /*!< Strict routing flag */
10609    int is_outbound = ast_test_flag(&p->flags[0], SIP_OUTGOING);   /* Session direction */
10610 
10611    memset(req, 0, sizeof(struct sip_request));
10612 
10613    snprintf(p->lastmsg, sizeof(p->lastmsg), "Tx: %s", sip_methods[sipmethod].text);
10614 
10615    if (!seqno) {
10616       p->ocseq++;
10617       seqno = p->ocseq;
10618    }
10619 
10620    /* A CANCEL must have the same branch as the INVITE that it is canceling. */
10621    if (sipmethod == SIP_CANCEL) {
10622       p->branch = p->invite_branch;
10623       build_via(p);
10624    } else if (newbranch && (sipmethod == SIP_INVITE)) {
10625       p->branch ^= ast_random();
10626       p->invite_branch = p->branch;
10627       build_via(p);
10628    } else if (newbranch) {
10629       p->branch ^= ast_random();
10630       build_via(p);
10631    }
10632 
10633    /* Check for strict or loose router */
10634    if (p->route && !ast_strlen_zero(p->route->hop) && strstr(p->route->hop, ";lr") == NULL) {
10635       is_strict = TRUE;
10636       if (sipdebug)
10637          ast_debug(1, "Strict routing enforced for session %s\n", p->callid);
10638    }
10639 
10640    if (sipmethod == SIP_CANCEL)
10641       c = REQ_OFFSET_TO_STR(&p->initreq, rlPart2); /* Use original URI */
10642    else if (sipmethod == SIP_ACK) {
10643       /* Use URI from Contact: in 200 OK (if INVITE)
10644       (we only have the contacturi on INVITEs) */
10645       if (!ast_strlen_zero(p->okcontacturi))
10646          c = is_strict ? p->route->hop : p->okcontacturi;
10647       else
10648          c = REQ_OFFSET_TO_STR(&p->initreq, rlPart2);
10649    } else if (!ast_strlen_zero(p->okcontacturi))
10650       c = is_strict ? p->route->hop : p->okcontacturi; /* Use for BYE or REINVITE */
10651    else if (!ast_strlen_zero(p->uri))
10652       c = p->uri;
10653    else {
10654       char *n;
10655       /* We have no URI, use To: or From:  header as URI (depending on direction) */
10656       ast_copy_string(stripped, sip_get_header(orig, is_outbound ? "To" : "From"),
10657             sizeof(stripped));
10658       n = get_in_brackets(stripped);
10659       c = remove_uri_parameters(n);
10660    }  
10661    init_req(req, sipmethod, c);
10662 
10663    snprintf(tmp, sizeof(tmp), "%u %s", seqno, sip_methods[sipmethod].text);
10664 
10665    add_header(req, "Via", p->via);
10666    if (p->route) {
10667       set_destination(p, p->route->hop);
10668       add_route(req, is_strict ? p->route->next : p->route);
10669    }
10670    add_header_max_forwards(p, req);
10671 
10672    ot = sip_get_header(orig, "To");
10673    of = sip_get_header(orig, "From");
10674 
10675    /* Add tag *unless* this is a CANCEL, in which case we need to send it exactly
10676       as our original request, including tag (or presumably lack thereof) */
10677    if (!strcasestr(ot, "tag=") && sipmethod != SIP_CANCEL) {
10678       /* Add the proper tag if we don't have it already.  If they have specified
10679          their tag, use it.  Otherwise, use our own tag */
10680       if (is_outbound && !ast_strlen_zero(p->theirtag))
10681          snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
10682       else if (!is_outbound)
10683          snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->tag);
10684       else
10685          snprintf(newto, sizeof(newto), "%s", ot);
10686       ot = newto;
10687    }
10688 
10689    if (is_outbound) {
10690       add_header(req, "From", of);
10691       add_header(req, "To", ot);
10692    } else {
10693       add_header(req, "From", ot);
10694       add_header(req, "To", of);
10695    }
10696    /* Do not add Contact for MESSAGE, BYE and Cancel requests */
10697    if (sipmethod != SIP_BYE && sipmethod != SIP_CANCEL && sipmethod != SIP_MESSAGE)
10698       add_header(req, "Contact", p->our_contact);
10699 
10700    copy_header(req, orig, "Call-ID");
10701    add_header(req, "CSeq", tmp);
10702 
10703    if (!ast_strlen_zero(global_useragent))
10704       add_header(req, "User-Agent", global_useragent);
10705 
10706    if (!ast_strlen_zero(p->url)) {
10707       add_header(req, "Access-URL", p->url);
10708       ast_string_field_set(p, url, NULL);
10709    }
10710 
10711    /* Add Session-Timers related headers if the feature is active for this session.
10712       An exception to this behavior is the ACK request. Since Asterisk never requires
10713       session-timers support from a remote end-point (UAS) in an INVITE, it must
10714       not send 'Require: timer' header in the ACK request.
10715       This should only be added in the INVITE transactions, not MESSAGE or REFER or other
10716       in-dialog messages.
10717    */
10718    if (p->stimer && p->stimer->st_active == TRUE && p->stimer->st_active_peer_ua == TRUE
10719        && sipmethod == SIP_INVITE) {
10720       char se_hdr[256];
10721       snprintf(se_hdr, sizeof(se_hdr), "%d;refresher=%s", p->stimer->st_interval,
10722          strefresher2str(p->stimer->st_ref));
10723       add_header(req, "Session-Expires", se_hdr);
10724       snprintf(se_hdr, sizeof(se_hdr), "%d", st_get_se(p, FALSE));
10725       add_header(req, "Min-SE", se_hdr);
10726    }
10727 
10728    return 0;
10729 }
10730 
10731 /*! \brief Base transmit response function */
10732 static int __transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable)
10733 {
10734    struct sip_request resp;
10735    uint32_t seqno = 0;
10736 
10737    if (reliable && (sscanf(sip_get_header(req, "CSeq"), "%30u ", &seqno) != 1)) {
10738       ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", sip_get_header(req, "CSeq"));
10739       return -1;
10740    }
10741    respprep(&resp, p, msg, req);
10742 
10743    if (ast_test_flag(&p->flags[0], SIP_SENDRPID)
10744          && ast_test_flag(&p->flags[1], SIP_PAGE2_CONNECTLINEUPDATE_PEND)
10745          && (!strncmp(msg, "180", 3) || !strncmp(msg, "183", 3))) {
10746       ast_clear_flag(&p->flags[1], SIP_PAGE2_CONNECTLINEUPDATE_PEND);
10747       add_rpid(&resp, p);
10748    }
10749    if (ast_test_flag(&p->flags[0], SIP_OFFER_CC)) {
10750       add_cc_call_info_to_response(p, &resp);
10751    }
10752 
10753    /* If we are sending a 302 Redirect we can add a diversion header if the redirect information is set */
10754    if (!strncmp(msg, "302", 3)) {
10755       add_diversion_header(&resp, p);
10756    }
10757 
10758    /* If we are cancelling an incoming invite for some reason, add information
10759       about the reason why we are doing this in clear text */
10760    if (p->method == SIP_INVITE && msg[0] != '1') {
10761       char buf[20];
10762 
10763       if (ast_test_flag(&p->flags[1], SIP_PAGE2_Q850_REASON)) {
10764          int hangupcause = 0;
10765 
10766          if (p->owner && p->owner->hangupcause) {
10767             hangupcause = p->owner->hangupcause;
10768          } else if (p->hangupcause) {
10769             hangupcause = p->hangupcause;
10770          } else {
10771             int respcode;
10772             if (sscanf(msg, "%30d ", &respcode))
10773                hangupcause = hangup_sip2cause(respcode);
10774          }
10775 
10776          if (hangupcause) {
10777             sprintf(buf, "Q.850;cause=%i", hangupcause & 0x7f);
10778             add_header(&resp, "Reason", buf);
10779          }
10780       }
10781 
10782       if (p->owner && p->owner->hangupcause) {
10783          add_header(&resp, "X-Asterisk-HangupCause", ast_cause2str(p->owner->hangupcause));
10784          snprintf(buf, sizeof(buf), "%d", p->owner->hangupcause);
10785          add_header(&resp, "X-Asterisk-HangupCauseCode", buf);
10786       }
10787    }
10788    return send_response(p, &resp, reliable, seqno);
10789 }
10790 
10791 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)
10792 {
10793    struct sip_request resp;
10794 
10795    if (need_new_etag) {
10796       create_new_sip_etag(esc_entry, 1);
10797    }
10798    respprep(&resp, p, msg, req);
10799    add_header(&resp, "SIP-ETag", esc_entry->entity_tag);
10800 
10801    return send_response(p, &resp, 0, 0);
10802 }
10803 
10804 static int temp_pvt_init(void *data)
10805 {
10806    struct sip_pvt *p = data;
10807 
10808    p->do_history = 0;   /* XXX do we need it ? isn't already all 0 ? */
10809    return ast_string_field_init(p, 512);
10810 }
10811 
10812 static void temp_pvt_cleanup(void *data)
10813 {
10814    struct sip_pvt *p = data;
10815 
10816    ast_string_field_free_memory(p);
10817 
10818    ast_free(data);
10819 }
10820 
10821 /*! \brief Transmit response, no retransmits, using a temporary pvt structure */
10822 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)
10823 {
10824    struct sip_pvt *p = NULL;
10825 
10826    if (!(p = ast_threadstorage_get(&ts_temp_pvt, sizeof(*p)))) {
10827       ast_log(LOG_ERROR, "Failed to get temporary pvt\n");
10828       return -1;
10829    }
10830 
10831    /* XXX the structure may be dirty from previous usage.
10832     * Here we should state clearly how we should reinitialize it
10833     * before using it.
10834     * E.g. certainly the threadstorage should be left alone,
10835     * but other thihngs such as flags etc. maybe need cleanup ?
10836     */
10837 
10838    /* Initialize the bare minimum */
10839    p->method = intended_method;
10840 
10841    if (!addr) {
10842       ast_sockaddr_copy(&p->ourip, &internip);
10843    } else {
10844       ast_sockaddr_copy(&p->sa, addr);
10845       ast_sip_ouraddrfor(&p->sa, &p->ourip, p);
10846    }
10847 
10848    p->branch = ast_random();
10849    make_our_tag(p->tag, sizeof(p->tag));
10850    p->ocseq = INITIAL_CSEQ;
10851 
10852    if (useglobal_nat && addr) {
10853       ast_copy_flags(&p->flags[0], &global_flags[0], SIP_NAT_FORCE_RPORT);
10854       ast_sockaddr_copy(&p->recv, addr);
10855       do_setnat(p);
10856    }
10857 
10858    ast_string_field_set(p, fromdomain, default_fromdomain);
10859    p->fromdomainport = default_fromdomainport;
10860    build_via(p);
10861    ast_string_field_set(p, callid, callid);
10862 
10863    copy_socket_data(&p->socket, &req->socket);
10864 
10865    /* Use this temporary pvt structure to send the message */
10866    __transmit_response(p, msg, req, XMIT_UNRELIABLE);
10867 
10868    /* Free the string fields, but not the pool space */
10869    ast_string_field_init(p, 0);
10870 
10871    return 0;
10872 }
10873 
10874 /*! \brief Transmit response, no retransmits */
10875 static int transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req)
10876 {
10877    return __transmit_response(p, msg, req, XMIT_UNRELIABLE);
10878 }
10879 
10880 /*! \brief Transmit response, no retransmits */
10881 static int transmit_response_with_unsupported(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *unsupported)
10882 {
10883    struct sip_request resp;
10884    respprep(&resp, p, msg, req);
10885    append_date(&resp);
10886    add_header(&resp, "Unsupported", unsupported);
10887    return send_response(p, &resp, XMIT_UNRELIABLE, 0);
10888 }
10889 
10890 /*! \brief Transmit 422 response with Min-SE header (Session-Timers)  */
10891 static int transmit_response_with_minse(struct sip_pvt *p, const char *msg, const struct sip_request *req, int minse_int)
10892 {
10893    struct sip_request resp;
10894    char minse_str[20];
10895 
10896    respprep(&resp, p, msg, req);
10897    append_date(&resp);
10898 
10899    snprintf(minse_str, sizeof(minse_str), "%d", minse_int);
10900    add_header(&resp, "Min-SE", minse_str);
10901    return send_response(p, &resp, XMIT_UNRELIABLE, 0);
10902 }
10903 
10904 
10905 /*! \brief Transmit response, Make sure you get an ACK
10906    This is only used for responses to INVITEs, where we need to make sure we get an ACK
10907 */
10908 static int transmit_response_reliable(struct sip_pvt *p, const char *msg, const struct sip_request *req)
10909 {
10910    return __transmit_response(p, msg, req, req->ignore ? XMIT_UNRELIABLE : XMIT_CRITICAL);
10911 }
10912 
10913 /*! \brief Append date to SIP message */
10914 static void append_date(struct sip_request *req)
10915 {
10916    char tmpdat[256];
10917    struct tm tm;
10918    time_t t = time(NULL);
10919 
10920    gmtime_r(&t, &tm);
10921    strftime(tmpdat, sizeof(tmpdat), "%a, %d %b %Y %T GMT", &tm);
10922    add_header(req, "Date", tmpdat);
10923 }
10924 
10925 /*! \brief Append Retry-After header field when transmitting response */
10926 static int transmit_response_with_retry_after(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *seconds)
10927 {
10928    struct sip_request resp;
10929    respprep(&resp, p, msg, req);
10930    add_header(&resp, "Retry-After", seconds);
10931    return send_response(p, &resp, XMIT_UNRELIABLE, 0);
10932 }
10933 
10934 /*! \brief Append date and content length before transmitting response */
10935 static int transmit_response_with_date(struct sip_pvt *p, const char *msg, const struct sip_request *req)
10936 {
10937    struct sip_request resp;
10938    respprep(&resp, p, msg, req);
10939    append_date(&resp);
10940    return send_response(p, &resp, XMIT_UNRELIABLE, 0);
10941 }
10942 
10943 /*! \brief Append Accept header, content length before transmitting response */
10944 static int transmit_response_with_allow(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable)
10945 {
10946    struct sip_request resp;
10947    respprep(&resp, p, msg, req);
10948    add_header(&resp, "Accept", "application/sdp");
10949    return send_response(p, &resp, reliable, 0);
10950 }
10951 
10952 /*! \brief Append Min-Expires header, content length before transmitting response */
10953 static int transmit_response_with_minexpires(struct sip_pvt *p, const char *msg, const struct sip_request *req)
10954 {
10955    struct sip_request resp;
10956    char tmp[32];
10957 
10958    snprintf(tmp, sizeof(tmp), "%d", min_expiry);
10959    respprep(&resp, p, msg, req);
10960    add_header(&resp, "Min-Expires", tmp);
10961    return send_response(p, &resp, XMIT_UNRELIABLE, 0);
10962 }
10963 
10964 /*! \brief Respond with authorization request */
10965 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)
10966 {
10967    struct sip_request resp;
10968    char tmp[512];
10969    uint32_t seqno = 0;
10970 
10971    if (reliable && (sscanf(sip_get_header(req, "CSeq"), "%30u ", &seqno) != 1)) {
10972       ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", sip_get_header(req, "CSeq"));
10973       return -1;
10974    }
10975    /* Choose Realm */
10976    get_realm(p, req);
10977 
10978    /* Stale means that they sent us correct authentication, but
10979       based it on an old challenge (nonce) */
10980    snprintf(tmp, sizeof(tmp), "Digest algorithm=MD5, realm=\"%s\", nonce=\"%s\"%s", p->realm, randdata, stale ? ", stale=true" : "");
10981    respprep(&resp, p, msg, req);
10982    add_header(&resp, header, tmp);
10983    append_history(p, "AuthChal", "Auth challenge sent for %s - nc %d", p->username, p->noncecount);
10984    return send_response(p, &resp, reliable, seqno);
10985 }
10986 
10987 /*!
10988  \brief Extract domain from SIP To/From header
10989  \return -1 on error, 1 if domain string is empty, 0 if domain was properly extracted
10990  \note TODO: Such code is all over SIP channel, there is a sense to organize
10991       this patern in one function
10992 */
10993 static int get_domain(const char *str, char *domain, int len)
10994 {
10995    char tmpf[256];
10996    char *a, *from;
10997 
10998    *domain = '\0';
10999    ast_copy_string(tmpf, str, sizeof(tmpf));
11000    from = get_in_brackets(tmpf);
11001    if (!ast_strlen_zero(from)) {
11002       if (strncasecmp(from, "sip:", 4)) {
11003          ast_log(LOG_WARNING, "Huh?  Not a SIP header (%s)?\n", from);
11004          return -1;
11005       }
11006       from += 4;
11007    } else
11008       from = NULL;
11009 
11010    if (from) {
11011       int bracket = 0;
11012 
11013       /* Strip any params or options from user */
11014       if ((a = strchr(from, ';')))
11015          *a = '\0';
11016       /* Strip port from domain if present */
11017       for (a = from; *a != '\0'; ++a) {
11018          if (*a == ':' && bracket == 0) {
11019             *a = '\0';
11020             break;
11021          } else if (*a == '[') {
11022             ++bracket;
11023          } else if (*a == ']') {
11024             --bracket;
11025          }
11026       }
11027       if ((a = strchr(from, '@'))) {
11028          *a = '\0';
11029          ast_copy_string(domain, a + 1, len);
11030       } else
11031          ast_copy_string(domain, from, len);
11032    }
11033 
11034    return ast_strlen_zero(domain);
11035 }
11036 
11037 /*!
11038   \brief Choose realm based on From header and then To header or use globaly configured realm.
11039   Realm from From/To header should be listed among served domains in config file: domain=...
11040 */
11041 static void get_realm(struct sip_pvt *p, const struct sip_request *req)
11042 {
11043    char domain[MAXHOSTNAMELEN];
11044 
11045    if (!ast_strlen_zero(p->realm))
11046       return;
11047 
11048    if (sip_cfg.domainsasrealm &&
11049        !AST_LIST_EMPTY(&domain_list))
11050    {
11051       /* Check From header first */
11052       if (!get_domain(sip_get_header(req, "From"), domain, sizeof(domain))) {
11053          if (check_sip_domain(domain, NULL, 0)) {
11054             ast_string_field_set(p, realm, domain);
11055             return;
11056          }
11057       }
11058       /* Check To header */
11059       if (!get_domain(sip_get_header(req, "To"), domain, sizeof(domain))) {
11060          if (check_sip_domain(domain, NULL, 0)) {
11061             ast_string_field_set(p, realm, domain);
11062             return;
11063          }
11064       }
11065    }
11066    
11067    /* Use default realm from config file */
11068    ast_string_field_set(p, realm, sip_cfg.realm);
11069 }
11070 
11071 /*!
11072  * \internal
11073  *
11074  * \arg msg Only use a string constant for the msg, here, it is shallow copied
11075  *
11076  * \note assumes the sip_pvt is locked.
11077  */
11078 static int transmit_provisional_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, int with_sdp)
11079 {
11080    int res;
11081 
11082    if (!(res = with_sdp ? transmit_response_with_sdp(p, msg, req, XMIT_UNRELIABLE, FALSE, FALSE) : transmit_response(p, msg, req))) {
11083       p->last_provisional = msg;
11084       update_provisional_keepalive(p, with_sdp);
11085    }
11086 
11087    return res;
11088 }
11089 
11090 /*!
11091  * \internal
11092  * \brief Destroy all additional MESSAGE headers.
11093  *
11094  * \param pvt SIP private dialog struct.
11095  *
11096  * \return Nothing
11097  */
11098 static void destroy_msg_headers(struct sip_pvt *pvt)
11099 {
11100    struct sip_msg_hdr *doomed;
11101 
11102    while ((doomed = AST_LIST_REMOVE_HEAD(&pvt->msg_headers, next))) {
11103       ast_free(doomed);
11104    }
11105 }
11106 
11107 /*!
11108  * \internal
11109  * \brief Add a MESSAGE header to the dialog.
11110  *
11111  * \param pvt SIP private dialog struct.
11112  * \param hdr_name Name of header for MESSAGE.
11113  * \param hdr_value Value of header for MESSAGE.
11114  *
11115  * \return Nothing
11116  */
11117 static void add_msg_header(struct sip_pvt *pvt, const char *hdr_name, const char *hdr_value)
11118 {
11119    size_t hdr_len_name;
11120    size_t hdr_len_value;
11121    struct sip_msg_hdr *node;
11122    char *pos;
11123 
11124    hdr_len_name = strlen(hdr_name) + 1;
11125    hdr_len_value = strlen(hdr_value) + 1;
11126 
11127    node = ast_calloc(1, sizeof(*node) + hdr_len_name + hdr_len_value);
11128    if (!node) {
11129       return;
11130    }
11131    pos = node->stuff;
11132    node->name = pos;
11133    strcpy(pos, hdr_name);
11134    pos += hdr_len_name;
11135    node->value = pos;
11136    strcpy(pos, hdr_value);
11137 
11138    AST_LIST_INSERT_TAIL(&pvt->msg_headers, node, next);
11139 }
11140 
11141 /*! \brief Add text body to SIP message */
11142 static int add_text(struct sip_request *req, struct sip_pvt *p)
11143 {
11144    const char *content_type = NULL;
11145    struct sip_msg_hdr *node;
11146 
11147    /* Add any additional MESSAGE headers. */
11148    AST_LIST_TRAVERSE(&p->msg_headers, node, next) {
11149       if (!strcasecmp(node->name, "Content-Type")) {
11150          /* Save content type */
11151          content_type = node->value;
11152       } else {
11153          add_header(req, node->name, node->value);
11154       }
11155    }
11156    if (ast_strlen_zero(content_type)) {
11157       /* "Content-Type" not set - use default value */
11158       content_type = "text/plain;charset=UTF-8";
11159    }
11160    add_header(req, "Content-Type", content_type);
11161 
11162    /* XXX Convert \n's to \r\n's XXX */
11163    add_content(req, p->msg_body);
11164    return 0;
11165 }
11166 
11167 /*! \brief Add DTMF INFO tone to sip message
11168    Mode =   0 for application/dtmf-relay (Cisco)
11169       1 for application/dtmf
11170 */
11171 static int add_digit(struct sip_request *req, char digit, unsigned int duration, int mode)
11172 {
11173    char tmp[256];
11174    int event;
11175    if (mode) {
11176       /* Application/dtmf short version used by some implementations */
11177       if ('0' <= digit && digit <= '9') {
11178          event = digit - '0';
11179       } else if (digit == '*') {
11180          event = 10;
11181       } else if (digit == '#') {
11182          event = 11;
11183       } else if ('A' <= digit && digit <= 'D') {
11184          event = 12 + digit - 'A';
11185       } else if ('a' <= digit && digit <= 'd') {
11186          event = 12 + digit - 'a';
11187       } else {
11188          /* Unknown digit */
11189          event = 0;
11190       }
11191       snprintf(tmp, sizeof(tmp), "%d\r\n", event);
11192       add_header(req, "Content-Type", "application/dtmf");
11193       add_content(req, tmp);
11194    } else {
11195       /* Application/dtmf-relay as documented by Cisco */
11196       snprintf(tmp, sizeof(tmp), "Signal=%c\r\nDuration=%u\r\n", digit, duration);
11197       add_header(req, "Content-Type", "application/dtmf-relay");
11198       add_content(req, tmp);
11199    }
11200    return 0;
11201 }
11202 
11203 /*!
11204  * \pre if p->owner exists, it must be locked
11205  * \brief Add Remote-Party-ID header to SIP message
11206  */
11207 static int add_rpid(struct sip_request *req, struct sip_pvt *p)
11208 {
11209    struct ast_str *tmp = ast_str_alloca(256);
11210    char tmp2[256];
11211    char *lid_num = NULL;
11212    char *lid_name = NULL;
11213    int lid_pres;
11214    const char *fromdomain;
11215    const char *privacy = NULL;
11216    const char *screen = NULL;
11217    const char *anonymous_string = "\"Anonymous\" <sip:anonymous@anonymous.invalid>";
11218 
11219    if (!ast_test_flag(&p->flags[0], SIP_SENDRPID)) {
11220       return 0;
11221    }
11222 
11223    if (p->owner && p->owner->connected.id.number.valid
11224       && p->owner->connected.id.number.str) {
11225       lid_num = p->owner->connected.id.number.str;
11226    }
11227    if (p->owner && p->owner->connected.id.name.valid
11228       && p->owner->connected.id.name.str) {
11229       lid_name = p->owner->connected.id.name.str;
11230    }
11231    lid_pres = (p->owner) ? ast_party_id_presentation(&p->owner->connected.id) : AST_PRES_NUMBER_NOT_AVAILABLE;
11232 
11233    if (ast_strlen_zero(lid_num))
11234       return 0;
11235    if (ast_strlen_zero(lid_name))
11236       lid_name = lid_num;
11237    fromdomain = S_OR(p->fromdomain, ast_sockaddr_stringify_host_remote(&p->ourip));
11238 
11239    lid_num = ast_uri_encode(lid_num, tmp2, sizeof(tmp2), ast_uri_sip_user);
11240 
11241    if (ast_test_flag(&p->flags[0], SIP_SENDRPID_PAI)) {
11242       if ((lid_pres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED) {
11243          ast_str_set(&tmp, -1, "%s", anonymous_string);
11244       } else {
11245          ast_str_set(&tmp, -1, "\"%s\" <sip:%s@%s>", lid_name, lid_num, fromdomain);
11246       }
11247       add_header(req, "P-Asserted-Identity", ast_str_buffer(tmp));
11248    } else {
11249       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");
11250 
11251       switch (lid_pres) {
11252       case AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED:
11253       case AST_PRES_ALLOWED_USER_NUMBER_FAILED_SCREEN:
11254          privacy = "off";
11255          screen = "no";
11256          break;
11257       case AST_PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN:
11258       case AST_PRES_ALLOWED_NETWORK_NUMBER:
11259          privacy = "off";
11260          screen = "yes";
11261          break;
11262       case AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED:
11263       case AST_PRES_PROHIB_USER_NUMBER_FAILED_SCREEN:
11264          privacy = "full";
11265          screen = "no";
11266          break;
11267       case AST_PRES_PROHIB_USER_NUMBER_PASSED_SCREEN:
11268       case AST_PRES_PROHIB_NETWORK_NUMBER:
11269          privacy = "full";
11270          screen = "yes";
11271          break;
11272       case AST_PRES_NUMBER_NOT_AVAILABLE:
11273          break;
11274       default:
11275          if ((lid_pres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED) {
11276             privacy = "full";
11277          }
11278          else
11279             privacy = "off";
11280          screen = "no";
11281          break;
11282       }
11283 
11284       if (!ast_strlen_zero(privacy) && !ast_strlen_zero(screen)) {
11285          ast_str_append(&tmp, -1, ";privacy=%s;screen=%s", privacy, screen);
11286       }
11287 
11288       add_header(req, "Remote-Party-ID", ast_str_buffer(tmp));
11289    }
11290    return 0;
11291 }
11292 
11293 /*! \brief add XML encoded media control with update
11294    \note XML: The only way to turn 0 bits of information into a few hundred. (markster) */
11295 static int add_vidupdate(struct sip_request *req)
11296 {
11297    const char *xml_is_a_huge_waste_of_space =
11298       "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\r\n"
11299       " <media_control>\r\n"
11300       "  <vc_primitive>\r\n"
11301       "   <to_encoder>\r\n"
11302       "    <picture_fast_update>\r\n"
11303       "    </picture_fast_update>\r\n"
11304       "   </to_encoder>\r\n"
11305       "  </vc_primitive>\r\n"
11306       " </media_control>\r\n";
11307    add_header(req, "Content-Type", "application/media_control+xml");
11308    add_content(req, xml_is_a_huge_waste_of_space);
11309    return 0;
11310 }
11311 
11312 /*! \brief Add codec offer to SDP offer/answer body in INVITE or 200 OK */
11313 static void add_codec_to_sdp(const struct sip_pvt *p,
11314    struct ast_format *format,
11315    struct ast_str **m_buf,
11316    struct ast_str **a_buf,
11317    int debug,
11318    int *min_packet_size)
11319 {
11320    int rtp_code;
11321    struct ast_format_list fmt;
11322    int val = 0;
11323 
11324    if (debug)
11325       ast_verbose("Adding codec %d (%s) to SDP\n", format->id, ast_getformatname(format));
11326    if ((rtp_code = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(p->rtp), 1, format, 0)) == -1)
11327       return;
11328 
11329    if (p->rtp) {
11330       struct ast_codec_pref *pref = &ast_rtp_instance_get_codecs(p->rtp)->pref;
11331       fmt = ast_codec_pref_getsize(pref, format);
11332    } 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 */
11333       return;
11334    ast_str_append(m_buf, 0, " %d", rtp_code);
11335    ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%d\r\n",
11336       rtp_code,
11337       ast_rtp_lookup_mime_subtype2(1, format, 0, ast_test_flag(&p->flags[0], SIP_G726_NONSTANDARD) ? AST_RTP_OPT_G726_NONSTANDARD : 0),
11338       ast_rtp_lookup_sample_rate2(1, format, 0));
11339 
11340    switch ((int) format->id) {
11341    case AST_FORMAT_G729A:
11342       /* Indicate that we don't support VAD (G.729 annex B) */
11343       ast_str_append(a_buf, 0, "a=fmtp:%d annexb=no\r\n", rtp_code);
11344       break;
11345    case AST_FORMAT_G723_1:
11346       /* Indicate that we don't support VAD (G.723.1 annex A) */
11347       ast_str_append(a_buf, 0, "a=fmtp:%d annexa=no\r\n", rtp_code);
11348       break;
11349    case AST_FORMAT_ILBC:
11350       /* Add information about us using only 20/30 ms packetization */
11351       ast_str_append(a_buf, 0, "a=fmtp:%d mode=%d\r\n", rtp_code, fmt.cur_ms);
11352       break;
11353    case AST_FORMAT_SIREN7:
11354       /* Indicate that we only expect 32Kbps */
11355       ast_str_append(a_buf, 0, "a=fmtp:%d bitrate=32000\r\n", rtp_code);
11356       break;
11357    case AST_FORMAT_SIREN14:
11358       /* Indicate that we only expect 48Kbps */
11359       ast_str_append(a_buf, 0, "a=fmtp:%d bitrate=48000\r\n", rtp_code);
11360       break;
11361    case AST_FORMAT_G719:
11362       /* Indicate that we only expect 64Kbps */
11363       ast_str_append(a_buf, 0, "a=fmtp:%d bitrate=64000\r\n", rtp_code);
11364       break;
11365    case AST_FORMAT_CELT:
11366       if (!ast_format_get_value(format, CELT_ATTR_KEY_FRAME_SIZE, &val) && val > 0) {
11367          ast_str_append(a_buf, 0, "a=fmtp:%d framesize=%u\r\n", rtp_code, val);
11368       }
11369       break;
11370    case AST_FORMAT_SILK:
11371       if (!ast_format_get_value(format, SILK_ATTR_KEY_MAX_BITRATE, &val) && val > 5000 && val < 40000) {
11372          ast_str_append(a_buf, 0, "a=fmtp:%d maxaveragebitrate=%u\r\n", rtp_code, val);
11373       }
11374       if (!ast_format_get_value(format, SILK_ATTR_KEY_DTX, &val)) {
11375          ast_str_append(a_buf, 0, "a=fmtp:%d usedtx=%u\r\n", rtp_code, val ? 1 : 0);
11376       }
11377       if (!ast_format_get_value(format, SILK_ATTR_KEY_FEC, &val)) {
11378          ast_str_append(a_buf, 0, "a=fmtp:%d useinbandfec=%u\r\n", rtp_code, val ? 1 : 0);
11379       }
11380       break;
11381    }
11382 
11383    if (fmt.cur_ms && (fmt.cur_ms < *min_packet_size))
11384       *min_packet_size = fmt.cur_ms;
11385 
11386    /* Our first codec packetization processed cannot be zero */
11387    if ((*min_packet_size)==0 && fmt.cur_ms)
11388       *min_packet_size = fmt.cur_ms;
11389 }
11390 
11391 /*! \brief Add video codec offer to SDP offer/answer body in INVITE or 200 OK */
11392 /* This is different to the audio one now so we can add more caps later */
11393 static void add_vcodec_to_sdp(const struct sip_pvt *p, struct ast_format *format,
11394               struct ast_str **m_buf, struct ast_str **a_buf,
11395               int debug, int *min_packet_size)
11396 {
11397    int rtp_code;
11398 
11399    if (!p->vrtp)
11400       return;
11401 
11402    if (debug)
11403       ast_verbose("Adding video codec %d (%s) to SDP\n", format->id, ast_getformatname(format));
11404 
11405    if ((rtp_code = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(p->vrtp), 1, format, 0)) == -1)
11406       return;
11407 
11408    ast_str_append(m_buf, 0, " %d", rtp_code);
11409    ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%d\r\n", rtp_code,
11410              ast_rtp_lookup_mime_subtype2(1, format, 0, 0),
11411              ast_rtp_lookup_sample_rate2(1, format, 0));
11412    /* Add fmtp code here */
11413 }
11414 
11415 /*! \brief Add text codec offer to SDP offer/answer body in INVITE or 200 OK */
11416 static void add_tcodec_to_sdp(const struct sip_pvt *p, struct ast_format *format,
11417               struct ast_str **m_buf, struct ast_str **a_buf,
11418               int debug, int *min_packet_size)
11419 {
11420    int rtp_code;
11421 
11422    if (!p->trtp)
11423       return;
11424 
11425    if (debug)
11426       ast_verbose("Adding text codec %d (%s) to SDP\n", format->id, ast_getformatname(format));
11427 
11428    if ((rtp_code = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(p->trtp), 1, format, 0)) == -1)
11429       return;
11430 
11431    ast_str_append(m_buf, 0, " %d", rtp_code);
11432    ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%d\r\n", rtp_code,
11433              ast_rtp_lookup_mime_subtype2(1, format, 0, 0),
11434              ast_rtp_lookup_sample_rate2(1, format, 0));
11435    /* Add fmtp code here */
11436 
11437    if (format->id == AST_FORMAT_T140RED) {
11438       struct ast_format tmp_fmt;
11439       int t140code = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(p->trtp), 1, ast_format_set(&tmp_fmt, AST_FORMAT_T140, 0), 0);
11440       ast_str_append(a_buf, 0, "a=fmtp:%d %d/%d/%d\r\n", rtp_code,
11441           t140code,
11442           t140code,
11443           t140code);
11444 
11445    }
11446 }
11447 
11448 
11449 /*! \brief Get Max T.38 Transmission rate from T38 capabilities */
11450 static unsigned int t38_get_rate(enum ast_control_t38_rate rate)
11451 {
11452    switch (rate) {
11453    case AST_T38_RATE_2400:
11454       return 2400;
11455    case AST_T38_RATE_4800:
11456       return 4800;
11457    case AST_T38_RATE_7200:
11458       return 7200;
11459    case AST_T38_RATE_9600:
11460       return 9600;
11461    case AST_T38_RATE_12000:
11462       return 12000;
11463    case AST_T38_RATE_14400:
11464       return 14400;
11465    default:
11466       return 0;
11467    }
11468 }
11469 
11470 /*! \brief Add RFC 2833 DTMF offer to SDP */
11471 static void add_noncodec_to_sdp(const struct sip_pvt *p, int format,
11472             struct ast_str **m_buf, struct ast_str **a_buf,
11473             int debug)
11474 {
11475    int rtp_code;
11476 
11477    if (debug)
11478       ast_verbose("Adding non-codec 0x%x (%s) to SDP\n", format, ast_rtp_lookup_mime_subtype2(0, NULL, format, 0));
11479    if ((rtp_code = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(p->rtp), 0, NULL, format)) == -1)
11480       return;
11481 
11482    ast_str_append(m_buf, 0, " %d", rtp_code);
11483    ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%d\r\n", rtp_code,
11484              ast_rtp_lookup_mime_subtype2(0, NULL, format, 0),
11485              ast_rtp_lookup_sample_rate2(0, NULL, format));
11486    if (format == AST_RTP_DTMF)   /* Indicate we support DTMF and FLASH... */
11487       ast_str_append(a_buf, 0, "a=fmtp:%d 0-16\r\n", rtp_code);
11488 }
11489 
11490 /*! \brief Set all IP media addresses for this call
11491    \note called from add_sdp()
11492 */
11493 static void get_our_media_address(struct sip_pvt *p, int needvideo, int needtext,
11494               struct ast_sockaddr *addr, struct ast_sockaddr *vaddr,
11495               struct ast_sockaddr *taddr, struct ast_sockaddr *dest,
11496               struct ast_sockaddr *vdest, struct ast_sockaddr *tdest)
11497 {
11498    int use_externip = 0;
11499 
11500    /* First, get our address */
11501    ast_rtp_instance_get_local_address(p->rtp, addr);
11502    if (p->vrtp) {
11503       ast_rtp_instance_get_local_address(p->vrtp, vaddr);
11504    }
11505    if (p->trtp) {
11506       ast_rtp_instance_get_local_address(p->trtp, taddr);
11507    }
11508 
11509    /* If our real IP differs from the local address returned by the RTP engine, use it. */
11510    /* The premise is that if we are already using that IP to communicate with the client, */
11511    /* we should be using it for RTP too. */
11512         use_externip = ast_sockaddr_cmp_addr(&p->ourip, addr);
11513 
11514    /* Now, try to figure out where we want them to send data */
11515    /* Is this a re-invite to move the media out, then use the original offer from caller  */
11516    if (!ast_sockaddr_isnull(&p->redirip)) {  /* If we have a redirection IP, use it */
11517       ast_sockaddr_copy(dest, &p->redirip);
11518    } else {
11519       /*
11520        * Audio Destination IP:
11521        *
11522        * 1. Specifically configured media address.
11523        * 2. Local address as specified by the RTP engine.
11524        * 3. The local IP as defined by chan_sip.
11525        *
11526        * Audio Destination Port:
11527        *
11528        * 1. Provided by the RTP engine.
11529        */
11530       ast_sockaddr_copy(dest,
11531               !ast_sockaddr_isnull(&media_address) ? &media_address :
11532               !ast_sockaddr_is_any(addr) && !use_externip ? addr    :
11533               &p->ourip);
11534       ast_sockaddr_set_port(dest, ast_sockaddr_port(addr));
11535    }
11536 
11537    if (needvideo) {
11538       /* Determine video destination */
11539       if (!ast_sockaddr_isnull(&p->vredirip)) {
11540          ast_sockaddr_copy(vdest, &p->vredirip);
11541       } else {
11542          /*
11543           * Video Destination IP:
11544           *
11545           * 1. Specifically configured media address.
11546           * 2. Local address as specified by the RTP engine.
11547           * 3. The local IP as defined by chan_sip.
11548           *
11549           * Video Destination Port:
11550           *
11551           * 1. Provided by the RTP engine.
11552           */
11553          ast_sockaddr_copy(vdest,
11554                  !ast_sockaddr_isnull(&media_address) ? &media_address :
11555                  !ast_sockaddr_is_any(vaddr) && !use_externip ? vaddr  :
11556                  &p->ourip);
11557          ast_sockaddr_set_port(vdest, ast_sockaddr_port(vaddr));
11558       }
11559    }
11560 
11561    if (needtext) {
11562       /* Determine text destination */
11563       if (!ast_sockaddr_isnull(&p->tredirip)) {
11564          ast_sockaddr_copy(tdest, &p->tredirip);
11565       } else {
11566          /*
11567           * Text Destination IP:
11568           *
11569           * 1. Specifically configured media address.
11570           * 2. Local address as specified by the RTP engine.
11571           * 3. The local IP as defined by chan_sip.
11572           *
11573           * Text Destination Port:
11574           *
11575           * 1. Provided by the RTP engine.
11576           */
11577          ast_sockaddr_copy(tdest,
11578                  !ast_sockaddr_isnull(&media_address) ? &media_address  :
11579                  !ast_sockaddr_is_any(taddr) && !use_externip ? taddr   :
11580                  &p->ourip);
11581          ast_sockaddr_set_port(tdest, ast_sockaddr_port(taddr));
11582       }
11583    }
11584 }
11585 
11586 static void get_crypto_attrib(struct sip_pvt *p, struct sip_srtp *srtp, const char **a_crypto)
11587 {
11588    int taglen = 80;
11589 
11590    /* Set encryption properties */
11591    if (srtp) {
11592       if (!srtp->crypto) {
11593          srtp->crypto = sdp_crypto_setup();
11594       }
11595 
11596       /* set the key length based on INVITE or settings */
11597       if (ast_test_flag(srtp, SRTP_CRYPTO_TAG_80)) {
11598          taglen = 80;
11599       } else if (ast_test_flag(&p->flags[2], SIP_PAGE3_SRTP_TAG_32) ||
11600           ast_test_flag(srtp, SRTP_CRYPTO_TAG_32)) {
11601          taglen = 32;
11602       }
11603 
11604       if (srtp->crypto && (sdp_crypto_offer(srtp->crypto, taglen) >= 0)) {
11605          *a_crypto = sdp_crypto_attrib(srtp->crypto);
11606       }
11607 
11608       if (!*a_crypto) {
11609          ast_log(LOG_WARNING, "No SRTP key management enabled\n");
11610       }
11611    }
11612 }
11613 
11614 /*! \brief Add Session Description Protocol message
11615 
11616     If oldsdp is TRUE, then the SDP version number is not incremented. This mechanism
11617     is used in Session-Timers where RE-INVITEs are used for refreshing SIP sessions
11618     without modifying the media session in any way.
11619 */
11620 static enum sip_result add_sdp(struct sip_request *resp, struct sip_pvt *p, int oldsdp, int add_audio, int add_t38)
11621 {
11622    struct ast_format_cap *alreadysent = ast_format_cap_alloc_nolock();
11623    struct ast_format_cap *tmpcap = ast_format_cap_alloc_nolock();
11624    int res = AST_SUCCESS;
11625    int doing_directmedia = FALSE;
11626    struct ast_sockaddr addr = { {0,} };
11627    struct ast_sockaddr vaddr = { {0,} };
11628    struct ast_sockaddr taddr = { {0,} };
11629    struct ast_sockaddr udptladdr = { {0,} };
11630    struct ast_sockaddr dest = { {0,} };
11631    struct ast_sockaddr vdest = { {0,} };
11632    struct ast_sockaddr tdest = { {0,} };
11633    struct ast_sockaddr udptldest = { {0,} };
11634 
11635    /* SDP fields */
11636    char *version =   "v=0\r\n";     /* Protocol version */
11637    char subject[256];            /* Subject of the session */
11638    char owner[256];           /* Session owner/creator */
11639    char connection[256];            /* Connection data */
11640    char *session_time = "t=0 0\r\n";         /* Time the session is active */
11641    char bandwidth[256] = "";        /* Max bitrate */
11642    char *hold = "";
11643    struct ast_str *m_audio = ast_str_alloca(256);  /* Media declaration line for audio */
11644    struct ast_str *m_video = ast_str_alloca(256);  /* Media declaration line for video */
11645    struct ast_str *m_text = ast_str_alloca(256);   /* Media declaration line for text */
11646    struct ast_str *m_modem = ast_str_alloca(256);  /* Media declaration line for modem */
11647    struct ast_str *a_audio = ast_str_alloca(1024); /* Attributes for audio */
11648    struct ast_str *a_video = ast_str_alloca(1024); /* Attributes for video */
11649    struct ast_str *a_text = ast_str_alloca(1024);  /* Attributes for text */
11650    struct ast_str *a_modem = ast_str_alloca(1024); /* Attributes for modem */
11651    const char *a_crypto = NULL;
11652    const char *v_a_crypto = NULL;
11653    const char *t_a_crypto = NULL;
11654 
11655    int x;
11656    struct ast_format tmp_fmt;
11657    int needaudio = FALSE;
11658    int needvideo = FALSE;
11659    int needtext = FALSE;
11660    int debug = sip_debug_test_pvt(p);
11661    int min_audio_packet_size = 0;
11662    int min_video_packet_size = 0;
11663    int min_text_packet_size = 0;
11664 
11665    char codecbuf[SIPBUFSIZE];
11666    char buf[SIPBUFSIZE];
11667    char dummy_answer[256];
11668 
11669    /* Set the SDP session name */
11670    snprintf(subject, sizeof(subject), "s=%s\r\n", ast_strlen_zero(global_sdpsession) ? "-" : global_sdpsession);
11671 
11672    if (!alreadysent || !tmpcap) {
11673       res = AST_FAILURE;
11674       goto add_sdp_cleanup;
11675    }
11676    if (!p->rtp) {
11677       ast_log(LOG_WARNING, "No way to add SDP without an RTP structure\n");
11678       res = AST_FAILURE;
11679       goto add_sdp_cleanup;
11680 
11681    }
11682    /* XXX We should not change properties in the SIP dialog until
11683       we have acceptance of the offer if this is a re-invite */
11684 
11685    /* Set RTP Session ID and version */
11686    if (!p->sessionid) {
11687       p->sessionid = (int)ast_random();
11688       p->sessionversion = p->sessionid;
11689    } else {
11690       if (oldsdp == FALSE)
11691          p->sessionversion++;
11692    }
11693 
11694    if (add_audio) {
11695       doing_directmedia = (!ast_sockaddr_isnull(&p->redirip) && !(ast_format_cap_is_empty(p->redircaps))) ? TRUE : FALSE;
11696       /* Check if we need video in this call */
11697       if ((ast_format_cap_has_type(p->jointcaps, AST_FORMAT_TYPE_VIDEO)) && !p->novideo) {
11698          ast_format_cap_joint_copy(p->jointcaps, p->redircaps, tmpcap);
11699          if (doing_directmedia && !ast_format_cap_has_type(tmpcap, AST_FORMAT_TYPE_VIDEO)) {
11700             ast_debug(2, "This call needs video offers, but caller probably did not offer it!\n");
11701          } else if (p->vrtp) {
11702             needvideo = TRUE;
11703             ast_debug(2, "This call needs video offers!\n");
11704          } else {
11705             ast_debug(2, "This call needs video offers, but there's no video support enabled!\n");
11706          }
11707       }
11708       /* Check if we need text in this call */
11709       if ((ast_format_cap_has_type(p->jointcaps, AST_FORMAT_TYPE_TEXT)) && !p->notext) {
11710          if (sipdebug_text)
11711             ast_verbose("We think we can do text\n");
11712          if (p->trtp) {
11713             if (sipdebug_text) {
11714                ast_verbose("And we have a text rtp object\n");
11715             }
11716             needtext = TRUE;
11717             ast_debug(2, "This call needs text offers! \n");
11718          } else {
11719             ast_debug(2, "This call needs text offers, but there's no text support enabled ! \n");
11720          }
11721       }
11722    }
11723 
11724    get_our_media_address(p, needvideo, needtext, &addr, &vaddr, &taddr, &dest, &vdest, &tdest);
11725 
11726    snprintf(owner, sizeof(owner), "o=%s %d %d IN %s %s\r\n",
11727        ast_strlen_zero(global_sdpowner) ? "-" : global_sdpowner,
11728        p->sessionid, p->sessionversion,
11729        (ast_sockaddr_is_ipv6(&dest) && !ast_sockaddr_is_ipv4_mapped(&dest)) ?
11730          "IP6" : "IP4",
11731        ast_sockaddr_stringify_addr_remote(&dest));
11732 
11733    snprintf(connection, sizeof(connection), "c=IN %s %s\r\n",
11734        (ast_sockaddr_is_ipv6(&dest) && !ast_sockaddr_is_ipv4_mapped(&dest)) ?
11735          "IP6" : "IP4",
11736        ast_sockaddr_stringify_addr_remote(&dest));
11737 
11738    if (add_audio) {
11739       if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD) == SIP_PAGE2_CALL_ONHOLD_ONEDIR) {
11740          hold = "a=recvonly\r\n";
11741          doing_directmedia = FALSE;
11742       } else if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD) == SIP_PAGE2_CALL_ONHOLD_INACTIVE) {
11743          hold = "a=inactive\r\n";
11744          doing_directmedia = FALSE;
11745       } else {
11746          hold = "a=sendrecv\r\n";
11747       }
11748 
11749       ast_format_cap_copy(tmpcap, p->jointcaps);
11750 
11751       /* XXX note, Video and Text are negated - 'true' means 'no' */
11752       ast_debug(1, "** Our capability: %s Video flag: %s Text flag: %s\n", ast_getformatname_multiple(codecbuf, sizeof(codecbuf), tmpcap),
11753            p->novideo ? "True" : "False", p->notext ? "True" : "False");
11754       ast_debug(1, "** Our prefcodec: %s \n", ast_getformatname_multiple(codecbuf, sizeof(codecbuf), p->prefcaps));
11755 
11756       if (doing_directmedia) {
11757          ast_format_cap_joint_copy(p->jointcaps, p->redircaps, tmpcap);
11758          ast_debug(1, "** Our native-bridge filtered capablity: %s\n", ast_getformatname_multiple(codecbuf, sizeof(codecbuf), tmpcap));
11759       }
11760 
11761       /* Check if we need audio */
11762       if (ast_format_cap_has_type(tmpcap, AST_FORMAT_TYPE_AUDIO))
11763          needaudio = TRUE;
11764 
11765       if (debug) {
11766          ast_verbose("Audio is at %s\n", ast_sockaddr_stringify_port(&addr));
11767       }
11768 
11769       /* Ok, we need video. Let's add what we need for video and set codecs.
11770          Video is handled differently than audio since we can not transcode. */
11771       if (needvideo) {
11772          get_crypto_attrib(p, p->vsrtp, &v_a_crypto);
11773          ast_str_append(&m_video, 0, "m=video %d RTP/%s", ast_sockaddr_port(&vdest),
11774             v_a_crypto ? "SAVP" : "AVP");
11775 
11776          /* Build max bitrate string */
11777          if (p->maxcallbitrate)
11778             snprintf(bandwidth, sizeof(bandwidth), "b=CT:%d\r\n", p->maxcallbitrate);
11779          if (debug) {
11780             ast_verbose("Video is at %s\n", ast_sockaddr_stringify(&vdest));
11781          }
11782       }
11783 
11784       /* Ok, we need text. Let's add what we need for text and set codecs.
11785          Text is handled differently than audio since we can not transcode. */
11786       if (needtext) {
11787          if (sipdebug_text)
11788             ast_verbose("Lets set up the text sdp\n");
11789          get_crypto_attrib(p, p->tsrtp, &t_a_crypto);
11790          ast_str_append(&m_text, 0, "m=text %d RTP/%s", ast_sockaddr_port(&tdest),
11791             t_a_crypto ? "SAVP" : "AVP");
11792          if (debug) {  /* XXX should I use tdest below ? */
11793             ast_verbose("Text is at %s\n", ast_sockaddr_stringify(&taddr));
11794          }
11795       }
11796 
11797       /* Start building generic SDP headers */
11798 
11799       /* We break with the "recommendation" and send our IP, in order that our
11800          peer doesn't have to ast_gethostbyname() us */
11801 
11802       get_crypto_attrib(p, p->srtp, &a_crypto);
11803       ast_str_append(&m_audio, 0, "m=audio %d RTP/%s", ast_sockaddr_port(&dest),
11804          a_crypto ? "SAVP" : "AVP");
11805 
11806       /* Now, start adding audio codecs. These are added in this order:
11807          - First what was requested by the calling channel
11808          - Then preferences in order from sip.conf device config for this peer/user
11809          - Then other codecs in capabilities, including video
11810       */
11811 
11812       /* Prefer the audio codec we were requested to use, first, no matter what
11813          Note that p->prefcodec can include video codecs, so mask them out
11814       */
11815       if (ast_format_cap_has_joint(tmpcap, p->prefcaps)) {
11816          ast_format_cap_iter_start(p->prefcaps);
11817          while (!(ast_format_cap_iter_next(p->prefcaps, &tmp_fmt))) {
11818             if (AST_FORMAT_GET_TYPE(tmp_fmt.id) != AST_FORMAT_TYPE_AUDIO) {
11819                continue;
11820             }
11821             add_codec_to_sdp(p, &tmp_fmt, &m_audio, &a_audio, debug, &min_audio_packet_size);
11822             ast_format_cap_add(alreadysent, &tmp_fmt);
11823          }
11824          ast_format_cap_iter_end(p->prefcaps);
11825       }
11826 
11827       /* Start by sending our preferred audio/video codecs */
11828       for (x = 0; x < AST_CODEC_PREF_SIZE; x++) {
11829          if (!(ast_codec_pref_index(&p->prefs, x, &tmp_fmt)))
11830             break;
11831 
11832          if (!(ast_format_cap_iscompatible(tmpcap, &tmp_fmt)))
11833             continue;
11834 
11835          if (ast_format_cap_iscompatible(alreadysent, &tmp_fmt))
11836             continue;
11837 
11838          if (AST_FORMAT_GET_TYPE(tmp_fmt.id) == AST_FORMAT_TYPE_AUDIO) {
11839             add_codec_to_sdp(p, &tmp_fmt, &m_audio, &a_audio, debug, &min_audio_packet_size);
11840          } else if (needvideo && (AST_FORMAT_GET_TYPE(tmp_fmt.id) == AST_FORMAT_TYPE_VIDEO)) {
11841             add_vcodec_to_sdp(p, &tmp_fmt, &m_video, &a_video, debug, &min_video_packet_size);
11842          } else if (needtext && (AST_FORMAT_GET_TYPE(tmp_fmt.id) == AST_FORMAT_TYPE_TEXT)) {
11843             add_tcodec_to_sdp(p, &tmp_fmt, &m_text, &a_text, debug, &min_text_packet_size);
11844          }
11845 
11846          ast_format_cap_add(alreadysent, &tmp_fmt);
11847       }
11848 
11849       /* Now send any other common audio and video codecs, and non-codec formats: */
11850       ast_format_cap_iter_start(tmpcap);
11851       while (!(ast_format_cap_iter_next(tmpcap, &tmp_fmt))) {
11852          if (ast_format_cap_iscompatible(alreadysent, &tmp_fmt))
11853             continue;
11854 
11855          if (AST_FORMAT_GET_TYPE(tmp_fmt.id) == AST_FORMAT_TYPE_AUDIO) {
11856             add_codec_to_sdp(p, &tmp_fmt, &m_audio, &a_audio, debug, &min_audio_packet_size);
11857          } else if (needvideo && (AST_FORMAT_GET_TYPE(tmp_fmt.id) == AST_FORMAT_TYPE_VIDEO)) {
11858             add_vcodec_to_sdp(p, &tmp_fmt, &m_video, &a_video, debug, &min_video_packet_size);
11859          } else if (needtext && (AST_FORMAT_GET_TYPE(tmp_fmt.id) == AST_FORMAT_TYPE_TEXT)) {
11860             add_tcodec_to_sdp(p, &tmp_fmt, &m_text, &a_text, debug, &min_text_packet_size);
11861          }
11862       }
11863       ast_format_cap_iter_end(tmpcap);
11864 
11865       /* Now add DTMF RFC2833 telephony-event as a codec */
11866       for (x = 1LL; x <= AST_RTP_MAX; x <<= 1) {
11867          if (!(p->jointnoncodeccapability & x))
11868             continue;
11869 
11870          add_noncodec_to_sdp(p, x, &m_audio, &a_audio, debug);
11871       }
11872 
11873       ast_debug(3, "-- Done with adding codecs to SDP\n");
11874 
11875       if (!p->owner || !ast_internal_timing_enabled(p->owner))
11876          ast_str_append(&a_audio, 0, "a=silenceSupp:off - - - -\r\n");
11877 
11878       if (min_audio_packet_size)
11879          ast_str_append(&a_audio, 0, "a=ptime:%d\r\n", min_audio_packet_size);
11880 
11881       /* XXX don't think you can have ptime for video */
11882       if (min_video_packet_size)
11883          ast_str_append(&a_video, 0, "a=ptime:%d\r\n", min_video_packet_size);
11884 
11885       /* XXX don't think you can have ptime for text */
11886       if (min_text_packet_size)
11887          ast_str_append(&a_text, 0, "a=ptime:%d\r\n", min_text_packet_size);
11888 
11889       if (m_audio->len - m_audio->used < 2 || m_video->len - m_video->used < 2 ||
11890           m_text->len - m_text->used < 2 || a_text->len - a_text->used < 2 ||
11891           a_audio->len - a_audio->used < 2 || a_video->len - a_video->used < 2)
11892          ast_log(LOG_WARNING, "SIP SDP may be truncated due to undersized buffer!!\n");
11893    }
11894 
11895    if (add_t38) {
11896       /* Our T.38 end is */
11897       ast_udptl_get_us(p->udptl, &udptladdr);
11898 
11899       /* Determine T.38 UDPTL destination */
11900       if (!ast_sockaddr_isnull(&p->udptlredirip)) {
11901          ast_sockaddr_copy(&udptldest, &p->udptlredirip);
11902       } else {
11903          ast_sockaddr_copy(&udptldest, &p->ourip);
11904          ast_sockaddr_set_port(&udptldest, ast_sockaddr_port(&udptladdr));
11905       }
11906 
11907       if (debug) {
11908          ast_debug(1, "T.38 UDPTL is at %s port %d\n", ast_sockaddr_stringify_addr(&p->ourip), ast_sockaddr_port(&udptladdr));
11909       }
11910 
11911       /* We break with the "recommendation" and send our IP, in order that our
11912          peer doesn't have to ast_gethostbyname() us */
11913 
11914       ast_str_append(&m_modem, 0, "m=image %d udptl t38\r\n", ast_sockaddr_port(&udptldest));
11915 
11916       if (!ast_sockaddr_cmp(&udptldest, &dest)) {
11917          ast_str_append(&m_modem, 0, "c=IN %s %s\r\n",
11918                (ast_sockaddr_is_ipv6(&dest) && !ast_sockaddr_is_ipv4_mapped(&dest)) ?
11919                "IP6" : "IP4", ast_sockaddr_stringify_addr_remote(&udptldest));
11920       }
11921 
11922       ast_str_append(&a_modem, 0, "a=T38FaxVersion:%d\r\n", p->t38.our_parms.version);
11923       ast_str_append(&a_modem, 0, "a=T38MaxBitRate:%d\r\n", t38_get_rate(p->t38.our_parms.rate));
11924       if (p->t38.our_parms.fill_bit_removal) {
11925          ast_str_append(&a_modem, 0, "a=T38FaxFillBitRemoval\r\n");
11926       }
11927       if (p->t38.our_parms.transcoding_mmr) {
11928          ast_str_append(&a_modem, 0, "a=T38FaxTranscodingMMR\r\n");
11929       }
11930       if (p->t38.our_parms.transcoding_jbig) {
11931          ast_str_append(&a_modem, 0, "a=T38FaxTranscodingJBIG\r\n");
11932       }
11933       switch (p->t38.our_parms.rate_management) {
11934       case AST_T38_RATE_MANAGEMENT_TRANSFERRED_TCF:
11935          ast_str_append(&a_modem, 0, "a=T38FaxRateManagement:transferredTCF\r\n");
11936          break;
11937       case AST_T38_RATE_MANAGEMENT_LOCAL_TCF:
11938          ast_str_append(&a_modem, 0, "a=T38FaxRateManagement:localTCF\r\n");
11939          break;
11940       }
11941       ast_str_append(&a_modem, 0, "a=T38FaxMaxDatagram:%u\r\n", ast_udptl_get_local_max_datagram(p->udptl));
11942       switch (ast_udptl_get_error_correction_scheme(p->udptl)) {
11943       case UDPTL_ERROR_CORRECTION_NONE:
11944          break;
11945       case UDPTL_ERROR_CORRECTION_FEC:
11946          ast_str_append(&a_modem, 0, "a=T38FaxUdpEC:t38UDPFEC\r\n");
11947          break;
11948       case UDPTL_ERROR_CORRECTION_REDUNDANCY:
11949          ast_str_append(&a_modem, 0, "a=T38FaxUdpEC:t38UDPRedundancy\r\n");
11950          break;
11951       }
11952    }
11953 
11954    if (needaudio)
11955       ast_str_append(&m_audio, 0, "\r\n");
11956    if (needvideo)
11957       ast_str_append(&m_video, 0, "\r\n");
11958    if (needtext)
11959       ast_str_append(&m_text, 0, "\r\n");
11960 
11961    add_header(resp, "Content-Type", "application/sdp");
11962    add_content(resp, version);
11963    add_content(resp, owner);
11964    add_content(resp, subject);
11965    add_content(resp, connection);
11966    /* only if video response is appropriate */
11967    if (needvideo) {
11968       add_content(resp, bandwidth);
11969    }
11970    add_content(resp, session_time);
11971    /* if this is a response to an invite, order our offers properly */
11972    if (p->offered_media[SDP_AUDIO].order_offered ||
11973       p->offered_media[SDP_VIDEO].order_offered ||
11974       p->offered_media[SDP_TEXT].order_offered ||
11975       p->offered_media[SDP_IMAGE].order_offered) {
11976       int i;
11977       /* we have up to 3 streams as limited by process_sdp */
11978       for (i = 1; i <= 3; i++) {
11979          if (p->offered_media[SDP_AUDIO].order_offered == i) {
11980             if (needaudio) {
11981                add_content(resp, m_audio->str);
11982                add_content(resp, a_audio->str);
11983                add_content(resp, hold);
11984                if (a_crypto) {
11985                   add_content(resp, a_crypto);
11986                }
11987             } else {
11988                snprintf(dummy_answer, sizeof(dummy_answer), "m=audio 0 RTP/AVP %s\r\n", p->offered_media[SDP_AUDIO].codecs);
11989                add_content(resp, dummy_answer);
11990             }
11991          } else if (p->offered_media[SDP_VIDEO].order_offered == i) {
11992             if (needvideo) { /* only if video response is appropriate */
11993                add_content(resp, m_video->str);
11994                add_content(resp, a_video->str);
11995                add_content(resp, hold);   /* Repeat hold for the video stream */
11996                if (v_a_crypto) {
11997                   add_content(resp, v_a_crypto);
11998                }
11999             } else {
12000                snprintf(dummy_answer, sizeof(dummy_answer), "m=video 0 RTP/AVP %s\r\n", p->offered_media[SDP_VIDEO].codecs);
12001                add_content(resp, dummy_answer);
12002             }
12003          } else if (p->offered_media[SDP_TEXT].order_offered == i) {
12004             if (needtext) { /* only if text response is appropriate */
12005                add_content(resp, m_text->str);
12006                add_content(resp, a_text->str);
12007                add_content(resp, hold);   /* Repeat hold for the text stream */
12008                if (t_a_crypto) {
12009                   add_content(resp, t_a_crypto);
12010                }
12011             } else {
12012                snprintf(dummy_answer, sizeof(dummy_answer), "m=text 0 RTP/AVP %s\r\n", p->offered_media[SDP_TEXT].codecs);
12013                add_content(resp, dummy_answer);
12014             }
12015          } else if (p->offered_media[SDP_IMAGE].order_offered == i) {
12016             if (add_t38) {
12017                add_content(resp, m_modem->str);
12018                add_content(resp, a_modem->str);
12019             } else {
12020                add_content(resp, "m=image 0 udptl t38\r\n");
12021             }
12022          }
12023       }
12024    } else {
12025       /* generate new SDP from scratch, no offers */
12026       if (needaudio) {
12027          add_content(resp, m_audio->str);
12028          add_content(resp, a_audio->str);
12029          add_content(resp, hold);
12030          if (a_crypto) {
12031             add_content(resp, a_crypto);
12032          }
12033       }
12034       if (needvideo) { /* only if video response is appropriate */
12035          add_content(resp, m_video->str);
12036          add_content(resp, a_video->str);
12037          add_content(resp, hold);   /* Repeat hold for the video stream */
12038          if (v_a_crypto) {
12039             add_content(resp, v_a_crypto);
12040          }
12041       }
12042       if (needtext) { /* only if text response is appropriate */
12043          add_content(resp, m_text->str);
12044          add_content(resp, a_text->str);
12045          add_content(resp, hold);   /* Repeat hold for the text stream */
12046          if (t_a_crypto) {
12047             add_content(resp, t_a_crypto);
12048          }
12049       }
12050       if (add_t38) {
12051          add_content(resp, m_modem->str);
12052          add_content(resp, a_modem->str);
12053       }
12054    }
12055 
12056    /* Update lastrtprx when we send our SDP */
12057    p->lastrtprx = p->lastrtptx = time(NULL); /* XXX why both ? */
12058 
12059    /*
12060     * We unlink this dialog and link again into the
12061     * dialogs_rtpcheck container so its not in there twice.
12062     */
12063    ao2_lock(dialogs_rtpcheck);
12064    ao2_t_unlink(dialogs_rtpcheck, p, "unlink pvt into dialogs_rtpcheck container");
12065    ao2_t_link(dialogs_rtpcheck, p, "link pvt into dialogs_rtpcheck container");
12066    ao2_unlock(dialogs_rtpcheck);
12067 
12068    ast_debug(3, "Done building SDP. Settling with this capability: %s\n", ast_getformatname_multiple(buf, SIPBUFSIZE, tmpcap));
12069 
12070 add_sdp_cleanup:
12071    alreadysent = ast_format_cap_destroy(alreadysent);
12072    tmpcap = ast_format_cap_destroy(tmpcap);
12073 
12074    return res;
12075 }
12076 
12077 /*! \brief Used for 200 OK and 183 early media */
12078 static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans)
12079 {
12080    struct sip_request resp;
12081    uint32_t seqno;
12082 
12083    if (sscanf(sip_get_header(req, "CSeq"), "%30u ", &seqno) != 1) {
12084       ast_log(LOG_WARNING, "Unable to get seqno from '%s'\n", sip_get_header(req, "CSeq"));
12085       return -1;
12086    }
12087    respprep(&resp, p, msg, req);
12088    if (p->udptl) {
12089       add_sdp(&resp, p, 0, 0, 1);
12090    } else
12091       ast_log(LOG_ERROR, "Can't add SDP to response, since we have no UDPTL session allocated. Call-ID %s\n", p->callid);
12092    if (retrans && !p->pendinginvite)
12093       p->pendinginvite = seqno;     /* Buggy clients sends ACK on RINGING too */
12094    return send_response(p, &resp, retrans, seqno);
12095 }
12096 
12097 /*! \brief copy SIP request (mostly used to save request for responses) */
12098 static void copy_request(struct sip_request *dst, const struct sip_request *src)
12099 {
12100    /* XXX this function can encounter memory allocation errors, perhaps it
12101     * should return a value */
12102 
12103    struct ast_str *duplicate = dst->data;
12104    struct ast_str *duplicate_content = dst->content;
12105 
12106    /* copy the entire request then restore the original data and content
12107     * members from the dst request */
12108    memcpy(dst, src, sizeof(*dst));
12109    dst->data = duplicate;
12110    dst->content = duplicate_content;
12111 
12112    /* copy the data into the dst request */
12113    if (!dst->data && !(dst->data = ast_str_create(ast_str_strlen(src->data) + 1)))
12114       return;
12115    ast_str_copy_string(&dst->data, src->data);
12116 
12117    /* copy the content into the dst request (if it exists) */
12118    if (src->content) {
12119       if (!dst->content && !(dst->content = ast_str_create(ast_str_strlen(src->content) + 1)))
12120          return;
12121       ast_str_copy_string(&dst->content, src->content);
12122    }
12123 }
12124 
12125 static void add_cc_call_info_to_response(struct sip_pvt *p, struct sip_request *resp)
12126 {
12127    char uri[SIPBUFSIZE];
12128    struct ast_str *header = ast_str_alloca(SIPBUFSIZE);
12129    struct ast_cc_agent *agent = find_sip_cc_agent_by_original_callid(p);
12130    struct sip_cc_agent_pvt *agent_pvt;
12131 
12132    if (!agent) {
12133       /* Um, what? How could the SIP_OFFER_CC flag be set but there not be an
12134        * agent? Oh well, we'll just warn and return without adding the header.
12135        */
12136       ast_log(LOG_WARNING, "Can't find SIP CC agent for call '%s' even though OFFER_CC flag was set?\n", p->callid);
12137       return;
12138    }
12139 
12140    agent_pvt = agent->private_data;
12141 
12142    if (!ast_strlen_zero(agent_pvt->subscribe_uri)) {
12143       ast_copy_string(uri, agent_pvt->subscribe_uri, sizeof(uri));
12144    } else {
12145       generate_uri(p, uri, sizeof(uri));
12146       ast_copy_string(agent_pvt->subscribe_uri, uri, sizeof(agent_pvt->subscribe_uri));
12147    }
12148    /* XXX Hardcode "NR" as the m reason for now. This should perhaps be changed
12149     * to be more accurate. This parameter has no bearing on the actual operation
12150     * of the feature; it's just there for informational purposes.
12151     */
12152    ast_str_set(&header, 0, "<%s>;purpose=call-completion;m=%s", uri, "NR");
12153    add_header(resp, "Call-Info", ast_str_buffer(header));
12154    ao2_ref(agent, -1);
12155 }
12156 
12157 /*! \brief Used for 200 OK and 183 early media
12158    \return Will return XMIT_ERROR for network errors.
12159 */
12160 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)
12161 {
12162    struct sip_request resp;
12163    uint32_t seqno;
12164    if (sscanf(sip_get_header(req, "CSeq"), "%30u ", &seqno) != 1) {
12165       ast_log(LOG_WARNING, "Unable to get seqno from '%s'\n", sip_get_header(req, "CSeq"));
12166       return -1;
12167    }
12168    respprep(&resp, p, msg, req);
12169    if (rpid == TRUE) {
12170       add_rpid(&resp, p);
12171    }
12172    if (ast_test_flag(&p->flags[0], SIP_OFFER_CC)) {
12173       add_cc_call_info_to_response(p, &resp);
12174    }
12175    if (p->rtp) {
12176       if (!p->autoframing && !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
12177          ast_debug(1, "Setting framing from config on incoming call\n");
12178          ast_rtp_codecs_packetization_set(ast_rtp_instance_get_codecs(p->rtp), p->rtp, &p->prefs);
12179       }
12180       ast_rtp_instance_activate(p->rtp);
12181       try_suggested_sip_codec(p);
12182       if (p->t38.state == T38_ENABLED) {
12183          add_sdp(&resp, p, oldsdp, TRUE, TRUE);
12184       } else {
12185          add_sdp(&resp, p, oldsdp, TRUE, FALSE);
12186       }
12187    } else
12188       ast_log(LOG_ERROR, "Can't add SDP to response, since we have no RTP session allocated. Call-ID %s\n", p->callid);
12189    if (reliable && !p->pendinginvite)
12190       p->pendinginvite = seqno;     /* Buggy clients sends ACK on RINGING too */
12191    return send_response(p, &resp, reliable, seqno);
12192 }
12193 
12194 /*! \brief Parse first line of incoming SIP request */
12195 static int determine_firstline_parts(struct sip_request *req)
12196 {
12197    char *e = ast_skip_blanks(req->data->str);   /* there shouldn't be any */
12198    char *local_rlPart1;
12199 
12200    if (!*e)
12201       return -1;
12202    req->rlPart1 = e - req->data->str;  /* method or protocol */
12203    local_rlPart1 = e;
12204    e = ast_skip_nonblanks(e);
12205    if (*e)
12206       *e++ = '\0';
12207    /* Get URI or status code */
12208    e = ast_skip_blanks(e);
12209    if ( !*e )
12210       return -1;
12211    ast_trim_blanks(e);
12212 
12213    if (!strcasecmp(local_rlPart1, "SIP/2.0") ) { /* We have a response */
12214       if (strlen(e) < 3)   /* status code is 3 digits */
12215          return -1;
12216       req->rlPart2 = e - req->data->str;
12217    } else { /* We have a request */
12218       if ( *e == '<' ) { /* XXX the spec says it must not be in <> ! */
12219          ast_debug(3, "Oops. Bogus uri in <> %s\n", e);
12220          e++;
12221          if (!*e)
12222             return -1;
12223       }
12224       req->rlPart2 = e - req->data->str;  /* URI */
12225       e = ast_skip_nonblanks(e);
12226       if (*e)
12227          *e++ = '\0';
12228       e = ast_skip_blanks(e);
12229       if (strcasecmp(e, "SIP/2.0") ) {
12230          ast_debug(3, "Skipping packet - Bad request protocol %s\n", e);
12231          return -1;
12232       }
12233    }
12234    return 1;
12235 }
12236 
12237 /*! \brief Transmit reinvite with SDP
12238 \note    A re-invite is basically a new INVITE with the same CALL-ID and TAG as the
12239    INVITE that opened the SIP dialogue
12240    We reinvite so that the audio stream (RTP) go directly between
12241    the SIP UAs. SIP Signalling stays with * in the path.
12242    
12243    If t38version is TRUE, we send T38 SDP for re-invite from audio/video to
12244    T38 UDPTL transmission on the channel
12245 
12246     If oldsdp is TRUE then the SDP version number is not incremented. This
12247     is needed for Session-Timers so we can send a re-invite to refresh the
12248     SIP session without modifying the media session.
12249 */
12250 static int transmit_reinvite_with_sdp(struct sip_pvt *p, int t38version, int oldsdp)
12251 {
12252    struct sip_request req;
12253    
12254    reqprep(&req, p, ast_test_flag(&p->flags[0], SIP_REINVITE_UPDATE) ?  SIP_UPDATE : SIP_INVITE, 0, 1);
12255 
12256    add_header(&req, "Allow", ALLOWED_METHODS);
12257    add_supported_header(p, &req);
12258    if (sipdebug) {
12259       if (oldsdp == TRUE)
12260          add_header(&req, "X-asterisk-Info", "SIP re-invite (Session-Timers)");
12261       else
12262          add_header(&req, "X-asterisk-Info", "SIP re-invite (External RTP bridge)");
12263    }
12264 
12265    if (ast_test_flag(&p->flags[0], SIP_SENDRPID))
12266       add_rpid(&req, p);
12267 
12268    if (p->do_history) {
12269       append_history(p, "ReInv", "Re-invite sent");
12270    }
12271    memset(p->offered_media, 0, sizeof(p->offered_media));
12272 
12273    try_suggested_sip_codec(p);
12274    if (t38version) {
12275       add_sdp(&req, p, oldsdp, FALSE, TRUE);
12276    } else {
12277       add_sdp(&req, p, oldsdp, TRUE, FALSE);
12278    }
12279 
12280    /* Use this as the basis */
12281    initialize_initreq(p, &req);
12282    p->lastinvite = p->ocseq;
12283    ast_set_flag(&p->flags[0], SIP_OUTGOING);       /* Change direction of this dialog */
12284 
12285    return send_request(p, &req, XMIT_CRITICAL, p->ocseq);
12286 }
12287 
12288 /* \brief Remove URI parameters at end of URI, not in username part though */
12289 static char *remove_uri_parameters(char *uri)
12290 {
12291    char *atsign;
12292    atsign = strchr(uri, '@'); /* First, locate the at sign */
12293    if (!atsign) {
12294       atsign = uri;  /* Ok hostname only, let's stick with the rest */
12295    }
12296    atsign = strchr(atsign, ';'); /* Locate semi colon */
12297    if (atsign)
12298       *atsign = '\0';   /* Kill at the semi colon */
12299    return uri;
12300 }
12301 
12302 /*! \brief Check Contact: URI of SIP message */
12303 static void extract_uri(struct sip_pvt *p, struct sip_request *req)
12304 {
12305    char stripped[SIPBUFSIZE];
12306    char *c;
12307 
12308    ast_copy_string(stripped, sip_get_header(req, "Contact"), sizeof(stripped));
12309    c = get_in_brackets(stripped);
12310    /* Cut the URI at the at sign after the @, not in the username part */
12311    c = remove_uri_parameters(c);
12312    if (!ast_strlen_zero(c)) {
12313       ast_string_field_set(p, uri, c);
12314    }
12315 
12316 }
12317 
12318 /*! \brief Build contact header - the contact header we send out */
12319 static void build_contact(struct sip_pvt *p)
12320 {
12321    char tmp[SIPBUFSIZE];
12322    char *user = ast_uri_encode(p->exten, tmp, sizeof(tmp), ast_uri_sip_user);
12323 
12324    if (p->socket.type == SIP_TRANSPORT_UDP) {
12325       ast_string_field_build(p, our_contact, "<sip:%s%s%s>", user,
12326          ast_strlen_zero(user) ? "" : "@", ast_sockaddr_stringify_remote(&p->ourip));
12327    } else {
12328       ast_string_field_build(p, our_contact, "<sip:%s%s%s;transport=%s>", user,
12329          ast_strlen_zero(user) ? "" : "@", ast_sockaddr_stringify_remote(&p->ourip),
12330          sip_get_transport(p->socket.type));
12331    }
12332 }
12333 
12334 /*! \brief Initiate new SIP request to peer/user */
12335 static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, const char * const explicit_uri)
12336 {
12337    struct ast_str *invite = ast_str_alloca(256);
12338    char from[256];
12339    char to[256];
12340    char tmp_n[SIPBUFSIZE/2];  /* build a local copy of 'n' if needed */
12341    char tmp_l[SIPBUFSIZE/2];  /* build a local copy of 'l' if needed */
12342    const char *l = NULL;   /* XXX what is this, exactly ? */
12343    const char *n = NULL;   /* XXX what is this, exactly ? */
12344    const char *d = NULL;   /* domain in from header */
12345    const char *urioptions = "";
12346    int ourport;
12347    int cid_has_name = 1;
12348    int cid_has_num = 1;
12349 
12350    if (ast_test_flag(&p->flags[0], SIP_USEREQPHONE)) {
12351       const char *s = p->username;  /* being a string field, cannot be NULL */
12352 
12353       /* Test p->username against allowed characters in AST_DIGIT_ANY
12354          If it matches the allowed characters list, then sipuser = ";user=phone"
12355          If not, then sipuser = ""
12356       */
12357       /* + is allowed in first position in a tel: uri */
12358       if (*s == '+')
12359          s++;
12360       for (; *s; s++) {
12361          if (!strchr(AST_DIGIT_ANYNUM, *s) )
12362             break;
12363       }
12364       /* If we have only digits, add ;user=phone to the uri */
12365       if (!*s)
12366          urioptions = ";user=phone";
12367    }
12368 
12369 
12370    snprintf(p->lastmsg, sizeof(p->lastmsg), "Init: %s", sip_methods[sipmethod].text);
12371 
12372    d = S_OR(p->fromdomain, ast_sockaddr_stringify_host_remote(&p->ourip));
12373    if (p->owner) {
12374       if ((ast_party_id_presentation(&p->owner->connected.id) & AST_PRES_RESTRICTION) == AST_PRES_ALLOWED) {
12375          l = p->owner->connected.id.number.valid ? p->owner->connected.id.number.str : NULL;
12376          n = p->owner->connected.id.name.valid ? p->owner->connected.id.name.str : NULL;
12377       } else {
12378          /* Even if we are using RPID, we shouldn't leak information in the From if the user wants
12379           * their callerid restricted */
12380          l = CALLERID_UNKNOWN;
12381          n = l;
12382          d = FROMDOMAIN_INVALID;
12383       }
12384    }
12385 
12386    /* Hey, it's a NOTIFY! See if they've configured a mwi_from.
12387     * XXX Right now, this logic works because the only place that mwi_from
12388     * is set on the sip_pvt is in sip_send_mwi_to_peer. If things changed, then
12389     * we might end up putting the mwi_from setting into other types of NOTIFY
12390     * messages as well.
12391     */
12392    if (sipmethod == SIP_NOTIFY && !ast_strlen_zero(p->mwi_from)) {
12393       l = p->mwi_from;
12394    }
12395 
12396    if (ast_strlen_zero(l)) {
12397       cid_has_num = 0;
12398       l = default_callerid;
12399    }
12400    if (ast_strlen_zero(n)) {
12401       cid_has_name = 0;
12402       n = l;
12403    }
12404 
12405    /* Allow user to be overridden */
12406    if (!ast_strlen_zero(p->fromuser))
12407       l = p->fromuser;
12408    else /* Save for any further attempts */
12409       ast_string_field_set(p, fromuser, l);
12410 
12411    /* Allow user to be overridden */
12412    if (!ast_strlen_zero(p->fromname))
12413       n = p->fromname;
12414    else /* Save for any further attempts */
12415       ast_string_field_set(p, fromname, n);
12416 
12417    if (sip_cfg.pedanticsipchecking) {
12418       ast_escape_quoted(n, tmp_n, sizeof(tmp_n));
12419       n = tmp_n;
12420       ast_uri_encode(l, tmp_l, sizeof(tmp_l), ast_uri_sip_user);
12421       l = tmp_l;
12422    }
12423 
12424    ourport = (p->fromdomainport) ? p->fromdomainport : ast_sockaddr_port(&p->ourip);
12425 
12426    /* If a caller id name was specified, add a display name. */
12427    if (cid_has_name || !cid_has_num) {
12428       snprintf(from, sizeof(from), "\"%s\" ", n);
12429    } else {
12430       from[0] = '\0';
12431    }
12432 
12433    if (!sip_standard_port(p->socket.type, ourport)) {
12434       size_t offset = strlen(from);
12435       snprintf(&from[offset], sizeof(from) - offset, "<sip:%s@%s:%d>;tag=%s", l, d, ourport, p->tag);
12436    } else {
12437       size_t offset = strlen(from);
12438       snprintf(&from[offset], sizeof(from) - offset, "<sip:%s@%s>;tag=%s", l, d, p->tag);
12439    }
12440 
12441    if (!ast_strlen_zero(explicit_uri)) {
12442       ast_str_set(&invite, 0, "%s", explicit_uri);
12443    } else {
12444       /* If we're calling a registered SIP peer, use the fullcontact to dial to the peer */
12445       if (!ast_strlen_zero(p->fullcontact)) {
12446          /* If we have full contact, trust it */
12447          ast_str_append(&invite, 0, "%s", p->fullcontact);
12448       } else {
12449          /* Otherwise, use the username while waiting for registration */
12450          ast_str_append(&invite, 0, "sip:");
12451          if (!ast_strlen_zero(p->username)) {
12452             n = p->username;
12453             if (sip_cfg.pedanticsipchecking) {
12454                ast_uri_encode(n, tmp_n, sizeof(tmp_n), ast_uri_sip_user);
12455                n = tmp_n;
12456             }
12457             ast_str_append(&invite, 0, "%s@", n);
12458          }
12459          ast_str_append(&invite, 0, "%s", p->tohost);
12460          if (p->portinuri) {
12461             ast_str_append(&invite, 0, ":%d", ast_sockaddr_port(&p->sa));
12462          }
12463          ast_str_append(&invite, 0, "%s", urioptions);
12464       }
12465    }
12466 
12467    /* If custom URI options have been provided, append them */
12468    if (p->options && !ast_strlen_zero(p->options->uri_options))
12469       ast_str_append(&invite, 0, ";%s", p->options->uri_options);
12470    
12471    /* This is the request URI, which is the next hop of the call
12472       which may or may not be the destination of the call
12473    */
12474    ast_string_field_set(p, uri, invite->str);
12475 
12476    if (!ast_strlen_zero(p->todnid)) {
12477       /*! \todo Need to add back the VXML URL here at some point, possibly use build_string for all this junk */
12478       if (!strchr(p->todnid, '@')) {
12479          /* We have no domain in the dnid */
12480          snprintf(to, sizeof(to), "<sip:%s@%s>%s%s", p->todnid, p->tohost, ast_strlen_zero(p->theirtag) ? "" : ";tag=", p->theirtag);
12481       } else {
12482          snprintf(to, sizeof(to), "<sip:%s>%s%s", p->todnid, ast_strlen_zero(p->theirtag) ? "" : ";tag=", p->theirtag);
12483       }
12484    } else {
12485       if (sipmethod == SIP_NOTIFY && !ast_strlen_zero(p->theirtag)) {
12486          /* If this is a NOTIFY, use the From: tag in the subscribe (RFC 3265) */
12487          snprintf(to, sizeof(to), "<%s%s>;tag=%s", (strncasecmp(p->uri, "sip:", 4) ? "sip:" : ""), p->uri, p->theirtag);
12488       } else if (p->options && p->options->vxml_url) {
12489          /* If there is a VXML URL append it to the SIP URL */
12490          snprintf(to, sizeof(to), "<%s>;%s", p->uri, p->options->vxml_url);
12491       } else {
12492          snprintf(to, sizeof(to), "<%s>", p->uri);
12493       }
12494    }
12495 
12496    init_req(req, sipmethod, p->uri);
12497    /* now tmp_n is available so reuse it to build the CSeq */
12498    snprintf(tmp_n, sizeof(tmp_n), "%u %s", ++p->ocseq, sip_methods[sipmethod].text);
12499 
12500    add_header(req, "Via", p->via);
12501    add_header_max_forwards(p, req);
12502    /* This will be a no-op most of the time. However, under certain circumstances,
12503     * NOTIFY messages will use this function for preparing the request and should
12504     * have Route headers present.
12505     */
12506    add_route(req, p->route);
12507 
12508    add_header(req, "From", from);
12509    add_header(req, "To", to);
12510    ast_string_field_set(p, exten, l);
12511    build_contact(p);
12512    add_header(req, "Contact", p->our_contact);
12513    add_header(req, "Call-ID", p->callid);
12514    add_header(req, "CSeq", tmp_n);
12515    if (!ast_strlen_zero(global_useragent)) {
12516       add_header(req, "User-Agent", global_useragent);
12517    }
12518 }
12519 
12520 /*! \brief Add "Diversion" header to outgoing message
12521  *
12522  * We need to add a Diversion header if the owner channel of
12523  * this dialog has redirecting information associated with it.
12524  *
12525  * \param req The request/response to which we will add the header
12526  * \param pvt The sip_pvt which represents the call-leg
12527  */
12528 static void add_diversion_header(struct sip_request *req, struct sip_pvt *pvt)
12529 {
12530    const char *diverting_number;
12531    const char *diverting_name;
12532    const char *reason;
12533    char header_text[256];
12534 
12535    if (!pvt->owner) {
12536       return;
12537    }
12538 
12539    diverting_number = pvt->owner->redirecting.from.number.str;
12540    if (!pvt->owner->redirecting.from.number.valid
12541       || ast_strlen_zero(diverting_number)) {
12542       return;
12543    }
12544 
12545    reason = sip_reason_code_to_str(pvt->owner->redirecting.reason);
12546 
12547    /* We at least have a number to place in the Diversion header, which is enough */
12548    diverting_name = pvt->owner->redirecting.from.name.str;
12549    if (!pvt->owner->redirecting.from.name.valid
12550       || ast_strlen_zero(diverting_name)) {
12551       snprintf(header_text, sizeof(header_text), "<sip:%s@%s>;reason=%s", diverting_number,
12552             ast_sockaddr_stringify_host_remote(&pvt->ourip), reason);
12553    } else {
12554       snprintf(header_text, sizeof(header_text), "\"%s\" <sip:%s@%s>;reason=%s",
12555             diverting_name, diverting_number,
12556             ast_sockaddr_stringify_host_remote(&pvt->ourip), reason);
12557    }
12558 
12559    add_header(req, "Diversion", header_text);
12560 }
12561 
12562 static int transmit_publish(struct sip_epa_entry *epa_entry, enum sip_publish_type publish_type, const char * const explicit_uri)
12563 {
12564    struct sip_pvt *pvt;
12565    int expires;
12566 
12567    epa_entry->publish_type = publish_type;
12568 
12569    if (!(pvt = sip_alloc(NULL, NULL, 0, SIP_PUBLISH, NULL))) {
12570       return -1;
12571    }
12572 
12573    sip_pvt_lock(pvt);
12574 
12575    if (create_addr(pvt, epa_entry->destination, NULL, TRUE, NULL)) {
12576       sip_pvt_unlock(pvt);
12577       dialog_unlink_all(pvt);
12578       dialog_unref(pvt, "create_addr failed in transmit_publish. Unref dialog");
12579       return -1;
12580    }
12581    ast_sip_ouraddrfor(&pvt->sa, &pvt->ourip, pvt);
12582    ast_set_flag(&pvt->flags[0], SIP_OUTGOING);
12583    expires = (publish_type == SIP_PUBLISH_REMOVE) ? 0 : DEFAULT_PUBLISH_EXPIRES;
12584    pvt->expiry = expires;
12585 
12586    /* Bump refcount for sip_pvt's reference */
12587    ao2_ref(epa_entry, +1);
12588    pvt->epa_entry = epa_entry;
12589 
12590    transmit_invite(pvt, SIP_PUBLISH, FALSE, 2, explicit_uri);
12591    sip_pvt_unlock(pvt);
12592    sip_scheddestroy(pvt, DEFAULT_TRANS_TIMEOUT);
12593    dialog_unref(pvt, "Done with the sip_pvt allocated for transmitting PUBLISH");
12594    return 0;
12595 }
12596 
12597 /*! 
12598  * \brief Build REFER/INVITE/OPTIONS/SUBSCRIBE message and transmit it
12599  * \param p sip_pvt structure
12600  * \param sipmethod
12601  * \param sdp unknown
12602  * \param init 0 = Prepare request within dialog, 1= prepare request, new branch,
12603  *  2= prepare new request and new dialog. do_proxy_auth calls this with init!=2
12604  * \param explicit_uri
12605 */
12606 static int transmit_invite(struct sip_pvt *p, int sipmethod, int sdp, int init, const char * const explicit_uri)
12607 {
12608    struct sip_request req;
12609    struct ast_variable *var;
12610    
12611    req.method = sipmethod;
12612    if (init) {/* Bump branch even on initial requests */
12613       p->branch ^= ast_random();
12614       p->invite_branch = p->branch;
12615       build_via(p);
12616    }
12617    if (init > 1) {
12618       initreqprep(&req, p, sipmethod, explicit_uri);
12619    } else {
12620       /* If init=1, we should not generate a new branch. If it's 0, we need a new branch. */
12621       reqprep(&req, p, sipmethod, 0, init ? 0 : 1);
12622    }
12623       
12624    if (p->options && p->options->auth) {
12625       add_header(&req, p->options->authheader, p->options->auth);
12626    }
12627    append_date(&req);
12628    if (sipmethod == SIP_REFER) { /* Call transfer */
12629       if (p->refer) {
12630          char buf[SIPBUFSIZE];
12631          if (!ast_strlen_zero(p->refer->refer_to)) {
12632             add_header(&req, "Refer-To", p->refer->refer_to);
12633          }
12634          if (!ast_strlen_zero(p->refer->referred_by)) {
12635             snprintf(buf, sizeof(buf), "%s <%s>", p->refer->referred_by_name, p->refer->referred_by);
12636             add_header(&req, "Referred-By", buf);
12637          }
12638       }
12639    } else if (sipmethod == SIP_SUBSCRIBE) {
12640       char buf[SIPBUFSIZE];
12641       if (p->subscribed == MWI_NOTIFICATION) {
12642          add_header(&req, "Event", "message-summary");
12643          add_header(&req, "Accept", "application/simple-message-summary");
12644       } else if (p->subscribed == CALL_COMPLETION) {
12645          add_header(&req, "Event", "call-completion");
12646          add_header(&req, "Accept", "application/call-completion");
12647       }
12648       snprintf(buf, sizeof(buf), "%d", p->expiry);
12649       add_header(&req, "Expires", buf);
12650    }
12651 
12652    /* This new INVITE is part of an attended transfer. Make sure that the
12653    other end knows and replace the current call with this new call */
12654    if (p->options && !ast_strlen_zero(p->options->replaces)) {
12655       add_header(&req, "Replaces", p->options->replaces);
12656       add_header(&req, "Require", "replaces");
12657    }
12658 
12659    /* Add Session-Timers related headers */
12660    if (st_get_mode(p, 0) == SESSION_TIMER_MODE_ORIGINATE) {
12661       char i2astr[10];
12662 
12663       if (!p->stimer->st_interval) {
12664          p->stimer->st_interval = st_get_se(p, TRUE);
12665       }
12666 
12667       p->stimer->st_active = TRUE;
12668       
12669       snprintf(i2astr, sizeof(i2astr), "%d", p->stimer->st_interval);
12670       add_header(&req, "Session-Expires", i2astr);
12671       snprintf(i2astr, sizeof(i2astr), "%d", st_get_se(p, FALSE));
12672       add_header(&req, "Min-SE", i2astr);
12673    }
12674 
12675    add_header(&req, "Allow", ALLOWED_METHODS);
12676    add_supported_header(p, &req);
12677 
12678    if (p->options && p->options->addsipheaders && p->owner) {
12679       struct ast_channel *chan = p->owner; /* The owner channel */
12680       struct varshead *headp;
12681    
12682       ast_channel_lock(chan);
12683 
12684       headp = &chan->varshead;
12685 
12686       if (!headp) {
12687          ast_log(LOG_WARNING, "No Headp for the channel...ooops!\n");
12688       } else {
12689          const struct ast_var_t *current;
12690          AST_LIST_TRAVERSE(headp, current, entries) {
12691             /* SIPADDHEADER: Add SIP header to outgoing call */
12692             if (!strncasecmp(ast_var_name(current), "SIPADDHEADER", strlen("SIPADDHEADER"))) {
12693                char *content, *end;
12694                const char *header = ast_var_value(current);
12695                char *headdup = ast_strdupa(header);
12696 
12697                /* Strip of the starting " (if it's there) */
12698                if (*headdup == '"') {
12699                   headdup++;
12700                }
12701                if ((content = strchr(headdup, ':'))) {
12702                   *content++ = '\0';
12703                   content = ast_skip_blanks(content); /* Skip white space */
12704                   /* Strip the ending " (if it's there) */
12705                   end = content + strlen(content) -1;
12706                   if (*end == '"') {
12707                      *end = '\0';
12708                   }
12709 
12710                   add_header(&req, headdup, content);
12711                   if (sipdebug) {
12712                      ast_debug(1, "Adding SIP Header \"%s\" with content :%s: \n", headdup, content);
12713                   }
12714                }
12715             }
12716          }
12717       }
12718 
12719       ast_channel_unlock(chan);
12720    }
12721    if ((sipmethod == SIP_INVITE || sipmethod == SIP_UPDATE) && ast_test_flag(&p->flags[0], SIP_SENDRPID))
12722       add_rpid(&req, p);
12723    if (sipmethod == SIP_INVITE) {
12724       add_diversion_header(&req, p);
12725    }
12726    if (sdp) {
12727       memset(p->offered_media, 0, sizeof(p->offered_media));
12728       if (p->udptl && p->t38.state == T38_LOCAL_REINVITE) {
12729          ast_debug(1, "T38 is in state %d on channel %s\n", p->t38.state, p->owner ? ast_channel_name(p->owner) : "<none>");
12730          add_sdp(&req, p, FALSE, FALSE, TRUE);
12731       } else if (p->rtp) {
12732          try_suggested_sip_codec(p);
12733          add_sdp(&req, p, FALSE, TRUE, FALSE);
12734       }
12735    } else if (p->notify) {
12736       for (var = p->notify->headers; var; var = var->next) {
12737          add_header(&req, var->name, var->value);
12738       }
12739       if (ast_str_strlen(p->notify->content)) {
12740          add_content(&req, ast_str_buffer(p->notify->content));
12741       }
12742    } else if (sipmethod == SIP_PUBLISH) {
12743       char expires[SIPBUFSIZE];
12744 
12745       switch (p->epa_entry->static_data->event) {
12746       case CALL_COMPLETION:
12747          snprintf(expires, sizeof(expires), "%d", p->expiry);
12748          add_header(&req, "Event", "call-completion");
12749          add_header(&req, "Expires", expires);
12750          if (p->epa_entry->publish_type != SIP_PUBLISH_INITIAL) {
12751             add_header(&req, "SIP-If-Match", p->epa_entry->entity_tag);
12752          }
12753 
12754          if (!ast_strlen_zero(p->epa_entry->body)) {
12755             add_header(&req, "Content-Type", "application/pidf+xml");
12756             add_content(&req, p->epa_entry->body);
12757          }
12758       default:
12759          break;
12760       }
12761    }
12762 
12763    if (!p->initreq.headers || init > 2) {
12764       initialize_initreq(p, &req);
12765    }
12766    if (sipmethod == SIP_INVITE || sipmethod == SIP_SUBSCRIBE) {
12767       p->lastinvite = p->ocseq;
12768    }
12769    return send_request(p, &req, init ? XMIT_CRITICAL : XMIT_RELIABLE, p->ocseq);
12770 }
12771 
12772 /*! \brief Send a subscription or resubscription for MWI */
12773 static int sip_subscribe_mwi_do(const void *data)
12774 {
12775    struct sip_subscription_mwi *mwi = (struct sip_subscription_mwi*)data;
12776    
12777    if (!mwi) {
12778       return -1;
12779    }
12780    
12781    mwi->resub = -1;
12782    __sip_subscribe_mwi_do(mwi);
12783    ASTOBJ_UNREF(mwi, sip_subscribe_mwi_destroy);
12784    
12785    return 0;
12786 }
12787 
12788 static void on_dns_update_registry(struct ast_sockaddr *old, struct ast_sockaddr *new, void *data)
12789 {
12790    struct sip_registry *reg = data;
12791    const char *old_str;
12792 
12793    /* This shouldn't happen, but just in case */
12794    if (ast_sockaddr_isnull(new)) {
12795       ast_debug(1, "Empty sockaddr change...ignoring!\n");
12796       return;
12797    }
12798 
12799    if (!ast_sockaddr_port(new)) {
12800       ast_sockaddr_set_port(new, reg->portno);
12801    }
12802 
12803    old_str = ast_strdupa(ast_sockaddr_stringify(old));
12804 
12805    ast_debug(1, "Changing registry %s from %s to %s\n", S_OR(reg->peername, reg->hostname), old_str, ast_sockaddr_stringify(new));
12806    ast_sockaddr_copy(&reg->us, new);
12807 }
12808 
12809 static void on_dns_update_peer(struct ast_sockaddr *old, struct ast_sockaddr *new, void *data)
12810 {
12811    struct sip_peer *peer = data;
12812    const char *old_str;
12813 
12814    /* This shouldn't happen, but just in case */
12815    if (ast_sockaddr_isnull(new)) {
12816       ast_debug(1, "Empty sockaddr change...ignoring!\n");
12817       return;
12818    }
12819 
12820    if (!ast_sockaddr_isnull(&peer->addr)) {
12821       ao2_unlink(peers_by_ip, peer);
12822    }
12823 
12824    if (!ast_sockaddr_port(new)) {
12825       ast_sockaddr_set_port(new, default_sip_port(peer->socket.type));
12826    }
12827 
12828    old_str = ast_strdupa(ast_sockaddr_stringify(old));
12829    ast_debug(1, "Changing peer %s address from %s to %s\n", peer->name, old_str, ast_sockaddr_stringify(new));
12830 
12831    ao2_lock(peer);
12832    ast_sockaddr_copy(&peer->addr, new);
12833    ao2_unlock(peer);
12834 
12835    ao2_link(peers_by_ip, peer);
12836 }
12837 
12838 static void on_dns_update_mwi(struct ast_sockaddr *old, struct ast_sockaddr *new, void *data)
12839 {
12840    struct sip_subscription_mwi *mwi = data;
12841    const char *old_str;
12842 
12843    /* This shouldn't happen, but just in case */
12844    if (ast_sockaddr_isnull(new)) {
12845       ast_debug(1, "Empty sockaddr change...ignoring!\n");
12846       return;
12847    }
12848 
12849    old_str = ast_strdupa(ast_sockaddr_stringify(old));
12850    ast_debug(1, "Changing mwi %s from %s to %s\n", mwi->hostname, old_str, ast_sockaddr_stringify(new));
12851    ast_sockaddr_copy(&mwi->us, new);
12852 }
12853 
12854 /*! \brief Actually setup an MWI subscription or resubscribe */
12855 static int __sip_subscribe_mwi_do(struct sip_subscription_mwi *mwi)
12856 {
12857    /* If we have no DNS manager let's do a lookup */
12858    if (!mwi->dnsmgr) {
12859       char transport[MAXHOSTNAMELEN];
12860       snprintf(transport, sizeof(transport), "_%s._%s", get_srv_service(mwi->transport), get_srv_protocol(mwi->transport));
12861 
12862       mwi->us.ss.ss_family = get_address_family_filter(&bindaddr); /* Filter address family */
12863       ASTOBJ_REF(mwi); /* Add a ref for storing the mwi on the dnsmgr for updates */
12864       ast_dnsmgr_lookup_cb(mwi->hostname, &mwi->us, &mwi->dnsmgr, sip_cfg.srvlookup ? transport : NULL, on_dns_update_mwi, mwi);
12865       if (!mwi->dnsmgr) {
12866          ASTOBJ_UNREF(mwi, sip_subscribe_mwi_destroy); /* dnsmgr disabled, remove reference */
12867       }
12868    }
12869 
12870    /* If we already have a subscription up simply send a resubscription */
12871    if (mwi->call) {
12872       transmit_invite(mwi->call, SIP_SUBSCRIBE, 0, 0, NULL);
12873       return 0;
12874    }
12875    
12876    /* Create a dialog that we will use for the subscription */
12877    if (!(mwi->call = sip_alloc(NULL, NULL, 0, SIP_SUBSCRIBE, NULL))) {
12878       return -1;
12879    }
12880 
12881    ref_proxy(mwi->call, obproxy_get(mwi->call, NULL));
12882 
12883    if (!ast_sockaddr_port(&mwi->us) && mwi->portno) {
12884       ast_sockaddr_set_port(&mwi->us, mwi->portno);
12885    }
12886    
12887    /* Setup the destination of our subscription */
12888    if (create_addr(mwi->call, mwi->hostname, &mwi->us, 0, NULL)) {
12889       dialog_unlink_all(mwi->call);
12890       mwi->call = dialog_unref(mwi->call, "unref dialog after unlink_all");
12891       return 0;
12892    }
12893 
12894    mwi->call->expiry = mwi_expiry;
12895    
12896    if (!mwi->dnsmgr && mwi->portno) {
12897       ast_sockaddr_set_port(&mwi->call->sa, mwi->portno);
12898       ast_sockaddr_set_port(&mwi->call->recv, mwi->portno);
12899    } else {
12900       mwi->portno = ast_sockaddr_port(&mwi->call->sa);
12901    }
12902    
12903    /* Set various other information */
12904    if (!ast_strlen_zero(mwi->authuser)) {
12905       ast_string_field_set(mwi->call, peername, mwi->authuser);
12906       ast_string_field_set(mwi->call, authname, mwi->authuser);
12907       ast_string_field_set(mwi->call, fromuser, mwi->authuser);
12908    } else {
12909       ast_string_field_set(mwi->call, peername, mwi->username);
12910       ast_string_field_set(mwi->call, authname, mwi->username);
12911       ast_string_field_set(mwi->call, fromuser, mwi->username);
12912    }
12913    ast_string_field_set(mwi->call, username, mwi->username);
12914    if (!ast_strlen_zero(mwi->secret)) {
12915       ast_string_field_set(mwi->call, peersecret, mwi->secret);
12916    }
12917    set_socket_transport(&mwi->call->socket, mwi->transport);
12918    mwi->call->socket.port = htons(mwi->portno);
12919    ast_sip_ouraddrfor(&mwi->call->sa, &mwi->call->ourip, mwi->call);
12920    build_contact(mwi->call);
12921    build_via(mwi->call);
12922 
12923    /* Change the dialog callid. */
12924    change_callid_pvt(mwi->call, NULL);
12925 
12926    ast_set_flag(&mwi->call->flags[0], SIP_OUTGOING);
12927    
12928    /* Associate the call with us */
12929    mwi->call->mwi = ASTOBJ_REF(mwi);
12930 
12931    mwi->call->subscribed = MWI_NOTIFICATION;
12932 
12933    /* Actually send the packet */
12934    transmit_invite(mwi->call, SIP_SUBSCRIBE, 0, 2, NULL);
12935 
12936    return 0;
12937 }
12938 
12939 /*! \brief Find the channel that is causing the RINGING update */
12940 static int find_calling_channel(void *obj, void *arg, void *data, int flags)
12941 {
12942    struct ast_channel *c = obj;
12943    struct sip_pvt *p = data;
12944    int res;
12945 
12946    ast_channel_lock(c);
12947 
12948    res = (c->pbx &&
12949          (!strcasecmp(c->macroexten, p->exten) || !strcasecmp(c->exten, p->exten)) &&
12950          (sip_cfg.notifycid == IGNORE_CONTEXT || !strcasecmp(c->context, p->context)));
12951 
12952    ast_channel_unlock(c);
12953 
12954    return res ? CMP_MATCH | CMP_STOP : 0;
12955 }
12956 
12957 /*! \brief Builds XML portion of NOTIFY messages for presence or dialog updates */
12958 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)
12959 {
12960    enum state { NOTIFY_OPEN, NOTIFY_INUSE, NOTIFY_CLOSED } local_state = NOTIFY_OPEN;
12961    const char *statestring = "terminated";
12962    const char *pidfstate = "--";
12963    const char *pidfnote= "Ready";
12964    char hint[AST_MAX_EXTENSION];
12965 
12966    switch (state) {
12967    case (AST_EXTENSION_RINGING | AST_EXTENSION_INUSE):
12968       statestring = (sip_cfg.notifyringing) ? "early" : "confirmed";
12969       local_state = NOTIFY_INUSE;
12970       pidfstate = "busy";
12971       pidfnote = "Ringing";
12972       break;
12973    case AST_EXTENSION_RINGING:
12974       statestring = "early";
12975       local_state = NOTIFY_INUSE;
12976       pidfstate = "busy";
12977       pidfnote = "Ringing";
12978       break;
12979    case AST_EXTENSION_INUSE:
12980       statestring = "confirmed";
12981       local_state = NOTIFY_INUSE;
12982       pidfstate = "busy";
12983       pidfnote = "On the phone";
12984       break;
12985    case AST_EXTENSION_BUSY:
12986       statestring = "confirmed";
12987       local_state = NOTIFY_CLOSED;
12988       pidfstate = "busy";
12989       pidfnote = "On the phone";
12990       break;
12991    case AST_EXTENSION_UNAVAILABLE:
12992       statestring = "terminated";
12993       local_state = NOTIFY_CLOSED;
12994       pidfstate = "away";
12995       pidfnote = "Unavailable";
12996       break;
12997    case AST_EXTENSION_ONHOLD:
12998       statestring = "confirmed";
12999       local_state = NOTIFY_CLOSED;
13000       pidfstate = "busy";
13001       pidfnote = "On hold";
13002       break;
13003    case AST_EXTENSION_NOT_INUSE:
13004    default:
13005       /* Default setting */
13006       break;
13007    }
13008 
13009    /* Check which device/devices we are watching  and if they are registered */
13010    if (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, context, exten)) {
13011       char *hint2 = hint, *individual_hint = NULL;
13012       int hint_count = 0, unavailable_count = 0;
13013 
13014       while ((individual_hint = strsep(&hint2, "&"))) {
13015          hint_count++;
13016 
13017          if (ast_device_state(individual_hint) == AST_DEVICE_UNAVAILABLE)
13018             unavailable_count++;
13019       }
13020 
13021       /* If none of the hinted devices are registered, we will
13022        * override notification and show no availability.
13023        */
13024       if (hint_count > 0 && hint_count == unavailable_count) {
13025          local_state = NOTIFY_CLOSED;
13026          pidfstate = "away";
13027          pidfnote = "Not online";
13028       }
13029    }
13030 
13031    switch (subscribed) {
13032    case XPIDF_XML:
13033    case CPIM_PIDF_XML:
13034       ast_str_append(tmp, 0,
13035          "<?xml version=\"1.0\"?>\n"
13036          "<!DOCTYPE presence PUBLIC \"-//IETF//DTD RFCxxxx XPIDF 1.0//EN\" \"xpidf.dtd\">\n"
13037          "<presence>\n");
13038       ast_str_append(tmp, 0, "<presentity uri=\"%s;method=SUBSCRIBE\" />\n", mfrom);
13039       ast_str_append(tmp, 0, "<atom id=\"%s\">\n", exten);
13040       ast_str_append(tmp, 0, "<address uri=\"%s;user=ip\" priority=\"0.800000\">\n", mto);
13041       ast_str_append(tmp, 0, "<status status=\"%s\" />\n", (local_state ==  NOTIFY_OPEN) ? "open" : (local_state == NOTIFY_INUSE) ? "inuse" : "closed");
13042       ast_str_append(tmp, 0, "<msnsubstatus substatus=\"%s\" />\n", (local_state == NOTIFY_OPEN) ? "online" : (local_state == NOTIFY_INUSE) ? "onthephone" : "offline");
13043       ast_str_append(tmp, 0, "</address>\n</atom>\n</presence>\n");
13044       break;
13045    case PIDF_XML: /* Eyebeam supports this format */
13046       ast_str_append(tmp, 0,
13047          "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n"
13048          "<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);
13049       ast_str_append(tmp, 0, "<pp:person><status>\n");
13050       if (pidfstate[0] != '-') {
13051          ast_str_append(tmp, 0, "<ep:activities><ep:%s/></ep:activities>\n", pidfstate);
13052       }
13053       ast_str_append(tmp, 0, "</status></pp:person>\n");
13054       ast_str_append(tmp, 0, "<note>%s</note>\n", pidfnote); /* Note */
13055       ast_str_append(tmp, 0, "<tuple id=\"%s\">\n", exten); /* Tuple start */
13056       ast_str_append(tmp, 0, "<contact priority=\"1\">%s</contact>\n", mto);
13057       if (pidfstate[0] == 'b') /* Busy? Still open ... */
13058          ast_str_append(tmp, 0, "<status><basic>open</basic></status>\n");
13059       else
13060          ast_str_append(tmp, 0, "<status><basic>%s</basic></status>\n", (local_state != NOTIFY_CLOSED) ? "open" : "closed");
13061       ast_str_append(tmp, 0, "</tuple>\n</presence>\n");
13062       break;
13063    case DIALOG_INFO_XML: /* SNOM subscribes in this format */
13064       ast_str_append(tmp, 0, "<?xml version=\"1.0\"?>\n");
13065       ast_str_append(tmp, 0, "<dialog-info xmlns=\"urn:ietf:params:xml:ns:dialog-info\" version=\"%u\" state=\"%s\" entity=\"%s\">\n", p->dialogver, full ? "full" : "partial", mto);
13066       if ((state & AST_EXTENSION_RINGING) && sip_cfg.notifyringing) {
13067          const char *local_display = exten;
13068          char *local_target = ast_strdupa(mto);
13069 
13070          /* There are some limitations to how this works.  The primary one is that the
13071             callee must be dialing the same extension that is being monitored.  Simply dialing
13072             the hint'd device is not sufficient. */
13073          if (sip_cfg.notifycid) {
13074             struct ast_channel *caller;
13075 
13076             if ((caller = ast_channel_callback(find_calling_channel, NULL, p, 0))) {
13077                char *cid_num;
13078                int need;
13079 
13080                ast_channel_lock(caller);
13081                cid_num = S_COR(caller->caller.id.number.valid,
13082                   caller->caller.id.number.str, "");
13083                need = strlen(cid_num) + strlen(p->fromdomain) + sizeof("sip:@");
13084                local_target = alloca(need);
13085                snprintf(local_target, need, "sip:%s@%s", cid_num, p->fromdomain);
13086                local_display = ast_strdupa(S_COR(caller->caller.id.name.valid,
13087                   caller->caller.id.name.str, ""));
13088                ast_channel_unlock(caller);
13089                caller = ast_channel_unref(caller);
13090             }
13091 
13092             /* We create a fake call-id which the phone will send back in an INVITE
13093                Replaces header which we can grab and do some magic with. */
13094             if (sip_cfg.pedanticsipchecking) {
13095                ast_str_append(tmp, 0, "<dialog id=\"%s\" call-id=\"pickup-%s\" local-tag=\"%s\" remote-tag=\"%s\" direction=\"recipient\">\n",
13096                   exten, p->callid, p->theirtag, p->tag);
13097             } else {
13098                ast_str_append(tmp, 0, "<dialog id=\"%s\" call-id=\"pickup-%s\" direction=\"recipient\">\n",
13099                   exten, p->callid);
13100             }
13101             ast_str_append(tmp, 0,
13102                   "<remote>\n"
13103                   /* See the limitations of this above.  Luckily the phone seems to still be
13104                      happy when these values are not correct. */
13105                   "<identity display=\"%s\">%s</identity>\n"
13106                   "<target uri=\"%s\"/>\n"
13107                   "</remote>\n"
13108                   "<local>\n"
13109                   "<identity>%s</identity>\n"
13110                   "<target uri=\"%s\"/>\n"
13111                   "</local>\n",
13112                   local_display, local_target, local_target, mto, mto);
13113          } else {
13114             ast_str_append(tmp, 0, "<dialog id=\"%s\" direction=\"recipient\">\n", exten);
13115          }
13116 
13117       } else {
13118          ast_str_append(tmp, 0, "<dialog id=\"%s\">\n", exten);
13119       }
13120       ast_str_append(tmp, 0, "<state>%s</state>\n", statestring);
13121       if (state == AST_EXTENSION_ONHOLD) {
13122             ast_str_append(tmp, 0, "<local>\n<target uri=\"%s\">\n"
13123                                              "<param pname=\"+sip.rendering\" pvalue=\"no\"/>\n"
13124                                              "</target>\n</local>\n", mto);
13125       }
13126       ast_str_append(tmp, 0, "</dialog>\n</dialog-info>\n");
13127       break;
13128    case NONE:
13129    default:
13130       break;
13131    }
13132 }
13133 
13134 static int transmit_cc_notify(struct ast_cc_agent *agent, struct sip_pvt *subscription, enum sip_cc_notify_state state)
13135 {
13136    struct sip_request req;
13137    struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
13138    char uri[SIPBUFSIZE];
13139    char state_str[64];
13140    char subscription_state_hdr[64];
13141 
13142    if (state < CC_QUEUED || state > CC_READY) {
13143       ast_log(LOG_WARNING, "Invalid state provided for transmit_cc_notify (%d)\n", state);
13144       return -1;
13145    }
13146 
13147    reqprep(&req, subscription, SIP_NOTIFY, 0, TRUE);
13148    snprintf(state_str, sizeof(state_str), "%s\r\n", sip_cc_notify_state_map[state].state_string);
13149    add_header(&req, "Event", "call-completion");
13150    add_header(&req, "Content-Type", "application/call-completion");
13151    snprintf(subscription_state_hdr, sizeof(subscription_state_hdr), "active;expires=%d", subscription->expiry);
13152    add_header(&req, "Subscription-State", subscription_state_hdr);
13153    if (state == CC_READY) {
13154       generate_uri(subscription, agent_pvt->notify_uri, sizeof(agent_pvt->notify_uri));
13155       snprintf(uri, sizeof(uri) - 1, "cc-URI: %s\r\n", agent_pvt->notify_uri);
13156    }
13157    add_content(&req, state_str);
13158    if (state == CC_READY) {
13159       add_content(&req, uri);
13160    }
13161    return send_request(subscription, &req, XMIT_RELIABLE, subscription->ocseq);
13162 }
13163 
13164 /*! \brief Used in the SUBSCRIBE notification subsystem (RFC3265) */
13165 static int transmit_state_notify(struct sip_pvt *p, int state, int full, int timeout)
13166 {
13167    struct ast_str *tmp = ast_str_alloca(4000);
13168    char from[256], to[256];
13169    char *c, *mfrom, *mto;
13170    struct sip_request req;
13171    const struct cfsubscription_types *subscriptiontype;
13172 
13173    memset(from, 0, sizeof(from));
13174    memset(to, 0, sizeof(to));
13175 
13176    subscriptiontype = find_subscription_type(p->subscribed);
13177 
13178    ast_copy_string(from, sip_get_header(&p->initreq, "From"), sizeof(from));
13179    c = get_in_brackets(from);
13180    if (strncasecmp(c, "sip:", 4) && strncasecmp(c, "sips:", 5)) {
13181       ast_log(LOG_WARNING, "Huh?  Not a SIP header (%s)?\n", c);
13182       return -1;
13183    }
13184 
13185    mfrom = remove_uri_parameters(c);
13186 
13187    ast_copy_string(to, sip_get_header(&p->initreq, "To"), sizeof(to));
13188    c = get_in_brackets(to);
13189    if (strncasecmp(c, "sip:", 4) && strncasecmp(c, "sips:", 5)) {
13190       ast_log(LOG_WARNING, "Huh?  Not a SIP header (%s)?\n", c);
13191       return -1;
13192    }
13193    mto = remove_uri_parameters(c);
13194 
13195    reqprep(&req, p, SIP_NOTIFY, 0, 1);
13196 
13197    switch(state) {
13198    case AST_EXTENSION_DEACTIVATED:
13199       if (timeout)
13200          add_header(&req, "Subscription-State", "terminated;reason=timeout");
13201       else {
13202          add_header(&req, "Subscription-State", "terminated;reason=probation");
13203          add_header(&req, "Retry-After", "60");
13204       }
13205       break;
13206    case AST_EXTENSION_REMOVED:
13207       add_header(&req, "Subscription-State", "terminated;reason=noresource");
13208       break;
13209    default:
13210       if (p->expiry)
13211          add_header(&req, "Subscription-State", "active");
13212       else  /* Expired */
13213          add_header(&req, "Subscription-State", "terminated;reason=timeout");
13214    }
13215 
13216    switch (p->subscribed) {
13217    case XPIDF_XML:
13218    case CPIM_PIDF_XML:
13219       add_header(&req, "Event", subscriptiontype->event);
13220       state_notify_build_xml(state, full, p->exten, p->context, &tmp, p, p->subscribed, mfrom, mto);
13221       add_header(&req, "Content-Type", subscriptiontype->mediatype);
13222       p->dialogver++;
13223       break;
13224    case PIDF_XML: /* Eyebeam supports this format */
13225       add_header(&req, "Event", subscriptiontype->event);
13226       state_notify_build_xml(state, full, p->exten, p->context, &tmp, p, p->subscribed, mfrom, mto);
13227       add_header(&req, "Content-Type", subscriptiontype->mediatype);
13228       p->dialogver++;
13229       break;
13230    case DIALOG_INFO_XML: /* SNOM subscribes in this format */
13231       add_header(&req, "Event", subscriptiontype->event);
13232       state_notify_build_xml(state, full, p->exten, p->context, &tmp, p, p->subscribed, mfrom, mto);
13233       add_header(&req, "Content-Type", subscriptiontype->mediatype);
13234       p->dialogver++;
13235       break;
13236    case NONE:
13237    default:
13238       break;
13239    }
13240 
13241    add_content(&req, tmp->str);
13242 
13243    p->pendinginvite = p->ocseq;  /* Remember that we have a pending NOTIFY in order not to confuse the NOTIFY subsystem */
13244 
13245    return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
13246 }
13247 
13248 /*! \brief Notify user of messages waiting in voicemail (RFC3842)
13249 \note - Notification only works for registered peers with mailbox= definitions
13250    in sip.conf
13251    - We use the SIP Event package message-summary
13252     MIME type defaults to  "application/simple-message-summary";
13253  */
13254 static int transmit_notify_with_mwi(struct sip_pvt *p, int newmsgs, int oldmsgs, const char *vmexten)
13255 {
13256    struct sip_request req;
13257    struct ast_str *out = ast_str_alloca(500);
13258    int ourport = (p->fromdomainport) ? p->fromdomainport : ast_sockaddr_port(&p->ourip);
13259    const char *domain;
13260    const char *exten = S_OR(vmexten, default_vmexten);
13261 
13262    initreqprep(&req, p, SIP_NOTIFY, NULL);
13263    add_header(&req, "Event", "message-summary");
13264    add_header(&req, "Content-Type", default_notifymime);
13265    ast_str_append(&out, 0, "Messages-Waiting: %s\r\n", newmsgs ? "yes" : "no");
13266 
13267    /* domain initialization occurs here because initreqprep changes ast_sockaddr_stringify string. */
13268    domain = S_OR(p->fromdomain, ast_sockaddr_stringify_host_remote(&p->ourip));
13269 
13270    if (!sip_standard_port(p->socket.type, ourport)) {
13271       if (p->socket.type == SIP_TRANSPORT_UDP) {
13272          ast_str_append(&out, 0, "Message-Account: sip:%s@%s:%d\r\n", exten, domain, ourport);
13273       } else {
13274          ast_str_append(&out, 0, "Message-Account: sip:%s@%s:%d;transport=%s\r\n", exten, domain, ourport, sip_get_transport(p->socket.type));
13275       }
13276    } else {
13277       if (p->socket.type == SIP_TRANSPORT_UDP) {
13278          ast_str_append(&out, 0, "Message-Account: sip:%s@%s\r\n", exten, domain);
13279       } else {
13280          ast_str_append(&out, 0, "Message-Account: sip:%s@%s;transport=%s\r\n", exten, domain, sip_get_transport(p->socket.type));
13281       }
13282    }
13283    /* Cisco has a bug in the SIP stack where it can't accept the
13284       (0/0) notification. This can temporarily be disabled in
13285       sip.conf with the "buggymwi" option */
13286    ast_str_append(&out, 0, "Voice-Message: %d/%d%s\r\n",
13287       newmsgs, oldmsgs, (ast_test_flag(&p->flags[1], SIP_PAGE2_BUGGY_MWI) ? "" : " (0/0)"));
13288 
13289    if (p->subscribed) {
13290       if (p->expiry) {
13291          add_header(&req, "Subscription-State", "active");
13292       } else { /* Expired */
13293          add_header(&req, "Subscription-State", "terminated;reason=timeout");
13294       }
13295    }
13296 
13297    add_content(&req, out->str);
13298 
13299    if (!p->initreq.headers) {
13300       initialize_initreq(p, &req);
13301    }
13302    return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
13303 }
13304 
13305 /*! \brief Notify a transferring party of the status of transfer (RFC3515) */
13306 static int transmit_notify_with_sipfrag(struct sip_pvt *p, int cseq, char *message, int terminate)
13307 {
13308    struct sip_request req;
13309    char tmp[SIPBUFSIZE/2];
13310    
13311    reqprep(&req, p, SIP_NOTIFY, 0, 1);
13312    snprintf(tmp, sizeof(tmp), "refer;id=%d", cseq);
13313    add_header(&req, "Event", tmp);
13314    add_header(&req, "Subscription-state", terminate ? "terminated;reason=noresource" : "active");
13315    add_header(&req, "Content-Type", "message/sipfrag;version=2.0");
13316    add_header(&req, "Allow", ALLOWED_METHODS);
13317    add_supported_header(p, &req);
13318 
13319    snprintf(tmp, sizeof(tmp), "SIP/2.0 %s\r\n", message);
13320    add_content(&req, tmp);
13321 
13322    if (!p->initreq.headers) {
13323       initialize_initreq(p, &req);
13324    }
13325 
13326    return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
13327 }
13328 
13329 static int manager_sipnotify(struct mansession *s, const struct message *m)
13330 {
13331    const char *channame = astman_get_header(m, "Channel");
13332    struct ast_variable *vars = astman_get_variables(m);
13333    struct sip_pvt *p;
13334    struct ast_variable *header, *var;
13335 
13336    if (ast_strlen_zero(channame)) {
13337       astman_send_error(s, m, "SIPNotify requires a channel name");
13338       return 0;
13339    }
13340 
13341    if (!strncasecmp(channame, "sip/", 4)) {
13342       channame += 4;
13343    }
13344 
13345    if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY, NULL))) {
13346       astman_send_error(s, m, "Unable to build sip pvt data for notify (memory/socket error)");
13347       return 0;
13348    }
13349 
13350    if (create_addr(p, channame, NULL, 0, NULL)) {
13351       /* Maybe they're not registered, etc. */
13352       dialog_unlink_all(p);
13353       dialog_unref(p, "unref dialog inside for loop" );
13354       /* sip_destroy(p); */
13355       astman_send_error(s, m, "Could not create address");
13356       return 0;
13357    }
13358 
13359    /* Notify is outgoing call */
13360    ast_set_flag(&p->flags[0], SIP_OUTGOING);
13361    sip_notify_allocate(p);
13362 
13363    p->notify->headers = header = ast_variable_new("Subscription-State", "terminated", "");
13364 
13365    for (var = vars; var; var = var->next) {
13366       if (!strcasecmp(var->name, "Content")) {
13367          if (ast_str_strlen(p->notify->content))
13368             ast_str_append(&p->notify->content, 0, "\r\n");
13369          ast_str_append(&p->notify->content, 0, "%s", var->value);
13370       } else if (!strcasecmp(var->name, "Content-Length")) {
13371          ast_log(LOG_WARNING, "it is not necessary to specify Content-Length, ignoring");
13372       } else {
13373          header->next = ast_variable_new(var->name, var->value, "");
13374          header = header->next;
13375       }
13376    }
13377 
13378    sip_scheddestroy(p, SIP_TRANS_TIMEOUT);
13379    transmit_invite(p, SIP_NOTIFY, 0, 2, NULL);
13380    dialog_unref(p, "bump down the count of p since we're done with it.");
13381 
13382    astman_send_ack(s, m, "Notify Sent");
13383    ast_variables_destroy(vars);
13384    return 0;
13385 }
13386 
13387 /*! \brief Send a provisional response indicating that a call was redirected
13388  */
13389 static void update_redirecting(struct sip_pvt *p, const void *data, size_t datalen)
13390 {
13391    struct sip_request resp;
13392 
13393    if (p->owner->_state == AST_STATE_UP || ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
13394       return;
13395    }
13396 
13397    respprep(&resp, p, "181 Call is being forwarded", &p->initreq);
13398    add_diversion_header(&resp, p);
13399    send_response(p, &resp, XMIT_UNRELIABLE, 0);
13400 }
13401 
13402 /*! \brief Notify peer that the connected line has changed */
13403 static void update_connectedline(struct sip_pvt *p, const void *data, size_t datalen)
13404 {
13405 
13406    if (!ast_test_flag(&p->flags[0], SIP_SENDRPID)) {
13407       return;
13408    }
13409    if (!p->owner->connected.id.number.valid
13410       || ast_strlen_zero(p->owner->connected.id.number.str)) {
13411       return;
13412    }
13413 
13414    append_history(p, "ConnectedLine", "%s party is now %s <%s>",
13415       ast_test_flag(&p->flags[0], SIP_OUTGOING) ? "Calling" : "Called",
13416       S_COR(p->owner->connected.id.name.valid, p->owner->connected.id.name.str, ""),
13417       S_COR(p->owner->connected.id.number.valid, p->owner->connected.id.number.str, ""));
13418 
13419    if (p->owner->_state == AST_STATE_UP || ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
13420       struct sip_request req;
13421 
13422       if (p->invitestate == INV_CONFIRMED || p->invitestate == INV_TERMINATED) {
13423          reqprep(&req, p, ast_test_flag(&p->flags[0], SIP_REINVITE_UPDATE) ? SIP_UPDATE : SIP_INVITE, 0, 1);
13424 
13425          add_header(&req, "Allow", ALLOWED_METHODS);
13426          add_supported_header(p, &req);
13427          add_rpid(&req, p);
13428          add_sdp(&req, p, FALSE, TRUE, FALSE);
13429 
13430          initialize_initreq(p, &req);
13431          p->lastinvite = p->ocseq;
13432          ast_set_flag(&p->flags[0], SIP_OUTGOING);
13433          p->invitestate = INV_CALLING;
13434          send_request(p, &req, XMIT_CRITICAL, p->ocseq);
13435       } else if ((is_method_allowed(&p->allowed_methods, SIP_UPDATE)) && (!ast_strlen_zero(p->okcontacturi))) { 
13436          reqprep(&req, p, SIP_UPDATE, 0, 1);
13437          add_rpid(&req, p);
13438          add_header(&req, "X-Asterisk-rpid-update", "Yes");
13439          send_request(p, &req, XMIT_CRITICAL, p->ocseq);
13440       } else {
13441          /* We cannot send the update yet, so we have to wait until we can */
13442          ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
13443       }
13444    } else {
13445       ast_set_flag(&p->flags[1], SIP_PAGE2_CONNECTLINEUPDATE_PEND);
13446       if (ast_test_flag(&p->flags[1], SIP_PAGE2_RPID_IMMEDIATE)) {
13447          struct sip_request resp;
13448 
13449          if ((p->owner->_state == AST_STATE_RING) && !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT)) {
13450             ast_clear_flag(&p->flags[1], SIP_PAGE2_CONNECTLINEUPDATE_PEND);
13451             respprep(&resp, p, "180 Ringing", &p->initreq);
13452             add_rpid(&resp, p);
13453             send_response(p, &resp, XMIT_UNRELIABLE, 0);
13454             ast_set_flag(&p->flags[0], SIP_RINGING);
13455          } else if (p->owner->_state == AST_STATE_RINGING) {
13456             ast_clear_flag(&p->flags[1], SIP_PAGE2_CONNECTLINEUPDATE_PEND);
13457             respprep(&resp, p, "183 Session Progress", &p->initreq);
13458             add_rpid(&resp, p);
13459             send_response(p, &resp, XMIT_UNRELIABLE, 0);
13460             ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
13461          } else {
13462             ast_debug(1, "Unable able to send update to '%s' in state '%s'\n", ast_channel_name(p->owner), ast_state2str(p->owner->_state));
13463          }
13464       }
13465    }
13466 }
13467 
13468 static const struct _map_x_s regstatestrings[] = {
13469    { REG_STATE_FAILED,     "Failed" },
13470    { REG_STATE_UNREGISTERED, "Unregistered"},
13471    { REG_STATE_REGSENT, "Request Sent"},
13472    { REG_STATE_AUTHSENT, "Auth. Sent"},
13473    { REG_STATE_REGISTERED, "Registered"},
13474    { REG_STATE_REJECTED, "Rejected"},
13475    { REG_STATE_TIMEOUT, "Timeout"},
13476    { REG_STATE_NOAUTH, "No Authentication"},
13477    { -1, NULL } /* terminator */
13478 };
13479 
13480 /*! \brief Convert registration state status to string */
13481 static const char *regstate2str(enum sipregistrystate regstate)
13482 {
13483    return map_x_s(regstatestrings, regstate, "Unknown");
13484 }
13485 
13486 /*! \brief Update registration with SIP Proxy.
13487  * Called from the scheduler when the previous registration expires,
13488  * so we don't have to cancel the pending event.
13489  * We assume the reference so the sip_registry is valid, since it
13490  * is stored in the scheduled event anyways.
13491  */
13492 static int sip_reregister(const void *data)
13493 {
13494    /* if we are here, we know that we need to reregister. */
13495    struct sip_registry *r = (struct sip_registry *) data;
13496 
13497    /* if we couldn't get a reference to the registry object, punt */
13498    if (!r) {
13499       return 0;
13500    }
13501 
13502    if (r->call && r->call->do_history) {
13503       append_history(r->call, "RegistryRenew", "Account: %s@%s", r->username, r->hostname);
13504    }
13505    /* Since registry's are only added/removed by the the monitor thread, this
13506       may be overkill to reference/dereference at all here */
13507    if (sipdebug) {
13508       ast_log(LOG_NOTICE, "   -- Re-registration for  %s@%s\n", r->username, r->hostname);
13509    }
13510 
13511    r->expire = -1;
13512    r->expiry = r->configured_expiry;
13513    __sip_do_register(r);
13514    registry_unref(r, "unref the re-register scheduled event");
13515    return 0;
13516 }
13517 
13518 /*! \brief Register with SIP proxy 
13519    \return see \ref __sip_xmit 
13520 */
13521 static int __sip_do_register(struct sip_registry *r)
13522 {
13523    int res;
13524 
13525    res = transmit_register(r, SIP_REGISTER, NULL, NULL);
13526    return res;
13527 }
13528 
13529 /*! \brief Registration timeout, register again
13530  * Registered as a timeout handler during transmit_register(),
13531  * to retransmit the packet if a reply does not come back.
13532  * This is called by the scheduler so the event is not pending anymore when
13533  * we are called.
13534  */
13535 static int sip_reg_timeout(const void *data)
13536 {
13537 
13538    /* if we are here, our registration timed out, so we'll just do it over */
13539    struct sip_registry *r = (struct sip_registry *)data; /* the ref count should have been bumped when the sched item was added */
13540    struct sip_pvt *p;
13541 
13542    /* if we couldn't get a reference to the registry object, punt */
13543    if (!r) {
13544       return 0;
13545    }
13546 
13547    if (r->dnsmgr) {
13548       /* If the registration has timed out, maybe the IP changed.  Force a refresh. */
13549       ast_dnsmgr_refresh(r->dnsmgr);
13550    }
13551 
13552    /* If the initial tranmission failed, we may not have an existing dialog,
13553     * so it is possible that r->call == NULL.
13554     * Otherwise destroy it, as we have a timeout so we don't want it.
13555     */
13556    if (r->call) {
13557       /* Unlink us, destroy old call.  Locking is not relevant here because all this happens
13558          in the single SIP manager thread. */
13559       p = r->call;
13560       sip_pvt_lock(p);
13561       pvt_set_needdestroy(p, "registration timeout");
13562       /* Pretend to ACK anything just in case */
13563       __sip_pretend_ack(p);
13564       sip_pvt_unlock(p);
13565 
13566       /* decouple the two objects */
13567       /* p->registry == r, so r has 2 refs, and the unref won't take the object away */
13568       if (p->registry) {
13569          p->registry = registry_unref(p->registry, "p->registry unreffed");
13570       }
13571       r->call = dialog_unref(r->call, "unrefing r->call");
13572    }
13573    /* If we have a limit, stop registration and give up */
13574    r->timeout = -1;
13575    if (global_regattempts_max && r->regattempts >= global_regattempts_max) {
13576       /* Ok, enough is enough. Don't try any more */
13577       /* We could add an external notification here...
13578          steal it from app_voicemail :-) */
13579       ast_log(LOG_NOTICE, "   -- Last Registration Attempt #%d failed, Giving up forever trying to register '%s@%s'\n", r->regattempts, r->username, r->hostname);
13580       r->regstate = REG_STATE_FAILED;
13581    } else {
13582       r->regstate = REG_STATE_UNREGISTERED;
13583       transmit_register(r, SIP_REGISTER, NULL, NULL);
13584       ast_log(LOG_NOTICE, "   -- Registration for '%s@%s' timed out, trying again (Attempt #%d)\n", r->username, r->hostname, r->regattempts);
13585    }
13586    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));
13587    registry_unref(r, "unreffing registry_unref r");
13588    return 0;
13589 }
13590 
13591 static const char *sip_sanitized_host(const char *host)
13592 {
13593    struct ast_sockaddr addr = { { 0, 0, }, };
13594 
13595    /* peer/sip_pvt->tohost and sip_registry->hostname should never have a port
13596     * in them, so we use PARSE_PORT_FORBID here. If this lookup fails, we return
13597     * the original host which is most likely a host name and not an IP. */
13598    if (!ast_sockaddr_parse(&addr, host, PARSE_PORT_FORBID)) {
13599       return host;
13600    }
13601    return ast_sockaddr_stringify_host_remote(&addr);
13602 }
13603 
13604 /*! \brief Transmit register to SIP proxy or UA
13605  * auth = NULL on the initial registration (from sip_reregister())
13606  */
13607 static int transmit_register(struct sip_registry *r, int sipmethod, const char *auth, const char *authheader)
13608 {
13609    struct sip_request req;
13610    char from[256];
13611    char to[256];
13612    char tmp[80];
13613    char addr[80];
13614    struct sip_pvt *p;
13615    struct sip_peer *peer = NULL;
13616    int res;
13617    int portno = 0;
13618 
13619    /* exit if we are already in process with this registrar ?*/
13620    if (r == NULL || ((auth == NULL) && (r->regstate == REG_STATE_REGSENT || r->regstate == REG_STATE_AUTHSENT))) {
13621       if (r) {
13622          ast_log(LOG_NOTICE, "Strange, trying to register %s@%s when registration already pending\n", r->username, r->hostname);
13623       }
13624       return 0;
13625    }
13626 
13627    if (r->dnsmgr == NULL) {
13628       char transport[MAXHOSTNAMELEN];
13629       peer = sip_find_peer(r->hostname, NULL, TRUE, FINDPEERS, FALSE, 0);
13630       snprintf(transport, sizeof(transport), "_%s._%s",get_srv_service(r->transport), get_srv_protocol(r->transport)); /* have to use static sip_get_transport function */
13631       r->us.ss.ss_family = get_address_family_filter(&bindaddr); /* Filter address family */
13632 
13633       /* No point in doing a DNS lookup of the register hostname if we're just going to
13634        * end up using an outbound proxy. obproxy_get is safe to call with either of r->call
13635        * or peer NULL. Since we're only concerned with its existence, we're not going to
13636        * bother getting a ref to the proxy*/
13637       if (!obproxy_get(r->call, peer)) {
13638          registry_addref(r, "add reg ref for dnsmgr");
13639          ast_dnsmgr_lookup_cb(peer ? peer->tohost : r->hostname, &r->us, &r->dnsmgr, sip_cfg.srvlookup ? transport : NULL, on_dns_update_registry, r);
13640          if (!r->dnsmgr) {
13641             /*dnsmgr refresh disabled, no reference added! */
13642             registry_unref(r, "remove reg ref, dnsmgr disabled");
13643          }
13644       }
13645       if (peer) {
13646          peer = sip_unref_peer(peer, "removing peer ref for dnsmgr_lookup");
13647       }
13648    }
13649 
13650    if (r->call) { /* We have a registration */
13651       if (!auth) {
13652          ast_log(LOG_WARNING, "Already have a REGISTER going on to %s@%s?? \n", r->username, r->hostname);
13653          return 0;
13654       } else {
13655          p = dialog_ref(r->call, "getting a copy of the r->call dialog in transmit_register");
13656          make_our_tag(p->tag, sizeof(p->tag));  /* create a new local tag for every register attempt */
13657          ast_string_field_set(p, theirtag, NULL);  /* forget their old tag, so we don't match tags when getting response */
13658       }
13659    } else {
13660       /* Build callid for registration if we haven't registered before */
13661       if (!r->callid_valid) {
13662          build_callid_registry(r, &internip, default_fromdomain);
13663          r->callid_valid = TRUE;
13664       }
13665       /* Allocate SIP dialog for registration */
13666       if (!(p = sip_alloc( r->callid, NULL, 0, SIP_REGISTER, NULL))) {
13667          ast_log(LOG_WARNING, "Unable to allocate registration transaction (memory or socket error)\n");
13668          return 0;
13669       }
13670       
13671       if (p->do_history) {
13672          append_history(p, "RegistryInit", "Account: %s@%s", r->username, r->hostname);
13673       }
13674 
13675       /* Use port number specified if no SRV record was found */
13676       if (!ast_sockaddr_isnull(&r->us)) {
13677          if (!ast_sockaddr_port(&r->us) && r->portno) {
13678             ast_sockaddr_set_port(&r->us, r->portno);
13679          }
13680 
13681          /* It is possible that DNS was unavailable at the time the peer was created.
13682           * Here, if we've updated the address in the registry via manually calling
13683           * ast_dnsmgr_lookup_cb() above, then we call the same function that dnsmgr would
13684           * call if it was updating a peer's address */
13685          if ((peer = sip_find_peer(S_OR(r->peername, r->hostname), NULL, TRUE, FINDPEERS, FALSE, 0))) {
13686             if (ast_sockaddr_cmp(&peer->addr, &r->us)) {
13687                on_dns_update_peer(&peer->addr, &r->us, peer);
13688             }
13689             peer = sip_unref_peer(peer, "unref after sip_find_peer");
13690          }
13691       }
13692 
13693       /* Find address to hostname */
13694       if (create_addr(p, S_OR(r->peername, r->hostname), &r->us, 0, NULL)) {
13695          /* we have what we hope is a temporary network error,
13696           * probably DNS.  We need to reschedule a registration try */
13697          dialog_unlink_all(p);
13698          p = dialog_unref(p, "unref dialog after unlink_all");
13699          if (r->timeout > -1) {
13700             AST_SCHED_REPLACE_UNREF(r->timeout, sched, global_reg_timeout * 1000, sip_reg_timeout, r,
13701                               registry_unref(_data, "del for REPLACE of registry ptr"),
13702                               registry_unref(r, "object ptr dec when SCHED_REPLACE add failed"),
13703                               registry_addref(r,"add for REPLACE registry ptr"));
13704             ast_log(LOG_WARNING, "Still have a registration timeout for %s@%s (create_addr() error), %d\n", r->username, r->hostname, r->timeout);
13705          } else {
13706             r->timeout = ast_sched_add(sched, global_reg_timeout * 1000, sip_reg_timeout, registry_addref(r, "add for REPLACE registry ptr"));
13707             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);
13708          }
13709          r->regattempts++;
13710          return 0;
13711       }
13712 
13713       /* Copy back Call-ID in case create_addr changed it */
13714       ast_string_field_set(r, callid, p->callid);
13715 
13716       if (!r->dnsmgr && r->portno) {
13717          ast_sockaddr_set_port(&p->sa, r->portno);
13718          ast_sockaddr_set_port(&p->recv, r->portno);
13719       }
13720       if (!ast_strlen_zero(p->fromdomain)) {
13721          portno = (p->fromdomainport) ? p->fromdomainport : STANDARD_SIP_PORT;
13722       } else if (!ast_strlen_zero(r->regdomain)) {
13723          portno = (r->regdomainport) ? r->regdomainport : STANDARD_SIP_PORT;
13724       } else {
13725          portno = ast_sockaddr_port(&p->sa);
13726       }
13727 
13728       ast_set_flag(&p->flags[0], SIP_OUTGOING); /* Registration is outgoing call */
13729       r->call = dialog_ref(p, "copying dialog into registry r->call");     /* Save pointer to SIP dialog */
13730       p->registry = registry_addref(r, "transmit_register: addref to p->registry in transmit_register"); /* Add pointer to registry in packet */
13731       if (!ast_strlen_zero(r->secret)) {  /* Secret (password) */
13732          ast_string_field_set(p, peersecret, r->secret);
13733       }
13734       if (!ast_strlen_zero(r->md5secret))
13735          ast_string_field_set(p, peermd5secret, r->md5secret);
13736       /* User name in this realm
13737       - if authuser is set, use that, otherwise use username */
13738       if (!ast_strlen_zero(r->authuser)) {
13739          ast_string_field_set(p, peername, r->authuser);
13740          ast_string_field_set(p, authname, r->authuser);
13741       } else if (!ast_strlen_zero(r->username)) {
13742          ast_string_field_set(p, peername, r->username);
13743          ast_string_field_set(p, authname, r->username);
13744          ast_string_field_set(p, fromuser, r->username);
13745       }
13746       if (!ast_strlen_zero(r->username)) {
13747          ast_string_field_set(p, username, r->username);
13748       }
13749       /* Save extension in packet */
13750       if (!ast_strlen_zero(r->callback)) {
13751          ast_string_field_set(p, exten, r->callback);
13752       }
13753 
13754       /* Set transport and port so the correct contact is built */
13755       set_socket_transport(&p->socket, r->transport);
13756       if (r->transport == SIP_TRANSPORT_TLS || r->transport == SIP_TRANSPORT_TCP) {
13757          p->socket.port =
13758              htons(ast_sockaddr_port(&sip_tcp_desc.local_address));
13759       }
13760 
13761       /*
13762         check which address we should use in our contact header
13763         based on whether the remote host is on the external or
13764         internal network so we can register through nat
13765        */
13766       ast_sip_ouraddrfor(&p->sa, &p->ourip, p);
13767       build_contact(p);
13768    }
13769 
13770    /* set up a timeout */
13771    if (auth == NULL)  {
13772       if (r->timeout > -1) {
13773          ast_log(LOG_WARNING, "Still have a registration timeout, #%d - deleting it\n", r->timeout);
13774       }
13775       AST_SCHED_REPLACE_UNREF(r->timeout, sched, global_reg_timeout * 1000, sip_reg_timeout, r,
13776                         registry_unref(_data,"reg ptr unrefed from del in SCHED_REPLACE"),
13777                         registry_unref(r,"reg ptr unrefed from add failure in SCHED_REPLACE"),
13778                         registry_addref(r,"reg ptr reffed from add in SCHED_REPLACE"));
13779       ast_debug(1, "Scheduled a registration timeout for %s id  #%d \n", r->hostname, r->timeout);
13780    }
13781 
13782    snprintf(from, sizeof(from), "<sip:%s@%s>;tag=%s", r->username, S_OR(r->regdomain, sip_sanitized_host(p->tohost)), p->tag);
13783    if (!ast_strlen_zero(p->theirtag)) {
13784       snprintf(to, sizeof(to), "<sip:%s@%s>;tag=%s", r->username, S_OR(r->regdomain, sip_sanitized_host(p->tohost)), p->theirtag);
13785    } else {
13786       snprintf(to, sizeof(to), "<sip:%s@%s>", r->username, S_OR(r->regdomain, sip_sanitized_host(p->tohost)));
13787    }
13788 
13789    /* Fromdomain is what we are registering to, regardless of actual
13790       host name from SRV */
13791    if (portno && portno != STANDARD_SIP_PORT) {
13792       snprintf(addr, sizeof(addr), "sip:%s:%d", S_OR(p->fromdomain,S_OR(r->regdomain, sip_sanitized_host(r->hostname))), portno);
13793    } else {
13794       snprintf(addr, sizeof(addr), "sip:%s", S_OR(p->fromdomain,S_OR(r->regdomain, sip_sanitized_host(r->hostname))));
13795    }
13796 
13797    ast_string_field_set(p, uri, addr);
13798 
13799    p->branch ^= ast_random();
13800 
13801    init_req(&req, sipmethod, addr);
13802 
13803    /* Add to CSEQ */
13804    snprintf(tmp, sizeof(tmp), "%u %s", ++r->ocseq, sip_methods[sipmethod].text);
13805    p->ocseq = r->ocseq;
13806 
13807    build_via(p);
13808    add_header(&req, "Via", p->via);
13809    add_header_max_forwards(p, &req);
13810    add_header(&req, "From", from);
13811    add_header(&req, "To", to);
13812    add_header(&req, "Call-ID", p->callid);
13813    add_header(&req, "CSeq", tmp);
13814    if (!ast_strlen_zero(global_useragent))
13815       add_header(&req, "User-Agent", global_useragent);
13816 
13817    if (auth) { /* Add auth header */
13818       add_header(&req, authheader, auth);
13819    } else if (!ast_strlen_zero(r->nonce)) {
13820       char digest[1024];
13821 
13822       /* We have auth data to reuse, build a digest header.
13823        * Note, this is not always useful because some parties do not
13824        * like nonces to be reused (for good reasons!) so they will
13825        * challenge us anyways.
13826        */
13827       if (sipdebug) {
13828          ast_debug(1, "   >>> Re-using Auth data for %s@%s\n", r->username, r->hostname);
13829       }
13830       ast_string_field_set(p, realm, r->realm);
13831       ast_string_field_set(p, nonce, r->nonce);
13832       ast_string_field_set(p, domain, r->authdomain);
13833       ast_string_field_set(p, opaque, r->opaque);
13834       ast_string_field_set(p, qop, r->qop);
13835       p->noncecount = ++r->noncecount;
13836 
13837       memset(digest, 0, sizeof(digest));
13838       if(!build_reply_digest(p, sipmethod, digest, sizeof(digest))) {
13839          add_header(&req, "Authorization", digest);
13840       } else {
13841          ast_log(LOG_NOTICE, "No authorization available for authentication of registration to %s@%s\n", r->username, r->hostname);
13842       }
13843    }
13844 
13845    snprintf(tmp, sizeof(tmp), "%d", r->expiry);
13846    add_header(&req, "Expires", tmp);
13847    add_header(&req, "Contact", p->our_contact);
13848 
13849    initialize_initreq(p, &req);
13850    if (sip_debug_test_pvt(p)) {
13851       ast_verbose("REGISTER %d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
13852    }
13853    r->regstate = auth ? REG_STATE_AUTHSENT : REG_STATE_REGSENT;
13854    r->regattempts++; /* Another attempt */
13855    ast_debug(4, "REGISTER attempt %d to %s@%s\n", r->regattempts, r->username, r->hostname);
13856    res = send_request(p, &req, XMIT_CRITICAL, p->ocseq);
13857    dialog_unref(p, "p is finished here at the end of transmit_register");
13858    return res;
13859 }
13860 
13861 /*!
13862  * \brief Transmit with SIP MESSAGE method
13863  * \note The p->msg_headers and p->msg_body are already setup.
13864  */
13865 static int transmit_message(struct sip_pvt *p, int init, int auth)
13866 {
13867    struct sip_request req;
13868 
13869    if (init) {
13870       initreqprep(&req, p, SIP_MESSAGE, NULL);
13871       initialize_initreq(p, &req);
13872    } else {
13873       reqprep(&req, p, SIP_MESSAGE, 0, 1);
13874    }
13875    if (auth) {
13876       return transmit_request_with_auth(p, SIP_MESSAGE, p->ocseq, XMIT_RELIABLE, 0);
13877    } else {
13878       add_text(&req, p);
13879       return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
13880    }
13881 }
13882 
13883 /*! \brief Allocate SIP refer structure */
13884 static int sip_refer_allocate(struct sip_pvt *p)
13885 {
13886    p->refer = ast_calloc(1, sizeof(struct sip_refer));
13887    return p->refer ? 1 : 0;
13888 }
13889 
13890 /*! \brief Allocate SIP refer structure */
13891 static int sip_notify_allocate(struct sip_pvt *p)
13892 {
13893    p->notify = ast_calloc(1, sizeof(struct sip_notify));
13894    if (p->notify) {
13895       p->notify->content = ast_str_create(128);
13896    }
13897    return p->notify ? 1 : 0;
13898 }
13899 
13900 /*! \brief Transmit SIP REFER message (initiated by the transfer() dialplan application
13901    \note this is currently broken as we have no way of telling the dialplan
13902    engine whether a transfer succeeds or fails.
13903    \todo Fix the transfer() dialplan function so that a transfer may fail
13904 */
13905 static int transmit_refer(struct sip_pvt *p, const char *dest)
13906 {
13907    struct sip_request req = {
13908       .headers = 0,
13909    };
13910    char from[256];
13911    const char *of;
13912    char *c;
13913    char referto[256];
13914    int   use_tls=FALSE;
13915 
13916    if (sipdebug) {
13917       ast_debug(1, "SIP transfer of %s to %s\n", p->callid, dest);
13918    }
13919 
13920    /* Are we transfering an inbound or outbound call ? */
13921    if (ast_test_flag(&p->flags[0], SIP_OUTGOING))  {
13922       of = sip_get_header(&p->initreq, "To");
13923    } else {
13924       of = sip_get_header(&p->initreq, "From");
13925    }
13926 
13927    ast_copy_string(from, of, sizeof(from));
13928    of = get_in_brackets(from);
13929    ast_string_field_set(p, from, of);
13930    if (!strncasecmp(of, "sip:", 4)) {
13931       of += 4;
13932    } else if (!strncasecmp(of, "sips:", 5)) {
13933       of += 5;
13934       use_tls = TRUE;
13935    } else {
13936       ast_log(LOG_NOTICE, "From address missing 'sip(s):', assuming sip:\n");
13937    }
13938    /* Get just the username part */
13939    if ((c = strchr(dest, '@'))) {
13940       c = NULL;
13941    } else if ((c = strchr(of, '@'))) {
13942       *c++ = '\0';
13943    }
13944    if (c) {
13945       snprintf(referto, sizeof(referto), "<sip%s:%s@%s>", use_tls ? "s" : "", dest, c);
13946    } else {
13947       snprintf(referto, sizeof(referto), "<sip%s:%s>", use_tls ? "s" : "", dest);
13948    }
13949 
13950    /* save in case we get 407 challenge */
13951    sip_refer_allocate(p);
13952    ast_copy_string(p->refer->refer_to, referto, sizeof(p->refer->refer_to));
13953    ast_copy_string(p->refer->referred_by, p->our_contact, sizeof(p->refer->referred_by));
13954    p->refer->status = REFER_SENT;   /* Set refer status */
13955 
13956    reqprep(&req, p, SIP_REFER, 0, 1);
13957 
13958    add_header(&req, "Refer-To", referto);
13959    add_header(&req, "Allow", ALLOWED_METHODS);
13960    add_supported_header(p, &req);
13961    if (!ast_strlen_zero(p->our_contact)) {
13962       add_header(&req, "Referred-By", p->our_contact);
13963    }
13964 
13965    return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
13966 
13967    /* We should propably wait for a NOTIFY here until we ack the transfer */
13968    /* Maybe fork a new thread and wait for a STATUS of REFER_200OK on the refer status before returning to app_transfer */
13969 
13970    /*! \todo In theory, we should hang around and wait for a reply, before
13971    returning to the dial plan here. Don't know really how that would
13972    affect the transfer() app or the pbx, but, well, to make this
13973    useful we should have a STATUS code on transfer().
13974    */
13975 }
13976 
13977 /*! \brief Send SIP INFO advice of charge message */
13978 static int transmit_info_with_aoc(struct sip_pvt *p, struct ast_aoc_decoded *decoded)
13979 {
13980    struct sip_request req;
13981    struct ast_str *str = ast_str_alloca(512);
13982    const struct ast_aoc_unit_entry *unit_entry = ast_aoc_get_unit_info(decoded, 0);
13983    enum ast_aoc_charge_type charging = ast_aoc_get_charge_type(decoded);
13984 
13985    reqprep(&req, p, SIP_INFO, 0, 1);
13986 
13987    if (ast_aoc_get_msg_type(decoded) == AST_AOC_D) {
13988       ast_str_append(&str, 0, "type=active;");
13989    } else if (ast_aoc_get_msg_type(decoded) == AST_AOC_E) {
13990       ast_str_append(&str, 0, "type=terminated;");
13991    } else {
13992       /* unsupported message type */
13993       return -1;
13994    }
13995 
13996    switch (charging) {
13997    case AST_AOC_CHARGE_FREE:
13998       ast_str_append(&str, 0, "free-of-charge;");
13999       break;
14000    case AST_AOC_CHARGE_CURRENCY:
14001       ast_str_append(&str, 0, "charging;");
14002       ast_str_append(&str, 0, "charging-info=currency;");
14003       ast_str_append(&str, 0, "amount=%u;", ast_aoc_get_currency_amount(decoded));
14004       ast_str_append(&str, 0, "multiplier=%s;", ast_aoc_get_currency_multiplier_decimal(decoded));
14005       if (!ast_strlen_zero(ast_aoc_get_currency_name(decoded))) {
14006          ast_str_append(&str, 0, "currency=%s;", ast_aoc_get_currency_name(decoded));
14007       }
14008       break;
14009    case AST_AOC_CHARGE_UNIT:
14010       ast_str_append(&str, 0, "charging;");
14011       ast_str_append(&str, 0, "charging-info=pulse;");
14012       if (unit_entry) {
14013          ast_str_append(&str, 0, "recorded-units=%u;", unit_entry->amount);
14014       }
14015       break;
14016    default:
14017       ast_str_append(&str, 0, "not-available;");
14018    };
14019 
14020    add_header(&req, "AOC", ast_str_buffer(str));
14021 
14022    return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
14023 }
14024 
14025 /*! \brief Send SIP INFO dtmf message, see Cisco documentation on cisco.com */
14026 static int transmit_info_with_digit(struct sip_pvt *p, const char digit, unsigned int duration)
14027 {
14028    struct sip_request req;
14029    
14030    reqprep(&req, p, SIP_INFO, 0, 1);
14031    add_digit(&req, digit, duration, (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_SHORTINFO));
14032    return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
14033 }
14034 
14035 /*! \brief Send SIP INFO with video update request */
14036 static int transmit_info_with_vidupdate(struct sip_pvt *p)
14037 {
14038    struct sip_request req;
14039    
14040    reqprep(&req, p, SIP_INFO, 0, 1);
14041    add_vidupdate(&req);
14042    return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
14043 }
14044 
14045 /*! \brief Transmit generic SIP request
14046    returns XMIT_ERROR if transmit failed with a critical error (don't retry)
14047 */
14048 static int transmit_request(struct sip_pvt *p, int sipmethod, uint32_t seqno, enum xmittype reliable, int newbranch)
14049 {
14050    struct sip_request resp;
14051    
14052    if (sipmethod == SIP_ACK) {
14053       p->invitestate = INV_CONFIRMED;
14054    }
14055 
14056    reqprep(&resp, p, sipmethod, seqno, newbranch);
14057    if (sipmethod == SIP_CANCEL && p->answered_elsewhere) {
14058       add_header(&resp, "Reason", "SIP;cause=200;text=\"Call completed elsewhere\"");
14059    }
14060 
14061    return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);
14062 }
14063 
14064 /*! \brief return the request and response header for a 401 or 407 code */
14065 void sip_auth_headers(enum sip_auth_type code, char **header, char **respheader)
14066 {
14067    if (code == WWW_AUTH) {       /* 401 */
14068       *header = "WWW-Authenticate";
14069       *respheader = "Authorization";
14070    } else if (code == PROXY_AUTH) { /* 407 */
14071       *header = "Proxy-Authenticate";
14072       *respheader = "Proxy-Authorization";
14073    } else {
14074       ast_verbose("-- wrong response code %d\n", code);
14075       *header = *respheader = "Invalid";
14076    }
14077 }
14078 
14079 /*! \brief Transmit SIP request, auth added */
14080 static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, uint32_t seqno, enum xmittype reliable, int newbranch)
14081 {
14082    struct sip_request resp;
14083    
14084    reqprep(&resp, p, sipmethod, seqno, newbranch);
14085    if (!ast_strlen_zero(p->realm)) {
14086       char digest[1024];
14087 
14088       memset(digest, 0, sizeof(digest));
14089       if(!build_reply_digest(p, sipmethod, digest, sizeof(digest))) {
14090          char *dummy, *response;
14091          enum sip_auth_type code = p->options ? p->options->auth_type : PROXY_AUTH; /* XXX force 407 if unknown */
14092          sip_auth_headers(code, &dummy, &response);
14093          add_header(&resp, response, digest);
14094       } else {
14095          ast_log(LOG_WARNING, "No authentication available for call %s\n", p->callid);
14096       }
14097    }
14098 
14099    switch (sipmethod) {
14100    case SIP_BYE:
14101    {
14102       char buf[20];
14103 
14104       /*
14105        * We are hanging up.  If we know a cause for that, send it in
14106        * clear text to make debugging easier.
14107        */
14108       if (ast_test_flag(&p->flags[1], SIP_PAGE2_Q850_REASON) && p->hangupcause) {
14109          snprintf(buf, sizeof(buf), "Q.850;cause=%d", p->hangupcause & 0x7f);
14110          add_header(&resp, "Reason", buf);
14111       }
14112 
14113       add_header(&resp, "X-Asterisk-HangupCause", ast_cause2str(p->hangupcause));
14114       snprintf(buf, sizeof(buf), "%d", p->hangupcause);
14115       add_header(&resp, "X-Asterisk-HangupCauseCode", buf);
14116       break;
14117    }
14118    case SIP_MESSAGE:
14119       add_text(&resp, p);
14120       break;
14121    default:
14122       break;
14123    }
14124 
14125    return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);   
14126 }
14127 
14128 /*! \brief Remove registration data from realtime database or AST/DB when registration expires */
14129 static void destroy_association(struct sip_peer *peer)
14130 {
14131    int realtimeregs = ast_check_realtime("sipregs");
14132    char *tablename = (realtimeregs) ? "sipregs" : "sippeers";
14133 
14134    if (!sip_cfg.ignore_regexpire) {
14135       if (peer->rt_fromcontact && sip_cfg.peer_rtupdate) {
14136          ast_update_realtime(tablename, "name", peer->name, "fullcontact", "", "ipaddr", "", "port", "", "regseconds", "0", "regserver", "", "useragent", "", "lastms", "0", SENTINEL);
14137       } else {
14138          ast_db_del("SIP/Registry", peer->name);
14139          ast_db_del("SIP/PeerMethods", peer->name);
14140       }
14141    }
14142 }
14143 
14144 static void set_socket_transport(struct sip_socket *socket, int transport)
14145 {
14146    /* if the transport type changes, clear all socket data */
14147    if (socket->type != transport) {
14148       socket->fd = -1;
14149       socket->type = transport;
14150       if (socket->tcptls_session) {
14151          ao2_ref(socket->tcptls_session, -1);
14152          socket->tcptls_session = NULL;
14153       }
14154    }
14155 }
14156 
14157 /*! \brief Expire registration of SIP peer */
14158 static int expire_register(const void *data)
14159 {
14160    struct sip_peer *peer = (struct sip_peer *)data;
14161 
14162    if (!peer) {      /* Hmmm. We have no peer. Weird. */
14163       return 0;
14164    }
14165 
14166    peer->expire = -1;
14167    peer->portinuri = 0;
14168 
14169    destroy_association(peer); /* remove registration data from storage */
14170    set_socket_transport(&peer->socket, peer->default_outbound_transport);
14171 
14172    if (peer->socket.tcptls_session) {
14173       ao2_ref(peer->socket.tcptls_session, -1);
14174       peer->socket.tcptls_session = NULL;
14175    }
14176 
14177    manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: Unregistered\r\nCause: Expired\r\n", peer->name);
14178    register_peer_exten(peer, FALSE);   /* Remove regexten */
14179    ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", peer->name);
14180 
14181    /* Do we need to release this peer from memory?
14182       Only for realtime peers and autocreated peers
14183    */
14184    if (peer->is_realtime) {
14185       ast_debug(3, "-REALTIME- peer expired registration. Name: %s. Realtime peer objects now %d\n", peer->name, rpeerobjs);
14186    }
14187 
14188    if (peer->selfdestruct ||
14189        ast_test_flag(&peer->flags[1], SIP_PAGE2_RTAUTOCLEAR)) {
14190       unlink_peer_from_tables(peer);
14191    } else if (!ast_sockaddr_isnull(&peer->addr)) {
14192       /* If we aren't self-destructing a temp_peer, we still need to unlink the peer
14193        * from the peers_by_ip table, otherwise we end up with multiple copies hanging
14194        * around each time a registration expires and the peer re-registers. */
14195       ao2_t_unlink(peers_by_ip, peer, "ao2_unlink of peer from peers_by_ip table");
14196    }
14197 
14198    /* Only clear the addr after we check for destruction.  The addr must remain
14199     * in order to unlink from the peers_by_ip container correctly */
14200    memset(&peer->addr, 0, sizeof(peer->addr));
14201 
14202    sip_unref_peer(peer, "removing peer ref for expire_register");
14203 
14204    return 0;
14205 }
14206 
14207 /*! \brief Poke peer (send qualify to check if peer is alive and well) */
14208 static int sip_poke_peer_s(const void *data)
14209 {
14210    struct sip_peer *peer = (struct sip_peer *)data;
14211    struct sip_peer *foundpeer;
14212 
14213    peer->pokeexpire = -1;
14214 
14215    foundpeer = ao2_find(peers, peer, OBJ_POINTER);
14216    if (!foundpeer) {
14217       sip_unref_peer(peer, "removing poke peer ref");
14218       return 0;
14219    } else if (foundpeer->name != peer->name) {
14220       sip_unref_peer(foundpeer, "removing above peer ref");
14221       sip_unref_peer(peer, "removing poke peer ref");
14222       return 0;
14223    }
14224 
14225    sip_unref_peer(foundpeer, "removing above peer ref");
14226    sip_poke_peer(peer, 0);
14227    sip_unref_peer(peer, "removing poke peer ref");
14228 
14229    return 0;
14230 }
14231 
14232 /*! \brief Get registration details from Asterisk DB */
14233 static void reg_source_db(struct sip_peer *peer)
14234 {
14235    char data[256];
14236    struct ast_sockaddr sa;
14237    int expire;
14238    char full_addr[128];
14239    AST_DECLARE_APP_ARGS(args,
14240       AST_APP_ARG(addr);
14241       AST_APP_ARG(port);
14242       AST_APP_ARG(expiry_str);
14243       AST_APP_ARG(username);
14244       AST_APP_ARG(contact);
14245    );
14246 
14247    /* If read-only RT backend, then refresh from local DB cache */
14248    if (peer->rt_fromcontact && sip_cfg.peer_rtupdate) {
14249       return;
14250    }
14251    if (ast_db_get("SIP/Registry", peer->name, data, sizeof(data))) {
14252       return;
14253    }
14254 
14255    AST_NONSTANDARD_RAW_ARGS(args, data, ':');
14256 
14257    snprintf(full_addr, sizeof(full_addr), "%s:%s", args.addr, args.port);
14258 
14259    if (!ast_sockaddr_parse(&sa, full_addr, 0)) {
14260       return;
14261    }
14262 
14263    if (args.expiry_str) {
14264       expire = atoi(args.expiry_str);
14265    } else {
14266       return;
14267    }
14268 
14269    if (args.username) {
14270       ast_string_field_set(peer, username, args.username);
14271    }
14272    if (args.contact) {
14273       ast_string_field_set(peer, fullcontact, args.contact);
14274    }
14275 
14276    ast_debug(2, "SIP Seeding peer from astdb: '%s' at %s@%s for %d\n",
14277        peer->name, peer->username, ast_sockaddr_stringify_host(&sa), expire);
14278 
14279    ast_sockaddr_copy(&peer->addr, &sa);
14280    if (sipsock < 0) {
14281       /* SIP isn't up yet, so schedule a poke only, pretty soon */
14282       AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched, ast_random() % 5000 + 1, sip_poke_peer_s, peer,
14283             sip_unref_peer(_data, "removing poke peer ref"),
14284             sip_unref_peer(peer, "removing poke peer ref"),
14285             sip_ref_peer(peer, "adding poke peer ref"));
14286    } else {
14287       sip_poke_peer(peer, 0);
14288    }
14289    AST_SCHED_REPLACE_UNREF(peer->expire, sched, (expire + 10) * 1000, expire_register, peer,
14290          sip_unref_peer(_data, "remove registration ref"),
14291          sip_unref_peer(peer, "remove registration ref"),
14292          sip_ref_peer(peer, "add registration ref"));
14293    register_peer_exten(peer, TRUE);
14294 }
14295 
14296 /*! \brief Save contact header for 200 OK on INVITE */
14297 static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req)
14298 {
14299    char contact[SIPBUFSIZE];
14300    char *c;
14301 
14302    /* Look for brackets */
14303    ast_copy_string(contact, sip_get_header(req, "Contact"), sizeof(contact));
14304    c = get_in_brackets(contact);
14305 
14306    /* Save full contact to call pvt for later bye or re-invite */
14307    ast_string_field_set(pvt, fullcontact, c);
14308 
14309    /* Save URI for later ACKs, BYE or RE-invites */
14310    ast_string_field_set(pvt, okcontacturi, c);
14311 
14312    /* We should return false for URI:s we can't handle,
14313       like tel:, mailto:,ldap: etc */
14314    return TRUE;      
14315 }
14316 
14317 /*! \brief parse uri in a way that allows semicolon stripping if legacy mode is enabled
14318  *
14319  * \note This calls parse_uri which has the unexpected property that passing more
14320  *       arguments results in more splitting. Most common is to leave out the pass
14321  *       argument, causing user to contain user:pass if available.
14322  */
14323 static int parse_uri_legacy_check(char *uri, const char *scheme, char **user, char **pass, char **hostport, char **transport)
14324 {
14325    int ret = parse_uri(uri, scheme, user, pass, hostport, transport);
14326    if (sip_cfg.legacy_useroption_parsing) { /* if legacy mode is active, strip semis from the user field */
14327       char *p;
14328       if ((p = strchr(uri, (int)';'))) {
14329          *p = '\0';
14330       }
14331    }
14332    return ret;
14333 }
14334 
14335 static int __set_address_from_contact(const char *fullcontact, struct ast_sockaddr *addr, int tcp)
14336 {
14337    char *hostport, *transport;
14338    char contact_buf[256];
14339    char *contact;
14340 
14341    /* Work on a copy */
14342    ast_copy_string(contact_buf, fullcontact, sizeof(contact_buf));
14343    contact = contact_buf;
14344 
14345    /* 
14346     * We have only the part in <brackets> here so we just need to parse a SIP URI.
14347     *
14348     * Note: The outbound proxy could be using UDP between the proxy and Asterisk.
14349     * We still need to be able to send to the remote agent through the proxy.
14350     */
14351 
14352    if (parse_uri_legacy_check(contact, "sip:,sips:", &contact, NULL, &hostport,
14353             &transport)) {
14354       ast_log(LOG_WARNING, "Invalid contact uri %s (missing sip: or sips:), attempting to use anyway\n", fullcontact);
14355    }
14356 
14357    /* XXX This could block for a long time XXX */
14358    /* We should only do this if it's a name, not an IP */
14359    /* \todo - if there's no PORT number in contact - we are required to check NAPTR/SRV records
14360       to find transport, port address and hostname. If there's a port number, we have to
14361       assume that the hostport part is a host name and only look for an A/AAAA record in DNS.
14362    */
14363 
14364    /* If we took in an invalid URI, hostport may not have been initialized */
14365    /* ast_sockaddr_resolve requires an initialized hostport string. */
14366    if (ast_strlen_zero(hostport)) {
14367       ast_log(LOG_WARNING, "Invalid URI: parse_uri failed to acquire hostport\n");
14368       return -1;
14369    }
14370 
14371    if (ast_sockaddr_resolve_first(addr, hostport, 0)) {
14372       ast_log(LOG_WARNING, "Invalid host name in Contact: (can't "
14373          "resolve in DNS) : '%s'\n", hostport);
14374       return -1;
14375    }
14376 
14377    /* set port */
14378    if (!ast_sockaddr_port(addr)) {
14379       ast_sockaddr_set_port(addr,
14380                   (get_transport_str2enum(transport) ==
14381                    SIP_TRANSPORT_TLS ||
14382                    !strncasecmp(fullcontact, "sips", 4)) ?
14383                   STANDARD_TLS_PORT : STANDARD_SIP_PORT);
14384    }
14385 
14386    return 0;
14387 }
14388 
14389 /*! \brief Change the other partys IP address based on given contact */
14390 static int set_address_from_contact(struct sip_pvt *pvt)
14391 {
14392    if (ast_test_flag(&pvt->flags[0], SIP_NAT_FORCE_RPORT)) {
14393       /* NAT: Don't trust the contact field.  Just use what they came to us
14394          with. */
14395       /*! \todo We need to save the TRANSPORT here too */
14396       pvt->sa = pvt->recv;
14397       return 0;
14398    }
14399 
14400    return __set_address_from_contact(pvt->fullcontact, &pvt->sa, pvt->socket.type == SIP_TRANSPORT_TLS ? 1 : 0);
14401 }
14402 
14403 /*! \brief Parse contact header and save registration (peer registration) */
14404 static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *peer, struct sip_request *req)
14405 {
14406    char contact[SIPBUFSIZE];
14407    char data[SIPBUFSIZE];
14408    const char *expires = sip_get_header(req, "Expires");
14409    int expire = atoi(expires);
14410    char *curi = NULL, *hostport = NULL, *transport = NULL;
14411    int transport_type;
14412    const char *useragent;
14413    struct ast_sockaddr oldsin, testsa;
14414    char *firstcuri = NULL;
14415    int start = 0;
14416    int wildcard_found = 0;
14417    int single_binding_found = 0;
14418 
14419    ast_copy_string(contact, __get_header(req, "Contact", &start), sizeof(contact));
14420 
14421    if (ast_strlen_zero(expires)) {  /* No expires header, try look in Contact: */
14422       char *s = strcasestr(contact, ";expires=");
14423       if (s) {
14424          expires = strsep(&s, ";"); /* trim ; and beyond */
14425          if (sscanf(expires + 9, "%30d", &expire) != 1) {
14426             expire = default_expiry;
14427          }
14428       } else {
14429          /* Nothing has been specified */
14430          expire = default_expiry;
14431       }
14432    }
14433 
14434    copy_socket_data(&pvt->socket, &req->socket);
14435 
14436    do {
14437       /* Look for brackets */
14438       curi = contact;
14439       if (strchr(contact, '<') == NULL)   /* No <, check for ; and strip it */
14440          strsep(&curi, ";");  /* This is Header options, not URI options */
14441       curi = get_in_brackets(contact);
14442       if (!firstcuri) {
14443          firstcuri = ast_strdupa(curi);
14444       }
14445 
14446       if (!strcasecmp(curi, "*")) {
14447          wildcard_found = 1;
14448       } else {
14449          single_binding_found = 1;
14450       }
14451 
14452       if (wildcard_found && (ast_strlen_zero(expires) || expire != 0 || single_binding_found)) {
14453          /* Contact header parameter "*" detected, so punt if: Expires header is missing,
14454           * Expires value is not zero, or another Contact header is present. */
14455          return PARSE_REGISTER_FAILED;
14456       }
14457 
14458       ast_copy_string(contact, __get_header(req, "Contact", &start), sizeof(contact));
14459    } while (!ast_strlen_zero(contact));
14460    curi = firstcuri;
14461 
14462    /* if they did not specify Contact: or Expires:, they are querying
14463       what we currently have stored as their contact address, so return
14464       it
14465    */
14466    if (ast_strlen_zero(curi) && ast_strlen_zero(expires)) {
14467       /* If we have an active registration, tell them when the registration is going to expire */
14468       if (peer->expire > -1 && !ast_strlen_zero(peer->fullcontact)) {
14469          pvt->expiry = ast_sched_when(sched, peer->expire);
14470       }
14471       return PARSE_REGISTER_QUERY;
14472    } else if (!strcasecmp(curi, "*") || !expire) { /* Unregister this peer */
14473       /* This means remove all registrations and return OK */
14474       AST_SCHED_DEL_UNREF(sched, peer->expire,
14475             sip_unref_peer(peer, "remove register expire ref"));
14476       ast_verb(3, "Unregistered SIP '%s'\n", peer->name);
14477       expire_register(sip_ref_peer(peer,"add ref for explicit expire_register"));
14478       return PARSE_REGISTER_UPDATE;
14479    }
14480 
14481    /* Store whatever we got as a contact from the client */
14482    ast_string_field_set(peer, fullcontact, curi);
14483 
14484    /* For the 200 OK, we should use the received contact */
14485    ast_string_field_build(pvt, our_contact, "<%s>", curi);
14486 
14487    /* Make sure it's a SIP URL */
14488    if (ast_strlen_zero(curi) || parse_uri_legacy_check(curi, "sip:,sips:", &curi, NULL, &hostport, &transport)) {
14489       ast_log(LOG_NOTICE, "Not a valid SIP contact (missing sip:/sips:) trying to use anyway\n");
14490    }
14491 
14492    /* handle the transport type specified in Contact header. */
14493    if (!(transport_type = get_transport_str2enum(transport))) {
14494       transport_type = pvt->socket.type;
14495    }
14496 
14497    /* if the peer's socket type is different than the Registration
14498     * transport type, change it.  If it got this far, it is a
14499     * supported type, but check just in case */
14500    if ((peer->socket.type != transport_type) && (peer->transports & transport_type)) {
14501       set_socket_transport(&peer->socket, transport_type);
14502    }
14503 
14504    oldsin = peer->addr;
14505 
14506    /* If we were already linked into the peers_by_ip container unlink ourselves so nobody can find us */
14507    if (!ast_sockaddr_isnull(&peer->addr) && (!peer->is_realtime || ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS))) {
14508       ao2_t_unlink(peers_by_ip, peer, "ao2_unlink of peer from peers_by_ip table");
14509    }
14510 
14511    if (!ast_test_flag(&peer->flags[0], SIP_NAT_FORCE_RPORT) && !ast_test_flag(&peer->flags[0], SIP_NAT_RPORT_PRESENT)) {
14512        /* use the data provided in the Contact header for call routing */
14513       ast_debug(1, "Store REGISTER's Contact header for call routing.\n");
14514       /* XXX This could block for a long time XXX */
14515       /*! \todo Check NAPTR/SRV if we have not got a port in the URI */
14516       if (ast_sockaddr_resolve_first(&testsa, hostport, 0)) {
14517          ast_log(LOG_WARNING, "Invalid hostport '%s'\n", hostport);
14518          ast_string_field_set(peer, fullcontact, "");
14519          ast_string_field_set(pvt, our_contact, "");
14520          return PARSE_REGISTER_FAILED;
14521       }
14522 
14523       /* If we have a port number in the given URI, make sure we do remember to not check for NAPTR/SRV records.
14524          The hostport part is actually a host. */
14525       peer->portinuri = ast_sockaddr_port(&testsa) ? TRUE : FALSE;
14526 
14527       if (!ast_sockaddr_port(&testsa)) {
14528          ast_sockaddr_set_port(&testsa, default_sip_port(transport_type));
14529       }
14530 
14531       ast_sockaddr_copy(&peer->addr, &testsa);
14532    } else {
14533       /* Don't trust the contact field.  Just use what they came to us
14534          with */
14535       ast_debug(1, "Store REGISTER's src-IP:port for call routing.\n");
14536       peer->addr = pvt->recv;
14537    }
14538 
14539    /* Check that they're allowed to register at this IP */
14540    if (ast_apply_ha(sip_cfg.contact_ha, &peer->addr) != AST_SENSE_ALLOW ||
14541          ast_apply_ha(peer->contactha, &peer->addr) != AST_SENSE_ALLOW) {
14542       ast_log(LOG_WARNING, "Domain '%s' disallowed by contact ACL (violating IP %s)\n", hostport,
14543          ast_sockaddr_stringify_addr(&testsa));
14544       ast_string_field_set(peer, fullcontact, "");
14545       ast_string_field_set(pvt, our_contact, "");
14546       return PARSE_REGISTER_DENIED;
14547    }
14548 
14549    /* if the Contact header information copied into peer->addr matches the
14550     * received address, and the transport types are the same, then copy socket
14551     * data into the peer struct */
14552    if ((peer->socket.type == pvt->socket.type) &&
14553       !ast_sockaddr_cmp(&peer->addr, &pvt->recv)) {
14554       copy_socket_data(&peer->socket, &pvt->socket);
14555    }
14556 
14557    /* Now that our address has been updated put ourselves back into the container for lookups */
14558    if (!peer->is_realtime || ast_test_flag(&peer->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
14559       ao2_t_link(peers_by_ip, peer, "ao2_link into peers_by_ip table");
14560    }
14561 
14562    /* Save SIP options profile */
14563    peer->sipoptions = pvt->sipoptions;
14564 
14565    if (!ast_strlen_zero(curi) && ast_strlen_zero(peer->username)) {
14566       ast_string_field_set(peer, username, curi);
14567    }
14568 
14569    AST_SCHED_DEL_UNREF(sched, peer->expire,
14570          sip_unref_peer(peer, "remove register expire ref"));
14571 
14572    if (expire > max_expiry) {
14573       expire = max_expiry;
14574    }
14575    if (expire < min_expiry) {
14576       expire = min_expiry;
14577    }
14578    if (peer->is_realtime && !ast_test_flag(&peer->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
14579       peer->expire = -1;
14580    } else {
14581       peer->expire = ast_sched_add(sched, (expire + 10) * 1000, expire_register,
14582             sip_ref_peer(peer, "add registration ref"));
14583       if (peer->expire == -1) {
14584          sip_unref_peer(peer, "remote registration ref");
14585       }
14586    }
14587    pvt->expiry = expire;
14588    snprintf(data, sizeof(data), "%s:%d:%s:%s", ast_sockaddr_stringify(&peer->addr),
14589        expire, peer->username, peer->fullcontact);
14590    /* We might not immediately be able to reconnect via TCP, but try caching it anyhow */
14591    if (!peer->rt_fromcontact || !sip_cfg.peer_rtupdate)
14592       ast_db_put("SIP/Registry", peer->name, data);
14593    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));
14594 
14595    /* Is this a new IP address for us? */
14596    if (ast_sockaddr_cmp(&peer->addr, &oldsin)) {
14597       ast_verb(3, "Registered SIP '%s' at %s\n", peer->name,
14598          ast_sockaddr_stringify(&peer->addr));
14599    }
14600    sip_poke_peer(peer, 0);
14601    register_peer_exten(peer, 1);
14602 
14603    /* Save User agent */
14604    useragent = sip_get_header(req, "User-Agent");
14605    if (strcasecmp(useragent, peer->useragent)) {
14606       ast_string_field_set(peer, useragent, useragent);
14607       ast_verb(4, "Saved useragent \"%s\" for peer %s\n", peer->useragent, peer->name);
14608    }
14609    return PARSE_REGISTER_UPDATE;
14610 }
14611 
14612 /*! \brief Remove route from route list */
14613 static void free_old_route(struct sip_route *route)
14614 {
14615    struct sip_route *next;
14616 
14617    while (route) {
14618       next = route->next;
14619       ast_free(route);
14620       route = next;
14621    }
14622 }
14623 
14624 /*! \brief List all routes - mostly for debugging */
14625 static void list_route(struct sip_route *route)
14626 {
14627    if (!route) {
14628       ast_verbose("list_route: no route\n");
14629    } else {
14630       for (;route; route = route->next)
14631          ast_verbose("list_route: hop: <%s>\n", route->hop);
14632    }
14633 }
14634 
14635 /*! \brief Build route list from Record-Route header */
14636 static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards)
14637 {
14638    struct sip_route *thishop, *head, *tail;
14639    int start = 0;
14640    int len;
14641    const char *rr, *c;
14642 
14643    /* Once a persistent route is set, don't fool with it */
14644    if (p->route && p->route_persistent) {
14645       ast_debug(1, "build_route: Retaining previous route: <%s>\n", p->route->hop);
14646       return;
14647    }
14648 
14649    if (p->route) {
14650       free_old_route(p->route);
14651       p->route = NULL;
14652    }
14653 
14654    /* We only want to create the route set the first time this is called */
14655    p->route_persistent = 1;
14656 
14657    /* Build a tailq, then assign it to p->route when done.
14658     * If backwards, we add entries from the head so they end up
14659     * in reverse order. However, we do need to maintain a correct
14660     * tail pointer because the contact is always at the end.
14661     */
14662    head = NULL;
14663    tail = head;
14664    /* 1st we pass through all the hops in any Record-Route headers */
14665    for (;;) {
14666       /* Each Record-Route header */
14667       char rr_copy[256];
14668       char *rr_copy_ptr;
14669       char *rr_iter;
14670       rr = __get_header(req, "Record-Route", &start);
14671       if (*rr == '\0') {
14672          break;
14673       }
14674       ast_copy_string(rr_copy, rr, sizeof(rr_copy));
14675       rr_copy_ptr = rr_copy;
14676       while ((rr_iter = strsep(&rr_copy_ptr, ","))) { /* Each route entry */
14677          char *uri = get_in_brackets(rr_iter);
14678          len = strlen(uri) + 1;
14679          /* Make a struct route */
14680          if ((thishop = ast_malloc(sizeof(*thishop) + len))) {
14681             /* ast_calloc is not needed because all fields are initialized in this block */
14682             ast_copy_string(thishop->hop, uri, len);
14683             ast_debug(2, "build_route: Record-Route hop: <%s>\n", thishop->hop);
14684             /* Link in */
14685             if (backwards) {
14686                /* Link in at head so they end up in reverse order */
14687                thishop->next = head;
14688                head = thishop;
14689                /* If this was the first then it'll be the tail */
14690                if (!tail) {
14691                   tail = thishop;
14692                }
14693             } else {
14694                thishop->next = NULL;
14695                /* Link in at the end */
14696                if (tail) {
14697                   tail->next = thishop;
14698                } else {
14699                   head = thishop;
14700                }
14701                tail = thishop;
14702             }
14703          }
14704       }
14705    }
14706 
14707    /* Only append the contact if we are dealing with a strict router */
14708    if (!head || (!ast_strlen_zero(head->hop) && strstr(head->hop, ";lr") == NULL) ) {
14709       /* 2nd append the Contact: if there is one */
14710       /* Can be multiple Contact headers, comma separated values - we just take the first */
14711       char *contact = ast_strdupa(sip_get_header(req, "Contact"));
14712       if (!ast_strlen_zero(contact)) {
14713          ast_debug(2, "build_route: Contact hop: %s\n", contact);
14714          /* Look for <: delimited address */
14715          c = get_in_brackets(contact);
14716          len = strlen(c) + 1;
14717          if ((thishop = ast_malloc(sizeof(*thishop) + len))) {
14718             /* ast_calloc is not needed because all fields are initialized in this block */
14719             ast_copy_string(thishop->hop, c, len);
14720             thishop->next = NULL;
14721             /* Goes at the end */
14722             if (tail) {
14723                tail->next = thishop;
14724             } else {
14725                head = thishop;
14726             }
14727          }
14728       }
14729    }
14730 
14731    /* Store as new route */
14732    p->route = head;
14733 
14734    /* For debugging dump what we ended up with */
14735    if (sip_debug_test_pvt(p)) {
14736       list_route(p->route);
14737    }
14738 }
14739 
14740 /*! \brief builds the sip_pvt's randdata field which is used for the nonce
14741  *  challenge.  When forceupdate is not set, the nonce is only updated if
14742  *  the current one is stale.  In this case, a stalenonce is one which
14743  *  has already received a response, if a nonce has not received a response
14744  *  it is not always necessary or beneficial to create a new one. */
14745 
14746 static void set_nonce_randdata(struct sip_pvt *p, int forceupdate)
14747 {
14748    if (p->stalenonce || forceupdate || ast_strlen_zero(p->randdata)) {
14749       ast_string_field_build(p, randdata, "%08lx", ast_random()); /* Create nonce for challenge */
14750       p->stalenonce = 0;
14751    }
14752 }
14753 
14754 /*! \brief Takes the digest response and parses it */
14755 void sip_digest_parser(char *c, struct digestkeys *keys)
14756 {
14757         struct digestkeys *i = i;
14758 
14759         while(c && *(c = ast_skip_blanks(c)) ) { /* lookup for keys */
14760                 for (i = keys; i->key != NULL; i++) {
14761                         const char *separator = ",";    /* default */
14762 
14763                         if (strncasecmp(c, i->key, strlen(i->key)) != 0) {
14764                                 continue;
14765                         }
14766                         /* Found. Skip keyword, take text in quotes or up to the separator. */
14767                         c += strlen(i->key);
14768                         if (*c == '"') { /* in quotes. Skip first and look for last */
14769                                 c++;
14770                                 separator = "\"";
14771                         }
14772                         i->s = c;
14773                         strsep(&c, separator);
14774                         break;
14775                 }
14776                 if (i->key == NULL) { /* not found, jump after space or comma */
14777          strsep(&c, " ,");
14778       }
14779         }
14780 }
14781 
14782 /*! \brief  Check user authorization from peer definition
14783    Some actions, like REGISTER and INVITEs from peers require
14784    authentication (if peer have secret set)
14785     \return 0 on success, non-zero on error
14786 */
14787 static enum check_auth_result check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
14788                 const char *secret, const char *md5secret, int sipmethod,
14789                 const char *uri, enum xmittype reliable, int ignore)
14790 {
14791    const char *response;
14792    char *reqheader, *respheader;
14793    const char *authtoken;
14794    char a1_hash[256];
14795    char resp_hash[256]="";
14796    char *c;
14797    int  wrongnonce = FALSE;
14798    int  good_response;
14799    const char *usednonce = p->randdata;
14800    struct ast_str *buf;
14801    int res;
14802 
14803    /* table of recognised keywords, and their value in the digest */
14804    struct digestkeys keys[] = {
14805       [K_RESP] = { "response=", "" },
14806       [K_URI] = { "uri=", "" },
14807       [K_USER] = { "username=", "" },
14808       [K_NONCE] = { "nonce=", "" },
14809       [K_LAST] = { NULL, NULL}
14810    };
14811 
14812    /* Always OK if no secret */
14813    if (ast_strlen_zero(secret) && ast_strlen_zero(md5secret)) {
14814       return AUTH_SUCCESSFUL;
14815    }
14816 
14817    /* Always auth with WWW-auth since we're NOT a proxy */
14818    /* Using proxy-auth in a B2BUA may block proxy authorization in the same transaction */
14819    response = "401 Unauthorized";
14820 
14821    /*
14822     * Note the apparent swap of arguments below, compared to other
14823     * usages of sip_auth_headers().
14824     */
14825    sip_auth_headers(WWW_AUTH, &respheader, &reqheader);
14826 
14827    authtoken =  sip_get_header(req, reqheader); 
14828    if (ignore && !ast_strlen_zero(p->randdata) && ast_strlen_zero(authtoken)) {
14829       /* This is a retransmitted invite/register/etc, don't reconstruct authentication
14830          information */
14831       if (!reliable) {
14832          /* Resend message if this was NOT a reliable delivery.   Otherwise the
14833             retransmission should get it */
14834          transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, 0);
14835          /* Schedule auto destroy in 32 seconds (according to RFC 3261) */
14836          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14837       }
14838       return AUTH_CHALLENGE_SENT;
14839    } else if (ast_strlen_zero(p->randdata) || ast_strlen_zero(authtoken)) {
14840       /* We have no auth, so issue challenge and request authentication */
14841       set_nonce_randdata(p, 1); /* Create nonce for challenge */
14842       transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, 0);
14843       /* Schedule auto destroy in 32 seconds */
14844       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14845       return AUTH_CHALLENGE_SENT;
14846    }
14847 
14848    /* --- We have auth, so check it */
14849 
14850    /* Whoever came up with the authentication section of SIP can suck my %&#$&* for not putting
14851       an example in the spec of just what it is you're doing a hash on. */
14852 
14853    if (!(buf = ast_str_thread_get(&check_auth_buf, CHECK_AUTH_BUF_INITLEN))) {
14854       return AUTH_SECRET_FAILED; /*! XXX \todo need a better return code here */
14855    }
14856 
14857    /* Make a copy of the response and parse it */
14858    res = ast_str_set(&buf, 0, "%s", authtoken);
14859 
14860    if (res == AST_DYNSTR_BUILD_FAILED) {
14861       return AUTH_SECRET_FAILED; /*! XXX \todo need a better return code here */
14862    }
14863 
14864    c = buf->str;
14865 
14866    sip_digest_parser(c, keys);
14867 
14868    /* Verify that digest username matches  the username we auth as */
14869    if (strcmp(username, keys[K_USER].s)) {
14870       ast_log(LOG_WARNING, "username mismatch, have <%s>, digest has <%s>\n",
14871          username, keys[K_USER].s);
14872       /* Oops, we're trying something here */
14873       return AUTH_USERNAME_MISMATCH;
14874    }
14875 
14876    /* Verify nonce from request matches our nonce, and the nonce has not already been responded to.
14877     * If this check fails, send 401 with new nonce */
14878    if (strcasecmp(p->randdata, keys[K_NONCE].s) || p->stalenonce) { /* XXX it was 'n'casecmp ? */
14879       wrongnonce = TRUE;
14880       usednonce = keys[K_NONCE].s;
14881    } else {
14882       p->stalenonce = 1; /* now, since the nonce has a response, mark it as stale so it can't be sent or responded to again */
14883    }
14884 
14885    if (!ast_strlen_zero(md5secret)) {
14886       ast_copy_string(a1_hash, md5secret, sizeof(a1_hash));
14887    } else {
14888       char a1[256];
14889 
14890       snprintf(a1, sizeof(a1), "%s:%s:%s", username, p->realm, secret);
14891       ast_md5_hash(a1_hash, a1);
14892    }
14893 
14894    /* compute the expected response to compare with what we received */
14895    {
14896       char a2[256];
14897       char a2_hash[256];
14898       char resp[256];
14899 
14900       snprintf(a2, sizeof(a2), "%s:%s", sip_methods[sipmethod].text,
14901             S_OR(keys[K_URI].s, uri));
14902       ast_md5_hash(a2_hash, a2);
14903       snprintf(resp, sizeof(resp), "%s:%s:%s", a1_hash, usednonce, a2_hash);
14904       ast_md5_hash(resp_hash, resp);
14905    }
14906 
14907    good_response = keys[K_RESP].s &&
14908          !strncasecmp(keys[K_RESP].s, resp_hash, strlen(resp_hash));
14909    if (wrongnonce) {
14910       if (good_response) {
14911          if (sipdebug)
14912             ast_log(LOG_NOTICE, "Correct auth, but based on stale nonce received from '%s'\n", sip_get_header(req, "From"));
14913          /* We got working auth token, based on stale nonce . */
14914          set_nonce_randdata(p, 0);
14915          transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, TRUE);
14916       } else {
14917          /* Everything was wrong, so give the device one more try with a new challenge */
14918          if (!req->ignore) {
14919             if (sipdebug) {
14920                ast_log(LOG_NOTICE, "Bad authentication received from '%s'\n", sip_get_header(req, "To"));
14921             }
14922             set_nonce_randdata(p, 1);
14923          } else {
14924             if (sipdebug) {
14925                ast_log(LOG_NOTICE, "Duplicate authentication received from '%s'\n", sip_get_header(req, "To"));
14926             }
14927          }
14928          transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, FALSE);
14929       }
14930 
14931       /* Schedule auto destroy in 32 seconds */
14932       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14933       return AUTH_CHALLENGE_SENT;
14934    }
14935    if (good_response) {
14936       append_history(p, "AuthOK", "Auth challenge successful for %s", username);
14937       return AUTH_SUCCESSFUL;
14938    }
14939 
14940    /* Ok, we have a bad username/secret pair */
14941    /* Tell the UAS not to re-send this authentication data, because
14942       it will continue to fail
14943    */
14944 
14945    return AUTH_SECRET_FAILED;
14946 }
14947 
14948 /*! \brief Change onhold state of a peer using a pvt structure */
14949 static void sip_peer_hold(struct sip_pvt *p, int hold)
14950 {
14951    if (!p->relatedpeer) {
14952       return;
14953    }
14954 
14955    /* If they put someone on hold, increment the value... otherwise decrement it */
14956    ast_atomic_fetchadd_int(&p->relatedpeer->onHold, (hold ? +1 : -1));
14957 
14958    /* Request device state update */
14959    ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", p->relatedpeer->name);
14960    
14961    return;
14962 }
14963 
14964 /*! \brief Receive MWI events that we have subscribed to */
14965 static void mwi_event_cb(const struct ast_event *event, void *userdata)
14966 {
14967    struct sip_peer *peer = userdata;
14968 
14969    sip_send_mwi_to_peer(peer, 0);
14970 }
14971 
14972 static void network_change_event_subscribe(void)
14973 {
14974    if (!network_change_event_subscription) {
14975       network_change_event_subscription = ast_event_subscribe(AST_EVENT_NETWORK_CHANGE,
14976          network_change_event_cb, "SIP Network Change", NULL, AST_EVENT_IE_END);
14977    }
14978 }
14979 
14980 static void network_change_event_unsubscribe(void)
14981 {
14982    if (network_change_event_subscription) {
14983       network_change_event_subscription = ast_event_unsubscribe(network_change_event_subscription);
14984    }
14985 }
14986 
14987 static int network_change_event_sched_cb(const void *data)
14988 {
14989    network_change_event_sched_id = -1;
14990    sip_send_all_registers();
14991    sip_send_all_mwi_subscriptions();
14992    return 0;
14993 }
14994 
14995 static void network_change_event_cb(const struct ast_event *event, void *userdata)
14996 {
14997    ast_debug(1, "SIP, got a network change event, renewing all SIP registrations.\n");
14998    if (network_change_event_sched_id == -1) {
14999       network_change_event_sched_id = ast_sched_add(sched, 1000, network_change_event_sched_cb, NULL);
15000    }
15001 }
15002 
15003 static void cb_extensionstate_destroy(int id, void *data)
15004 {
15005    struct sip_pvt *p = data;
15006 
15007    dialog_unref(p, "the extensionstate containing this dialog ptr was destroyed");
15008 }
15009 
15010 /*! \brief Callback for the devicestate notification (SUBSCRIBE) support subsystem
15011 \note If you add an "hint" priority to the extension in the dial plan,
15012    you will get notifications on device state changes */
15013 static int cb_extensionstate(const char *context, const char *exten, enum ast_extension_states state, void *data)
15014 {
15015    struct sip_pvt *p = data;
15016 
15017    sip_pvt_lock(p);
15018 
15019    switch(state) {
15020    case AST_EXTENSION_DEACTIVATED:  /* Retry after a while */
15021    case AST_EXTENSION_REMOVED:   /* Extension is gone */
15022       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);  /* Delete subscription in 32 secs */
15023       ast_verb(2, "Extension state: Watcher for hint %s %s. Notify User %s\n", exten, state == AST_EXTENSION_DEACTIVATED ? "deactivated" : "removed", p->username);
15024       p->subscribed = NONE;
15025       append_history(p, "Subscribestatus", "%s", state == AST_EXTENSION_REMOVED ? "HintRemoved" : "Deactivated");
15026       break;
15027    default: /* Tell user */
15028       p->laststate = state;
15029       break;
15030    }
15031    if (p->subscribed != NONE) {  /* Only send state NOTIFY if we know the format */
15032       if (!p->pendinginvite) {
15033          transmit_state_notify(p, state, 1, FALSE);
15034       } else {
15035          /* We already have a NOTIFY sent that is not answered. Queue the state up.
15036             if many state changes happen meanwhile, we will only send a notification of the last one */
15037          ast_set_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE);
15038       }
15039    }
15040    ast_verb(2, "Extension Changed %s[%s] new state %s for Notify User %s %s\n", exten, context, ast_extension_state2str(state), p->username,
15041          ast_test_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE) ? "(queued)" : "");
15042 
15043    sip_pvt_unlock(p);
15044 
15045    return 0;
15046 }
15047 
15048 /*! \brief Send a fake 401 Unauthorized response when the administrator
15049   wants to hide the names of local devices  from fishers
15050  */
15051 static void transmit_fake_auth_response(struct sip_pvt *p, int sipmethod, struct sip_request *req, enum xmittype reliable)
15052 {
15053    /* We have to emulate EXACTLY what we'd get with a good peer
15054     * and a bad password, or else we leak information. */
15055    const char *response = "407 Proxy Authentication Required";
15056    const char *reqheader = "Proxy-Authorization";
15057    const char *respheader = "Proxy-Authenticate";
15058    const char *authtoken;
15059    struct ast_str *buf;
15060    char *c;
15061 
15062    /* table of recognised keywords, and their value in the digest */
15063    enum keys { K_NONCE, K_LAST };
15064    struct x {
15065       const char *key;
15066       const char *s;
15067    } *i, keys[] = {
15068       [K_NONCE] = { "nonce=", "" },
15069       [K_LAST] = { NULL, NULL}
15070    };
15071 
15072    if (sipmethod == SIP_REGISTER || sipmethod == SIP_SUBSCRIBE) {
15073       response = "401 Unauthorized";
15074       reqheader = "Authorization";
15075       respheader = "WWW-Authenticate";
15076    }
15077    authtoken = sip_get_header(req, reqheader);
15078    if (req->ignore && !ast_strlen_zero(p->randdata) && ast_strlen_zero(authtoken)) {
15079       /* This is a retransmitted invite/register/etc, don't reconstruct authentication
15080        * information */
15081       transmit_response_with_auth(p, response, req, p->randdata, 0, respheader, 0);
15082       /* Schedule auto destroy in 32 seconds (according to RFC 3261) */
15083       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
15084       return;
15085    } else if (ast_strlen_zero(p->randdata) || ast_strlen_zero(authtoken)) {
15086       /* We have no auth, so issue challenge and request authentication */
15087       set_nonce_randdata(p, 1);
15088       transmit_response_with_auth(p, response, req, p->randdata, 0, respheader, 0);
15089       /* Schedule auto destroy in 32 seconds */
15090       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
15091       return;
15092    }
15093 
15094    if (!(buf = ast_str_thread_get(&check_auth_buf, CHECK_AUTH_BUF_INITLEN))) {
15095       transmit_response(p, "403 Forbidden (Bad auth)", &p->initreq);
15096       return;
15097    }
15098 
15099    /* Make a copy of the response and parse it */
15100    if (ast_str_set(&buf, 0, "%s", authtoken) == AST_DYNSTR_BUILD_FAILED) {
15101       transmit_response(p, "403 Forbidden (Bad auth)", &p->initreq);
15102       return;
15103    }
15104 
15105    c = buf->str;
15106 
15107    while (c && *(c = ast_skip_blanks(c))) { /* lookup for keys */
15108       for (i = keys; i->key != NULL; i++) {
15109          const char *separator = ",";  /* default */
15110 
15111          if (strncasecmp(c, i->key, strlen(i->key)) != 0) {
15112             continue;
15113          }
15114          /* Found. Skip keyword, take text in quotes or up to the separator. */
15115          c += strlen(i->key);
15116          if (*c == '"') { /* in quotes. Skip first and look for last */
15117             c++;
15118             separator = "\"";
15119          }
15120          i->s = c;
15121          strsep(&c, separator);
15122          break;
15123       }
15124       if (i->key == NULL) { /* not found, jump after space or comma */
15125          strsep(&c, " ,");
15126       }
15127    }
15128 
15129    /* Verify nonce from request matches our nonce.  If not, send 401 with new nonce */
15130    if (strcasecmp(p->randdata, keys[K_NONCE].s)) {
15131       if (!req->ignore) {
15132          set_nonce_randdata(p, 1);
15133       }
15134       transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, FALSE);
15135 
15136       /* Schedule auto destroy in 32 seconds */
15137       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
15138    } else {
15139       transmit_response(p, "403 Forbidden (Bad auth)", &p->initreq);
15140    }
15141 }
15142 
15143 /*!
15144  * Terminate the uri at the first ';' or space.
15145  * Technically we should ignore escaped space per RFC3261 (19.1.1 etc)
15146  * but don't do it for the time being. Remember the uri format is:
15147  * (User-parameters was added after RFC 3261)
15148  *\verbatim
15149  *
15150  * sip:user:password;user-parameters@host:port;uri-parameters?headers
15151  * sips:user:password;user-parameters@host:port;uri-parameters?headers
15152  *
15153  *\endverbatim
15154  * \todo As this function does not support user-parameters, it's considered broken
15155  * and needs fixing.
15156  */
15157 static char *terminate_uri(char *uri)
15158 {
15159    char *t = uri;
15160    while (*t && *t > ' ' && *t != ';') {
15161       t++;
15162    }
15163    *t = '\0';
15164    return uri;
15165 }
15166 
15167 /*! \brief Terminate a host:port at the ':'
15168  * \param hostport The address of the hostport string
15169  *
15170  * \note In the case of a bracket-enclosed IPv6 address, the hostport variable
15171  * will contain the non-bracketed host as a result of calling this function.
15172  */
15173 static void extract_host_from_hostport(char **hostport)
15174 {
15175    char *dont_care;
15176    ast_sockaddr_split_hostport(*hostport, hostport, &dont_care, PARSE_PORT_IGNORE);
15177 }
15178 
15179 /*! \brief Verify registration of user
15180    - Registration is done in several steps, first a REGISTER without auth
15181      to get a challenge (nonce) then a second one with auth
15182    - Registration requests are only matched with peers that are marked as "dynamic"
15183  */
15184 static enum check_auth_result register_verify(struct sip_pvt *p, struct ast_sockaddr *addr,
15185                      struct sip_request *req, const char *uri)
15186 {
15187    enum check_auth_result res = AUTH_NOT_FOUND;
15188    struct sip_peer *peer;
15189    char tmp[256];
15190    char *c, *name, *unused_password, *domain;
15191    char *uri2 = ast_strdupa(uri);
15192 
15193    terminate_uri(uri2);
15194 
15195    ast_copy_string(tmp, sip_get_header(req, "To"), sizeof(tmp));
15196 
15197    c = get_in_brackets(tmp);
15198    c = remove_uri_parameters(c);
15199 
15200    if (parse_uri_legacy_check(c, "sip:,sips:", &name, &unused_password, &domain, NULL)) {
15201       ast_log(LOG_NOTICE, "Invalid to address: '%s' from %s (missing sip:) trying to use anyway...\n", c, ast_sockaddr_stringify_addr(addr));
15202       return -1;
15203    }
15204 
15205    SIP_PEDANTIC_DECODE(name);
15206    SIP_PEDANTIC_DECODE(domain);
15207 
15208    extract_host_from_hostport(&domain);
15209 
15210    if (ast_strlen_zero(domain)) {
15211       /* <sip:name@[EMPTY]>, never good */
15212       transmit_response(p, "404 Not found", &p->initreq);
15213       return AUTH_UNKNOWN_DOMAIN;
15214    }
15215 
15216    if (ast_strlen_zero(name)) {
15217       /* <sip:[EMPTY][@]hostport>, unsure whether valid for
15218        * registration. RFC 3261, 10.2 states:
15219        * "The To header field and the Request-URI field typically
15220        * differ, as the former contains a user name."
15221        * But, Asterisk has always treated the domain-only uri as a
15222        * username: we allow admins to create accounts described by
15223        * domain name. */
15224       name = domain;
15225    }
15226 
15227    /* This here differs from 1.4 and 1.6: the domain matching ACLs were
15228     * skipped if it was a domain-only URI (used as username). Here we treat
15229     * <sip:hostport> as <sip:host@hostport> and won't forget to test the
15230     * domain ACLs against host. */
15231    if (!AST_LIST_EMPTY(&domain_list)) {
15232       if (!check_sip_domain(domain, NULL, 0)) {
15233          if (sip_cfg.alwaysauthreject) {
15234             transmit_fake_auth_response(p, SIP_REGISTER, &p->initreq, XMIT_UNRELIABLE);
15235          } else {
15236             transmit_response(p, "404 Not found (unknown domain)", &p->initreq);
15237          }
15238          return AUTH_UNKNOWN_DOMAIN;
15239       }
15240    }
15241 
15242    ast_string_field_set(p, exten, name);
15243    build_contact(p);
15244    if (req->ignore) {
15245       /* Expires is a special case, where we only want to load the peer if this isn't a deregistration attempt */
15246       const char *expires = sip_get_header(req, "Expires");
15247       int expire = atoi(expires);
15248 
15249       if (ast_strlen_zero(expires)) { /* No expires header; look in Contact */
15250          if ((expires = strcasestr(sip_get_header(req, "Contact"), ";expires="))) {
15251             expire = atoi(expires + 9);
15252          }
15253       }
15254       if (!ast_strlen_zero(expires) && expire == 0) {
15255          transmit_response_with_date(p, "200 OK", req);
15256          return 0;
15257       }
15258    }
15259    peer = sip_find_peer(name, NULL, TRUE, FINDPEERS, FALSE, 0);
15260 
15261    if (!(peer && ast_apply_ha(peer->ha, addr))) {
15262       /* Peer fails ACL check */
15263       if (peer) {
15264          sip_unref_peer(peer, "register_verify: sip_unref_peer: from sip_find_peer operation");
15265          peer = NULL;
15266          res = AUTH_ACL_FAILED;
15267       } else {
15268          res = AUTH_NOT_FOUND;
15269       }
15270    }
15271 
15272    if (peer) {
15273       ao2_lock(peer);
15274       if (!peer->host_dynamic) {
15275          ast_log(LOG_ERROR, "Peer '%s' is trying to register, but not configured as host=dynamic\n", peer->name);
15276          res = AUTH_PEER_NOT_DYNAMIC;
15277       } else {
15278          if (ast_test_flag(&peer->flags[2], SIP_PAGE3_NAT_AUTO_RPORT)) {
15279             if (p->natdetected) {
15280                ast_set_flag(&peer->flags[0], SIP_NAT_FORCE_RPORT);
15281             } else {
15282                ast_clear_flag(&peer->flags[0], SIP_NAT_FORCE_RPORT);
15283             }
15284          }
15285          if (ast_test_flag(&peer->flags[2], SIP_PAGE3_NAT_AUTO_COMEDIA)) {
15286             if (p->natdetected) {
15287                ast_set_flag(&peer->flags[1], SIP_PAGE2_SYMMETRICRTP);
15288             } else {
15289                ast_clear_flag(&peer->flags[1], SIP_PAGE2_SYMMETRICRTP);
15290             }
15291          }
15292 
15293          ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_NAT_FORCE_RPORT);
15294          if (!(res = check_auth(p, req, peer->name, peer->secret, peer->md5secret, SIP_REGISTER, uri2, XMIT_UNRELIABLE, req->ignore))) {
15295             if (sip_cancel_destroy(p))
15296                ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
15297 
15298             if (check_request_transport(peer, req)) {
15299                ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
15300                transmit_response_with_date(p, "403 Forbidden", req);
15301                res = AUTH_BAD_TRANSPORT;
15302             } else {
15303 
15304                /* We have a successful registration attempt with proper authentication,
15305                now, update the peer */
15306                switch (parse_register_contact(p, peer, req)) {
15307                case PARSE_REGISTER_DENIED:
15308                   ast_log(LOG_WARNING, "Registration denied because of contact ACL\n");
15309                   transmit_response_with_date(p, "603 Denied", req);
15310                   res = 0;
15311                   break;
15312                case PARSE_REGISTER_FAILED:
15313                   ast_log(LOG_WARNING, "Failed to parse contact info\n");
15314                   transmit_response_with_date(p, "400 Bad Request", req);
15315                   res = 0;
15316                   break;
15317                case PARSE_REGISTER_QUERY:
15318                   ast_string_field_set(p, fullcontact, peer->fullcontact);
15319                   transmit_response_with_date(p, "200 OK", req);
15320                   res = 0;
15321                   break;
15322                case PARSE_REGISTER_UPDATE:
15323                   ast_string_field_set(p, fullcontact, peer->fullcontact);
15324                   update_peer(peer, p->expiry);
15325                   /* Say OK and ask subsystem to retransmit msg counter */
15326                   transmit_response_with_date(p, "200 OK", req);
15327                   res = 0;
15328                   break;
15329                }
15330             }
15331 
15332          }
15333       }
15334       ao2_unlock(peer);
15335    }
15336    if (!peer && sip_cfg.autocreatepeer != AUTOPEERS_DISABLED) {
15337       /* Create peer if we have autocreate mode enabled */
15338       peer = temp_peer(name);
15339       if (peer) {
15340          ao2_t_link(peers, peer, "link peer into peer table");
15341          if (!ast_sockaddr_isnull(&peer->addr)) {
15342             ao2_t_link(peers_by_ip, peer, "link peer into peers-by-ip table");
15343          }
15344          ao2_lock(peer);
15345          if (sip_cancel_destroy(p))
15346             ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
15347          switch (parse_register_contact(p, peer, req)) {
15348          case PARSE_REGISTER_DENIED:
15349             ast_log(LOG_WARNING, "Registration denied because of contact ACL\n");
15350             transmit_response_with_date(p, "403 Forbidden (ACL)", req);
15351             res = 0;
15352             break;
15353          case PARSE_REGISTER_FAILED:
15354             ast_log(LOG_WARNING, "Failed to parse contact info\n");
15355             transmit_response_with_date(p, "400 Bad Request", req);
15356             res = 0;
15357             break;
15358          case PARSE_REGISTER_QUERY:
15359             ast_string_field_set(p, fullcontact, peer->fullcontact);
15360             transmit_response_with_date(p, "200 OK", req);
15361             res = 0;
15362             break;
15363          case PARSE_REGISTER_UPDATE:
15364             ast_string_field_set(p, fullcontact, peer->fullcontact);
15365             /* Say OK and ask subsystem to retransmit msg counter */
15366             transmit_response_with_date(p, "200 OK", req);
15367             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));
15368             res = 0;
15369             break;
15370          }
15371          ao2_unlock(peer);
15372       }
15373    }
15374    if (!res) {
15375       ao2_unlock(p);
15376       sip_send_mwi_to_peer(peer, 0);
15377       ao2_lock(p);
15378       ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", peer->name);
15379    }
15380    if (res < 0) {
15381       switch (res) {
15382       case AUTH_SECRET_FAILED:
15383          /* Wrong password in authentication. Go away, don't try again until you fixed it */
15384          transmit_response(p, "403 Forbidden (Bad auth)", &p->initreq);
15385          if (global_authfailureevents) {
15386             const char *peer_addr = ast_strdupa(ast_sockaddr_stringify_addr(addr));
15387             const char *peer_port = ast_strdupa(ast_sockaddr_stringify_port(addr));
15388             manager_event(EVENT_FLAG_SYSTEM, "PeerStatus",
15389                      "ChannelType: SIP\r\n"
15390                      "Peer: SIP/%s\r\n"
15391                      "PeerStatus: Rejected\r\n"
15392                      "Cause: AUTH_SECRET_FAILED\r\n"
15393                      "Address: %s\r\n"
15394                      "Port: %s\r\n",
15395                      name, peer_addr, peer_port);
15396          }
15397          break;
15398       case AUTH_USERNAME_MISMATCH:
15399          /* Username and digest username does not match.
15400             Asterisk uses the From: username for authentication. We need the
15401             devices to use the same authentication user name until we support
15402             proper authentication by digest auth name */
15403       case AUTH_NOT_FOUND:
15404       case AUTH_PEER_NOT_DYNAMIC:
15405       case AUTH_ACL_FAILED:
15406          if (sip_cfg.alwaysauthreject) {
15407             transmit_fake_auth_response(p, SIP_REGISTER, &p->initreq, XMIT_UNRELIABLE);
15408             if (global_authfailureevents) {
15409                const char *peer_addr = ast_strdupa(ast_sockaddr_stringify_addr(addr));
15410                const char *peer_port = ast_strdupa(ast_sockaddr_stringify_port(addr));
15411                manager_event(EVENT_FLAG_SYSTEM, "PeerStatus",
15412                         "ChannelType: SIP\r\n"
15413                         "Peer: SIP/%s\r\n"
15414                         "PeerStatus: Rejected\r\n"
15415                         "Cause: %s\r\n"
15416                         "Address: %s\r\n"
15417                         "Port: %s\r\n",
15418                         name,
15419                         res == AUTH_PEER_NOT_DYNAMIC ? "AUTH_PEER_NOT_DYNAMIC" : "URI_NOT_FOUND",
15420                         peer_addr, peer_port);
15421             }
15422          } else {
15423             /* URI not found */
15424             if (res == AUTH_PEER_NOT_DYNAMIC) {
15425                transmit_response(p, "403 Forbidden", &p->initreq);
15426                if (global_authfailureevents) {
15427                   const char *peer_addr = ast_strdupa(ast_sockaddr_stringify_addr(addr));
15428                   const char *peer_port = ast_strdupa(ast_sockaddr_stringify_port(addr));
15429                   manager_event(EVENT_FLAG_SYSTEM, "PeerStatus",
15430                      "ChannelType: SIP\r\n"
15431                      "Peer: SIP/%s\r\n"
15432                      "PeerStatus: Rejected\r\n"
15433                      "Cause: AUTH_PEER_NOT_DYNAMIC\r\n"
15434                      "Address: %s\r\n"
15435                      "Port: %s\r\n",
15436                      name, peer_addr, peer_port);
15437                }
15438             } else {
15439                transmit_response(p, "404 Not found", &p->initreq);
15440                if (global_authfailureevents) {
15441                   const char *peer_addr = ast_strdupa(ast_sockaddr_stringify_addr(addr));
15442                   const char *peer_port = ast_strdupa(ast_sockaddr_stringify_port(addr));
15443                   manager_event(EVENT_FLAG_SYSTEM, "PeerStatus",
15444                      "ChannelType: SIP\r\n"
15445                      "Peer: SIP/%s\r\n"
15446                      "PeerStatus: Rejected\r\n"
15447                      "Cause: %s\r\n"
15448                      "Address: %s\r\n"
15449                      "Port: %s\r\n",
15450                      name,
15451                      (res == AUTH_USERNAME_MISMATCH) ? "AUTH_USERNAME_MISMATCH" : "URI_NOT_FOUND",
15452                      peer_addr, peer_port);
15453                }
15454             }
15455          }
15456          break;
15457       case AUTH_BAD_TRANSPORT:
15458       default:
15459          break;
15460       }
15461    }
15462    if (peer) {
15463       sip_unref_peer(peer, "register_verify: sip_unref_peer: tossing stack peer pointer at end of func");
15464    }
15465 
15466    return res;
15467 }
15468 
15469 /*! \brief Translate referring cause */
15470 static void sip_set_redirstr(struct sip_pvt *p, char *reason) {
15471 
15472    if (!strcmp(reason, "unknown")) {
15473       ast_string_field_set(p, redircause, "UNKNOWN");
15474    } else if (!strcmp(reason, "user-busy")) {
15475       ast_string_field_set(p, redircause, "BUSY");
15476    } else if (!strcmp(reason, "no-answer")) {
15477       ast_string_field_set(p, redircause, "NOANSWER");
15478    } else if (!strcmp(reason, "unavailable")) {
15479       ast_string_field_set(p, redircause, "UNREACHABLE");
15480    } else if (!strcmp(reason, "unconditional")) {
15481       ast_string_field_set(p, redircause, "UNCONDITIONAL");
15482    } else if (!strcmp(reason, "time-of-day")) {
15483       ast_string_field_set(p, redircause, "UNKNOWN");
15484    } else if (!strcmp(reason, "do-not-disturb")) {
15485       ast_string_field_set(p, redircause, "UNKNOWN");
15486    } else if (!strcmp(reason, "deflection")) {
15487       ast_string_field_set(p, redircause, "UNKNOWN");
15488    } else if (!strcmp(reason, "follow-me")) {
15489       ast_string_field_set(p, redircause, "UNKNOWN");
15490    } else if (!strcmp(reason, "out-of-service")) {
15491       ast_string_field_set(p, redircause, "UNREACHABLE");
15492    } else if (!strcmp(reason, "away")) {
15493       ast_string_field_set(p, redircause, "UNREACHABLE");
15494    } else {
15495       ast_string_field_set(p, redircause, "UNKNOWN");
15496    }
15497 }
15498 
15499 /*! \brief Parse the parts of the P-Asserted-Identity header
15500  * on an incoming packet. Returns 1 if a valid header is found
15501  * and it is different from the current caller id.
15502  */
15503 static int get_pai(struct sip_pvt *p, struct sip_request *req)
15504 {
15505    char pai[256];
15506    char privacy[64];
15507    char *cid_num = NULL;
15508    char *cid_name = NULL;
15509    char emptyname[1] = "";
15510    int callingpres = AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
15511    char *uri = NULL;
15512    int is_anonymous = 0, do_update = 1, no_name = 0;
15513 
15514    ast_copy_string(pai, sip_get_header(req, "P-Asserted-Identity"), sizeof(pai));
15515 
15516    if (ast_strlen_zero(pai)) {
15517       return 0;
15518    }
15519 
15520    /* use the reqresp_parser function get_name_and_number*/
15521    if (get_name_and_number(pai, &cid_name, &cid_num)) {
15522       return 0;
15523    }
15524 
15525    if (global_shrinkcallerid && ast_is_shrinkable_phonenumber(cid_num)) {
15526       ast_shrink_phone_number(cid_num);
15527    }
15528 
15529    uri = get_in_brackets(pai);
15530    if (!strncasecmp(uri, "sip:anonymous@anonymous.invalid", 31)) {
15531       callingpres = AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED;
15532       /*XXX Assume no change in cid_num. Perhaps it should be
15533        * blanked?
15534        */
15535       ast_free(cid_num);
15536       is_anonymous = 1;
15537       cid_num = (char *)p->cid_num;
15538    }
15539 
15540    ast_copy_string(privacy, sip_get_header(req, "Privacy"), sizeof(privacy));
15541    if (!ast_strlen_zero(privacy) && strncmp(privacy, "id", 2)) {
15542       callingpres = AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED;
15543    }
15544    if (!cid_name) {
15545       no_name = 1;
15546       cid_name = (char *)emptyname;
15547    }  
15548    /* Only return true if the supplied caller id is different */
15549    if (!strcasecmp(p->cid_num, cid_num) && !strcasecmp(p->cid_name, cid_name) && p->callingpres == callingpres) {
15550       do_update = 0;
15551    } else {
15552 
15553       ast_string_field_set(p, cid_num, cid_num);
15554       ast_string_field_set(p, cid_name, cid_name);
15555       p->callingpres = callingpres;
15556 
15557       if (p->owner) {
15558          ast_set_callerid(p->owner, cid_num, cid_name, NULL);
15559          p->owner->caller.id.name.presentation = callingpres;
15560          p->owner->caller.id.number.presentation = callingpres;
15561       }
15562    }
15563 
15564    /* get_name_and_number allocates memory for cid_num and cid_name so we have to free it */
15565    if (!is_anonymous) {
15566       ast_free(cid_num);
15567    }
15568    if (!no_name) {
15569       ast_free(cid_name);
15570    }
15571 
15572    return do_update;
15573 }
15574 
15575 /*! \brief Get name, number and presentation from remote party id header,
15576  *  returns true if a valid header was found and it was different from the
15577  *  current caller id.
15578  */
15579 static int get_rpid(struct sip_pvt *p, struct sip_request *oreq)
15580 {
15581    char tmp[256];
15582    struct sip_request *req;
15583    char *cid_num = "";
15584    char *cid_name = "";
15585    int callingpres = AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
15586    char *privacy = "";
15587    char *screen = "";
15588    char *start, *end;
15589 
15590    if (!ast_test_flag(&p->flags[0], SIP_TRUSTRPID))
15591       return 0;
15592    req = oreq;
15593    if (!req)
15594       req = &p->initreq;
15595    ast_copy_string(tmp, sip_get_header(req, "Remote-Party-ID"), sizeof(tmp));
15596    if (ast_strlen_zero(tmp)) {
15597       return get_pai(p, req);
15598    }
15599 
15600    start = tmp;
15601    if (*start == '"') {
15602       *start++ = '\0';
15603       end = strchr(start, '"');
15604       if (!end)
15605          return 0;
15606       *end++ = '\0';
15607       cid_name = start;
15608       start = ast_skip_blanks(end);
15609    }
15610 
15611    if (*start != '<')
15612       return 0;
15613    *start++ = '\0';
15614    end = strchr(start, '@');
15615    if (!end)
15616       return 0;
15617    *end++ = '\0';
15618    if (strncasecmp(start, "sip:", 4))
15619       return 0;
15620    cid_num = start + 4;
15621    if (global_shrinkcallerid && ast_is_shrinkable_phonenumber(cid_num))
15622       ast_shrink_phone_number(cid_num);
15623    start = end;
15624 
15625    end = strchr(start, '>');
15626    if (!end)
15627       return 0;
15628    *end++ = '\0';
15629    if (*end) {
15630       start = end;
15631       if (*start != ';')
15632          return 0;
15633       *start++ = '\0';
15634       while (!ast_strlen_zero(start)) {
15635          end = strchr(start, ';');
15636          if (end)
15637             *end++ = '\0';
15638          if (!strncasecmp(start, "privacy=", 8))
15639             privacy = start + 8;
15640          else if (!strncasecmp(start, "screen=", 7))
15641             screen = start + 7;
15642          start = end;
15643       }
15644 
15645       if (!strcasecmp(privacy, "full")) {
15646          if (!strcasecmp(screen, "yes"))
15647             callingpres = AST_PRES_PROHIB_USER_NUMBER_PASSED_SCREEN;
15648          else if (!strcasecmp(screen, "no"))
15649             callingpres = AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED;
15650       } else {
15651          if (!strcasecmp(screen, "yes"))
15652             callingpres = AST_PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN;
15653          else if (!strcasecmp(screen, "no"))
15654             callingpres = AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
15655       }
15656    }
15657 
15658    /* Only return true if the supplied caller id is different */
15659    if (!strcasecmp(p->cid_num, cid_num) && !strcasecmp(p->cid_name, cid_name) && p->callingpres == callingpres)
15660       return 0;
15661 
15662    ast_string_field_set(p, cid_num, cid_num);
15663    ast_string_field_set(p, cid_name, cid_name);
15664    p->callingpres = callingpres;
15665 
15666    if (p->owner) {
15667       ast_set_callerid(p->owner, cid_num, cid_name, NULL);
15668       p->owner->caller.id.name.presentation = callingpres;
15669       p->owner->caller.id.number.presentation = callingpres;
15670    }
15671 
15672    return 1;
15673 }
15674 
15675 /*! \brief Get referring dnis */
15676 static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq, char **name, char **number, int *reason)
15677 {
15678    char tmp[256], *exten, *rexten, *rdomain, *rname = NULL;
15679    char *params, *reason_param = NULL;
15680    struct sip_request *req;
15681 
15682    req = oreq ? oreq : &p->initreq;
15683 
15684    ast_copy_string(tmp, sip_get_header(req, "Diversion"), sizeof(tmp));
15685    if (ast_strlen_zero(tmp))
15686       return -1;
15687 
15688    if ((params = strchr(tmp, '>'))) {
15689       params = strchr(params, ';');
15690    }
15691 
15692    exten = get_in_brackets(tmp);
15693    if (!strncasecmp(exten, "sip:", 4)) {
15694       exten += 4;
15695    } else if (!strncasecmp(exten, "sips:", 5)) {
15696       exten += 5;
15697    } else {
15698       ast_log(LOG_WARNING, "Huh?  Not an RDNIS SIP header (%s)?\n", exten);
15699       return -1;
15700    }
15701 
15702    /* Get diversion-reason param if present */
15703    if (params) {
15704       *params = '\0';   /* Cut off parameters  */
15705       params++;
15706       while (*params == ';' || *params == ' ')
15707          params++;
15708       /* Check if we have a reason parameter */
15709       if ((reason_param = strcasestr(params, "reason="))) {
15710          char *end;
15711          reason_param+=7;
15712          if ((end = strchr(reason_param, ';'))) {
15713             *end = '\0';
15714          }
15715          /* Remove enclosing double-quotes */
15716          if (*reason_param == '"')
15717             ast_strip_quoted(reason_param, "\"", "\"");
15718          if (!ast_strlen_zero(reason_param)) {
15719             sip_set_redirstr(p, reason_param);
15720             if (p->owner) {
15721                pbx_builtin_setvar_helper(p->owner, "__PRIREDIRECTREASON", p->redircause);
15722                pbx_builtin_setvar_helper(p->owner, "__SIPREDIRECTREASON", reason_param);
15723             }
15724          }
15725       }
15726    }
15727 
15728    rdomain = exten;
15729    rexten = strsep(&rdomain, "@");  /* trim anything after @ */
15730    if (p->owner)
15731       pbx_builtin_setvar_helper(p->owner, "__SIPRDNISDOMAIN", rdomain);
15732 
15733    if (sip_debug_test_pvt(p))
15734       ast_verbose("RDNIS for this call is %s (reason %s)\n", exten, reason ? reason_param : "");
15735 
15736    /*ast_string_field_set(p, rdnis, rexten);*/
15737 
15738    if (*tmp == '\"') {
15739       char *end_quote;
15740       rname = tmp + 1;
15741       end_quote = strchr(rname, '\"');
15742       *end_quote = '\0';
15743    }
15744 
15745    if (number) {
15746       *number = ast_strdup(rexten);
15747    }
15748 
15749    if (name && rname) {
15750       *name = ast_strdup(rname);
15751    }
15752 
15753    if (reason && !ast_strlen_zero(reason_param)) {
15754       *reason = sip_reason_str_to_code(reason_param);
15755    }
15756 
15757    return 0;
15758 }
15759 
15760 /*!
15761  * \brief Find out who the call is for.
15762  *
15763  * \details
15764  * We use the request uri as a destination.
15765  * This code assumes authentication has been done, so that the
15766  * device (peer/user) context is already set.
15767  *
15768  * \return 0 on success (found a matching extension), non-zero on failure
15769  *
15770  * \note If the incoming uri is a SIPS: uri, we are required to carry this across
15771  * the dialplan, so that the outbound call also is a sips: call or encrypted
15772  * IAX2 call. If that's not available, the call should FAIL.
15773  */
15774 static enum sip_get_dest_result get_destination(struct sip_pvt *p, struct sip_request *oreq, int *cc_recall_core_id)
15775 {
15776    char tmp[256] = "", *uri, *unused_password, *domain;
15777    char tmpf[256] = "", *from = NULL;
15778    struct sip_request *req;
15779    char *decoded_uri;
15780 
15781    req = oreq;
15782    if (!req) {
15783       req = &p->initreq;
15784    }
15785 
15786    /* Find the request URI */
15787    if (req->rlPart2)
15788       ast_copy_string(tmp, REQ_OFFSET_TO_STR(req, rlPart2), sizeof(tmp));
15789    
15790    uri = ast_strdupa(get_in_brackets(tmp));
15791 
15792    if (parse_uri_legacy_check(uri, "sip:,sips:", &uri, &unused_password, &domain, NULL)) {
15793       ast_log(LOG_WARNING, "Not a SIP header (%s)?\n", uri);
15794       return SIP_GET_DEST_INVALID_URI;
15795    }
15796 
15797    SIP_PEDANTIC_DECODE(domain);
15798    SIP_PEDANTIC_DECODE(uri);
15799 
15800    extract_host_from_hostport(&domain);
15801 
15802    if (ast_strlen_zero(uri)) {
15803       /*
15804        * Either there really was no extension found or the request
15805        * URI had encoded nulls that made the string "empty".  Use "s"
15806        * as the extension.
15807        */
15808       uri = "s";
15809    }
15810 
15811    ast_string_field_set(p, domain, domain);
15812 
15813    /* Now find the From: caller ID and name */
15814    /* XXX Why is this done in get_destination? Isn't it already done?
15815       Needs to be checked
15816         */
15817    ast_copy_string(tmpf, sip_get_header(req, "From"), sizeof(tmpf));
15818    if (!ast_strlen_zero(tmpf)) {
15819       from = get_in_brackets(tmpf);
15820       if (parse_uri_legacy_check(from, "sip:,sips:", &from, NULL, &domain, NULL)) {
15821          ast_log(LOG_WARNING, "Not a SIP header (%s)?\n", from);
15822          return SIP_GET_DEST_INVALID_URI;
15823       }
15824 
15825       SIP_PEDANTIC_DECODE(from);
15826       SIP_PEDANTIC_DECODE(domain);
15827 
15828       extract_host_from_hostport(&domain);
15829 
15830       ast_string_field_set(p, fromdomain, domain);
15831    }
15832 
15833    if (!AST_LIST_EMPTY(&domain_list)) {
15834       char domain_context[AST_MAX_EXTENSION];
15835 
15836       domain_context[0] = '\0';
15837       if (!check_sip_domain(p->domain, domain_context, sizeof(domain_context))) {
15838          if (!sip_cfg.allow_external_domains && (req->method == SIP_INVITE || req->method == SIP_REFER)) {
15839             ast_debug(1, "Got SIP %s to non-local domain '%s'; refusing request.\n", sip_methods[req->method].text, p->domain);
15840             return SIP_GET_DEST_REFUSED;
15841          }
15842       }
15843       /* If we don't have a peer (i.e. we're a guest call),
15844        * overwrite the original context */
15845       if (!ast_test_flag(&p->flags[1], SIP_PAGE2_HAVEPEERCONTEXT) && !ast_strlen_zero(domain_context)) {
15846          ast_string_field_set(p, context, domain_context);
15847       }
15848    }
15849 
15850    /* If the request coming in is a subscription and subscribecontext has been specified use it */
15851    if (req->method == SIP_SUBSCRIBE && !ast_strlen_zero(p->subscribecontext)) {
15852       ast_string_field_set(p, context, p->subscribecontext);
15853    }
15854 
15855    if (sip_debug_test_pvt(p)) {
15856       ast_verbose("Looking for %s in %s (domain %s)\n", uri, p->context, p->domain);
15857    }
15858 
15859    /* Since extensions.conf can have unescaped characters, try matching a
15860     * decoded uri in addition to the non-decoded uri. */
15861    decoded_uri = ast_strdupa(uri);
15862    ast_uri_decode(decoded_uri, ast_uri_sip_user);
15863 
15864    /* If this is a subscription we actually just need to see if a hint exists for the extension */
15865    if (req->method == SIP_SUBSCRIBE) {
15866       char hint[AST_MAX_EXTENSION];
15867       int which = 0;
15868       if (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, p->context, uri) ||
15869           (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, p->context, decoded_uri) && (which = 1))) {
15870          if (!oreq) {
15871             ast_string_field_set(p, exten, which ? decoded_uri : uri);
15872          }
15873          return SIP_GET_DEST_EXTEN_FOUND;
15874       } else {
15875          return SIP_GET_DEST_EXTEN_NOT_FOUND;
15876       }
15877    } else {
15878       struct ast_cc_agent *agent;
15879       /* Check the dialplan for the username part of the request URI,
15880          the domain will be stored in the SIPDOMAIN variable
15881          Return 0 if we have a matching extension */
15882       if (ast_exists_extension(NULL, p->context, uri, 1, S_OR(p->cid_num, from))) {
15883          if (!oreq) {
15884             ast_string_field_set(p, exten, uri);
15885          }
15886          return SIP_GET_DEST_EXTEN_FOUND;
15887       }
15888       if (ast_exists_extension(NULL, p->context, decoded_uri, 1, S_OR(p->cid_num, from))
15889          || !strcmp(decoded_uri, ast_pickup_ext())) {
15890          if (!oreq) {
15891             ast_string_field_set(p, exten, decoded_uri);
15892          }
15893          return SIP_GET_DEST_EXTEN_FOUND;
15894       }
15895       if ((agent = find_sip_cc_agent_by_notify_uri(tmp))) {
15896          struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
15897          /* This is a CC recall. We can set p's extension to the exten from
15898           * the original INVITE
15899           */
15900          ast_string_field_set(p, exten, agent_pvt->original_exten);
15901          /* And we need to let the CC core know that the caller is attempting
15902           * his recall
15903           */
15904          ast_cc_agent_recalling(agent->core_id, "SIP caller %s is attempting recall",
15905                agent->device_name);
15906          if (cc_recall_core_id) {
15907             *cc_recall_core_id = agent->core_id;
15908          }
15909          ao2_ref(agent, -1);
15910          return SIP_GET_DEST_EXTEN_FOUND;
15911       }
15912    }
15913 
15914    if (ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP)
15915       && (ast_canmatch_extension(NULL, p->context, uri, 1, S_OR(p->cid_num, from))
15916          || ast_canmatch_extension(NULL, p->context, decoded_uri, 1, S_OR(p->cid_num, from))
15917          || !strncmp(decoded_uri, ast_pickup_ext(), strlen(decoded_uri)))) {
15918       /* Overlap dialing is enabled and we need more digits to match an extension. */
15919       return SIP_GET_DEST_EXTEN_MATCHMORE;
15920    }
15921 
15922    return SIP_GET_DEST_EXTEN_NOT_FOUND;
15923 }
15924 
15925 /*! \brief Lock dialog lock and find matching pvt lock
15926    \return a reference, remember to release it when done
15927 */
15928 static struct sip_pvt *get_sip_pvt_byid_locked(const char *callid, const char *totag, const char *fromtag)
15929 {
15930    struct sip_pvt *sip_pvt_ptr;
15931    struct sip_pvt tmp_dialog = {
15932       .callid = callid,
15933    };
15934 
15935    if (totag) {
15936       ast_debug(4, "Looking for callid %s (fromtag %s totag %s)\n", callid, fromtag ? fromtag : "<no fromtag>", totag ? totag : "<no totag>");
15937    }
15938 
15939    /* Search dialogs and find the match */
15940 
15941    sip_pvt_ptr = ao2_t_find(dialogs, &tmp_dialog, OBJ_POINTER, "ao2_find of dialog in dialogs table");
15942    if (sip_pvt_ptr) {
15943       /* Go ahead and lock it (and its owner) before returning */
15944       sip_pvt_lock(sip_pvt_ptr);
15945       if (sip_cfg.pedanticsipchecking) {
15946          unsigned char frommismatch = 0, tomismatch = 0;
15947 
15948          if (ast_strlen_zero(fromtag)) {
15949             sip_pvt_unlock(sip_pvt_ptr);
15950             ast_debug(4, "Matched %s call for callid=%s - no from tag specified, pedantic check fails\n",
15951                  sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid);
15952             return NULL;
15953          }
15954 
15955          if (ast_strlen_zero(totag)) {
15956             sip_pvt_unlock(sip_pvt_ptr);
15957             ast_debug(4, "Matched %s call for callid=%s - no to tag specified, pedantic check fails\n",
15958                  sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid);
15959             return NULL;
15960          }
15961          /* RFC 3891
15962           * > 3.  User Agent Server Behavior: Receiving a Replaces Header
15963           * > The Replaces header contains information used to match an existing
15964           * > SIP dialog (call-id, to-tag, and from-tag).  Upon receiving an INVITE
15965           * > with a Replaces header, the User Agent (UA) attempts to match this
15966           * > information with a confirmed or early dialog.  The User Agent Server
15967           * > (UAS) matches the to-tag and from-tag parameters as if they were tags
15968           * > present in an incoming request.  In other words, the to-tag parameter
15969           * > is compared to the local tag, and the from-tag parameter is compared
15970           * > to the remote tag.
15971           *
15972           * Thus, the totag is always compared to the local tag, regardless if
15973           * this our call is an incoming or outgoing call.
15974           */
15975          frommismatch = !!strcmp(fromtag, sip_pvt_ptr->theirtag);
15976          tomismatch = !!strcmp(totag, sip_pvt_ptr->tag);
15977 
15978          if (frommismatch || tomismatch) {
15979             sip_pvt_unlock(sip_pvt_ptr);
15980             if (frommismatch) {
15981                ast_debug(4, "Matched %s call for callid=%s - pedantic from tag check fails; their tag is %s our tag is %s\n",
15982                     sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid,
15983                     fromtag, sip_pvt_ptr->theirtag);
15984             }
15985             if (tomismatch) {
15986                ast_debug(4, "Matched %s call for callid=%s - pedantic to tag check fails; their tag is %s our tag is %s\n",
15987                     sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid,
15988                     totag, sip_pvt_ptr->tag);
15989             }
15990             return NULL;
15991          }
15992       }
15993 
15994       if (totag)
15995          ast_debug(4, "Matched %s call - their tag is %s Our tag is %s\n",
15996                  sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING",
15997                  sip_pvt_ptr->theirtag, sip_pvt_ptr->tag);
15998 
15999       /* deadlock avoidance... */
16000       while (sip_pvt_ptr->owner && ast_channel_trylock(sip_pvt_ptr->owner)) {
16001          sip_pvt_unlock(sip_pvt_ptr);
16002          usleep(1);
16003          sip_pvt_lock(sip_pvt_ptr);
16004       }
16005    }
16006    
16007    return sip_pvt_ptr;
16008 }
16009 
16010 /*! \brief Call transfer support (the REFER method)
16011  *    Extracts Refer headers into pvt dialog structure
16012  *
16013  * \note If we get a SIPS uri in the refer-to header, we're required to set up a secure signalling path
16014  * to that extension. As a minimum, this needs to be added to a channel variable, if not a channel
16015  * flag.
16016  */
16017 static int get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req)
16018 {
16019 
16020    const char *p_referred_by = NULL;
16021    char *h_refer_to = NULL;
16022    char *h_referred_by = NULL;
16023    char *refer_to;
16024    const char *p_refer_to;
16025    char *referred_by_uri = NULL;
16026    char *ptr;
16027    struct sip_request *req = NULL;
16028    const char *transfer_context = NULL;
16029    struct sip_refer *referdata;
16030 
16031 
16032    req = outgoing_req;
16033    referdata = transferer->refer;
16034 
16035    if (!req) {
16036       req = &transferer->initreq;
16037    }
16038 
16039    p_refer_to = sip_get_header(req, "Refer-To");
16040    if (ast_strlen_zero(p_refer_to)) {
16041       ast_log(LOG_WARNING, "Refer-To Header missing. Skipping transfer.\n");
16042       return -2;  /* Syntax error */
16043    }
16044    h_refer_to = ast_strdupa(p_refer_to);
16045    refer_to = get_in_brackets(h_refer_to);
16046    if (!strncasecmp(refer_to, "sip:", 4)) {
16047       refer_to += 4;       /* Skip sip: */
16048    } else if (!strncasecmp(refer_to, "sips:", 5)) {
16049       refer_to += 5;
16050    } else {
16051       ast_log(LOG_WARNING, "Can't transfer to non-sip: URI.  (Refer-to: %s)?\n", refer_to);
16052       return -3;
16053    }
16054 
16055    /* Get referred by header if it exists */
16056    p_referred_by = sip_get_header(req, "Referred-By");
16057 
16058    /* Give useful transfer information to the dialplan */
16059    if (transferer->owner) {
16060       struct ast_channel *peer = ast_bridged_channel(transferer->owner);
16061       if (peer) {
16062          pbx_builtin_setvar_helper(peer, "SIPREFERRINGCONTEXT", transferer->context);
16063          pbx_builtin_setvar_helper(peer, "SIPREFERREDBYHDR", p_referred_by);
16064       }
16065    }
16066 
16067    if (!ast_strlen_zero(p_referred_by)) {
16068       char *lessthan;
16069       h_referred_by = ast_strdupa(p_referred_by);
16070 
16071       /* Store referrer's caller ID name */
16072       ast_copy_string(referdata->referred_by_name, h_referred_by, sizeof(referdata->referred_by_name));
16073       if ((lessthan = strchr(referdata->referred_by_name, '<'))) {
16074          *(lessthan - 1) = '\0'; /* Space */
16075       }
16076 
16077       referred_by_uri = get_in_brackets(h_referred_by);
16078 
16079       if (!strncasecmp(referred_by_uri, "sip:", 4)) {
16080          referred_by_uri += 4;      /* Skip sip: */
16081       } else if (!strncasecmp(referred_by_uri, "sips:", 5)) {
16082          referred_by_uri += 5;      /* Skip sips: */
16083       } else {
16084          ast_log(LOG_WARNING, "Huh?  Not a sip: header (Referred-by: %s). Skipping.\n", referred_by_uri);
16085          referred_by_uri = NULL;
16086       }
16087    }
16088 
16089    /* Check for arguments in the refer_to header */
16090    if ((ptr = strcasestr(refer_to, "replaces="))) {
16091       char *to = NULL, *from = NULL;
16092       
16093       /* This is an attended transfer */
16094       referdata->attendedtransfer = 1;
16095       ast_copy_string(referdata->replaces_callid, ptr+9, sizeof(referdata->replaces_callid));
16096       ast_uri_decode(referdata->replaces_callid, ast_uri_sip_user);
16097       if ((ptr = strchr(referdata->replaces_callid, ';')))  /* Find options */ {
16098          *ptr++ = '\0';
16099       }
16100       
16101       if (ptr) {
16102          /* Find the different tags before we destroy the string */
16103          to = strcasestr(ptr, "to-tag=");
16104          from = strcasestr(ptr, "from-tag=");
16105       }
16106       
16107       /* Grab the to header */
16108       if (to) {
16109          ptr = to + 7;
16110          if ((to = strchr(ptr, '&'))) {
16111             *to = '\0';
16112          }
16113          if ((to = strchr(ptr, ';'))) {
16114             *to = '\0';
16115          }
16116          ast_copy_string(referdata->replaces_callid_totag, ptr, sizeof(referdata->replaces_callid_totag));
16117       }
16118 
16119       if (from) {
16120          ptr = from + 9;
16121          if ((to = strchr(ptr, '&'))) {
16122             *to = '\0';
16123          }
16124          if ((to = strchr(ptr, ';'))) {
16125             *to = '\0';
16126          }
16127          ast_copy_string(referdata->replaces_callid_fromtag, ptr, sizeof(referdata->replaces_callid_fromtag));
16128       }
16129 
16130       if (!strcmp(referdata->replaces_callid, transferer->callid) &&
16131          (!sip_cfg.pedanticsipchecking ||
16132          (!strcmp(referdata->replaces_callid_fromtag, transferer->theirtag) &&
16133          !strcmp(referdata->replaces_callid_totag, transferer->tag)))) {
16134             ast_log(LOG_WARNING, "Got an attempt to replace own Call-ID on %s\n", transferer->callid);
16135             return -4;
16136       }
16137 
16138       if (!sip_cfg.pedanticsipchecking) {
16139          ast_debug(2, "Attended transfer: Will use Replace-Call-ID : %s (No check of from/to tags)\n", referdata->replaces_callid );
16140       } else {
16141          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>" );
16142       }
16143    }
16144 
16145    if ((ptr = strchr(refer_to, '@'))) {   /* Separate domain */
16146       char *urioption = NULL, *domain;
16147       int bracket = 0;
16148       *ptr++ = '\0';
16149 
16150       if ((urioption = strchr(ptr, ';'))) { /* Separate urioptions */
16151          *urioption++ = '\0';
16152       }
16153 
16154       domain = ptr;
16155 
16156       /* Remove :port */
16157       for (; *ptr != '\0'; ++ptr) {
16158          if (*ptr == ':' && bracket == 0) {
16159             *ptr = '\0';
16160             break;
16161          } else if (*ptr == '[') {
16162             ++bracket;
16163          } else if (*ptr == ']') {
16164             --bracket;
16165          }
16166       }
16167 
16168       SIP_PEDANTIC_DECODE(domain);
16169       SIP_PEDANTIC_DECODE(urioption);
16170 
16171       /* Save the domain for the dial plan */
16172       ast_copy_string(referdata->refer_to_domain, domain, sizeof(referdata->refer_to_domain));
16173       if (urioption) {
16174          ast_copy_string(referdata->refer_to_urioption, urioption, sizeof(referdata->refer_to_urioption));
16175       }
16176    }
16177 
16178    if ((ptr = strchr(refer_to, ';')))  /* Remove options */
16179       *ptr = '\0';
16180 
16181    SIP_PEDANTIC_DECODE(refer_to);
16182    ast_copy_string(referdata->refer_to, refer_to, sizeof(referdata->refer_to));
16183    
16184    if (referred_by_uri) {
16185       if ((ptr = strchr(referred_by_uri, ';')))    /* Remove options */
16186          *ptr = '\0';
16187       SIP_PEDANTIC_DECODE(referred_by_uri);
16188       ast_copy_string(referdata->referred_by, referred_by_uri, sizeof(referdata->referred_by));
16189    } else {
16190       referdata->referred_by[0] = '\0';
16191    }
16192 
16193    /* Determine transfer context */
16194    if (transferer->owner)  /* Mimic behaviour in res_features.c */
16195       transfer_context = pbx_builtin_getvar_helper(transferer->owner, "TRANSFER_CONTEXT");
16196 
16197    /* By default, use the context in the channel sending the REFER */
16198    if (ast_strlen_zero(transfer_context)) {
16199       transfer_context = S_OR(transferer->owner->macrocontext,
16200                S_OR(transferer->context, sip_cfg.default_context));
16201    }
16202 
16203    ast_copy_string(referdata->refer_to_context, transfer_context, sizeof(referdata->refer_to_context));
16204    
16205    /* Either an existing extension or the parking extension */
16206    if (referdata->attendedtransfer || ast_exists_extension(NULL, transfer_context, refer_to, 1, NULL) ) {
16207       if (sip_debug_test_pvt(transferer)) {
16208          ast_verbose("SIP transfer to extension %s@%s by %s\n", refer_to, transfer_context, referred_by_uri);
16209       }
16210       /* We are ready to transfer to the extension */
16211       return 0;
16212    }
16213    if (sip_debug_test_pvt(transferer))
16214       ast_verbose("Failed SIP Transfer to non-existing extension %s in context %s\n n", refer_to, transfer_context);
16215 
16216    /* Failure, we can't find this extension */
16217    return -1;
16218 }
16219 
16220 
16221 /*! \brief Call transfer support (old way, deprecated by the IETF)
16222  * \note does not account for SIPS: uri requirements, nor check transport
16223  */
16224 static int get_also_info(struct sip_pvt *p, struct sip_request *oreq)
16225 {
16226    char tmp[256] = "", *c, *a;
16227    struct sip_request *req = oreq ? oreq : &p->initreq;
16228    struct sip_refer *referdata = NULL;
16229    const char *transfer_context = NULL;
16230    
16231    if (!p->refer && !sip_refer_allocate(p))
16232       return -1;
16233 
16234    referdata = p->refer;
16235 
16236    ast_copy_string(tmp, sip_get_header(req, "Also"), sizeof(tmp));
16237    c = get_in_brackets(tmp);
16238 
16239    if (parse_uri_legacy_check(c, "sip:,sips:", &c, NULL, &a, NULL)) {
16240       ast_log(LOG_WARNING, "Huh?  Not a SIP header in Also: transfer (%s)?\n", c);
16241       return -1;
16242    }
16243    
16244    SIP_PEDANTIC_DECODE(c);
16245    SIP_PEDANTIC_DECODE(a);
16246 
16247    if (!ast_strlen_zero(a)) {
16248       ast_copy_string(referdata->refer_to_domain, a, sizeof(referdata->refer_to_domain));
16249    }
16250 
16251    if (sip_debug_test_pvt(p))
16252       ast_verbose("Looking for %s in %s\n", c, p->context);
16253 
16254    if (p->owner)  /* Mimic behaviour in res_features.c */
16255       transfer_context = pbx_builtin_getvar_helper(p->owner, "TRANSFER_CONTEXT");
16256 
16257    /* By default, use the context in the channel sending the REFER */
16258    if (ast_strlen_zero(transfer_context)) {
16259       transfer_context = S_OR(p->owner->macrocontext,
16260                S_OR(p->context, sip_cfg.default_context));
16261    }
16262    if (ast_exists_extension(NULL, transfer_context, c, 1, NULL)) {
16263       /* This is a blind transfer */
16264       ast_debug(1, "SIP Bye-also transfer to Extension %s@%s \n", c, transfer_context);
16265       ast_copy_string(referdata->refer_to, c, sizeof(referdata->refer_to));
16266       ast_copy_string(referdata->referred_by, "", sizeof(referdata->referred_by));
16267       ast_copy_string(referdata->refer_contact, "", sizeof(referdata->refer_contact));
16268       referdata->refer_call = dialog_unref(referdata->refer_call, "unreffing referdata->refer_call");
16269       /* Set new context */
16270       ast_string_field_set(p, context, transfer_context);
16271       return 0;
16272    } else if (ast_canmatch_extension(NULL, p->context, c, 1, NULL)) {
16273       return 1;
16274    }
16275 
16276    return -1;
16277 }
16278 
16279 /*! \brief check received= and rport= in a SIP response.
16280  * If we get a response with received= and/or rport= in the Via:
16281  * line, use them as 'p->ourip' (see RFC 3581 for rport,
16282  * and RFC 3261 for received).
16283  * Using these two fields SIP can produce the correct
16284  * address and port in the SIP headers without the need for STUN.
16285  * The address part is also reused for the media sessions.
16286  * Note that ast_sip_ouraddrfor() still rewrites p->ourip
16287  * if you specify externaddr/seternaddr/.
16288  */
16289 static attribute_unused void check_via_response(struct sip_pvt *p, struct sip_request *req)
16290 {
16291    char via[256];
16292    char *cur, *opts;
16293 
16294    ast_copy_string(via, sip_get_header(req, "Via"), sizeof(via));
16295 
16296    /* Work on the leftmost value of the topmost Via header */
16297    opts = strchr(via, ',');
16298    if (opts)
16299       *opts = '\0';
16300 
16301    /* parse all relevant options */
16302    opts = strchr(via, ';');
16303    if (!opts)
16304       return;  /* no options to parse */
16305    *opts++ = '\0';
16306    while ( (cur = strsep(&opts, ";")) ) {
16307       if (!strncmp(cur, "rport=", 6)) {
16308          int port = strtol(cur+6, NULL, 10);
16309          /* XXX add error checking */
16310          ast_sockaddr_set_port(&p->ourip, port);
16311       } else if (!strncmp(cur, "received=", 9)) {
16312          if (ast_parse_arg(cur + 9, PARSE_ADDR, &p->ourip))
16313             ;  /* XXX add error checking */
16314       }
16315    }
16316 }
16317 
16318 /*! \brief check Via: header for hostname, port and rport request/answer */
16319 static void check_via(struct sip_pvt *p, struct sip_request *req)
16320 {
16321    char via[512];
16322    char *c, *maddr;
16323    struct ast_sockaddr tmp = { { 0, } };
16324    uint16_t port;
16325 
16326    ast_copy_string(via, sip_get_header(req, "Via"), sizeof(via));
16327 
16328    /* Work on the leftmost value of the topmost Via header */
16329    c = strchr(via, ',');
16330    if (c)
16331       *c = '\0';
16332 
16333    /* Check for rport */
16334    c = strstr(via, ";rport");
16335    if (c && (c[6] != '=')) { /* rport query, not answer */
16336       ast_set_flag(&p->flags[1], SIP_PAGE2_RPORT_PRESENT);
16337       ast_set_flag(&p->flags[0], SIP_NAT_RPORT_PRESENT);
16338    }
16339 
16340    /* Check for maddr */
16341    maddr = strstr(via, "maddr=");
16342    if (maddr) {
16343       maddr += 6;
16344       c = maddr + strspn(maddr, "abcdefghijklmnopqrstuvwxyz"
16345                       "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-.:[]");
16346       *c = '\0';
16347    }
16348 
16349    c = strchr(via, ';');
16350    if (c)
16351       *c = '\0';
16352 
16353    c = strchr(via, ' ');
16354    if (c) {
16355       *c = '\0';
16356       c = ast_skip_blanks(c+1);
16357       if (strcasecmp(via, "SIP/2.0/UDP") && strcasecmp(via, "SIP/2.0/TCP") && strcasecmp(via, "SIP/2.0/TLS")) {
16358          ast_log(LOG_WARNING, "Don't know how to respond via '%s'\n", via);
16359          return;
16360       }
16361 
16362       if (maddr && ast_sockaddr_resolve_first(&p->sa, maddr, 0)) {
16363          p->sa = p->recv;
16364       }
16365 
16366       ast_sockaddr_resolve_first(&tmp, c, 0);
16367       port = ast_sockaddr_port(&tmp);
16368       ast_sockaddr_set_port(&p->sa,
16369                   port != 0 ? port : STANDARD_SIP_PORT);
16370 
16371       /* Check and see if the requesting UA is likely to be behind a NAT. If they are, set the
16372        * natdetected flag so that later, peers with nat=auto_* can use the value. Also
16373        * set the flags so that Asterisk responds identically whether or not a peer exists
16374        * so as not to leak peer name information. */
16375       if (ast_sockaddr_cmp(&tmp, &p->recv)) {
16376          char *tmp_str = ast_strdupa(ast_sockaddr_stringify(&tmp));
16377          ast_debug(3, "NAT detected for %s / %s\n", tmp_str, ast_sockaddr_stringify(&p->recv));
16378          p->natdetected = 1;
16379          if (ast_test_flag(&p->flags[2], SIP_PAGE3_NAT_AUTO_RPORT)) {
16380             ast_set_flag(&p->flags[0], SIP_NAT_FORCE_RPORT);
16381          }
16382          if (ast_test_flag(&p->flags[2], SIP_PAGE3_NAT_AUTO_COMEDIA)) {
16383             ast_set_flag(&p->flags[1], SIP_PAGE2_SYMMETRICRTP);
16384          }
16385       } else {
16386          p->natdetected = 0;
16387          if (ast_test_flag(&p->flags[2], SIP_PAGE3_NAT_AUTO_RPORT)) {
16388             ast_clear_flag(&p->flags[0], SIP_NAT_FORCE_RPORT);
16389          }
16390          if (ast_test_flag(&p->flags[2], SIP_PAGE3_NAT_AUTO_COMEDIA)) {
16391             ast_clear_flag(&p->flags[1], SIP_PAGE2_SYMMETRICRTP);
16392          }
16393       }
16394 
16395       if (sip_debug_test_pvt(p)) {
16396          ast_verbose("Sending to %s (%s)\n",
16397                 ast_sockaddr_stringify(sip_real_dst(p)),
16398                 sip_nat_mode(p));
16399       }
16400    }
16401 }
16402 
16403 /*! \brief Validate device authentication */
16404 static enum check_auth_result check_peer_ok(struct sip_pvt *p, char *of,
16405    struct sip_request *req, int sipmethod, struct ast_sockaddr *addr,
16406    struct sip_peer **authpeer,
16407    enum xmittype reliable, char *calleridname, char *uri2)
16408 {
16409    enum check_auth_result res;
16410    int debug = sip_debug_test_addr(addr);
16411    struct sip_peer *peer;
16412 
16413    if (sipmethod == SIP_SUBSCRIBE) {
16414       /* For subscribes, match on device name only; for other methods,
16415       * match on IP address-port of the incoming request.
16416       */
16417       peer = sip_find_peer(of, NULL, TRUE, FINDALLDEVICES, FALSE, 0);
16418    } else {
16419       /* First find devices based on username (avoid all type=peer's) */
16420       peer = sip_find_peer(of, NULL, TRUE, FINDUSERS, FALSE, 0);
16421 
16422       /* Then find devices based on IP */
16423       if (!peer) {
16424          char *uri_tmp, *callback = NULL, *dummy;
16425          uri_tmp = ast_strdupa(uri2);
16426          parse_uri(uri_tmp, "sip:,sips:", &callback, &dummy, &dummy, &dummy);
16427          if (!ast_strlen_zero(callback) && (peer = sip_find_peer_by_ip_and_exten(&p->recv, callback, p->socket.type))) {
16428             ; /* found, fall through */
16429          } else {
16430             peer = sip_find_peer(NULL, &p->recv, TRUE, FINDPEERS, FALSE, p->socket.type);
16431          }
16432       }
16433    }
16434 
16435    if (!peer) {
16436       if (debug) {
16437          ast_verbose("No matching peer for '%s' from '%s'\n",
16438             of, ast_sockaddr_stringify(&p->recv));
16439       }
16440       return AUTH_DONT_KNOW;
16441    }
16442 
16443    if (!ast_apply_ha(peer->ha, addr)) {
16444       ast_debug(2, "Found peer '%s' for '%s', but fails host access\n", peer->name, of);
16445       sip_unref_peer(peer, "sip_unref_peer: check_peer_ok: from sip_find_peer call, early return of AUTH_ACL_FAILED");
16446       return AUTH_ACL_FAILED;
16447    }
16448    if (debug)
16449       ast_verbose("Found peer '%s' for '%s' from %s\n",
16450          peer->name, of, ast_sockaddr_stringify(&p->recv));
16451 
16452    /* XXX what about p->prefs = peer->prefs; ? */
16453    /* Set Frame packetization */
16454    if (p->rtp) {
16455       ast_rtp_codecs_packetization_set(ast_rtp_instance_get_codecs(p->rtp), p->rtp, &peer->prefs);
16456       p->autoframing = peer->autoframing;
16457    }
16458 
16459    /* Take the peer */
16460    ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
16461    ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
16462    ast_copy_flags(&p->flags[2], &peer->flags[2], SIP_PAGE3_FLAGS_TO_COPY);
16463 
16464    if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) && p->udptl) {
16465       p->t38_maxdatagram = peer->t38_maxdatagram;
16466       set_t38_capabilities(p);
16467    }
16468 
16469    /* Copy SIP extensions profile to peer */
16470    /* XXX is this correct before a successful auth ? */
16471    if (p->sipoptions)
16472       peer->sipoptions = p->sipoptions;
16473 
16474    do_setnat(p);
16475 
16476    ast_string_field_set(p, peersecret, peer->secret);
16477    ast_string_field_set(p, peermd5secret, peer->md5secret);
16478    ast_string_field_set(p, subscribecontext, peer->subscribecontext);
16479    ast_string_field_set(p, mohinterpret, peer->mohinterpret);
16480    ast_string_field_set(p, mohsuggest, peer->mohsuggest);
16481    if (!ast_strlen_zero(peer->parkinglot)) {
16482       ast_string_field_set(p, parkinglot, peer->parkinglot);
16483    }
16484    ast_string_field_set(p, engine, peer->engine);
16485    p->disallowed_methods = peer->disallowed_methods;
16486    set_pvt_allowed_methods(p, req);
16487    ast_cc_copy_config_params(p->cc_params, peer->cc_params);
16488    if (peer->callingpres)  /* Peer calling pres setting will override RPID */
16489       p->callingpres = peer->callingpres;
16490    if (peer->maxms && peer->lastms)
16491       p->timer_t1 = peer->lastms < global_t1min ? global_t1min : peer->lastms;
16492    else
16493       p->timer_t1 = peer->timer_t1;
16494 
16495    /* Set timer B to control transaction timeouts */
16496    if (peer->timer_b)
16497       p->timer_b = peer->timer_b;
16498    else
16499       p->timer_b = 64 * p->timer_t1;
16500 
16501    if (ast_test_flag(&peer->flags[0], SIP_INSECURE_INVITE)) {
16502       /* Pretend there is no required authentication */
16503       ast_string_field_set(p, peersecret, NULL);
16504       ast_string_field_set(p, peermd5secret, NULL);
16505    }
16506    if (!(res = check_auth(p, req, peer->name, p->peersecret, p->peermd5secret, sipmethod, uri2, reliable, req->ignore))) {
16507       ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
16508       ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
16509       ast_copy_flags(&p->flags[2], &peer->flags[2], SIP_PAGE3_FLAGS_TO_COPY);
16510       /* If we have a call limit, set flag */
16511       if (peer->call_limit)
16512          ast_set_flag(&p->flags[0], SIP_CALL_LIMIT);
16513       ast_string_field_set(p, peername, peer->name);
16514       ast_string_field_set(p, authname, peer->name);
16515 
16516       if (sipmethod == SIP_INVITE) {
16517          /* destroy old channel vars and copy in new ones. */
16518          ast_variables_destroy(p->chanvars);
16519          p->chanvars = copy_vars(peer->chanvars);
16520       }
16521 
16522       if (authpeer) {
16523          ao2_t_ref(peer, 1, "copy pointer into (*authpeer)");
16524          (*authpeer) = peer;  /* Add a ref to the object here, to keep it in memory a bit longer if it is realtime */
16525       }
16526 
16527       if (!ast_strlen_zero(peer->username)) {
16528          ast_string_field_set(p, username, peer->username);
16529          /* Use the default username for authentication on outbound calls */
16530          /* XXX this takes the name from the caller... can we override ? */
16531          ast_string_field_set(p, authname, peer->username);
16532       }
16533       if (!get_rpid(p, req)) {
16534          if (!ast_strlen_zero(peer->cid_num)) {
16535             char *tmp = ast_strdupa(peer->cid_num);
16536             if (global_shrinkcallerid && ast_is_shrinkable_phonenumber(tmp))
16537                ast_shrink_phone_number(tmp);
16538             ast_string_field_set(p, cid_num, tmp);
16539          }
16540          if (!ast_strlen_zero(peer->cid_name))
16541             ast_string_field_set(p, cid_name, peer->cid_name);
16542          if (!ast_strlen_zero(peer->cid_tag))
16543             ast_string_field_set(p, cid_tag, peer->cid_tag);
16544          if (peer->callingpres)
16545             p->callingpres = peer->callingpres;
16546       }
16547       ast_string_field_set(p, fullcontact, peer->fullcontact);
16548       if (!ast_strlen_zero(peer->context)) {
16549          ast_string_field_set(p, context, peer->context);
16550       }
16551       if (!ast_strlen_zero(peer->messagecontext)) {
16552          ast_string_field_set(p, messagecontext, peer->messagecontext);
16553       }
16554       if (!ast_strlen_zero(peer->mwi_from)) {
16555          ast_string_field_set(p, mwi_from, peer->mwi_from);
16556       }
16557       ast_string_field_set(p, peersecret, peer->secret);
16558       ast_string_field_set(p, peermd5secret, peer->md5secret);
16559       ast_string_field_set(p, language, peer->language);
16560       ast_string_field_set(p, accountcode, peer->accountcode);
16561       p->amaflags = peer->amaflags;
16562       p->callgroup = peer->callgroup;
16563       p->pickupgroup = peer->pickupgroup;
16564       ast_format_cap_copy(p->caps, peer->caps);
16565       ast_format_cap_copy(p->jointcaps, peer->caps);
16566       p->prefs = peer->prefs;
16567       ast_copy_string(p->zone, peer->zone, sizeof(p->zone));
16568       if (peer->maxforwards > 0) {
16569          p->maxforwards = peer->maxforwards;
16570       }
16571       if (!(ast_format_cap_is_empty(p->peercaps))) {
16572          struct ast_format_cap *tmp = ast_format_cap_joint(p->jointcaps, p->peercaps);
16573          struct ast_format_cap *tmp2;
16574          if (tmp) {
16575             tmp2 = p->jointcaps;
16576             p->jointcaps = tmp;
16577             ast_format_cap_destroy(tmp2);
16578          }
16579       }
16580       p->maxcallbitrate = peer->maxcallbitrate;
16581       if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
16582           (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
16583          p->noncodeccapability |= AST_RTP_DTMF;
16584       else
16585          p->noncodeccapability &= ~AST_RTP_DTMF;
16586       p->jointnoncodeccapability = p->noncodeccapability;
16587       p->rtptimeout = peer->rtptimeout;
16588       p->rtpholdtimeout = peer->rtpholdtimeout;
16589       p->rtpkeepalive = peer->rtpkeepalive;
16590       if (!dialog_initialize_rtp(p)) {
16591          if (p->rtp) {
16592             ast_rtp_codecs_packetization_set(ast_rtp_instance_get_codecs(p->rtp), p->rtp, &peer->prefs);
16593             p->autoframing = peer->autoframing;
16594          }
16595       } else {
16596          res = AUTH_RTP_FAILED;
16597       }
16598    }
16599    sip_unref_peer(peer, "check_peer_ok: sip_unref_peer: tossing temp ptr to peer from sip_find_peer");
16600    return res;
16601 }
16602 
16603 
16604 /*! \brief  Check if matching user or peer is defined
16605    Match user on From: user name and peer on IP/port
16606    This is used on first invite (not re-invites) and subscribe requests
16607     \return 0 on success, non-zero on failure
16608 */
16609 static enum check_auth_result check_user_full(struct sip_pvt *p, struct sip_request *req,
16610                      int sipmethod, const char *uri, enum xmittype reliable,
16611                      struct ast_sockaddr *addr, struct sip_peer **authpeer)
16612 {
16613    char from[256] = "", *of, *name, *unused_password, *domain;
16614    enum check_auth_result res = AUTH_DONT_KNOW;
16615    char calleridname[50];
16616    char *uri2 = ast_strdupa(uri);
16617 
16618    terminate_uri(uri2); /* trim extra stuff */
16619 
16620    ast_copy_string(from, sip_get_header(req, "From"), sizeof(from));
16621    /* XXX here tries to map the username for invite things */
16622 
16623    /* strip the display-name portion off the beginning of the FROM header. */
16624    if (!(of = (char *) get_calleridname(from, calleridname, sizeof(calleridname)))) {
16625       ast_log(LOG_ERROR, "FROM header can not be parsed \n");
16626       return res;
16627    }
16628 
16629    if (calleridname[0]) {
16630       ast_string_field_set(p, cid_name, calleridname);
16631    }
16632 
16633    if (ast_strlen_zero(p->exten)) {
16634       char *t = uri2;
16635       if (!strncasecmp(t, "sip:", 4))
16636          t+= 4;
16637       else if (!strncasecmp(t, "sips:", 5))
16638          t += 5;
16639       ast_string_field_set(p, exten, t);
16640       t = strchr(p->exten, '@');
16641       if (t)
16642          *t = '\0';
16643 
16644       if (ast_strlen_zero(p->our_contact))
16645          build_contact(p);
16646    }
16647 
16648    of = get_in_brackets(of);
16649 
16650    /* save the URI part of the From header */
16651    ast_string_field_set(p, from, of);
16652 
16653    if (parse_uri_legacy_check(of, "sip:,sips:", &name, &unused_password, &domain, NULL)) {
16654       ast_log(LOG_NOTICE, "From address missing 'sip:', using it anyway\n");
16655    }
16656 
16657    SIP_PEDANTIC_DECODE(name);
16658    SIP_PEDANTIC_DECODE(domain);
16659 
16660    extract_host_from_hostport(&domain);
16661 
16662    if (ast_strlen_zero(domain)) {
16663       /* <sip:name@[EMPTY]>, never good */
16664       ast_log(LOG_ERROR, "Empty domain name in FROM header\n");
16665       return res;
16666    }
16667 
16668    if (ast_strlen_zero(name)) {
16669       /* <sip:[EMPTY][@]hostport>. Asterisk 1.4 and 1.6 have always
16670        * treated that as a username, so we continue the tradition:
16671        * uri is now <sip:host@hostport>. */
16672       name = domain;
16673    } else {
16674       /* Non-empty name, try to get caller id from it */
16675       char *tmp = ast_strdupa(name);
16676       /* We need to be able to handle from-headers looking like
16677          <sip:8164444422;phone-context=+1@1.2.3.4:5060;user=phone;tag=SDadkoa01-gK0c3bdb43>
16678       */
16679       tmp = strsep(&tmp, ";");
16680       if (global_shrinkcallerid && ast_is_shrinkable_phonenumber(tmp)) {
16681          ast_shrink_phone_number(tmp);
16682       }
16683       ast_string_field_set(p, cid_num, tmp);
16684    }
16685 
16686    if (global_match_auth_username) {
16687       /*
16688        * XXX This is experimental code to grab the search key from the
16689        * Auth header's username instead of the 'From' name, if available.
16690        * Do not enable this block unless you understand the side effects (if any!)
16691        * Note, the search for "username" should be done in a more robust way.
16692        * Note2, at the moment we check both fields, though maybe we should
16693        * pick one or another depending on the request ? XXX
16694        */
16695       const char *hdr = sip_get_header(req, "Authorization");
16696       if (ast_strlen_zero(hdr)) {
16697          hdr = sip_get_header(req, "Proxy-Authorization");
16698       }
16699 
16700       if (!ast_strlen_zero(hdr) && (hdr = strstr(hdr, "username=\""))) {
16701          ast_copy_string(from, hdr + strlen("username=\""), sizeof(from));
16702          name = from;
16703          name = strsep(&name, "\"");
16704       }
16705    }
16706 
16707    res = check_peer_ok(p, name, req, sipmethod, addr,
16708          authpeer, reliable, calleridname, uri2);
16709    if (res != AUTH_DONT_KNOW) {
16710       return res;
16711    }
16712 
16713    /* Finally, apply the guest policy */
16714    if (sip_cfg.allowguest) {
16715       get_rpid(p, req);
16716       p->rtptimeout = global_rtptimeout;
16717       p->rtpholdtimeout = global_rtpholdtimeout;
16718       p->rtpkeepalive = global_rtpkeepalive;
16719       if (!dialog_initialize_rtp(p)) {
16720          res = AUTH_SUCCESSFUL;
16721       } else {
16722          res = AUTH_RTP_FAILED;
16723       }
16724    } else if (sip_cfg.alwaysauthreject) {
16725       res = AUTH_FAKE_AUTH; /* reject with fake authorization request */
16726    } else {
16727       res = AUTH_SECRET_FAILED; /* we don't want any guests, authentication will fail */
16728    }
16729 
16730    if (ast_test_flag(&p->flags[1], SIP_PAGE2_RPORT_PRESENT)) {
16731       ast_set_flag(&p->flags[0], SIP_NAT_RPORT_PRESENT);
16732    }
16733 
16734    return res;
16735 }
16736 
16737 /*! \brief  Find user
16738    If we get a match, this will add a reference pointer to the user object in ASTOBJ, that needs to be unreferenced
16739 */
16740 static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, const char *uri, enum xmittype reliable, struct ast_sockaddr *addr)
16741 {
16742    return check_user_full(p, req, sipmethod, uri, reliable, addr, NULL);
16743 }
16744 
16745 /*! \brief Get message body from a SIP request
16746  * \param buf Destination buffer
16747  * \param len Destination buffer size
16748  * \param req The SIP request
16749  *
16750  * When parsing the request originally, the lines are split by LF or CRLF.
16751  * This function adds a single LF after every line.
16752  */
16753 static int get_msg_text(char *buf, int len, struct sip_request *req)
16754 {
16755    int x;
16756    int linelen;
16757 
16758    buf[0] = '\0';
16759    --len; /* reserve strncat null */
16760    for (x = 0; len && x < req->lines; ++x) {
16761       const char *line = REQ_OFFSET_TO_STR(req, line[x]);
16762       strncat(buf, line, len); /* safe */
16763       linelen = strlen(buf);
16764       buf += linelen;
16765       len -= linelen;
16766       if (len) {
16767          strcat(buf, "\n"); /* safe */
16768          ++buf;
16769          --len;
16770       }
16771    }
16772    return 0;
16773 }
16774 
16775 static int get_msg_text2(struct ast_str **buf, struct sip_request *req)
16776 {
16777    int i, res = 0;
16778 
16779    ast_str_reset(*buf);
16780 
16781    for (i = 0; res >= 0 && i < req->lines; i++) {
16782       const char *line = REQ_OFFSET_TO_STR(req, line[i]);
16783 
16784       res = ast_str_append(buf, 0, "%s\n", line);
16785    }
16786 
16787    return res < 0 ? -1 : 0;
16788 }
16789 
16790 static int set_message_vars_from_req(struct ast_msg *msg, struct sip_request *req)
16791 {
16792    size_t x;
16793    char name_buf[1024];
16794    char val_buf[1024];
16795    const char *name;
16796    char *c;
16797    int res = 0;
16798 
16799    for (x = 0; x < req->headers; x++) {
16800       const char *header = REQ_OFFSET_TO_STR(req, header[x]);
16801 
16802       if ((c = strchr(header, ':'))) {
16803          ast_copy_string(name_buf, header, MIN((c - header + 1), sizeof(name_buf)));
16804          ast_copy_string(val_buf, ast_skip_blanks(c + 1), sizeof(val_buf));
16805          ast_trim_blanks(name_buf);
16806 
16807          /* Convert header name to full name alias. */
16808          name = find_full_alias(name_buf, name_buf);
16809 
16810          res = ast_msg_set_var(msg, name, val_buf);
16811          if (res) {
16812             break;
16813          }
16814       }
16815    }
16816    return res;
16817 }
16818 
16819 AST_THREADSTORAGE(sip_msg_buf);
16820 
16821 /*! \brief  Receive SIP MESSAGE method messages
16822 \note We only handle messages within current calls currently
16823    Reference: RFC 3428 */
16824 static void receive_message(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, const char *e)
16825 {
16826    struct ast_str *buf;
16827    char *cbuf;
16828    size_t len;
16829    struct ast_frame f;
16830    const char *content_type = sip_get_header(req, "Content-Type");
16831    struct ast_msg *msg;
16832    int res;
16833    char *from;
16834    char *to;
16835    char from_name[50];
16836 
16837    if (strncmp(content_type, "text/plain", strlen("text/plain"))) { /* No text/plain attachment */
16838       transmit_response(p, "415 Unsupported Media Type", req); /* Good enough, or? */
16839       if (!p->owner) {
16840          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
16841       }
16842       return;
16843    }
16844 
16845    if (!(buf = ast_str_thread_get(&sip_msg_buf, 128))) {
16846       transmit_response(p, "500 Internal Server Error", req);
16847       if (!p->owner) {
16848          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
16849       }
16850       return;
16851    }
16852 
16853    if (get_msg_text2(&buf, req)) {
16854       ast_log(LOG_WARNING, "Unable to retrieve text from %s\n", p->callid);
16855       transmit_response(p, "500 Internal Server Error", req);
16856       if (!p->owner) {
16857          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
16858       }
16859       return;
16860    }
16861 
16862    /* Strip trailing line feeds from message body. (get_msg_text2 may add
16863     * a trailing linefeed and we don't need any at the end) */
16864    cbuf = ast_str_buffer(buf);
16865    len = ast_str_strlen(buf);
16866    while (len > 0) {
16867       if (cbuf[--len] != '\n') {
16868          ++len;
16869          break;
16870       }
16871    }
16872    ast_str_truncate(buf, len);
16873 
16874    if (p->owner) {
16875       if (sip_debug_test_pvt(p)) {
16876          ast_verbose("SIP Text message received: '%s'\n", ast_str_buffer(buf));
16877       }
16878       memset(&f, 0, sizeof(f));
16879       f.frametype = AST_FRAME_TEXT;
16880       f.subclass.integer = 0;
16881       f.offset = 0;
16882       f.data.ptr = ast_str_buffer(buf);
16883       f.datalen = ast_str_strlen(buf) + 1;
16884       ast_queue_frame(p->owner, &f);
16885       transmit_response(p, "202 Accepted", req); /* We respond 202 accepted, since we relay the message */
16886       return;
16887    }
16888 
16889    /*
16890     * At this point MESSAGE is outside of a call.
16891     *
16892     * NOTE: p->owner is NULL so no additional check is needed after
16893     * this point.
16894     */
16895 
16896    if (!sip_cfg.accept_outofcall_message) {
16897       /* Message outside of a call, we do not support that */
16898       ast_debug(1, "MESSAGE outside of a call administratively disabled.\n");
16899       transmit_response(p, "405 Method Not Allowed", req);
16900       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
16901       return;
16902    }
16903 
16904    copy_request(&p->initreq, req);
16905 
16906    if (sip_cfg.auth_message_requests) {
16907       int res;
16908 
16909       set_pvt_allowed_methods(p, req);
16910       res = check_user(p, req, SIP_MESSAGE, e, XMIT_UNRELIABLE, addr);
16911       if (res == AUTH_CHALLENGE_SENT) {
16912          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
16913          return;
16914       }
16915       if (res < 0) { /* Something failed in authentication */
16916          if (res == AUTH_FAKE_AUTH) {
16917             ast_log(LOG_NOTICE, "Sending fake auth rejection for device %s\n", sip_get_header(req, "From"));
16918             transmit_fake_auth_response(p, SIP_MESSAGE, req, XMIT_UNRELIABLE);
16919          } else {
16920             ast_log(LOG_NOTICE, "Failed to authenticate device %s\n", sip_get_header(req, "From"));
16921             transmit_response(p, "403 Forbidden", req);
16922          }
16923          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
16924          return;
16925       }
16926       /* Auth was successful.  Proceed. */
16927    } else {
16928       struct sip_peer *peer;
16929 
16930       /*
16931        * MESSAGE outside of a call, not authenticating it.
16932        * Check to see if we match a peer anyway so that we can direct
16933        * it to the right context.
16934        */
16935 
16936       peer = sip_find_peer(NULL, &p->recv, TRUE, FINDPEERS, 0, p->socket.type);
16937       if (peer) {
16938          /* Only if no auth is required. */
16939          if (ast_strlen_zero(peer->secret) && ast_strlen_zero(peer->md5secret)) {
16940             ast_string_field_set(p, context, peer->context);
16941          }
16942          if (!ast_strlen_zero(peer->messagecontext)) {
16943             ast_string_field_set(p, messagecontext, peer->messagecontext);
16944          }
16945          ast_string_field_set(p, peername, peer->name);
16946          peer = sip_unref_peer(peer, "from sip_find_peer() in receive_message");
16947       }
16948    }
16949 
16950    /* Override the context with the message context _BEFORE_
16951     * getting the destination.  This way we can guarantee the correct
16952     * extension is used in the message context when it is present. */
16953    if (!ast_strlen_zero(p->messagecontext)) {
16954       ast_string_field_set(p, context, p->messagecontext);
16955    } else if (!ast_strlen_zero(sip_cfg.messagecontext)) {
16956       ast_string_field_set(p, context, sip_cfg.messagecontext);
16957    }
16958 
16959    get_destination(p, NULL, NULL);
16960 
16961    if (!(msg = ast_msg_alloc())) {
16962       transmit_response(p, "500 Internal Server Error", req);
16963       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
16964       return;
16965    }
16966 
16967    to = ast_strdupa(REQ_OFFSET_TO_STR(req, rlPart2));
16968    from = ast_strdupa(sip_get_header(req, "From"));
16969 
16970    res = ast_msg_set_to(msg, "%s", to);
16971 
16972    /* Build "display" <uri> for from string. */
16973    from = (char *) get_calleridname(from, from_name, sizeof(from_name));
16974    from = get_in_brackets(from);
16975    if (from_name[0]) {
16976       res |= ast_msg_set_from(msg, "\"%s\" <%s>", from_name, from);
16977    } else {
16978       res |= ast_msg_set_from(msg, "<%s>", from);
16979    }
16980 
16981    res |= ast_msg_set_body(msg, "%s", ast_str_buffer(buf));
16982    res |= ast_msg_set_context(msg, "%s", p->context);
16983 
16984    if (!ast_strlen_zero(p->peername)) {
16985       res |= ast_msg_set_var(msg, "SIP_PEERNAME", p->peername);
16986    }
16987 
16988    res |= ast_msg_set_exten(msg, "%s", p->exten);
16989    res |= set_message_vars_from_req(msg, req);
16990 
16991    if (res) {
16992       ast_msg_destroy(msg);
16993       transmit_response(p, "500 Internal Server Error", req);
16994    } else {
16995       ast_msg_queue(msg);
16996       transmit_response(p, "202 Accepted", req);
16997    }
16998 
16999    sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
17000 }
17001 
17002 /*! \brief  CLI Command to show calls within limits set by call_limit */
17003 static char *sip_show_inuse(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
17004 {
17005 #define FORMAT "%-25.25s %-15.15s %-15.15s \n"
17006 #define FORMAT2 "%-25.25s %-15.15s %-15.15s \n"
17007    char ilimits[40];
17008    char iused[40];
17009    int showall = FALSE;
17010    struct ao2_iterator i;
17011    struct sip_peer *peer;
17012    
17013    switch (cmd) {
17014    case CLI_INIT:
17015       e->command = "sip show inuse";
17016       e->usage =
17017          "Usage: sip show inuse [all]\n"
17018          "       List all SIP devices usage counters and limits.\n"
17019          "       Add option \"all\" to show all devices, not only those with a limit.\n";
17020       return NULL;
17021    case CLI_GENERATE:
17022       return NULL;
17023    }
17024 
17025    if (a->argc < 3)
17026       return CLI_SHOWUSAGE;
17027 
17028    if (a->argc == 4 && !strcmp(a->argv[3], "all"))
17029       showall = TRUE;
17030    
17031    ast_cli(a->fd, FORMAT, "* Peer name", "In use", "Limit");
17032 
17033    i = ao2_iterator_init(peers, 0);
17034    while ((peer = ao2_t_iterator_next(&i, "iterate thru peer table"))) {
17035       ao2_lock(peer);
17036       if (peer->call_limit)
17037          snprintf(ilimits, sizeof(ilimits), "%d", peer->call_limit);
17038       else
17039          ast_copy_string(ilimits, "N/A", sizeof(ilimits));
17040       snprintf(iused, sizeof(iused), "%d/%d/%d", peer->inUse, peer->inRinging, peer->onHold);
17041       if (showall || peer->call_limit)
17042          ast_cli(a->fd, FORMAT2, peer->name, iused, ilimits);
17043       ao2_unlock(peer);
17044       sip_unref_peer(peer, "toss iterator pointer");
17045    }
17046    ao2_iterator_destroy(&i);
17047 
17048    return CLI_SUCCESS;
17049 #undef FORMAT
17050 #undef FORMAT2
17051 }
17052 
17053 
17054 /*! \brief Convert transfer mode to text string */
17055 static char *transfermode2str(enum transfermodes mode)
17056 {
17057    if (mode == TRANSFER_OPENFORALL)
17058       return "open";
17059    else if (mode == TRANSFER_CLOSED)
17060       return "closed";
17061    return "strict";
17062 }
17063 
17064 /*! \brief  Report Peer status in character string
17065  *  \return 0 if peer is unreachable, 1 if peer is online, -1 if unmonitored
17066  */
17067 
17068 
17069 /* Session-Timer Modes */
17070 static const struct _map_x_s stmodes[] = {
17071         { SESSION_TIMER_MODE_ACCEPT,    "Accept"},
17072         { SESSION_TIMER_MODE_ORIGINATE, "Originate"},
17073         { SESSION_TIMER_MODE_REFUSE,    "Refuse"},
17074         { -1,                           NULL},
17075 };
17076 
17077 static const char *stmode2str(enum st_mode m)
17078 {
17079    return map_x_s(stmodes, m, "Unknown");
17080 }
17081 
17082 static enum st_mode str2stmode(const char *s)
17083 {
17084    return map_s_x(stmodes, s, -1);
17085 }
17086 
17087 /* Session-Timer Refreshers */
17088 static const struct _map_x_s strefreshers[] = {
17089         { SESSION_TIMER_REFRESHER_AUTO,     "auto"},
17090         { SESSION_TIMER_REFRESHER_UAC,      "uac"},
17091         { SESSION_TIMER_REFRESHER_UAS,      "uas"},
17092         { -1,                               NULL},
17093 };
17094 
17095 static const char *strefresher2str(enum st_refresher r)
17096 {
17097    return map_x_s(strefreshers, r, "Unknown");
17098 }
17099 
17100 static enum st_refresher str2strefresher(const char *s)
17101 {
17102    return map_s_x(strefreshers, s, -1);
17103 }
17104 
17105 /* Autocreatepeer modes */
17106 static struct _map_x_s autopeermodes[] = {
17107         { AUTOPEERS_DISABLED, "Off"},
17108         { AUTOPEERS_VOLATILE, "Volatile"},
17109         { AUTOPEERS_PERSIST,  "Persisted"},
17110         { -1, NULL},
17111 };
17112 
17113 static const char *autocreatepeer2str(enum autocreatepeer_mode r)
17114 {
17115    return map_x_s(autopeermodes, r, "Unknown");
17116 }
17117 
17118 static int peer_status(struct sip_peer *peer, char *status, int statuslen)
17119 {
17120    int res = 0;
17121    if (peer->maxms) {
17122       if (peer->lastms < 0) {
17123          ast_copy_string(status, "UNREACHABLE", statuslen);
17124       } else if (peer->lastms > peer->maxms) {
17125          snprintf(status, statuslen, "LAGGED (%d ms)", peer->lastms);
17126          res = 1;
17127       } else if (peer->lastms) {
17128          snprintf(status, statuslen, "OK (%d ms)", peer->lastms);
17129          res = 1;
17130       } else {
17131          ast_copy_string(status, "UNKNOWN", statuslen);
17132       }
17133    } else {
17134       ast_copy_string(status, "Unmonitored", statuslen);
17135       /* Checking if port is 0 */
17136       res = -1;
17137    }
17138    return res;
17139 }
17140 
17141 /*! \brief  Show active TCP connections */
17142 static char *sip_show_tcp(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
17143 {
17144    struct sip_threadinfo *th;
17145    struct ao2_iterator i;
17146 
17147 #define FORMAT2 "%-47.47s %9.9s %6.6s\n"
17148 #define FORMAT  "%-47.47s %-9.9s %-6.6s\n"
17149 
17150    switch (cmd) {
17151    case CLI_INIT:
17152       e->command = "sip show tcp";
17153       e->usage =
17154          "Usage: sip show tcp\n"
17155          "       Lists all active TCP/TLS sessions.\n";
17156       return NULL;
17157    case CLI_GENERATE:
17158       return NULL;
17159    }
17160 
17161    if (a->argc != 3)
17162       return CLI_SHOWUSAGE;
17163 
17164    ast_cli(a->fd, FORMAT2, "Address", "Transport", "Type");
17165 
17166    i = ao2_iterator_init(threadt, 0);
17167    while ((th = ao2_t_iterator_next(&i, "iterate through tcp threads for 'sip show tcp'"))) {
17168       ast_cli(a->fd, FORMAT,
17169          ast_sockaddr_stringify(&th->tcptls_session->remote_address),
17170          sip_get_transport(th->type),
17171          (th->tcptls_session->client ? "Client" : "Server"));
17172       ao2_t_ref(th, -1, "decrement ref from iterator");
17173    }
17174    ao2_iterator_destroy(&i);
17175 
17176    return CLI_SUCCESS;
17177 #undef FORMAT
17178 #undef FORMAT2
17179 }
17180 
17181 /*! \brief  CLI Command 'SIP Show Users' */
17182 static char *sip_show_users(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
17183 {
17184    regex_t regexbuf;
17185    int havepattern = FALSE;
17186    struct ao2_iterator user_iter;
17187    struct sip_peer *user;
17188 
17189 #define FORMAT  "%-25.25s  %-15.15s  %-15.15s  %-15.15s  %-5.5s%-10.10s\n"
17190 
17191    switch (cmd) {
17192    case CLI_INIT:
17193       e->command = "sip show users";
17194       e->usage =
17195          "Usage: sip show users [like <pattern>]\n"
17196          "       Lists all known SIP users.\n"
17197          "       Optional regular expression pattern is used to filter the user list.\n";
17198       return NULL;
17199    case CLI_GENERATE:
17200       return NULL;
17201    }
17202 
17203    switch (a->argc) {
17204    case 5:
17205       if (!strcasecmp(a->argv[3], "like")) {
17206          if (regcomp(&regexbuf, a->argv[4], REG_EXTENDED | REG_NOSUB))
17207             return CLI_SHOWUSAGE;
17208          havepattern = TRUE;
17209       } else
17210          return CLI_SHOWUSAGE;
17211    case 3:
17212       break;
17213    default:
17214       return CLI_SHOWUSAGE;
17215    }
17216 
17217    ast_cli(a->fd, FORMAT, "Username", "Secret", "Accountcode", "Def.Context", "ACL", "ForcerPort");
17218 
17219    user_iter = ao2_iterator_init(peers, 0);
17220    while ((user = ao2_t_iterator_next(&user_iter, "iterate thru peers table"))) {
17221       ao2_lock(user);
17222       if (!(user->type & SIP_TYPE_USER)) {
17223          ao2_unlock(user);
17224          sip_unref_peer(user, "sip show users");
17225          continue;
17226       }
17227 
17228       if (havepattern && regexec(&regexbuf, user->name, 0, NULL, 0)) {
17229          ao2_unlock(user);
17230          sip_unref_peer(user, "sip show users");
17231          continue;
17232       }
17233 
17234       ast_cli(a->fd, FORMAT, user->name,
17235          user->secret,
17236          user->accountcode,
17237          user->context,
17238          AST_CLI_YESNO(user->ha != NULL),
17239          AST_CLI_YESNO(ast_test_flag(&user->flags[0], SIP_NAT_FORCE_RPORT)));
17240       ao2_unlock(user);
17241       sip_unref_peer(user, "sip show users");
17242    }
17243    ao2_iterator_destroy(&user_iter);
17244 
17245    if (havepattern)
17246       regfree(&regexbuf);
17247 
17248    return CLI_SUCCESS;
17249 #undef FORMAT
17250 }
17251 
17252 /*! \brief Show SIP registrations in the manager API */
17253 static int manager_show_registry(struct mansession *s, const struct message *m)
17254 {
17255    const char *id = astman_get_header(m, "ActionID");
17256    char idtext[256] = "";
17257    int total = 0;
17258 
17259    if (!ast_strlen_zero(id))
17260       snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
17261 
17262    astman_send_listack(s, m, "Registrations will follow", "start");
17263 
17264    ASTOBJ_CONTAINER_TRAVERSE(&regl, 1, do {
17265       ASTOBJ_RDLOCK(iterator);
17266       astman_append(s,
17267          "Event: RegistryEntry\r\n"
17268          "%s"
17269          "Host: %s\r\n"
17270          "Port: %d\r\n"
17271          "Username: %s\r\n"
17272          "Domain: %s\r\n"
17273          "DomainPort: %d\r\n"
17274          "Refresh: %d\r\n"
17275          "State: %s\r\n"
17276          "RegistrationTime: %ld\r\n"
17277          "\r\n",
17278          idtext,
17279          iterator->hostname,
17280          iterator->portno ? iterator->portno : STANDARD_SIP_PORT,
17281          iterator->username,
17282          S_OR(iterator->regdomain,iterator->hostname),
17283          iterator->regdomainport ? iterator->regdomainport : STANDARD_SIP_PORT,
17284          iterator->refresh,
17285          regstate2str(iterator->regstate),
17286          (long) iterator->regtime.tv_sec);
17287       ASTOBJ_UNLOCK(iterator);
17288       total++;
17289    } while(0));
17290 
17291    astman_append(s,
17292       "Event: RegistrationsComplete\r\n"
17293       "EventList: Complete\r\n"
17294       "ListItems: %d\r\n"
17295       "%s"
17296       "\r\n", total, idtext);
17297    
17298    return 0;
17299 }
17300 
17301 /*! \brief  Show SIP peers in the manager API */
17302 /*    Inspired from chan_iax2 */
17303 static int manager_sip_show_peers(struct mansession *s, const struct message *m)
17304 {
17305    const char *id = astman_get_header(m, "ActionID");
17306    const char *a[] = {"sip", "show", "peers"};
17307    char idtext[256] = "";
17308    int total = 0;
17309 
17310    if (!ast_strlen_zero(id))
17311       snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
17312 
17313    astman_send_listack(s, m, "Peer status list will follow", "start");
17314    /* List the peers in separate manager events */
17315    _sip_show_peers(-1, &total, s, m, 3, a);
17316    /* Send final confirmation */
17317    astman_append(s,
17318    "Event: PeerlistComplete\r\n"
17319    "EventList: Complete\r\n"
17320    "ListItems: %d\r\n"
17321    "%s"
17322    "\r\n", total, idtext);
17323    return 0;
17324 }
17325 
17326 /*! \brief  CLI Show Peers command */
17327 static char *sip_show_peers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
17328 {
17329    switch (cmd) {
17330    case CLI_INIT:
17331       e->command = "sip show peers";
17332       e->usage =
17333          "Usage: sip show peers [like <pattern>]\n"
17334          "       Lists all known SIP peers.\n"
17335          "       Optional regular expression pattern is used to filter the peer list.\n";
17336       return NULL;
17337    case CLI_GENERATE:
17338       return NULL;
17339    }
17340 
17341    return _sip_show_peers(a->fd, NULL, NULL, NULL, a->argc, (const char **) a->argv);
17342 }
17343 
17344 int peercomparefunc(const void *a, const void *b);
17345 
17346 int peercomparefunc(const void *a, const void *b)
17347 {
17348    struct sip_peer **ap = (struct sip_peer **)a;
17349    struct sip_peer **bp = (struct sip_peer **)b;
17350    return strcmp((*ap)->name, (*bp)->name);
17351 }
17352 
17353 
17354 /*! \brief Execute sip show peers command */
17355 static char *_sip_show_peers(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char *argv[])
17356 {
17357    regex_t regexbuf;
17358    int havepattern = FALSE;
17359    struct sip_peer *peer;
17360    struct ao2_iterator i;
17361 
17362 /* the last argument is left-aligned, so we don't need a size anyways */
17363 #define FORMAT2 "%-25.25s %-39.39s %-3.3s %-10.10s %-3.3s %-8s %-11s %-32.32s %s\n"
17364 
17365    char name[256];
17366    int total_peers = 0;
17367    int peers_mon_online = 0;
17368    int peers_mon_offline = 0;
17369    int peers_unmon_offline = 0;
17370    int peers_unmon_online = 0;
17371    const char *id;
17372    char idtext[256] = "";
17373    int realtimepeers;
17374    int objcount = ao2_container_count(peers);
17375    struct sip_peer **peerarray;
17376    int k;
17377 
17378    realtimepeers = ast_check_realtime("sippeers");
17379    peerarray = ast_calloc(sizeof(struct sip_peer *), objcount);
17380 
17381    if (s) { /* Manager - get ActionID */
17382       id = astman_get_header(m, "ActionID");
17383       if (!ast_strlen_zero(id))
17384          snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
17385    }
17386 
17387    switch (argc) {
17388    case 5:
17389       if (!strcasecmp(argv[3], "like")) {
17390          if (regcomp(&regexbuf, argv[4], REG_EXTENDED | REG_NOSUB))
17391             return CLI_SHOWUSAGE;
17392          havepattern = TRUE;
17393       } else
17394          return CLI_SHOWUSAGE;
17395    case 3:
17396       break;
17397    default:
17398       return CLI_SHOWUSAGE;
17399    }
17400 
17401    if (!s) /* Normal list */
17402       ast_cli(fd, FORMAT2, "Name/username", "Host", "Dyn", "Forcerport", "ACL", "Port", "Status", "Description", (realtimepeers ? "Realtime" : ""));
17403 
17404    i = ao2_iterator_init(peers, 0);
17405    while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
17406       ao2_lock(peer);
17407 
17408       if (!(peer->type & SIP_TYPE_PEER)) {
17409          ao2_unlock(peer);
17410          sip_unref_peer(peer, "unref peer because it's actually a user");
17411          continue;
17412       }
17413 
17414       if (havepattern && regexec(&regexbuf, peer->name, 0, NULL, 0)) {
17415          objcount--;
17416          ao2_unlock(peer);
17417          sip_unref_peer(peer, "toss iterator peer ptr before continue");
17418          continue;
17419       }
17420 
17421       peerarray[total_peers++] = peer;
17422       ao2_unlock(peer);
17423    }
17424    ao2_iterator_destroy(&i);
17425 
17426    qsort(peerarray, total_peers, sizeof(struct sip_peer *), peercomparefunc);
17427 
17428    for(k=0; k < total_peers; k++) {
17429       char status[20] = "";
17430       char srch[2000];
17431       char pstatus;
17432 
17433       /*
17434        * tmp_port and tmp_host store copies of ast_sockaddr_stringify strings since the
17435        * string pointers for that function aren't valid between subsequent calls to
17436        * ast_sockaddr_stringify functions
17437        */
17438       char *tmp_port;
17439       char *tmp_host;
17440 
17441       peer = peerarray[k];
17442 
17443       tmp_port = ast_sockaddr_isnull(&peer->addr) ?
17444          "0" : ast_strdupa(ast_sockaddr_stringify_port(&peer->addr));
17445 
17446       tmp_host = ast_sockaddr_isnull(&peer->addr) ?
17447          "(Unspecified)" : ast_strdupa(ast_sockaddr_stringify_addr(&peer->addr));
17448 
17449       ao2_lock(peer);
17450       if (havepattern && regexec(&regexbuf, peer->name, 0, NULL, 0)) {
17451          ao2_unlock(peer);
17452          peer = peerarray[k] = sip_unref_peer(peer, "toss iterator peer ptr before continue");
17453          continue;
17454       }
17455 
17456       if (!ast_strlen_zero(peer->username) && !s)
17457          snprintf(name, sizeof(name), "%s/%s", peer->name, peer->username);
17458       else
17459          ast_copy_string(name, peer->name, sizeof(name));
17460 
17461       pstatus = peer_status(peer, status, sizeof(status));
17462       if (pstatus == 1)
17463          peers_mon_online++;
17464       else if (pstatus == 0)
17465          peers_mon_offline++;
17466       else {
17467          if (ast_sockaddr_isnull(&peer->addr) ||
17468              !ast_sockaddr_port(&peer->addr)) {
17469             peers_unmon_offline++;
17470          } else {
17471             peers_unmon_online++;
17472          }
17473       }
17474 
17475       snprintf(srch, sizeof(srch), FORMAT2, name,
17476          tmp_host,
17477          peer->host_dynamic ? " D " : "   ", /* Dynamic or not? */
17478          ast_test_flag(&peer->flags[2], SIP_PAGE3_NAT_AUTO_RPORT) ?
17479             ast_test_flag(&peer->flags[0], SIP_NAT_FORCE_RPORT) ? " A " : " a " :
17480             ast_test_flag(&peer->flags[0], SIP_NAT_FORCE_RPORT) ? " N " : "   ", /* NAT=yes? */
17481          peer->ha ? " A " : "   ",  /* permit/deny */
17482          tmp_port, status,
17483          peer->description ? peer->description : "",
17484          realtimepeers ? (peer->is_realtime ? "Cached RT":"") : "");
17485 
17486       if (!s)  {/* Normal CLI list */
17487          ast_cli(fd, FORMAT2, name,
17488          tmp_host,
17489          peer->host_dynamic ? " D " : "   ", /* Dynamic or not? */
17490          ast_test_flag(&peer->flags[2], SIP_PAGE3_NAT_AUTO_RPORT) ?
17491             ast_test_flag(&peer->flags[0], SIP_NAT_FORCE_RPORT) ? " A " : " a " :
17492             ast_test_flag(&peer->flags[0], SIP_NAT_FORCE_RPORT) ? " N " : "   ", /* NAT=yes? */
17493          peer->ha ? " A " : "   ",       /* permit/deny */
17494          tmp_port, status,
17495          peer->description ? peer->description : "",
17496          realtimepeers ? (peer->is_realtime ? "Cached RT":"") : "");
17497       } else { /* Manager format */
17498          /* The names here need to be the same as other channels */
17499          astman_append(s,
17500          "Event: PeerEntry\r\n%s"
17501          "Channeltype: SIP\r\n"
17502          "ObjectName: %s\r\n"
17503          "ChanObjectType: peer\r\n" /* "peer" or "user" */
17504          "IPaddress: %s\r\n"
17505          "IPport: %s\r\n"
17506          "Dynamic: %s\r\n"
17507          "AutoForcerport: %s\r\n"
17508          "Forcerport: %s\r\n"
17509          "AutoComedia: %s\r\n"
17510          "Comedia: %s\r\n"
17511          "VideoSupport: %s\r\n"
17512          "TextSupport: %s\r\n"
17513          "ACL: %s\r\n"
17514          "Status: %s\r\n"
17515          "RealtimeDevice: %s\r\n"
17516          "Description: %s\r\n\r\n",
17517          idtext,
17518          peer->name,
17519          ast_sockaddr_isnull(&peer->addr) ? "-none-" : tmp_host,
17520          ast_sockaddr_isnull(&peer->addr) ? "0" : tmp_port,
17521          peer->host_dynamic ? "yes" : "no",  /* Dynamic or not? */
17522          ast_test_flag(&peer->flags[2], SIP_PAGE3_NAT_AUTO_RPORT) ? "yes" : "no",
17523          ast_test_flag(&peer->flags[0], SIP_NAT_FORCE_RPORT) ? "yes" : "no",  /* NAT=yes? */
17524          ast_test_flag(&peer->flags[2], SIP_PAGE3_NAT_AUTO_COMEDIA) ? "yes" : "no",
17525          ast_test_flag(&peer->flags[1], SIP_PAGE2_SYMMETRICRTP) ? "yes" : "no",
17526          ast_test_flag(&peer->flags[1], SIP_PAGE2_VIDEOSUPPORT) ? "yes" : "no",  /* VIDEOSUPPORT=yes? */
17527          ast_test_flag(&peer->flags[1], SIP_PAGE2_TEXTSUPPORT) ? "yes" : "no",   /* TEXTSUPPORT=yes? */
17528          peer->ha ? "yes" : "no",       /* permit/deny */
17529          status,
17530          realtimepeers ? (peer->is_realtime ? "yes":"no") : "no",
17531          peer->description);
17532       }
17533       ao2_unlock(peer);
17534       peer = peerarray[k] = sip_unref_peer(peer, "toss iterator peer ptr");
17535    }
17536 
17537    if (!s)
17538       ast_cli(fd, "%d sip peers [Monitored: %d online, %d offline Unmonitored: %d online, %d offline]\n",
17539               total_peers, peers_mon_online, peers_mon_offline, peers_unmon_online, peers_unmon_offline);
17540 
17541    if (havepattern)
17542       regfree(&regexbuf);
17543 
17544    if (total)
17545       *total = total_peers;
17546 
17547    ast_free(peerarray);
17548 
17549    return CLI_SUCCESS;
17550 #undef FORMAT2
17551 }
17552 
17553 static int peer_dump_func(void *userobj, void *arg, int flags)
17554 {
17555    struct sip_peer *peer = userobj;
17556    int refc = ao2_t_ref(userobj, 0, "");
17557    struct ast_cli_args *a = (struct ast_cli_args *) arg;
17558    
17559    ast_cli(a->fd, "name: %s\ntype: peer\nobjflags: %d\nrefcount: %d\n\n",
17560       peer->name, 0, refc);
17561    return 0;
17562 }
17563 
17564 static int dialog_dump_func(void *userobj, void *arg, int flags)
17565 {
17566    struct sip_pvt *pvt = userobj;
17567    int refc = ao2_t_ref(userobj, 0, "");
17568    struct ast_cli_args *a = (struct ast_cli_args *) arg;
17569    
17570    ast_cli(a->fd, "name: %s\ntype: dialog\nobjflags: %d\nrefcount: %d\n\n",
17571       pvt->callid, 0, refc);
17572    return 0;
17573 }
17574 
17575 
17576 /*! \brief List all allocated SIP Objects (realtime or static) */
17577 static char *sip_show_objects(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
17578 {
17579    char tmp[256];
17580    
17581    switch (cmd) {
17582    case CLI_INIT:
17583       e->command = "sip show objects";
17584       e->usage =
17585          "Usage: sip show objects\n"
17586          "       Lists status of known SIP objects\n";
17587       return NULL;
17588    case CLI_GENERATE:
17589       return NULL;
17590    }  
17591 
17592    if (a->argc != 3)
17593       return CLI_SHOWUSAGE;
17594    ast_cli(a->fd, "-= Peer objects: %d static, %d realtime, %d autocreate =-\n\n", speerobjs, rpeerobjs, apeerobjs);
17595    ao2_t_callback(peers, OBJ_NODATA, peer_dump_func, a, "initiate ao2_callback to dump peers");
17596    ast_cli(a->fd, "-= Peer objects by IP =-\n\n"); 
17597    ao2_t_callback(peers_by_ip, OBJ_NODATA, peer_dump_func, a, "initiate ao2_callback to dump peers_by_ip");
17598    ast_cli(a->fd, "-= Registry objects: %d =-\n\n", regobjs);
17599    ASTOBJ_CONTAINER_DUMP(a->fd, tmp, sizeof(tmp), &regl);
17600    ast_cli(a->fd, "-= Dialog objects:\n\n");
17601    ao2_t_callback(dialogs, OBJ_NODATA, dialog_dump_func, a, "initiate ao2_callback to dump dialogs");
17602    return CLI_SUCCESS;
17603 }
17604 /*! \brief Print call group and pickup group */
17605 static void print_group(int fd, ast_group_t group, int crlf)
17606 {
17607    char buf[256];
17608    ast_cli(fd, crlf ? "%s\r\n" : "%s\n", ast_print_group(buf, sizeof(buf), group) );
17609 }
17610 
17611 /*! \brief mapping between dtmf flags and strings */
17612 static const struct _map_x_s dtmfstr[] = {
17613    { SIP_DTMF_RFC2833,     "rfc2833" },
17614    { SIP_DTMF_INFO,        "info" },
17615    { SIP_DTMF_SHORTINFO,   "shortinfo" },
17616    { SIP_DTMF_INBAND,      "inband" },
17617    { SIP_DTMF_AUTO,        "auto" },
17618    { -1,                   NULL }, /* terminator */
17619 };
17620 
17621 /*! \brief Convert DTMF mode to printable string */
17622 static const char *dtmfmode2str(int mode)
17623 {
17624    return map_x_s(dtmfstr, mode, "<error>");
17625 }
17626 
17627 /*! \brief maps a string to dtmfmode, returns -1 on error */
17628 static int str2dtmfmode(const char *str)
17629 {
17630    return map_s_x(dtmfstr, str, -1);
17631 }
17632 
17633 static const struct _map_x_s insecurestr[] = {
17634    { SIP_INSECURE_PORT,    "port" },
17635    { SIP_INSECURE_INVITE,  "invite" },
17636    { SIP_INSECURE_PORT | SIP_INSECURE_INVITE, "port,invite" },
17637    { 0,                    "no" },
17638    { -1,                   NULL }, /* terminator */
17639 };
17640 
17641 /*! \brief Convert Insecure setting to printable string */
17642 static const char *insecure2str(int mode)
17643 {
17644    return map_x_s(insecurestr, mode, "<error>");
17645 }
17646 
17647 static const struct _map_x_s allowoverlapstr[] = {
17648    { SIP_PAGE2_ALLOWOVERLAP_YES,   "Yes" },
17649    { SIP_PAGE2_ALLOWOVERLAP_DTMF,  "DTMF" },
17650    { SIP_PAGE2_ALLOWOVERLAP_NO,    "No" },
17651    { -1,                           NULL }, /* terminator */
17652 };
17653 
17654 /*! \brief Convert AllowOverlap setting to printable string */
17655 static const char *allowoverlap2str(int mode)
17656 {
17657    return map_x_s(allowoverlapstr, mode, "<error>");
17658 }
17659 
17660 /*! \brief Destroy disused contexts between reloads
17661    Only used in reload_config so the code for regcontext doesn't get ugly
17662 */
17663 static void cleanup_stale_contexts(char *new, char *old)
17664 {
17665    char *oldcontext, *newcontext, *stalecontext, *stringp, newlist[AST_MAX_CONTEXT];
17666 
17667    while ((oldcontext = strsep(&old, "&"))) {
17668       stalecontext = '\0';
17669       ast_copy_string(newlist, new, sizeof(newlist));
17670       stringp = newlist;
17671       while ((newcontext = strsep(&stringp, "&"))) {
17672          if (!strcmp(newcontext, oldcontext)) {
17673             /* This is not the context you're looking for */
17674             stalecontext = '\0';
17675             break;
17676          } else if (strcmp(newcontext, oldcontext)) {
17677             stalecontext = oldcontext;
17678          }
17679          
17680       }
17681       if (stalecontext)
17682          ast_context_destroy(ast_context_find(stalecontext), "SIP");
17683    }
17684 }
17685 
17686 /*!
17687  * \brief Check RTP Timeout on dialogs
17688  *
17689  * \details This is used with ao2_callback to check rtptimeout
17690  * rtponholdtimeout and send rtpkeepalive packets.
17691  *
17692  * \return CMP_MATCH for items to be unlinked from dialogs_rtpcheck.
17693  */
17694 static int dialog_checkrtp_cb(void *dialogobj, void *arg, int flags)
17695 {
17696    struct sip_pvt *dialog = dialogobj;
17697    time_t *t = arg;
17698    int match_status;
17699 
17700    if (sip_pvt_trylock(dialog)) {
17701       return 0;
17702    }
17703 
17704    if (dialog->rtp || dialog->vrtp) {
17705       match_status = check_rtp_timeout(dialog, *t);
17706    } else {
17707       /* Dialog has no active RTP or VRTP. unlink it from dialogs_rtpcheck. */
17708       match_status = CMP_MATCH;
17709    }
17710    sip_pvt_unlock(dialog);
17711 
17712    return match_status;
17713 }
17714 
17715 /*!
17716  * \brief Match dialogs that need to be destroyed
17717  *
17718  * \details This is used with ao2_callback to unlink/delete all dialogs that
17719  * are marked needdestroy.
17720  *
17721  * \todo Re-work this to improve efficiency.  Currently, this function is called
17722  * on _every_ dialog after processing _every_ incoming SIP/UDP packet, or
17723  * potentially even more often when the scheduler has entries to run.
17724  */
17725 static int dialog_needdestroy(void *dialogobj, void *arg, int flags)
17726 {
17727    struct sip_pvt *dialog = dialogobj;
17728 
17729    if (sip_pvt_trylock(dialog)) {
17730       /* Don't block the monitor thread.  This function is called often enough
17731        * that we can wait for the next time around. */
17732       return 0;
17733    }
17734 
17735    /* If we have sessions that needs to be destroyed, do it now */
17736    /* Check if we have outstanding requests not responsed to or an active call
17737       - if that's the case, wait with destruction */
17738    if (dialog->needdestroy && !dialog->packets && !dialog->owner) {
17739       /* We absolutely cannot destroy the rtp struct while a bridge is active or we WILL crash */
17740       if (dialog->rtp && ast_rtp_instance_get_bridged(dialog->rtp)) {
17741          ast_debug(2, "Bridge still active.  Delaying destruction of SIP dialog '%s' Method: %s\n", dialog->callid, sip_methods[dialog->method].text);
17742          sip_pvt_unlock(dialog);
17743          return 0;
17744       }
17745 
17746       if (dialog->vrtp && ast_rtp_instance_get_bridged(dialog->vrtp)) {
17747          ast_debug(2, "Bridge still active.  Delaying destroy of SIP dialog '%s' Method: %s\n", dialog->callid, sip_methods[dialog->method].text);
17748          sip_pvt_unlock(dialog);
17749          return 0;
17750       }
17751 
17752       sip_pvt_unlock(dialog);
17753       /* no, the unlink should handle this: dialog_unref(dialog, "needdestroy: one more refcount decrement to allow dialog to be destroyed"); */
17754       /* the CMP_MATCH will unlink this dialog from the dialog hash table */
17755       dialog_unlink_all(dialog);
17756       return 0; /* the unlink_all should unlink this from the table, so.... no need to return a match */
17757    }
17758 
17759    sip_pvt_unlock(dialog);
17760 
17761    return 0;
17762 }
17763 
17764 /*! \brief Remove temporary realtime objects from memory (CLI) */
17765 /*! \todo XXXX Propably needs an overhaul after removal of the devices */
17766 static char *sip_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
17767 {
17768    struct sip_peer *peer, *pi;
17769    int prunepeer = FALSE;
17770    int multi = FALSE;
17771    const char *name = NULL;
17772    regex_t regexbuf;
17773    int havepattern = 0;
17774    struct ao2_iterator i;
17775    static const char * const choices[] = { "all", "like", NULL };
17776    char *cmplt;
17777    
17778    if (cmd == CLI_INIT) {
17779       e->command = "sip prune realtime [peer|all]";
17780       e->usage =
17781          "Usage: sip prune realtime [peer [<name>|all|like <pattern>]|all]\n"
17782          "       Prunes object(s) from the cache.\n"
17783          "       Optional regular expression pattern is used to filter the objects.\n";
17784       return NULL;
17785    } else if (cmd == CLI_GENERATE) {
17786       if (a->pos == 4 && !strcasecmp(a->argv[3], "peer")) {
17787          cmplt = ast_cli_complete(a->word, choices, a->n);
17788          if (!cmplt)
17789             cmplt = complete_sip_peer(a->word, a->n - sizeof(choices), SIP_PAGE2_RTCACHEFRIENDS);
17790          return cmplt;
17791       }
17792       if (a->pos == 5 && !strcasecmp(a->argv[4], "like"))
17793          return complete_sip_peer(a->word, a->n, SIP_PAGE2_RTCACHEFRIENDS);
17794       return NULL;
17795    }
17796    switch (a->argc) {
17797    case 4:
17798       name = a->argv[3];
17799       /* we accept a name in position 3, but keywords are not good. */
17800       if (!strcasecmp(name, "peer") || !strcasecmp(name, "like"))
17801          return CLI_SHOWUSAGE;
17802       prunepeer = TRUE;
17803       if (!strcasecmp(name, "all")) {
17804          multi = TRUE;
17805          name = NULL;
17806       }
17807       /* else a single name, already set */
17808       break;
17809    case 5:
17810       /* sip prune realtime {peer|like} name */
17811       name = a->argv[4];
17812       if (!strcasecmp(a->argv[3], "peer"))
17813          prunepeer = TRUE;
17814       else if (!strcasecmp(a->argv[3], "like")) {
17815          prunepeer = TRUE;
17816          multi = TRUE;
17817       } else
17818          return CLI_SHOWUSAGE;
17819       if (!strcasecmp(name, "like"))
17820          return CLI_SHOWUSAGE;
17821       if (!multi && !strcasecmp(name, "all")) {
17822          multi = TRUE;
17823          name = NULL;
17824       }
17825       break;
17826    case 6:
17827       name = a->argv[5];
17828       multi = TRUE;
17829       /* sip prune realtime {peer} like name */
17830       if (strcasecmp(a->argv[4], "like"))
17831          return CLI_SHOWUSAGE;
17832       if (!strcasecmp(a->argv[3], "peer")) {
17833          prunepeer = TRUE;
17834       } else
17835          return CLI_SHOWUSAGE;
17836       break;
17837    default:
17838       return CLI_SHOWUSAGE;
17839    }
17840 
17841    if (multi && name) {
17842       if (regcomp(&regexbuf, name, REG_EXTENDED | REG_NOSUB)) {
17843          return CLI_SHOWUSAGE;
17844       }
17845       havepattern = 1;
17846    }
17847 
17848    if (multi) {
17849       if (prunepeer) {
17850          int pruned = 0;
17851          
17852          i = ao2_iterator_init(peers, 0);
17853          while ((pi = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
17854             ao2_lock(pi);
17855             if (name && regexec(&regexbuf, pi->name, 0, NULL, 0)) {
17856                ao2_unlock(pi);
17857                sip_unref_peer(pi, "toss iterator peer ptr before continue");
17858                continue;
17859             };
17860             if (ast_test_flag(&pi->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
17861                pi->the_mark = 1;
17862                pruned++;
17863             }
17864             ao2_unlock(pi);
17865             sip_unref_peer(pi, "toss iterator peer ptr");
17866          }
17867          ao2_iterator_destroy(&i);
17868          if (pruned) {
17869             unlink_marked_peers_from_tables();
17870             ast_cli(a->fd, "%d peers pruned.\n", pruned);
17871          } else
17872             ast_cli(a->fd, "No peers found to prune.\n");
17873       }
17874    } else {
17875       if (prunepeer) {
17876          struct sip_peer tmp;
17877          ast_copy_string(tmp.name, name, sizeof(tmp.name));
17878          if ((peer = ao2_t_find(peers, &tmp, OBJ_POINTER | OBJ_UNLINK, "finding to unlink from peers"))) {
17879             if (!ast_sockaddr_isnull(&peer->addr)) {
17880                ao2_t_unlink(peers_by_ip, peer, "unlinking peer from peers_by_ip also");
17881             }
17882             if (!ast_test_flag(&peer->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
17883                ast_cli(a->fd, "Peer '%s' is not a Realtime peer, cannot be pruned.\n", name);
17884                /* put it back! */
17885                ao2_t_link(peers, peer, "link peer into peer table");
17886                if (!ast_sockaddr_isnull(&peer->addr)) {
17887                   ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
17888                }
17889             } else
17890                ast_cli(a->fd, "Peer '%s' pruned.\n", name);
17891             sip_unref_peer(peer, "sip_prune_realtime: sip_unref_peer: tossing temp peer ptr");
17892          } else
17893             ast_cli(a->fd, "Peer '%s' not found.\n", name);
17894       }
17895    }
17896 
17897    if (havepattern) {
17898       regfree(&regexbuf);
17899    }
17900 
17901    return CLI_SUCCESS;
17902 }
17903 
17904 /*! \brief Print codec list from preference to CLI/manager */
17905 static void print_codec_to_cli(int fd, struct ast_codec_pref *pref)
17906 {
17907    int x;
17908    struct ast_format codec;
17909 
17910    for(x = 0; x < AST_CODEC_PREF_SIZE; x++) {
17911       if (!(ast_codec_pref_index(pref, x, &codec))) {
17912          break;
17913       }
17914       ast_cli(fd, "%s", ast_getformatname(&codec));
17915       ast_cli(fd, ":%d", pref->framing[x]);
17916       if (x < 31 && ast_codec_pref_index(pref, x + 1, &codec))
17917          ast_cli(fd, ",");
17918    }
17919    if (!x)
17920       ast_cli(fd, "none");
17921 }
17922 
17923 /*! \brief Print domain mode to cli */
17924 static const char *domain_mode_to_text(const enum domain_mode mode)
17925 {
17926    switch (mode) {
17927    case SIP_DOMAIN_AUTO:
17928       return "[Automatic]";
17929    case SIP_DOMAIN_CONFIG:
17930       return "[Configured]";
17931    }
17932 
17933    return "";
17934 }
17935 
17936 /*! \brief CLI command to list local domains */
17937 static char *sip_show_domains(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
17938 {
17939    struct domain *d;
17940 #define FORMAT "%-40.40s %-20.20s %-16.16s\n"
17941 
17942    switch (cmd) {
17943    case CLI_INIT:
17944       e->command = "sip show domains";
17945       e->usage =
17946          "Usage: sip show domains\n"
17947          "       Lists all configured SIP local domains.\n"
17948          "       Asterisk only responds to SIP messages to local domains.\n";
17949       return NULL;
17950    case CLI_GENERATE:
17951       return NULL;
17952    }
17953 
17954    if (AST_LIST_EMPTY(&domain_list)) {
17955       ast_cli(a->fd, "SIP Domain support not enabled.\n\n");
17956       return CLI_SUCCESS;
17957    } else {
17958       ast_cli(a->fd, FORMAT, "Our local SIP domains:", "Context", "Set by");
17959       AST_LIST_LOCK(&domain_list);
17960       AST_LIST_TRAVERSE(&domain_list, d, list)
17961          ast_cli(a->fd, FORMAT, d->domain, S_OR(d->context, "(default)"),
17962             domain_mode_to_text(d->mode));
17963       AST_LIST_UNLOCK(&domain_list);
17964       ast_cli(a->fd, "\n");
17965       return CLI_SUCCESS;
17966    }
17967 }
17968 #undef FORMAT
17969 
17970 /*! \brief Show SIP peers in the manager API  */
17971 static int manager_sip_show_peer(struct mansession *s, const struct message *m)
17972 {
17973    const char *a[4];
17974    const char *peer;
17975 
17976    peer = astman_get_header(m, "Peer");
17977    if (ast_strlen_zero(peer)) {
17978       astman_send_error(s, m, "Peer: <name> missing.");
17979       return 0;
17980    }
17981    a[0] = "sip";
17982    a[1] = "show";
17983    a[2] = "peer";
17984    a[3] = peer;
17985 
17986    _sip_show_peer(1, -1, s, m, 4, a);
17987    astman_append(s, "\r\n" );
17988    return 0;
17989 }
17990 
17991 /*! \brief Show one peer in detail */
17992 static char *sip_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
17993 {
17994    switch (cmd) {
17995    case CLI_INIT:
17996       e->command = "sip show peer";
17997       e->usage =
17998          "Usage: sip show peer <name> [load]\n"
17999          "       Shows all details on one SIP peer and the current status.\n"
18000          "       Option \"load\" forces lookup of peer in realtime storage.\n";
18001       return NULL;
18002    case CLI_GENERATE:
18003       return complete_sip_show_peer(a->line, a->word, a->pos, a->n);
18004    }
18005    return _sip_show_peer(0, a->fd, NULL, NULL, a->argc, (const char **) a->argv);
18006 }
18007 
18008 /*! \brief Send qualify message to peer from cli or manager. Mostly for debugging. */
18009 static char *_sip_qualify_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[])
18010 {
18011    struct sip_peer *peer;
18012    int load_realtime;
18013 
18014    if (argc < 4)
18015       return CLI_SHOWUSAGE;
18016 
18017    load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? TRUE : FALSE;
18018    if ((peer = sip_find_peer(argv[3], NULL, load_realtime, FINDPEERS, FALSE, 0))) {
18019       sip_poke_peer(peer, 1);
18020       sip_unref_peer(peer, "qualify: done with peer");
18021    } else if (type == 0) {
18022       ast_cli(fd, "Peer '%s' not found\n", argv[3]);
18023    } else {
18024       astman_send_error(s, m, "Peer not found");
18025    }
18026    return CLI_SUCCESS;
18027 }
18028 
18029 /*! \brief Qualify SIP peers in the manager API  */
18030 static int manager_sip_qualify_peer(struct mansession *s, const struct message *m)
18031 {
18032    const char *a[4];
18033    const char *peer;
18034 
18035    peer = astman_get_header(m, "Peer");
18036    if (ast_strlen_zero(peer)) {
18037       astman_send_error(s, m, "Peer: <name> missing.");
18038       return 0;
18039    }
18040    a[0] = "sip";
18041    a[1] = "qualify";
18042    a[2] = "peer";
18043    a[3] = peer;
18044 
18045    _sip_qualify_peer(1, -1, s, m, 4, a);
18046    astman_append(s, "\r\n\r\n" );
18047    return 0;
18048 }
18049 
18050 /*! \brief Send an OPTIONS packet to a SIP peer */
18051 static char *sip_qualify_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
18052 {
18053    switch (cmd) {
18054    case CLI_INIT:
18055       e->command = "sip qualify peer";
18056       e->usage =
18057          "Usage: sip qualify peer <name> [load]\n"
18058          "       Requests a response from one SIP peer and the current status.\n"
18059          "       Option \"load\" forces lookup of peer in realtime storage.\n";
18060       return NULL;
18061    case CLI_GENERATE:
18062       return complete_sip_show_peer(a->line, a->word, a->pos, a->n);
18063    }
18064    return _sip_qualify_peer(0, a->fd, NULL, NULL, a->argc, (const char **) a->argv);
18065 }
18066 
18067 /*! \brief list peer mailboxes to CLI */
18068 static void peer_mailboxes_to_str(struct ast_str **mailbox_str, struct sip_peer *peer)
18069 {
18070    struct sip_mailbox *mailbox;
18071 
18072    AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
18073       ast_str_append(mailbox_str, 0, "%s%s%s%s",
18074          mailbox->mailbox,
18075          ast_strlen_zero(mailbox->context) ? "" : "@",
18076          S_OR(mailbox->context, ""),
18077          AST_LIST_NEXT(mailbox, entry) ? "," : "");
18078    }
18079 }
18080 
18081 static struct _map_x_s faxecmodes[] = {
18082    { SIP_PAGE2_T38SUPPORT_UDPTL,       "None"},
18083    { SIP_PAGE2_T38SUPPORT_UDPTL_FEC,      "FEC"},
18084    { SIP_PAGE2_T38SUPPORT_UDPTL_REDUNDANCY,  "Redundancy"},
18085    { -1,                NULL},
18086 };
18087 
18088 static const char *faxec2str(int faxec)
18089 {
18090    return map_x_s(faxecmodes, faxec, "Unknown");
18091 }
18092 
18093 /*! \brief Show one peer in detail (main function) */
18094 static char *_sip_show_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[])
18095 {
18096    char status[30] = "";
18097    char cbuf[256];
18098    struct sip_peer *peer;
18099    char codec_buf[512];
18100    struct ast_codec_pref *pref;
18101    struct ast_variable *v;
18102    int x = 0, load_realtime;
18103    struct ast_format codec;
18104    int realtimepeers;
18105 
18106    realtimepeers = ast_check_realtime("sippeers");
18107 
18108    if (argc < 4)
18109       return CLI_SHOWUSAGE;
18110 
18111    load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? TRUE : FALSE;
18112    peer = sip_find_peer(argv[3], NULL, load_realtime, FINDPEERS, FALSE, 0);
18113 
18114    if (s) {    /* Manager */
18115       if (peer) {
18116          const char *id = astman_get_header(m, "ActionID");
18117 
18118          astman_append(s, "Response: Success\r\n");
18119          if (!ast_strlen_zero(id))
18120             astman_append(s, "ActionID: %s\r\n", id);
18121       } else {
18122          snprintf (cbuf, sizeof(cbuf), "Peer %s not found.", argv[3]);
18123          astman_send_error(s, m, cbuf);
18124          return CLI_SUCCESS;
18125       }
18126    }
18127    if (peer && type==0 ) { /* Normal listing */
18128       struct ast_str *mailbox_str = ast_str_alloca(512);
18129       struct sip_auth_container *credentials;
18130 
18131       ao2_lock(peer);
18132       credentials = peer->auth;
18133       if (credentials) {
18134          ao2_t_ref(credentials, +1, "Ref peer auth for show");
18135       }
18136       ao2_unlock(peer);
18137 
18138       ast_cli(fd, "\n\n");
18139       ast_cli(fd, "  * Name       : %s\n", peer->name);
18140       ast_cli(fd, "  Description  : %s\n", peer->description);
18141       if (realtimepeers) { /* Realtime is enabled */
18142          ast_cli(fd, "  Realtime peer: %s\n", peer->is_realtime ? "Yes, cached" : "No");
18143       }
18144       ast_cli(fd, "  Secret       : %s\n", ast_strlen_zero(peer->secret)?"<Not set>":"<Set>");
18145       ast_cli(fd, "  MD5Secret    : %s\n", ast_strlen_zero(peer->md5secret)?"<Not set>":"<Set>");
18146       ast_cli(fd, "  Remote Secret: %s\n", ast_strlen_zero(peer->remotesecret)?"<Not set>":"<Set>");
18147       if (credentials) {
18148          struct sip_auth *auth;
18149 
18150          AST_LIST_TRAVERSE(&credentials->list, auth, node) {
18151             ast_cli(fd, "  Realm-auth   : Realm %-15.15s User %-10.20s %s\n",
18152                auth->realm,
18153                auth->username,
18154                !ast_strlen_zero(auth->secret)
18155                   ? "<Secret set>"
18156                   : (!ast_strlen_zero(auth->md5secret)
18157                      ? "<MD5secret set>" : "<Not set>"));
18158          }
18159          ao2_t_ref(credentials, -1, "Unref peer auth for show");
18160       }
18161       ast_cli(fd, "  Context      : %s\n", peer->context);
18162       ast_cli(fd, "  Record On feature : %s\n", peer->record_on_feature);
18163       ast_cli(fd, "  Record Off feature : %s\n", peer->record_off_feature);
18164       ast_cli(fd, "  Subscr.Cont. : %s\n", S_OR(peer->subscribecontext, "<Not set>") );
18165       ast_cli(fd, "  Language     : %s\n", peer->language);
18166       ast_cli(fd, "  Tonezone     : %s\n", peer->zone[0] != '\0' ? peer->zone : "<Not set>");
18167       if (!ast_strlen_zero(peer->accountcode))
18168          ast_cli(fd, "  Accountcode  : %s\n", peer->accountcode);
18169       ast_cli(fd, "  AMA flags    : %s\n", ast_cdr_flags2str(peer->amaflags));
18170       ast_cli(fd, "  Transfer mode: %s\n", transfermode2str(peer->allowtransfer));
18171       ast_cli(fd, "  CallingPres  : %s\n", ast_describe_caller_presentation(peer->callingpres));
18172       if (!ast_strlen_zero(peer->fromuser))
18173          ast_cli(fd, "  FromUser     : %s\n", peer->fromuser);
18174       if (!ast_strlen_zero(peer->fromdomain))
18175          ast_cli(fd, "  FromDomain   : %s Port %d\n", peer->fromdomain, (peer->fromdomainport) ? peer->fromdomainport : STANDARD_SIP_PORT);
18176       ast_cli(fd, "  Callgroup    : ");
18177       print_group(fd, peer->callgroup, 0);
18178       ast_cli(fd, "  Pickupgroup  : ");
18179       print_group(fd, peer->pickupgroup, 0);
18180       peer_mailboxes_to_str(&mailbox_str, peer);
18181       ast_cli(fd, "  MOH Suggest  : %s\n", peer->mohsuggest);
18182       ast_cli(fd, "  Mailbox      : %s\n", mailbox_str->str);
18183       ast_cli(fd, "  VM Extension : %s\n", peer->vmexten);
18184       ast_cli(fd, "  Call limit   : %d\n", peer->call_limit);
18185       ast_cli(fd, "  Max forwards : %d\n", peer->maxforwards);
18186       if (peer->busy_level)
18187          ast_cli(fd, "  Busy level   : %d\n", peer->busy_level);
18188       ast_cli(fd, "  Dynamic      : %s\n", AST_CLI_YESNO(peer->host_dynamic));
18189       ast_cli(fd, "  Callerid     : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, "<unspecified>"));
18190       ast_cli(fd, "  MaxCallBR    : %d kbps\n", peer->maxcallbitrate);
18191       ast_cli(fd, "  Expire       : %ld\n", ast_sched_when(sched, peer->expire));
18192       ast_cli(fd, "  Insecure     : %s\n", insecure2str(ast_test_flag(&peer->flags[0], SIP_INSECURE)));
18193       ast_cli(fd, "  Force rport  : %s\n", force_rport_string(peer->flags));
18194       ast_cli(fd, "  Symmetric RTP: %s\n", comedia_string(peer->flags));
18195       ast_cli(fd, "  ACL          : %s\n", AST_CLI_YESNO(peer->ha != NULL));
18196       ast_cli(fd, "  DirectMedACL : %s\n", AST_CLI_YESNO(peer->directmediaha != NULL));
18197       ast_cli(fd, "  T.38 support : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)));
18198       ast_cli(fd, "  T.38 EC mode : %s\n", faxec2str(ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)));
18199       ast_cli(fd, "  T.38 MaxDtgrm: %d\n", peer->t38_maxdatagram);
18200       ast_cli(fd, "  DirectMedia  : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[0], SIP_DIRECT_MEDIA)));
18201       ast_cli(fd, "  PromiscRedir : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[0], SIP_PROMISCREDIR)));
18202       ast_cli(fd, "  User=Phone   : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[0], SIP_USEREQPHONE)));
18203       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)));
18204       ast_cli(fd, "  Text Support : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[1], SIP_PAGE2_TEXTSUPPORT)));
18205       ast_cli(fd, "  Ign SDP ver  : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[1], SIP_PAGE2_IGNORESDPVERSION)));
18206       ast_cli(fd, "  Trust RPID   : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[0], SIP_TRUSTRPID)));
18207       ast_cli(fd, "  Send RPID    : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[0], SIP_SENDRPID)));
18208       ast_cli(fd, "  Subscriptions: %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)));
18209       ast_cli(fd, "  Overlap dial : %s\n", allowoverlap2str(ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWOVERLAP)));
18210       if (peer->outboundproxy)
18211          ast_cli(fd, "  Outb. proxy  : %s %s\n", ast_strlen_zero(peer->outboundproxy->name) ? "<not set>" : peer->outboundproxy->name,
18212                      peer->outboundproxy->force ? "(forced)" : "");
18213 
18214       /* - is enumerated */
18215       ast_cli(fd, "  DTMFmode     : %s\n", dtmfmode2str(ast_test_flag(&peer->flags[0], SIP_DTMF)));
18216       ast_cli(fd, "  Timer T1     : %d\n", peer->timer_t1);
18217       ast_cli(fd, "  Timer B      : %d\n", peer->timer_b);
18218       ast_cli(fd, "  ToHost       : %s\n", peer->tohost);
18219       ast_cli(fd, "  Addr->IP     : %s\n", ast_sockaddr_stringify(&peer->addr));
18220       ast_cli(fd, "  Defaddr->IP  : %s\n", ast_sockaddr_stringify(&peer->defaddr));
18221       ast_cli(fd, "  Prim.Transp. : %s\n", sip_get_transport(peer->socket.type));
18222       ast_cli(fd, "  Allowed.Trsp : %s\n", get_transport_list(peer->transports));
18223       if (!ast_strlen_zero(sip_cfg.regcontext))
18224          ast_cli(fd, "  Reg. exten   : %s\n", peer->regexten);
18225       ast_cli(fd, "  Def. Username: %s\n", peer->username);
18226       ast_cli(fd, "  SIP Options  : ");
18227       if (peer->sipoptions) {
18228          int lastoption = -1;
18229          for (x = 0 ; x < ARRAY_LEN(sip_options); x++) {
18230             if (sip_options[x].id != lastoption) {
18231                if (peer->sipoptions & sip_options[x].id)
18232                   ast_cli(fd, "%s ", sip_options[x].text);
18233                lastoption = x;
18234             }
18235          }
18236       } else
18237          ast_cli(fd, "(none)");
18238 
18239       ast_cli(fd, "\n");
18240       ast_cli(fd, "  Codecs       : ");
18241       ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->caps);
18242       ast_cli(fd, "%s\n", codec_buf);
18243       ast_cli(fd, "  Codec Order  : (");
18244       print_codec_to_cli(fd, &peer->prefs);
18245       ast_cli(fd, ")\n");
18246 
18247       ast_cli(fd, "  Auto-Framing :  %s \n", AST_CLI_YESNO(peer->autoframing));
18248       ast_cli(fd, "  Status       : ");
18249       peer_status(peer, status, sizeof(status));
18250       ast_cli(fd, "%s\n", status);
18251       ast_cli(fd, "  Useragent    : %s\n", peer->useragent);
18252       ast_cli(fd, "  Reg. Contact : %s\n", peer->fullcontact);
18253       ast_cli(fd, "  Qualify Freq : %d ms\n", peer->qualifyfreq);
18254       if (peer->chanvars) {
18255          ast_cli(fd, "  Variables    :\n");
18256          for (v = peer->chanvars ; v ; v = v->next)
18257             ast_cli(fd, "                 %s = %s\n", v->name, v->value);
18258       }
18259 
18260       ast_cli(fd, "  Sess-Timers  : %s\n", stmode2str(peer->stimer.st_mode_oper));
18261       ast_cli(fd, "  Sess-Refresh : %s\n", strefresher2str(peer->stimer.st_ref));
18262       ast_cli(fd, "  Sess-Expires : %d secs\n", peer->stimer.st_max_se);
18263       ast_cli(fd, "  Min-Sess     : %d secs\n", peer->stimer.st_min_se);
18264       ast_cli(fd, "  RTP Engine   : %s\n", peer->engine);
18265       ast_cli(fd, "  Parkinglot   : %s\n", peer->parkinglot);
18266       ast_cli(fd, "  Use Reason   : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[1], SIP_PAGE2_Q850_REASON)));
18267       ast_cli(fd, "  Encryption   : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[1], SIP_PAGE2_USE_SRTP)));
18268       ast_cli(fd, "\n");
18269       peer = sip_unref_peer(peer, "sip_show_peer: sip_unref_peer: done with peer ptr");
18270    } else  if (peer && type == 1) { /* manager listing */
18271       char buffer[256];
18272       struct ast_str *mailbox_str = ast_str_alloca(512);
18273       astman_append(s, "Channeltype: SIP\r\n");
18274       astman_append(s, "ObjectName: %s\r\n", peer->name);
18275       astman_append(s, "ChanObjectType: peer\r\n");
18276       astman_append(s, "SecretExist: %s\r\n", ast_strlen_zero(peer->secret)?"N":"Y");
18277       astman_append(s, "RemoteSecretExist: %s\r\n", ast_strlen_zero(peer->remotesecret)?"N":"Y");
18278       astman_append(s, "MD5SecretExist: %s\r\n", ast_strlen_zero(peer->md5secret)?"N":"Y");
18279       astman_append(s, "Context: %s\r\n", peer->context);
18280       astman_append(s, "Language: %s\r\n", peer->language);
18281       astman_append(s, "ToneZone: %s\r\n", peer->zone[0] != '\0' ? peer->zone : "<Not set>");
18282       if (!ast_strlen_zero(peer->accountcode))
18283          astman_append(s, "Accountcode: %s\r\n", peer->accountcode);
18284       astman_append(s, "AMAflags: %s\r\n", ast_cdr_flags2str(peer->amaflags));
18285       astman_append(s, "CID-CallingPres: %s\r\n", ast_describe_caller_presentation(peer->callingpres));
18286       if (!ast_strlen_zero(peer->fromuser))
18287          astman_append(s, "SIP-FromUser: %s\r\n", peer->fromuser);
18288       if (!ast_strlen_zero(peer->fromdomain))
18289          astman_append(s, "SIP-FromDomain: %s\r\nSip-FromDomain-Port: %d\r\n", peer->fromdomain, (peer->fromdomainport) ? peer->fromdomainport : STANDARD_SIP_PORT);
18290       astman_append(s, "Callgroup: ");
18291       astman_append(s, "%s\r\n", ast_print_group(buffer, sizeof(buffer), peer->callgroup));
18292       astman_append(s, "Pickupgroup: ");
18293       astman_append(s, "%s\r\n", ast_print_group(buffer, sizeof(buffer), peer->pickupgroup));
18294       astman_append(s, "MOHSuggest: %s\r\n", peer->mohsuggest);
18295       peer_mailboxes_to_str(&mailbox_str, peer);
18296       astman_append(s, "VoiceMailbox: %s\r\n", mailbox_str->str);
18297       astman_append(s, "TransferMode: %s\r\n", transfermode2str(peer->allowtransfer));
18298       astman_append(s, "Maxforwards: %d\r\n", peer->maxforwards);
18299       astman_append(s, "Call-limit: %d\r\n", peer->call_limit);
18300       astman_append(s, "Busy-level: %d\r\n", peer->busy_level);
18301       astman_append(s, "MaxCallBR: %d kbps\r\n", peer->maxcallbitrate);
18302       astman_append(s, "Dynamic: %s\r\n", peer->host_dynamic?"Y":"N");
18303       astman_append(s, "Callerid: %s\r\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, ""));
18304       astman_append(s, "RegExpire: %ld seconds\r\n", ast_sched_when(sched, peer->expire));
18305       astman_append(s, "SIP-AuthInsecure: %s\r\n", insecure2str(ast_test_flag(&peer->flags[0], SIP_INSECURE)));
18306       astman_append(s, "SIP-Forcerport: %s\r\n", ast_test_flag(&peer->flags[2], SIP_PAGE3_NAT_AUTO_RPORT) ?
18307             (ast_test_flag(&peer->flags[0], SIP_NAT_FORCE_RPORT) ? "A" : "a") :
18308             (ast_test_flag(&peer->flags[0], SIP_NAT_FORCE_RPORT) ? "Y" : "N"));
18309       astman_append(s, "SIP-Comedia: %s\r\n", ast_test_flag(&peer->flags[2], SIP_PAGE3_NAT_AUTO_COMEDIA) ?
18310             (ast_test_flag(&peer->flags[1], SIP_PAGE2_SYMMETRICRTP) ? "A" : "a") :
18311             (ast_test_flag(&peer->flags[1], SIP_PAGE2_SYMMETRICRTP) ? "Y" : "N"));
18312       astman_append(s, "ACL: %s\r\n", (peer->ha?"Y":"N"));
18313       astman_append(s, "SIP-CanReinvite: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_DIRECT_MEDIA)?"Y":"N"));
18314       astman_append(s, "SIP-DirectMedia: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_DIRECT_MEDIA)?"Y":"N"));
18315       astman_append(s, "SIP-PromiscRedir: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_PROMISCREDIR)?"Y":"N"));
18316       astman_append(s, "SIP-UserPhone: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_USEREQPHONE)?"Y":"N"));
18317       astman_append(s, "SIP-VideoSupport: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_VIDEOSUPPORT)?"Y":"N"));
18318       astman_append(s, "SIP-TextSupport: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_TEXTSUPPORT)?"Y":"N"));
18319       astman_append(s, "SIP-T.38Support: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)?"Y":"N"));
18320       astman_append(s, "SIP-T.38EC: %s\r\n", faxec2str(ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)));
18321       astman_append(s, "SIP-T.38MaxDtgrm: %d\r\n", peer->t38_maxdatagram);
18322       astman_append(s, "SIP-Sess-Timers: %s\r\n", stmode2str(peer->stimer.st_mode_oper));
18323       astman_append(s, "SIP-Sess-Refresh: %s\r\n", strefresher2str(peer->stimer.st_ref));
18324       astman_append(s, "SIP-Sess-Expires: %d\r\n", peer->stimer.st_max_se);
18325       astman_append(s, "SIP-Sess-Min: %d\r\n", peer->stimer.st_min_se);
18326       astman_append(s, "SIP-RTP-Engine: %s\r\n", peer->engine);
18327       astman_append(s, "SIP-Encryption: %s\r\n", ast_test_flag(&peer->flags[1], SIP_PAGE2_USE_SRTP) ? "Y" : "N");
18328 
18329       /* - is enumerated */
18330       astman_append(s, "SIP-DTMFmode: %s\r\n", dtmfmode2str(ast_test_flag(&peer->flags[0], SIP_DTMF)));
18331       astman_append(s, "ToHost: %s\r\n", peer->tohost);
18332       astman_append(s, "Address-IP: %s\r\nAddress-Port: %d\r\n", ast_sockaddr_stringify_addr(&peer->addr), ast_sockaddr_port(&peer->addr));
18333       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));
18334       astman_append(s, "Default-Username: %s\r\n", peer->username);
18335       if (!ast_strlen_zero(sip_cfg.regcontext))
18336          astman_append(s, "RegExtension: %s\r\n", peer->regexten);
18337       astman_append(s, "Codecs: ");
18338       ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->caps);
18339       astman_append(s, "%s\r\n", codec_buf);
18340       astman_append(s, "CodecOrder: ");
18341       pref = &peer->prefs;
18342       for(x = 0; x < AST_CODEC_PREF_SIZE ; x++) {
18343          if (!(ast_codec_pref_index(pref, x, &codec))) {
18344             break;
18345          }
18346          astman_append(s, "%s", ast_getformatname(&codec));
18347          if ((x < (AST_CODEC_PREF_SIZE - 1)) && ast_codec_pref_index(pref, x+1, &codec))
18348             astman_append(s, ",");
18349       }
18350 
18351       astman_append(s, "\r\n");
18352       astman_append(s, "Status: ");
18353       peer_status(peer, status, sizeof(status));
18354       astman_append(s, "%s\r\n", status);
18355       astman_append(s, "SIP-Useragent: %s\r\n", peer->useragent);
18356       astman_append(s, "Reg-Contact: %s\r\n", peer->fullcontact);
18357       astman_append(s, "QualifyFreq: %d ms\r\n", peer->qualifyfreq);
18358       astman_append(s, "Parkinglot: %s\r\n", peer->parkinglot);
18359       if (peer->chanvars) {
18360          for (v = peer->chanvars ; v ; v = v->next) {
18361             astman_append(s, "ChanVariable: %s=%s\r\n", v->name, v->value);
18362          }
18363       }
18364       astman_append(s, "SIP-Use-Reason-Header: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_Q850_REASON)) ? "Y" : "N");
18365       astman_append(s, "Description: %s\r\n", peer->description);
18366 
18367       peer = sip_unref_peer(peer, "sip_show_peer: sip_unref_peer: done with peer");
18368 
18369    } else {
18370       ast_cli(fd, "Peer %s not found.\n", argv[3]);
18371       ast_cli(fd, "\n");
18372    }
18373 
18374    return CLI_SUCCESS;
18375 }
18376 
18377 /*! \brief Do completion on user name */
18378 static char *complete_sip_user(const char *word, int state)
18379 {
18380    char *result = NULL;
18381    int wordlen = strlen(word);
18382    int which = 0;
18383    struct ao2_iterator user_iter;
18384    struct sip_peer *user;
18385 
18386    user_iter = ao2_iterator_init(peers, 0);
18387    while ((user = ao2_t_iterator_next(&user_iter, "iterate thru peers table"))) {
18388       ao2_lock(user);
18389       if (!(user->type & SIP_TYPE_USER)) {
18390          ao2_unlock(user);
18391          sip_unref_peer(user, "complete sip user");
18392          continue;
18393       }
18394       /* locking of the object is not required because only the name and flags are being compared */
18395       if (!strncasecmp(word, user->name, wordlen) && ++which > state) {
18396          result = ast_strdup(user->name);
18397       }
18398       ao2_unlock(user);
18399       sip_unref_peer(user, "complete sip user");
18400       if (result) {
18401          break;
18402       }
18403    }
18404    ao2_iterator_destroy(&user_iter);
18405    return result;
18406 }
18407 /*! \brief Support routine for 'sip show user' CLI */
18408 static char *complete_sip_show_user(const char *line, const char *word, int pos, int state)
18409 {
18410    if (pos == 3)
18411       return complete_sip_user(word, state);
18412 
18413    return NULL;
18414 }
18415 
18416 /*! \brief Show one user in detail */
18417 static char *sip_show_user(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
18418 {
18419    char cbuf[256];
18420    struct sip_peer *user;
18421    struct ast_variable *v;
18422    int load_realtime;
18423 
18424    switch (cmd) {
18425    case CLI_INIT:
18426       e->command = "sip show user";
18427       e->usage =
18428          "Usage: sip show user <name> [load]\n"
18429          "       Shows all details on one SIP user and the current status.\n"
18430          "       Option \"load\" forces lookup of peer in realtime storage.\n";
18431       return NULL;
18432    case CLI_GENERATE:
18433       return complete_sip_show_user(a->line, a->word, a->pos, a->n);
18434    }
18435 
18436    if (a->argc < 4)
18437       return CLI_SHOWUSAGE;
18438 
18439    /* Load from realtime storage? */
18440    load_realtime = (a->argc == 5 && !strcmp(a->argv[4], "load")) ? TRUE : FALSE;
18441 
18442    if ((user = sip_find_peer(a->argv[3], NULL, load_realtime, FINDUSERS, FALSE, 0))) {
18443       ao2_lock(user);
18444       ast_cli(a->fd, "\n\n");
18445       ast_cli(a->fd, "  * Name       : %s\n", user->name);
18446       ast_cli(a->fd, "  Secret       : %s\n", ast_strlen_zero(user->secret)?"<Not set>":"<Set>");
18447       ast_cli(a->fd, "  MD5Secret    : %s\n", ast_strlen_zero(user->md5secret)?"<Not set>":"<Set>");
18448       ast_cli(a->fd, "  Context      : %s\n", user->context);
18449       ast_cli(a->fd, "  Language     : %s\n", user->language);
18450       if (!ast_strlen_zero(user->accountcode))
18451          ast_cli(a->fd, "  Accountcode  : %s\n", user->accountcode);
18452       ast_cli(a->fd, "  AMA flags    : %s\n", ast_cdr_flags2str(user->amaflags));
18453       ast_cli(a->fd, "  Tonezone     : %s\n", user->zone[0] != '\0' ? user->zone : "<Not set>");
18454       ast_cli(a->fd, "  Transfer mode: %s\n", transfermode2str(user->allowtransfer));
18455       ast_cli(a->fd, "  MaxCallBR    : %d kbps\n", user->maxcallbitrate);
18456       ast_cli(a->fd, "  CallingPres  : %s\n", ast_describe_caller_presentation(user->callingpres));
18457       ast_cli(a->fd, "  Call limit   : %d\n", user->call_limit);
18458       ast_cli(a->fd, "  Callgroup    : ");
18459       print_group(a->fd, user->callgroup, 0);
18460       ast_cli(a->fd, "  Pickupgroup  : ");
18461       print_group(a->fd, user->pickupgroup, 0);
18462       ast_cli(a->fd, "  Callerid     : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), user->cid_name, user->cid_num, "<unspecified>"));
18463       ast_cli(a->fd, "  ACL          : %s\n", AST_CLI_YESNO(user->ha != NULL));
18464       ast_cli(a->fd, "  Sess-Timers  : %s\n", stmode2str(user->stimer.st_mode_oper));
18465       ast_cli(a->fd, "  Sess-Refresh : %s\n", strefresher2str(user->stimer.st_ref));
18466       ast_cli(a->fd, "  Sess-Expires : %d secs\n", user->stimer.st_max_se);
18467       ast_cli(a->fd, "  Sess-Min-SE  : %d secs\n", user->stimer.st_min_se);
18468       ast_cli(a->fd, "  RTP Engine   : %s\n", user->engine);
18469 
18470       ast_cli(a->fd, "  Codec Order  : (");
18471       print_codec_to_cli(a->fd, &user->prefs);
18472       ast_cli(a->fd, ")\n");
18473 
18474       ast_cli(a->fd, "  Auto-Framing:  %s \n", AST_CLI_YESNO(user->autoframing));
18475       if (user->chanvars) {
18476          ast_cli(a->fd, "  Variables    :\n");
18477          for (v = user->chanvars ; v ; v = v->next)
18478             ast_cli(a->fd, "                 %s = %s\n", v->name, v->value);
18479       }
18480 
18481       ast_cli(a->fd, "\n");
18482 
18483       ao2_unlock(user);
18484       sip_unref_peer(user, "sip show user");
18485    } else {
18486       ast_cli(a->fd, "User %s not found.\n", a->argv[3]);
18487       ast_cli(a->fd, "\n");
18488    }
18489 
18490    return CLI_SUCCESS;
18491 }
18492 
18493 
18494 static char *sip_show_sched(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
18495 {
18496    struct ast_str *cbuf;
18497    struct ast_cb_names cbnames = {9, { "retrans_pkt",
18498                                         "__sip_autodestruct",
18499                                         "expire_register",
18500                                         "auto_congest",
18501                                         "sip_reg_timeout",
18502                                         "sip_poke_peer_s",
18503                                         "sip_poke_noanswer",
18504                                         "sip_reregister",
18505                                         "sip_reinvite_retry"},
18506                            { retrans_pkt,
18507                                      __sip_autodestruct,
18508                                      expire_register,
18509                                      auto_congest,
18510                                      sip_reg_timeout,
18511                                      sip_poke_peer_s,
18512                                      sip_poke_noanswer,
18513                                      sip_reregister,
18514                                      sip_reinvite_retry}};
18515    
18516    switch (cmd) {
18517    case CLI_INIT:
18518       e->command = "sip show sched";
18519       e->usage =
18520          "Usage: sip show sched\n"
18521          "       Shows stats on what's in the sched queue at the moment\n";
18522       return NULL;
18523    case CLI_GENERATE:
18524       return NULL;
18525    }
18526 
18527    cbuf = ast_str_alloca(2048);
18528 
18529    ast_cli(a->fd, "\n");
18530    ast_sched_report(sched, &cbuf, &cbnames);
18531    ast_cli(a->fd, "%s", cbuf->str);
18532 
18533    return CLI_SUCCESS;
18534 }
18535 
18536 /*! \brief  Show SIP Registry (registrations with other SIP proxies */
18537 static char *sip_show_registry(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
18538 {
18539 #define FORMAT2 "%-39.39s %-6.6s %-12.12s  %8.8s %-20.20s %-25.25s\n"
18540 #define FORMAT  "%-39.39s %-6.6s %-12.12s  %8d %-20.20s %-25.25s\n"
18541    char host[80];
18542    char user[80];
18543    char tmpdat[256];
18544    struct ast_tm tm;
18545    int counter = 0;
18546 
18547    switch (cmd) {
18548    case CLI_INIT:
18549       e->command = "sip show registry";
18550       e->usage =
18551          "Usage: sip show registry\n"
18552          "       Lists all registration requests and status.\n";
18553       return NULL;
18554    case CLI_GENERATE:
18555       return NULL;
18556    }
18557 
18558    if (a->argc != 3)
18559       return CLI_SHOWUSAGE;
18560    ast_cli(a->fd, FORMAT2, "Host", "dnsmgr", "Username", "Refresh", "State", "Reg.Time");
18561    
18562    ASTOBJ_CONTAINER_TRAVERSE(&regl, 1, do {
18563       ASTOBJ_RDLOCK(iterator);
18564       snprintf(host, sizeof(host), "%s:%d", iterator->hostname, iterator->portno ? iterator->portno : STANDARD_SIP_PORT);
18565       snprintf(user, sizeof(user), "%s", iterator->username);
18566       if (!ast_strlen_zero(iterator->regdomain)) {
18567          snprintf(tmpdat, sizeof(tmpdat), "%s", user);
18568          snprintf(user, sizeof(user), "%s@%s", tmpdat, iterator->regdomain);}
18569       if (iterator->regdomainport) {
18570          snprintf(tmpdat, sizeof(tmpdat), "%s", user);
18571          snprintf(user, sizeof(user), "%s:%d", tmpdat, iterator->regdomainport);}
18572       if (iterator->regtime.tv_sec) {
18573          ast_localtime(&iterator->regtime, &tm, NULL);
18574          ast_strftime(tmpdat, sizeof(tmpdat), "%a, %d %b %Y %T", &tm);
18575       } else
18576          tmpdat[0] = '\0';
18577       ast_cli(a->fd, FORMAT, host, (iterator->dnsmgr) ? "Y" : "N", user, iterator->refresh, regstate2str(iterator->regstate), tmpdat);
18578       ASTOBJ_UNLOCK(iterator);
18579       counter++;
18580    } while(0));
18581    ast_cli(a->fd, "%d SIP registrations.\n", counter);
18582    return CLI_SUCCESS;
18583 #undef FORMAT
18584 #undef FORMAT2
18585 }
18586 
18587 /*! \brief Unregister (force expiration) a SIP peer in the registry via CLI
18588    \note This function does not tell the SIP device what's going on,
18589    so use it with great care.
18590 */
18591 static char *sip_unregister(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
18592 {
18593    struct sip_peer *peer;
18594    int load_realtime = 0;
18595 
18596    switch (cmd) {
18597    case CLI_INIT:
18598       e->command = "sip unregister";
18599       e->usage =
18600          "Usage: sip unregister <peer>\n"
18601          "       Unregister (force expiration) a SIP peer from the registry\n";
18602       return NULL;
18603    case CLI_GENERATE:
18604       return complete_sip_unregister(a->line, a->word, a->pos, a->n);
18605    }
18606    
18607    if (a->argc != 3)
18608       return CLI_SHOWUSAGE;
18609    
18610    if ((peer = sip_find_peer(a->argv[2], NULL, load_realtime, FINDPEERS, TRUE, 0))) {
18611       if (peer->expire > 0) {
18612          AST_SCHED_DEL_UNREF(sched, peer->expire,
18613             sip_unref_peer(peer, "remove register expire ref"));
18614          expire_register(sip_ref_peer(peer, "ref for expire_register"));
18615          ast_cli(a->fd, "Unregistered peer \'%s\'\n\n", a->argv[2]);
18616       } else {
18617          ast_cli(a->fd, "Peer %s not registered\n", a->argv[2]);
18618       }
18619       sip_unref_peer(peer, "sip_unregister: sip_unref_peer via sip_unregister: done with peer from sip_find_peer call");
18620    } else {
18621       ast_cli(a->fd, "Peer unknown: \'%s\'. Not unregistered.\n", a->argv[2]);
18622    }
18623    
18624    return CLI_SUCCESS;
18625 }
18626 
18627 /*! \brief Callback for show_chanstats */
18628 static int show_chanstats_cb(void *__cur, void *__arg, int flags)
18629 {
18630 #define FORMAT2 "%-15.15s  %-11.11s  %-8.8s %-10.10s  %-10.10s (     %%) %-6.6s %-10.10s  %-10.10s (     %%) %-6.6s\n"
18631 #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"
18632    struct sip_pvt *cur = __cur;
18633    struct ast_rtp_instance_stats stats;
18634    char durbuf[10];
18635    int duration;
18636    int durh, durm, durs;
18637    struct ast_channel *c = cur->owner;
18638    struct __show_chan_arg *arg = __arg;
18639    int fd = arg->fd;
18640 
18641 
18642    if (cur->subscribed != NONE) /* Subscriptions */
18643       return 0;   /* don't care, we scan all channels */
18644 
18645    if (!cur->rtp) {
18646       if (sipdebug) {
18647          ast_cli(fd, "%-15.15s  %-11.11s (inv state: %s) -- %s\n",
18648             ast_sockaddr_stringify_addr(&cur->sa), cur->callid,
18649             invitestate2string[cur->invitestate].desc,
18650             "-- No RTP active");
18651       }
18652       return 0;   /* don't care, we scan all channels */
18653    }
18654 
18655    ast_rtp_instance_get_stats(cur->rtp, &stats, AST_RTP_INSTANCE_STAT_ALL);
18656 
18657    if (c && c->cdr && !ast_tvzero(c->cdr->start)) {
18658       duration = (int)(ast_tvdiff_ms(ast_tvnow(), c->cdr->start) / 1000);
18659       durh = duration / 3600;
18660       durm = (duration % 3600) / 60;
18661       durs = duration % 60;
18662       snprintf(durbuf, sizeof(durbuf), "%02d:%02d:%02d", durh, durm, durs);
18663    } else {
18664       durbuf[0] = '\0';
18665    }
18666 
18667    ast_cli(fd, FORMAT,
18668       ast_sockaddr_stringify_addr(&cur->sa),
18669       cur->callid,
18670       durbuf,
18671       stats.rxcount > (unsigned int) 100000 ? (unsigned int) (stats.rxcount)/(unsigned int) 1000 : stats.rxcount,
18672       stats.rxcount > (unsigned int) 100000 ? "K":" ",
18673       stats.rxploss,
18674       (stats.rxcount + stats.rxploss) > 0 ? (double) stats.rxploss / (stats.rxcount + stats.rxploss) * 100 : 0,
18675       stats.rxjitter,
18676       stats.txcount > (unsigned int) 100000 ? (unsigned int) (stats.txcount)/(unsigned int) 1000 : stats.txcount,
18677       stats.txcount > (unsigned int) 100000 ? "K":" ",
18678       stats.txploss,
18679       stats.txcount > 0 ? (double) stats.txploss / stats.txcount * 100 : 0,
18680       stats.txjitter
18681    );
18682    arg->numchans++;
18683 
18684    return 0;   /* don't care, we scan all channels */
18685 }
18686 
18687 /*! \brief SIP show channelstats CLI (main function) */
18688 static char *sip_show_channelstats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
18689 {
18690    struct __show_chan_arg arg = { .fd = a->fd, .numchans = 0 };
18691 
18692    switch (cmd) {
18693    case CLI_INIT:
18694       e->command = "sip show channelstats";
18695       e->usage =
18696          "Usage: sip show channelstats\n"
18697          "       Lists all currently active SIP channel's RTCP statistics.\n"
18698          "       Note that calls in the much optimized RTP P2P bridge mode will not show any packets here.";
18699       return NULL;
18700    case CLI_GENERATE:
18701       return NULL;
18702    }
18703 
18704    if (a->argc != 3)
18705       return CLI_SHOWUSAGE;
18706 
18707    ast_cli(a->fd, FORMAT2, "Peer", "Call ID", "Duration", "Recv: Pack", "Lost", "Jitter", "Send: Pack", "Lost", "Jitter");
18708    /* iterate on the container and invoke the callback on each item */
18709    ao2_t_callback(dialogs, OBJ_NODATA, show_chanstats_cb, &arg, "callback to sip show chanstats");
18710    ast_cli(a->fd, "%d active SIP channel%s\n", arg.numchans, (arg.numchans != 1) ? "s" : "");
18711    return CLI_SUCCESS;
18712 }
18713 #undef FORMAT
18714 #undef FORMAT2
18715 
18716 /*! \brief List global settings for the SIP channel */
18717 static char *sip_show_settings(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
18718 {
18719    int realtimepeers;
18720    int realtimeregs;
18721    char codec_buf[SIPBUFSIZE];
18722    const char *msg;  /* temporary msg pointer */
18723    struct sip_auth_container *credentials;
18724 
18725    switch (cmd) {
18726    case CLI_INIT:
18727       e->command = "sip show settings";
18728       e->usage =
18729          "Usage: sip show settings\n"
18730          "       Provides detailed list of the configuration of the SIP channel.\n";
18731       return NULL;
18732    case CLI_GENERATE:
18733       return NULL;
18734    }
18735 
18736    if (a->argc != 3)
18737       return CLI_SHOWUSAGE;
18738 
18739    realtimepeers = ast_check_realtime("sippeers");
18740    realtimeregs = ast_check_realtime("sipregs");
18741 
18742    ast_mutex_lock(&authl_lock);
18743    credentials = authl;
18744    if (credentials) {
18745       ao2_t_ref(credentials, +1, "Ref global auth for show");
18746    }
18747    ast_mutex_unlock(&authl_lock);
18748 
18749    ast_cli(a->fd, "\n\nGlobal Settings:\n");
18750    ast_cli(a->fd, "----------------\n");
18751    ast_cli(a->fd, "  UDP Bindaddress:        %s\n", ast_sockaddr_stringify(&bindaddr));
18752    if (ast_sockaddr_is_ipv6(&bindaddr) && ast_sockaddr_is_any(&bindaddr)) {
18753       ast_cli(a->fd, "  ** Additional Info:\n");
18754       ast_cli(a->fd, "     [::] may include IPv4 in addition to IPv6, if such a feature is enabled in the OS.\n");
18755    }
18756    ast_cli(a->fd, "  TCP SIP Bindaddress:    %s\n",
18757       sip_cfg.tcp_enabled != FALSE ?
18758             ast_sockaddr_stringify(&sip_tcp_desc.local_address) :
18759             "Disabled");
18760    ast_cli(a->fd, "  TLS SIP Bindaddress:    %s\n",
18761       default_tls_cfg.enabled != FALSE ?
18762             ast_sockaddr_stringify(&sip_tls_desc.local_address) :
18763             "Disabled");
18764    ast_cli(a->fd, "  Videosupport:           %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_VIDEOSUPPORT)));
18765    ast_cli(a->fd, "  Textsupport:            %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_TEXTSUPPORT)));
18766    ast_cli(a->fd, "  Ignore SDP sess. ver.:  %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_IGNORESDPVERSION)));
18767    ast_cli(a->fd, "  AutoCreate Peer:        %s\n", autocreatepeer2str(sip_cfg.autocreatepeer));
18768    ast_cli(a->fd, "  Match Auth Username:    %s\n", AST_CLI_YESNO(global_match_auth_username));
18769    ast_cli(a->fd, "  Allow unknown access:   %s\n", AST_CLI_YESNO(sip_cfg.allowguest));
18770    ast_cli(a->fd, "  Allow subscriptions:    %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)));
18771    ast_cli(a->fd, "  Allow overlap dialing:  %s\n", allowoverlap2str(ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP)));
18772    ast_cli(a->fd, "  Allow promisc. redir:   %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[0], SIP_PROMISCREDIR)));
18773    ast_cli(a->fd, "  Enable call counters:   %s\n", AST_CLI_YESNO(global_callcounter));
18774    ast_cli(a->fd, "  SIP domain support:     %s\n", AST_CLI_YESNO(!AST_LIST_EMPTY(&domain_list)));
18775    ast_cli(a->fd, "  Realm. auth:            %s\n", AST_CLI_YESNO(credentials != NULL));
18776    if (credentials) {
18777       struct sip_auth *auth;
18778 
18779       AST_LIST_TRAVERSE(&credentials->list, auth, node) {
18780          ast_cli(a->fd, "  Realm. auth entry:      Realm %-15.15s User %-10.20s %s\n",
18781             auth->realm,
18782             auth->username,
18783             !ast_strlen_zero(auth->secret)
18784                ? "<Secret set>"
18785                : (!ast_strlen_zero(auth->md5secret)
18786                   ? "<MD5secret set>" : "<Not set>"));
18787       }
18788       ao2_t_ref(credentials, -1, "Unref global auth for show");
18789    }
18790    ast_cli(a->fd, "  Our auth realm          %s\n", sip_cfg.realm);
18791    ast_cli(a->fd, "  Use domains as realms:  %s\n", AST_CLI_YESNO(sip_cfg.domainsasrealm));
18792    ast_cli(a->fd, "  Call to non-local dom.: %s\n", AST_CLI_YESNO(sip_cfg.allow_external_domains));
18793    ast_cli(a->fd, "  URI user is phone no:   %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[0], SIP_USEREQPHONE)));
18794    ast_cli(a->fd, "  Always auth rejects:    %s\n", AST_CLI_YESNO(sip_cfg.alwaysauthreject));
18795    ast_cli(a->fd, "  Direct RTP setup:       %s\n", AST_CLI_YESNO(sip_cfg.directrtpsetup));
18796    ast_cli(a->fd, "  User Agent:             %s\n", global_useragent);
18797    ast_cli(a->fd, "  SDP Session Name:       %s\n", ast_strlen_zero(global_sdpsession) ? "-" : global_sdpsession);
18798    ast_cli(a->fd, "  SDP Owner Name:         %s\n", ast_strlen_zero(global_sdpowner) ? "-" : global_sdpowner);
18799    ast_cli(a->fd, "  Reg. context:           %s\n", S_OR(sip_cfg.regcontext, "(not set)"));
18800    ast_cli(a->fd, "  Regexten on Qualify:    %s\n", AST_CLI_YESNO(sip_cfg.regextenonqualify));
18801    ast_cli(a->fd, "  Trust RPID:             %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[0], SIP_TRUSTRPID)));
18802    ast_cli(a->fd, "  Send RPID:              %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[0], SIP_SENDRPID)));
18803    ast_cli(a->fd, "  Legacy userfield parse: %s\n", AST_CLI_YESNO(sip_cfg.legacy_useroption_parsing));
18804    ast_cli(a->fd, "  Caller ID:              %s\n", default_callerid);
18805    if ((default_fromdomainport) && (default_fromdomainport != STANDARD_SIP_PORT)) {
18806       ast_cli(a->fd, "  From: Domain:           %s:%d\n", default_fromdomain, default_fromdomainport);
18807    } else {
18808       ast_cli(a->fd, "  From: Domain:           %s\n", default_fromdomain);
18809    }
18810    ast_cli(a->fd, "  Record SIP history:     %s\n", AST_CLI_ONOFF(recordhistory));
18811    ast_cli(a->fd, "  Call Events:            %s\n", AST_CLI_ONOFF(sip_cfg.callevents));
18812    ast_cli(a->fd, "  Auth. Failure Events:   %s\n", AST_CLI_ONOFF(global_authfailureevents));
18813 
18814    ast_cli(a->fd, "  T.38 support:           %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_T38SUPPORT)));
18815    ast_cli(a->fd, "  T.38 EC mode:           %s\n", faxec2str(ast_test_flag(&global_flags[1], SIP_PAGE2_T38SUPPORT)));
18816    ast_cli(a->fd, "  T.38 MaxDtgrm:          %d\n", global_t38_maxdatagram);
18817    if (!realtimepeers && !realtimeregs)
18818       ast_cli(a->fd, "  SIP realtime:           Disabled\n" );
18819    else
18820       ast_cli(a->fd, "  SIP realtime:           Enabled\n" );
18821    ast_cli(a->fd, "  Qualify Freq :          %d ms\n", global_qualifyfreq);
18822    ast_cli(a->fd, "  Q.850 Reason header:    %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_Q850_REASON)));
18823    ast_cli(a->fd, "  Store SIP_CAUSE:        %s\n", AST_CLI_YESNO(global_store_sip_cause));
18824    ast_cli(a->fd, "\nNetwork QoS Settings:\n");
18825    ast_cli(a->fd, "---------------------------\n");
18826    ast_cli(a->fd, "  IP ToS SIP:             %s\n", ast_tos2str(global_tos_sip));
18827    ast_cli(a->fd, "  IP ToS RTP audio:       %s\n", ast_tos2str(global_tos_audio));
18828    ast_cli(a->fd, "  IP ToS RTP video:       %s\n", ast_tos2str(global_tos_video));
18829    ast_cli(a->fd, "  IP ToS RTP text:        %s\n", ast_tos2str(global_tos_text));
18830    ast_cli(a->fd, "  802.1p CoS SIP:         %d\n", global_cos_sip);
18831    ast_cli(a->fd, "  802.1p CoS RTP audio:   %d\n", global_cos_audio);
18832    ast_cli(a->fd, "  802.1p CoS RTP video:   %d\n", global_cos_video);
18833    ast_cli(a->fd, "  802.1p CoS RTP text:    %d\n", global_cos_text);
18834    ast_cli(a->fd, "  Jitterbuffer enabled:   %s\n", AST_CLI_YESNO(ast_test_flag(&global_jbconf, AST_JB_ENABLED)));
18835    if (ast_test_flag(&global_jbconf, AST_JB_ENABLED)) {
18836       ast_cli(a->fd, "  Jitterbuffer forced:    %s\n", AST_CLI_YESNO(ast_test_flag(&global_jbconf, AST_JB_FORCED)));
18837       ast_cli(a->fd, "  Jitterbuffer max size:  %ld\n", global_jbconf.max_size);
18838       ast_cli(a->fd, "  Jitterbuffer resync:    %ld\n", global_jbconf.resync_threshold);
18839       ast_cli(a->fd, "  Jitterbuffer impl:      %s\n", global_jbconf.impl);
18840       if (!strcasecmp(global_jbconf.impl, "adaptive")) {
18841          ast_cli(a->fd, "  Jitterbuffer tgt extra: %ld\n", global_jbconf.target_extra);
18842       }
18843       ast_cli(a->fd, "  Jitterbuffer log:       %s\n", AST_CLI_YESNO(ast_test_flag(&global_jbconf, AST_JB_LOG)));
18844    }
18845 
18846    ast_cli(a->fd, "\nNetwork Settings:\n");
18847    ast_cli(a->fd, "---------------------------\n");
18848    /* determine if/how SIP address can be remapped */
18849    if (localaddr == NULL)
18850       msg = "Disabled, no localnet list";
18851    else if (ast_sockaddr_isnull(&externaddr))
18852       msg = "Disabled";
18853    else if (!ast_strlen_zero(externhost))
18854       msg = "Enabled using externhost";
18855    else
18856       msg = "Enabled using externaddr";
18857    ast_cli(a->fd, "  SIP address remapping:  %s\n", msg);
18858    ast_cli(a->fd, "  Externhost:             %s\n", S_OR(externhost, "<none>"));
18859    ast_cli(a->fd, "  Externaddr:             %s\n", ast_sockaddr_stringify(&externaddr));
18860    ast_cli(a->fd, "  Externrefresh:          %d\n", externrefresh);
18861    {
18862       struct ast_ha *d;
18863       const char *prefix = "Localnet:";
18864 
18865       for (d = localaddr; d ; prefix = "", d = d->next) {
18866          const char *addr = ast_strdupa(ast_sockaddr_stringify_addr(&d->addr));
18867          const char *mask = ast_strdupa(ast_sockaddr_stringify_addr(&d->netmask));
18868          ast_cli(a->fd, "  %-24s%s/%s\n", prefix, addr, mask);
18869       }
18870    }
18871    ast_cli(a->fd, "\nGlobal Signalling Settings:\n");
18872    ast_cli(a->fd, "---------------------------\n");
18873    ast_cli(a->fd, "  Codecs:                 ");
18874    ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, sip_cfg.caps);
18875    ast_cli(a->fd, "%s\n", codec_buf);
18876    ast_cli(a->fd, "  Codec Order:            ");
18877    print_codec_to_cli(a->fd, &default_prefs);
18878    ast_cli(a->fd, "\n");
18879    ast_cli(a->fd, "  Relax DTMF:             %s\n", AST_CLI_YESNO(global_relaxdtmf));
18880    ast_cli(a->fd, "  RFC2833 Compensation:   %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_RFC2833_COMPENSATE)));
18881    ast_cli(a->fd, "  Symmetric RTP:          %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_SYMMETRICRTP)));
18882    ast_cli(a->fd, "  Compact SIP headers:    %s\n", AST_CLI_YESNO(sip_cfg.compactheaders));
18883    ast_cli(a->fd, "  RTP Keepalive:          %d %s\n", global_rtpkeepalive, global_rtpkeepalive ? "" : "(Disabled)" );
18884    ast_cli(a->fd, "  RTP Timeout:            %d %s\n", global_rtptimeout, global_rtptimeout ? "" : "(Disabled)" );
18885    ast_cli(a->fd, "  RTP Hold Timeout:       %d %s\n", global_rtpholdtimeout, global_rtpholdtimeout ? "" : "(Disabled)");
18886    ast_cli(a->fd, "  MWI NOTIFY mime type:   %s\n", default_notifymime);
18887    ast_cli(a->fd, "  DNS SRV lookup:         %s\n", AST_CLI_YESNO(sip_cfg.srvlookup));
18888    ast_cli(a->fd, "  Pedantic SIP support:   %s\n", AST_CLI_YESNO(sip_cfg.pedanticsipchecking));
18889    ast_cli(a->fd, "  Reg. min duration       %d secs\n", min_expiry);
18890    ast_cli(a->fd, "  Reg. max duration:      %d secs\n", max_expiry);
18891    ast_cli(a->fd, "  Reg. default duration:  %d secs\n", default_expiry);
18892    ast_cli(a->fd, "  Outbound reg. timeout:  %d secs\n", global_reg_timeout);
18893    ast_cli(a->fd, "  Outbound reg. attempts: %d\n", global_regattempts_max);
18894    ast_cli(a->fd, "  Notify ringing state:   %s\n", AST_CLI_YESNO(sip_cfg.notifyringing));
18895    if (sip_cfg.notifyringing) {
18896       ast_cli(a->fd, "    Include CID:          %s%s\n",
18897             AST_CLI_YESNO(sip_cfg.notifycid),
18898             sip_cfg.notifycid == IGNORE_CONTEXT ? " (Ignoring context)" : "");
18899    }
18900    ast_cli(a->fd, "  Notify hold state:      %s\n", AST_CLI_YESNO(sip_cfg.notifyhold));
18901    ast_cli(a->fd, "  SIP Transfer mode:      %s\n", transfermode2str(sip_cfg.allowtransfer));
18902    ast_cli(a->fd, "  Max Call Bitrate:       %d kbps\n", default_maxcallbitrate);
18903    ast_cli(a->fd, "  Auto-Framing:           %s\n", AST_CLI_YESNO(global_autoframing));
18904    ast_cli(a->fd, "  Outb. proxy:            %s %s\n", ast_strlen_zero(sip_cfg.outboundproxy.name) ? "<not set>" : sip_cfg.outboundproxy.name,
18905                      sip_cfg.outboundproxy.force ? "(forced)" : "");
18906    ast_cli(a->fd, "  Session Timers:         %s\n", stmode2str(global_st_mode));
18907    ast_cli(a->fd, "  Session Refresher:      %s\n", strefresher2str (global_st_refresher));
18908    ast_cli(a->fd, "  Session Expires:        %d secs\n", global_max_se);
18909    ast_cli(a->fd, "  Session Min-SE:         %d secs\n", global_min_se);
18910    ast_cli(a->fd, "  Timer T1:               %d\n", global_t1);
18911    ast_cli(a->fd, "  Timer T1 minimum:       %d\n", global_t1min);
18912    ast_cli(a->fd, "  Timer B:                %d\n", global_timer_b);
18913    ast_cli(a->fd, "  No premature media:     %s\n", AST_CLI_YESNO(global_prematuremediafilter));
18914    ast_cli(a->fd, "  Max forwards:           %d\n", sip_cfg.default_max_forwards);
18915 
18916    ast_cli(a->fd, "\nDefault Settings:\n");
18917    ast_cli(a->fd, "-----------------\n");
18918    ast_cli(a->fd, "  Allowed transports:     %s\n", get_transport_list(default_transports));
18919    ast_cli(a->fd, "  Outbound transport:    %s\n", sip_get_transport(default_primary_transport));
18920    ast_cli(a->fd, "  Context:                %s\n", sip_cfg.default_context);
18921    ast_cli(a->fd, "  Record on feature:      %s\n", sip_cfg.default_record_on_feature);
18922    ast_cli(a->fd, "  Record off feature:     %s\n", sip_cfg.default_record_off_feature);
18923    ast_cli(a->fd, "  Force rport:            %s\n", force_rport_string(global_flags));
18924    ast_cli(a->fd, "  DTMF:                   %s\n", dtmfmode2str(ast_test_flag(&global_flags[0], SIP_DTMF)));
18925    ast_cli(a->fd, "  Qualify:                %d\n", default_qualify);
18926    ast_cli(a->fd, "  Use ClientCode:         %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[0], SIP_USECLIENTCODE)));
18927    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)));
18928    ast_cli(a->fd, "  Language:               %s\n", default_language);
18929    ast_cli(a->fd, "  Tone zone:              %s\n", default_zone[0] != '\0' ? default_zone : "<Not set>");
18930    ast_cli(a->fd, "  MOH Interpret:          %s\n", default_mohinterpret);
18931    ast_cli(a->fd, "  MOH Suggest:            %s\n", default_mohsuggest);
18932    ast_cli(a->fd, "  Voice Mail Extension:   %s\n", default_vmexten);
18933 
18934    
18935    if (realtimepeers || realtimeregs) {
18936       ast_cli(a->fd, "\nRealtime SIP Settings:\n");
18937       ast_cli(a->fd, "----------------------\n");
18938       ast_cli(a->fd, "  Realtime Peers:         %s\n", AST_CLI_YESNO(realtimepeers));
18939       ast_cli(a->fd, "  Realtime Regs:          %s\n", AST_CLI_YESNO(realtimeregs));
18940       ast_cli(a->fd, "  Cache Friends:          %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)));
18941       ast_cli(a->fd, "  Update:                 %s\n", AST_CLI_YESNO(sip_cfg.peer_rtupdate));
18942       ast_cli(a->fd, "  Ignore Reg. Expire:     %s\n", AST_CLI_YESNO(sip_cfg.ignore_regexpire));
18943       ast_cli(a->fd, "  Save sys. name:         %s\n", AST_CLI_YESNO(sip_cfg.rtsave_sysname));
18944       ast_cli(a->fd, "  Auto Clear:             %d (%s)\n", sip_cfg.rtautoclear, ast_test_flag(&global_flags[1], SIP_PAGE2_RTAUTOCLEAR) ? "Enabled" : "Disabled");
18945    }
18946    ast_cli(a->fd, "\n----\n");
18947    return CLI_SUCCESS;
18948 }
18949 
18950 static char *sip_show_mwi(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
18951 {
18952 #define FORMAT  "%-30.30s  %-12.12s  %-10.10s  %-10.10s\n"
18953    char host[80];
18954    
18955    switch (cmd) {
18956    case CLI_INIT:
18957       e->command = "sip show mwi";
18958       e->usage =
18959          "Usage: sip show mwi\n"
18960          "       Provides a list of MWI subscriptions and status.\n";
18961       return NULL;
18962    case CLI_GENERATE:
18963       return NULL;
18964    }
18965    
18966    ast_cli(a->fd, FORMAT, "Host", "Username", "Mailbox", "Subscribed");
18967    
18968    ASTOBJ_CONTAINER_TRAVERSE(&submwil, 1, do {
18969       ASTOBJ_RDLOCK(iterator);
18970       snprintf(host, sizeof(host), "%s:%d", iterator->hostname, iterator->portno ? iterator->portno : STANDARD_SIP_PORT);
18971       ast_cli(a->fd, FORMAT, host, iterator->username, iterator->mailbox, AST_CLI_YESNO(iterator->subscribed));
18972       ASTOBJ_UNLOCK(iterator);
18973    } while(0));
18974 
18975    return CLI_SUCCESS;
18976 #undef FORMAT
18977 }
18978 
18979 
18980 /*! \brief Show subscription type in string format */
18981 static const char *subscription_type2str(enum subscriptiontype subtype)
18982 {
18983    int i;
18984 
18985    for (i = 1; i < ARRAY_LEN(subscription_types); i++) {
18986       if (subscription_types[i].type == subtype) {
18987          return subscription_types[i].text;
18988       }
18989    }
18990    return subscription_types[0].text;
18991 }
18992 
18993 /*! \brief Find subscription type in array */
18994 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype)
18995 {
18996    int i;
18997 
18998    for (i = 1; i < ARRAY_LEN(subscription_types); i++) {
18999       if (subscription_types[i].type == subtype) {
19000          return &subscription_types[i];
19001       }
19002    }
19003    return &subscription_types[0];
19004 }
19005 
19006 /*
19007  * We try to structure all functions that loop on data structures as
19008  * a handler for individual entries, and a mainloop that iterates
19009  * on the main data structure. This way, moving the code to containers
19010  * that support iteration through callbacks will be a lot easier.
19011  */
19012 
19013 #define FORMAT4 "%-15.15s  %-15.15s  %-15.15s  %-15.15s  %-13.13s  %-15.15s %-10.10s %-6.6d\n"
19014 #define FORMAT3 "%-15.15s  %-15.15s  %-15.15s  %-15.15s  %-13.13s  %-15.15s %-10.10s %-6.6s\n"
19015 #define FORMAT2 "%-15.15s  %-15.15s  %-15.15s  %-15.15s  %-7.7s  %-15.15s %-10.10s %-10.10s\n"
19016 #define FORMAT  "%-15.15s  %-15.15s  %-15.15s  %-15.15s  %-3.3s %-3.3s  %-15.15s %-10.10s %-10.10s\n"
19017 
19018 /*! \brief callback for show channel|subscription */
19019 static int show_channels_cb(void *__cur, void *__arg, int flags)
19020 {
19021    struct sip_pvt *cur = __cur;
19022    struct __show_chan_arg *arg = __arg;
19023    const struct ast_sockaddr *dst = sip_real_dst(cur);
19024    
19025    /* XXX indentation preserved to reduce diff. Will be fixed later */
19026    if (cur->subscribed == NONE && !arg->subscriptions) {
19027       /* set if SIP transfer in progress */
19028       const char *referstatus = cur->refer ? referstatus2str(cur->refer->status) : "";
19029       char formatbuf[SIPBUFSIZE/2];
19030       
19031       ast_cli(arg->fd, FORMAT, ast_sockaddr_stringify_addr(dst),
19032             S_OR(cur->username, S_OR(cur->cid_num, "(None)")),
19033             cur->callid,
19034             cur->owner ? ast_getformatname_multiple(formatbuf, sizeof(formatbuf), cur->owner->nativeformats) : "(nothing)",
19035             AST_CLI_YESNO(ast_test_flag(&cur->flags[1], SIP_PAGE2_CALL_ONHOLD)),
19036             cur->needdestroy ? "(d)" : "",
19037             cur->lastmsg ,
19038             referstatus,
19039             cur->relatedpeer ? cur->relatedpeer->name : "<guest>"
19040          );
19041       arg->numchans++;
19042    }
19043    if (cur->subscribed != NONE && arg->subscriptions) {
19044       struct ast_str *mailbox_str = ast_str_alloca(512);
19045       if (cur->subscribed == MWI_NOTIFICATION && cur->relatedpeer)
19046          peer_mailboxes_to_str(&mailbox_str, cur->relatedpeer);
19047       ast_cli(arg->fd, FORMAT4, ast_sockaddr_stringify_addr(dst),
19048             S_OR(cur->username, S_OR(cur->cid_num, "(None)")),
19049                cur->callid,
19050             /* the 'complete' exten/context is hidden in the refer_to field for subscriptions */
19051             cur->subscribed == MWI_NOTIFICATION ? "--" : cur->subscribeuri,
19052             cur->subscribed == MWI_NOTIFICATION ? "<none>" : ast_extension_state2str(cur->laststate),
19053             subscription_type2str(cur->subscribed),
19054             cur->subscribed == MWI_NOTIFICATION ? S_OR(mailbox_str->str, "<none>") : "<none>",
19055             cur->expiry
19056          );
19057       arg->numchans++;
19058    }
19059    return 0;   /* don't care, we scan all channels */
19060 }
19061 
19062 /*! \brief CLI for show channels or subscriptions.
19063  * This is a new-style CLI handler so a single function contains
19064  * the prototype for the function, the 'generator' to produce multiple
19065  * entries in case it is required, and the actual handler for the command.
19066  */
19067 static char *sip_show_channels(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
19068 {
19069    struct __show_chan_arg arg = { .fd = a->fd, .numchans = 0 };
19070 
19071 
19072    if (cmd == CLI_INIT) {
19073       e->command = "sip show {channels|subscriptions}";
19074       e->usage =
19075          "Usage: sip show channels\n"
19076          "       Lists all currently active SIP calls (dialogs).\n"
19077          "Usage: sip show subscriptions\n"
19078          "       Lists active SIP subscriptions.\n";
19079       return NULL;
19080    } else if (cmd == CLI_GENERATE)
19081       return NULL;
19082 
19083    if (a->argc != e->args)
19084       return CLI_SHOWUSAGE;
19085    arg.subscriptions = !strcasecmp(a->argv[e->args - 1], "subscriptions");
19086    if (!arg.subscriptions)
19087       ast_cli(arg.fd, FORMAT2, "Peer", "User/ANR", "Call ID", "Format", "Hold", "Last Message", "Expiry", "Peer");
19088    else
19089       ast_cli(arg.fd, FORMAT3, "Peer", "User", "Call ID", "Extension", "Last state", "Type", "Mailbox", "Expiry");
19090 
19091    /* iterate on the container and invoke the callback on each item */
19092    ao2_t_callback(dialogs, OBJ_NODATA, show_channels_cb, &arg, "callback to show channels");
19093    
19094    /* print summary information */
19095    ast_cli(arg.fd, "%d active SIP %s%s\n", arg.numchans,
19096       (arg.subscriptions ? "subscription" : "dialog"),
19097       ESS(arg.numchans));  /* ESS(n) returns an "s" if n>1 */
19098    return CLI_SUCCESS;
19099 #undef FORMAT
19100 #undef FORMAT2
19101 #undef FORMAT3
19102 }
19103 
19104 /*! \brief Support routine for 'sip show channel' and 'sip show history' CLI
19105  * This is in charge of generating all strings that match a prefix in the
19106  * given position. As many functions of this kind, each invokation has
19107  * O(state) time complexity so be careful in using it.
19108  */
19109 static char *complete_sipch(const char *line, const char *word, int pos, int state)
19110 {
19111    int which=0;
19112    struct sip_pvt *cur;
19113    char *c = NULL;
19114    int wordlen = strlen(word);
19115    struct ao2_iterator i;
19116 
19117    if (pos != 3) {
19118       return NULL;
19119    }
19120 
19121    i = ao2_iterator_init(dialogs, 0);
19122    while ((cur = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
19123       sip_pvt_lock(cur);
19124       if (!strncasecmp(word, cur->callid, wordlen) && ++which > state) {
19125          c = ast_strdup(cur->callid);
19126          sip_pvt_unlock(cur);
19127          dialog_unref(cur, "drop ref in iterator loop break");
19128          break;
19129       }
19130       sip_pvt_unlock(cur);
19131       dialog_unref(cur, "drop ref in iterator loop");
19132    }
19133    ao2_iterator_destroy(&i);
19134    return c;
19135 }
19136 
19137 
19138 /*! \brief Do completion on peer name */
19139 static char *complete_sip_peer(const char *word, int state, int flags2)
19140 {
19141    char *result = NULL;
19142    int wordlen = strlen(word);
19143    int which = 0;
19144    struct ao2_iterator i = ao2_iterator_init(peers, 0);
19145    struct sip_peer *peer;
19146 
19147    while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
19148       /* locking of the object is not required because only the name and flags are being compared */
19149       if (!strncasecmp(word, peer->name, wordlen) &&
19150             (!flags2 || ast_test_flag(&peer->flags[1], flags2)) &&
19151             ++which > state)
19152          result = ast_strdup(peer->name);
19153       sip_unref_peer(peer, "toss iterator peer ptr before break");
19154       if (result) {
19155          break;
19156       }
19157    }
19158    ao2_iterator_destroy(&i);
19159    return result;
19160 }
19161 
19162 /*! \brief Do completion on registered peer name */
19163 static char *complete_sip_registered_peer(const char *word, int state, int flags2)
19164 {
19165        char *result = NULL;
19166        int wordlen = strlen(word);
19167        int which = 0;
19168        struct ao2_iterator i;
19169        struct sip_peer *peer;
19170        
19171        i = ao2_iterator_init(peers, 0);
19172        while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
19173           if (!strncasecmp(word, peer->name, wordlen) &&
19174          (!flags2 || ast_test_flag(&peer->flags[1], flags2)) &&
19175          ++which > state && peer->expire > 0)
19176              result = ast_strdup(peer->name);
19177           if (result) {
19178              sip_unref_peer(peer, "toss iterator peer ptr before break");
19179              break;
19180           }
19181           sip_unref_peer(peer, "toss iterator peer ptr");
19182        }
19183        ao2_iterator_destroy(&i);
19184        return result;
19185 }
19186 
19187 /*! \brief Support routine for 'sip show history' CLI */
19188 static char *complete_sip_show_history(const char *line, const char *word, int pos, int state)
19189 {
19190    if (pos == 3)
19191       return complete_sipch(line, word, pos, state);
19192 
19193    return NULL;
19194 }
19195 
19196 /*! \brief Support routine for 'sip show peer' CLI */
19197 static char *complete_sip_show_peer(const char *line, const char *word, int pos, int state)
19198 {
19199    if (pos == 3) {
19200       return complete_sip_peer(word, state, 0);
19201    }
19202 
19203    return NULL;
19204 }
19205 
19206 /*! \brief Support routine for 'sip unregister' CLI */
19207 static char *complete_sip_unregister(const char *line, const char *word, int pos, int state)
19208 {
19209        if (pos == 2)
19210                return complete_sip_registered_peer(word, state, 0);
19211 
19212        return NULL;
19213 }
19214 
19215 /*! \brief Support routine for 'sip notify' CLI */
19216 static char *complete_sipnotify(const char *line, const char *word, int pos, int state)
19217 {
19218    char *c = NULL;
19219 
19220    if (pos == 2) {
19221       int which = 0;
19222       char *cat = NULL;
19223       int wordlen = strlen(word);
19224 
19225       /* do completion for notify type */
19226 
19227       if (!notify_types)
19228          return NULL;
19229       
19230       while ( (cat = ast_category_browse(notify_types, cat)) ) {
19231          if (!strncasecmp(word, cat, wordlen) && ++which > state) {
19232             c = ast_strdup(cat);
19233             break;
19234          }
19235       }
19236       return c;
19237    }
19238 
19239    if (pos > 2)
19240       return complete_sip_peer(word, state, 0);
19241 
19242    return NULL;
19243 }
19244 
19245 /*! \brief Show details of one active dialog */
19246 static char *sip_show_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
19247 {
19248    struct sip_pvt *cur;
19249    size_t len;
19250    int found = 0;
19251    struct ao2_iterator i;
19252 
19253    switch (cmd) {
19254    case CLI_INIT:
19255       e->command = "sip show channel";
19256       e->usage =
19257          "Usage: sip show channel <call-id>\n"
19258          "       Provides detailed status on a given SIP dialog (identified by SIP call-id).\n";
19259       return NULL;
19260    case CLI_GENERATE:
19261       return complete_sipch(a->line, a->word, a->pos, a->n);
19262    }
19263 
19264    if (a->argc != 4)
19265       return CLI_SHOWUSAGE;
19266    len = strlen(a->argv[3]);
19267    
19268    i = ao2_iterator_init(dialogs, 0);
19269    while ((cur = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
19270       sip_pvt_lock(cur);
19271 
19272       if (!strncasecmp(cur->callid, a->argv[3], len)) {
19273          char formatbuf[SIPBUFSIZE/2];
19274          ast_cli(a->fd, "\n");
19275          if (cur->subscribed != NONE) {
19276             ast_cli(a->fd, "  * Subscription (type: %s)\n", subscription_type2str(cur->subscribed));
19277          } else {
19278             ast_cli(a->fd, "  * SIP Call\n");
19279          }
19280          ast_cli(a->fd, "  Curr. trans. direction:  %s\n", ast_test_flag(&cur->flags[0], SIP_OUTGOING) ? "Outgoing" : "Incoming");
19281          ast_cli(a->fd, "  Call-ID:                %s\n", cur->callid);
19282          ast_cli(a->fd, "  Owner channel ID:       %s\n", cur->owner ? ast_channel_name(cur->owner) : "<none>");
19283          ast_cli(a->fd, "  Our Codec Capability:   %s\n", ast_getformatname_multiple(formatbuf, sizeof(formatbuf), cur->caps));
19284          ast_cli(a->fd, "  Non-Codec Capability (DTMF):   %d\n", cur->noncodeccapability);
19285          ast_cli(a->fd, "  Their Codec Capability:   %s\n", ast_getformatname_multiple(formatbuf, sizeof(formatbuf), cur->peercaps));
19286          ast_cli(a->fd, "  Joint Codec Capability:   %s\n", ast_getformatname_multiple(formatbuf, sizeof(formatbuf), cur->jointcaps));
19287          ast_cli(a->fd, "  Format:                 %s\n", cur->owner ? ast_getformatname_multiple(formatbuf, sizeof(formatbuf), cur->owner->nativeformats) : "(nothing)" );
19288          ast_cli(a->fd, "  T.38 support            %s\n", AST_CLI_YESNO(cur->udptl != NULL));
19289          ast_cli(a->fd, "  Video support           %s\n", AST_CLI_YESNO(cur->vrtp != NULL));
19290          ast_cli(a->fd, "  MaxCallBR:              %d kbps\n", cur->maxcallbitrate);
19291          ast_cli(a->fd, "  Theoretical Address:    %s\n", ast_sockaddr_stringify(&cur->sa));
19292          ast_cli(a->fd, "  Received Address:       %s\n", ast_sockaddr_stringify(&cur->recv));
19293          ast_cli(a->fd, "  SIP Transfer mode:      %s\n", transfermode2str(cur->allowtransfer));
19294          ast_cli(a->fd, "  Force rport:            %s\n", force_rport_string(cur->flags));
19295          if (ast_sockaddr_isnull(&cur->redirip)) {
19296             ast_cli(a->fd,
19297                "  Audio IP:               %s (local)\n",
19298                ast_sockaddr_stringify_addr(&cur->ourip));
19299          } else {
19300             ast_cli(a->fd,
19301                "  Audio IP:               %s (Outside bridge)\n",
19302                ast_sockaddr_stringify_addr(&cur->redirip));
19303          }
19304          ast_cli(a->fd, "  Our Tag:                %s\n", cur->tag);
19305          ast_cli(a->fd, "  Their Tag:              %s\n", cur->theirtag);
19306          ast_cli(a->fd, "  SIP User agent:         %s\n", cur->useragent);
19307          if (!ast_strlen_zero(cur->username)) {
19308             ast_cli(a->fd, "  Username:               %s\n", cur->username);
19309          }
19310          if (!ast_strlen_zero(cur->peername)) {
19311             ast_cli(a->fd, "  Peername:               %s\n", cur->peername);
19312          }
19313          if (!ast_strlen_zero(cur->uri)) {
19314             ast_cli(a->fd, "  Original uri:           %s\n", cur->uri);
19315          }
19316          if (!ast_strlen_zero(cur->cid_num)) {
19317             ast_cli(a->fd, "  Caller-ID:              %s\n", cur->cid_num);
19318          }
19319          ast_cli(a->fd, "  Need Destroy:           %s\n", AST_CLI_YESNO(cur->needdestroy));
19320          ast_cli(a->fd, "  Last Message:           %s\n", cur->lastmsg);
19321          ast_cli(a->fd, "  Promiscuous Redir:      %s\n", AST_CLI_YESNO(ast_test_flag(&cur->flags[0], SIP_PROMISCREDIR)));
19322          ast_cli(a->fd, "  Route:                  ");
19323          if (cur->route) {
19324             struct sip_route *route;
19325             int first = 1;
19326 
19327             for (route = cur->route; route; route = route->next) {
19328                ast_cli(a->fd, "%s<%s>", first ? "" : ", ", route->hop);
19329                first = 0;
19330             }
19331             ast_cli(a->fd, "\n");
19332          } else {
19333             ast_cli(a->fd, "N/A\n");
19334          }
19335          ast_cli(a->fd, "  DTMF Mode:              %s\n", dtmfmode2str(ast_test_flag(&cur->flags[0], SIP_DTMF)));
19336          ast_cli(a->fd, "  SIP Options:            ");
19337          if (cur->sipoptions) {
19338             int x;
19339             for (x = 0 ; x < ARRAY_LEN(sip_options); x++) {
19340                if (cur->sipoptions & sip_options[x].id)
19341                   ast_cli(a->fd, "%s ", sip_options[x].text);
19342             }
19343             ast_cli(a->fd, "\n");
19344          } else {
19345             ast_cli(a->fd, "(none)\n");
19346          }
19347 
19348          if (!cur->stimer) {
19349             ast_cli(a->fd, "  Session-Timer:          Uninitiallized\n");
19350          } else {
19351             ast_cli(a->fd, "  Session-Timer:          %s\n", cur->stimer->st_active ? "Active" : "Inactive");
19352             if (cur->stimer->st_active == TRUE) {
19353                ast_cli(a->fd, "  S-Timer Interval:       %d\n", cur->stimer->st_interval);
19354                ast_cli(a->fd, "  S-Timer Refresher:      %s\n", strefresher2str(cur->stimer->st_ref));
19355                ast_cli(a->fd, "  S-Timer Expirys:        %d\n", cur->stimer->st_expirys);
19356                ast_cli(a->fd, "  S-Timer Sched Id:       %d\n", cur->stimer->st_schedid);
19357                ast_cli(a->fd, "  S-Timer Peer Sts:       %s\n", cur->stimer->st_active_peer_ua ? "Active" : "Inactive");
19358                ast_cli(a->fd, "  S-Timer Cached Min-SE:  %d\n", cur->stimer->st_cached_min_se);
19359                ast_cli(a->fd, "  S-Timer Cached SE:      %d\n", cur->stimer->st_cached_max_se);
19360                ast_cli(a->fd, "  S-Timer Cached Ref:     %s\n", strefresher2str(cur->stimer->st_cached_ref));
19361                ast_cli(a->fd, "  S-Timer Cached Mode:    %s\n", stmode2str(cur->stimer->st_cached_mode));
19362             }
19363          }
19364 
19365          ast_cli(a->fd, "\n\n");
19366 
19367          found++;
19368       }
19369 
19370       sip_pvt_unlock(cur);
19371 
19372       ao2_t_ref(cur, -1, "toss dialog ptr set by iterator_next");
19373    }
19374    ao2_iterator_destroy(&i);
19375 
19376    if (!found) {
19377       ast_cli(a->fd, "No such SIP Call ID starting with '%s'\n", a->argv[3]);
19378    }
19379 
19380    return CLI_SUCCESS;
19381 }
19382 
19383 /*! \brief Show history details of one dialog */
19384 static char *sip_show_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
19385 {
19386    struct sip_pvt *cur;
19387    size_t len;
19388    int found = 0;
19389    struct ao2_iterator i;
19390 
19391    switch (cmd) {
19392    case CLI_INIT:
19393       e->command = "sip show history";
19394       e->usage =
19395          "Usage: sip show history <call-id>\n"
19396          "       Provides detailed dialog history on a given SIP call (specified by call-id).\n";
19397       return NULL;
19398    case CLI_GENERATE:
19399       return complete_sip_show_history(a->line, a->word, a->pos, a->n);
19400    }
19401 
19402    if (a->argc != 4) {
19403       return CLI_SHOWUSAGE;
19404    }
19405 
19406    if (!recordhistory) {
19407       ast_cli(a->fd, "\n***Note: History recording is currently DISABLED.  Use 'sip set history on' to ENABLE.\n");
19408    }
19409 
19410    len = strlen(a->argv[3]);
19411 
19412    i = ao2_iterator_init(dialogs, 0);
19413    while ((cur = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
19414       sip_pvt_lock(cur);
19415       if (!strncasecmp(cur->callid, a->argv[3], len)) {
19416          struct sip_history *hist;
19417          int x = 0;
19418 
19419          ast_cli(a->fd, "\n");
19420          if (cur->subscribed != NONE) {
19421             ast_cli(a->fd, "  * Subscription\n");
19422          } else {
19423             ast_cli(a->fd, "  * SIP Call\n");
19424          }
19425          if (cur->history) {
19426             AST_LIST_TRAVERSE(cur->history, hist, list)
19427                ast_cli(a->fd, "%d. %s\n", ++x, hist->event);
19428          }
19429          if (x == 0) {
19430             ast_cli(a->fd, "Call '%s' has no history\n", cur->callid);
19431          }
19432          found++;
19433       }
19434       sip_pvt_unlock(cur);
19435       ao2_t_ref(cur, -1, "toss dialog ptr from iterator_next");
19436    }
19437    ao2_iterator_destroy(&i);
19438 
19439    if (!found) {
19440       ast_cli(a->fd, "No such SIP Call ID starting with '%s'\n", a->argv[3]);
19441    }
19442 
19443    return CLI_SUCCESS;
19444 }
19445 
19446 /*! \brief Dump SIP history to debug log file at end of lifespan for SIP dialog */
19447 static void sip_dump_history(struct sip_pvt *dialog)
19448 {
19449    int x = 0;
19450    struct sip_history *hist;
19451    static int errmsg = 0;
19452 
19453    if (!dialog) {
19454       return;
19455    }
19456 
19457    if (!option_debug && !sipdebug) {
19458       if (!errmsg) {
19459          ast_log(LOG_NOTICE, "You must have debugging enabled (SIP or Asterisk) in order to dump SIP history.\n");
19460          errmsg = 1;
19461       }
19462       return;
19463    }
19464 
19465    ast_debug(1, "\n---------- SIP HISTORY for '%s' \n", dialog->callid);
19466    if (dialog->subscribed) {
19467       ast_debug(1, "  * Subscription\n");
19468    } else {
19469       ast_debug(1, "  * SIP Call\n");
19470    }
19471    if (dialog->history) {
19472       AST_LIST_TRAVERSE(dialog->history, hist, list)
19473          ast_debug(1, "  %-3.3d. %s\n", ++x, hist->event);
19474    }
19475    if (!x) {
19476       ast_debug(1, "Call '%s' has no history\n", dialog->callid);
19477    }
19478    ast_debug(1, "\n---------- END SIP HISTORY for '%s' \n", dialog->callid);
19479 }
19480 
19481 
19482 /*! \brief  Receive SIP INFO Message */
19483 static void handle_request_info(struct sip_pvt *p, struct sip_request *req)
19484 {
19485    char buf[1024] = "";
19486    unsigned int event;
19487    const char *c = sip_get_header(req, "Content-Type");
19488 
19489    /* Need to check the media/type */
19490    if (!strcasecmp(c, "application/dtmf-relay") ||
19491        !strcasecmp(c, "application/vnd.nortelnetworks.digits") ||
19492        !strcasecmp(c, "application/dtmf")) {
19493       unsigned int duration = 0;
19494 
19495       if (!p->owner) {  /* not a PBX call */
19496          transmit_response(p, "481 Call leg/transaction does not exist", req);
19497          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19498          return;
19499       }
19500 
19501       /* If dtmf-relay or vnd.nortelnetworks.digits, parse the signal and duration;
19502        * otherwise use the body as the signal */
19503       if (strcasecmp(c, "application/dtmf")) {
19504          const char *msg_body;
19505 
19506          if (   ast_strlen_zero(msg_body = get_body(req, "Signal", '='))
19507             && ast_strlen_zero(msg_body = get_body(req, "d", '='))) {
19508             ast_log(LOG_WARNING, "Unable to retrieve DTMF signal for INFO message on "
19509                   "call %s\n", p->callid);
19510             transmit_response(p, "200 OK", req);
19511             return;
19512          }
19513          ast_copy_string(buf, msg_body, sizeof(buf));
19514 
19515          if (!ast_strlen_zero((msg_body = get_body(req, "Duration", '=')))) {
19516             sscanf(msg_body, "%30u", &duration);
19517          }
19518       } else {
19519          /* Type is application/dtmf, simply use what's in the message body */
19520          get_msg_text(buf, sizeof(buf), req);
19521       }
19522 
19523       /* An empty message body requires us to send a 200 OK */
19524       if (ast_strlen_zero(buf)) {
19525          transmit_response(p, "200 OK", req);
19526          return;
19527       }
19528 
19529       if (!duration) {
19530          duration = 100; /* 100 ms */
19531       }
19532 
19533       if (buf[0] == '*') {
19534          event = 10;
19535       } else if (buf[0] == '#') {
19536          event = 11;
19537       } else if (buf[0] == '!') {
19538          event = 16;
19539       } else if ('A' <= buf[0] && buf[0] <= 'D') {
19540          event = 12 + buf[0] - 'A';
19541       } else if ('a' <= buf[0] && buf[0] <= 'd') {
19542          event = 12 + buf[0] - 'a';
19543       } else if ((sscanf(buf, "%30u", &event) != 1) || event > 16) {
19544          ast_log(AST_LOG_WARNING, "Unable to convert DTMF event signal code to a valid "
19545                "value for INFO message on call %s\n", p->callid);
19546          transmit_response(p, "200 OK", req);
19547          return;
19548       }
19549 
19550       if (event == 16) {
19551          /* send a FLASH event */
19552          struct ast_frame f = { AST_FRAME_CONTROL, { AST_CONTROL_FLASH, } };
19553          ast_queue_frame(p->owner, &f);
19554          if (sipdebug) {
19555             ast_verbose("* DTMF-relay event received: FLASH\n");
19556          }
19557       } else {
19558          /* send a DTMF event */
19559          struct ast_frame f = { AST_FRAME_DTMF, };
19560          if (event < 10) {
19561             f.subclass.integer = '0' + event;
19562          } else if (event == 10) {
19563             f.subclass.integer = '*';
19564          } else if (event == 11) {
19565             f.subclass.integer = '#';
19566          } else {
19567             f.subclass.integer = 'A' + (event - 12);
19568          }
19569          f.len = duration;
19570          ast_queue_frame(p->owner, &f);
19571          if (sipdebug) {
19572             ast_verbose("* DTMF-relay event received: %c\n", (int) f.subclass.integer);
19573          }
19574       }
19575       transmit_response(p, "200 OK", req);
19576       return;
19577    } else if (!strcasecmp(c, "application/media_control+xml")) {
19578       /* Eh, we'll just assume it's a fast picture update for now */
19579       if (p->owner) {
19580          ast_queue_control(p->owner, AST_CONTROL_VIDUPDATE);
19581       }
19582       transmit_response(p, "200 OK", req);
19583       return;
19584    } else if (!ast_strlen_zero(c = sip_get_header(req, "X-ClientCode"))) {
19585       /* Client code (from SNOM phone) */
19586       if (ast_test_flag(&p->flags[0], SIP_USECLIENTCODE)) {
19587          if (p->owner && p->owner->cdr) {
19588             ast_cdr_setuserfield(p->owner, c);
19589          }
19590          if (p->owner && ast_bridged_channel(p->owner) && ast_bridged_channel(p->owner)->cdr) {
19591             ast_cdr_setuserfield(ast_bridged_channel(p->owner), c);
19592          }
19593          transmit_response(p, "200 OK", req);
19594       } else {
19595          transmit_response(p, "403 Forbidden", req);
19596       }
19597       return;
19598    } else if (!ast_strlen_zero(c = sip_get_header(req, "Record"))) {
19599       /* INFO messages generated by some phones to start/stop recording
19600        * on phone calls.
19601        */
19602 
19603       struct ast_call_feature *feat = NULL;
19604       int j;
19605       struct ast_frame f = { AST_FRAME_DTMF, };
19606       int suppress_warning = 0; /* Supress warning if the feature is blank */
19607 
19608       if (!p->owner) {        /* not a PBX call */
19609          transmit_response(p, "481 Call leg/transaction does not exist", req);
19610          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19611          return;
19612       }
19613 
19614       /* first, get the feature string, if it exists */
19615       ast_rdlock_call_features();
19616       if (p->relatedpeer) {
19617          if (!strcasecmp(c, "on")) {
19618             if (ast_strlen_zero(p->relatedpeer->record_on_feature)) {
19619                suppress_warning = 1;
19620             } else {
19621                feat = ast_find_call_feature(p->relatedpeer->record_on_feature);
19622             }
19623          } else if (!strcasecmp(c, "off")) {
19624             if (ast_strlen_zero(p->relatedpeer->record_on_feature)) {
19625                suppress_warning = 1;
19626             } else {
19627                feat = ast_find_call_feature(p->relatedpeer->record_off_feature);
19628             }
19629          } else {
19630             ast_log(LOG_ERROR, "Received INFO requesting to record with invalid value: %s\n", c);
19631          }
19632       }
19633       if (!feat || ast_strlen_zero(feat->exten)) {
19634          if (!suppress_warning) {
19635             ast_log(LOG_WARNING, "Recording requested, but no One Touch Monitor registered. (See features.conf)\n");
19636          }
19637          /* 403 means that we don't support this feature, so don't request it again */
19638          transmit_response(p, "403 Forbidden", req);
19639          ast_unlock_call_features();
19640          return;
19641       }
19642       /* Send the feature code to the PBX as DTMF, just like the handset had sent it */
19643       f.len = 100;
19644       for (j=0; j < strlen(feat->exten); j++) {
19645          f.subclass.integer = feat->exten[j];
19646          ast_queue_frame(p->owner, &f);
19647          if (sipdebug) {
19648             ast_verbose("* DTMF-relay event faked: %c\n", f.subclass.integer);
19649          }
19650       }
19651       ast_unlock_call_features();
19652 
19653       ast_debug(1, "Got a Request to Record the channel, state %s\n", c);
19654       transmit_response(p, "200 OK", req);
19655       return;
19656    } else if (ast_strlen_zero(c = sip_get_header(req, "Content-Length")) || !strcasecmp(c, "0")) {
19657       /* This is probably just a packet making sure the signalling is still up, just send back a 200 OK */
19658       transmit_response(p, "200 OK", req);
19659       return;
19660    }
19661 
19662    /* Other type of INFO message, not really understood by Asterisk */
19663    /* if (get_msg_text(buf, sizeof(buf), req)) { */
19664 
19665    ast_log(LOG_WARNING, "Unable to parse INFO message from %s. Content %s\n", p->callid, buf);
19666    transmit_response(p, "415 Unsupported media type", req);
19667    return;
19668 }
19669 
19670 /*! \brief Enable SIP Debugging for a single IP */
19671 static char *sip_do_debug_ip(int fd, const char *arg)
19672 {
19673    if (ast_sockaddr_resolve_first(&debugaddr, arg, 0)) {
19674       return CLI_SHOWUSAGE;
19675    }
19676 
19677    ast_cli(fd, "SIP Debugging Enabled for IP: %s\n", ast_sockaddr_stringify_addr(&debugaddr));
19678    sipdebug |= sip_debug_console;
19679 
19680    return CLI_SUCCESS;
19681 }
19682 
19683 /*! \brief  Turn on SIP debugging for a given peer */
19684 static char *sip_do_debug_peer(int fd, const char *arg)
19685 {
19686    struct sip_peer *peer = sip_find_peer(arg, NULL, TRUE, FINDPEERS, FALSE, 0);
19687    if (!peer) {
19688       ast_cli(fd, "No such peer '%s'\n", arg);
19689    } else if (ast_sockaddr_isnull(&peer->addr)) {
19690       ast_cli(fd, "Unable to get IP address of peer '%s'\n", arg);
19691    } else {
19692       ast_sockaddr_copy(&debugaddr, &peer->addr);
19693       ast_cli(fd, "SIP Debugging Enabled for IP: %s\n", ast_sockaddr_stringify_addr(&debugaddr));
19694       sipdebug |= sip_debug_console;
19695    }
19696    if (peer) {
19697       sip_unref_peer(peer, "sip_do_debug_peer: sip_unref_peer, from sip_find_peer call");
19698    }
19699    return CLI_SUCCESS;
19700 }
19701 
19702 /*! \brief Turn on SIP debugging (CLI command) */
19703 static char *sip_do_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
19704 {
19705    int oldsipdebug = sipdebug & sip_debug_console;
19706    const char *what;
19707 
19708    if (cmd == CLI_INIT) {
19709       e->command = "sip set debug {on|off|ip|peer}";
19710       e->usage =
19711          "Usage: sip set debug {off|on|ip addr[:port]|peer peername}\n"
19712          "       Globally disables dumping of SIP packets,\n"
19713          "       or enables it either globally or for a (single)\n"
19714          "       IP address or registered peer.\n";
19715       return NULL;
19716    } else if (cmd == CLI_GENERATE) {
19717       if (a->pos == 4 && !strcasecmp(a->argv[3], "peer"))
19718          return complete_sip_peer(a->word, a->n, 0);
19719       return NULL;
19720         }
19721 
19722    what = a->argv[e->args-1];      /* guaranteed to exist */
19723    if (a->argc == e->args) {       /* on/off */
19724       if (!strcasecmp(what, "on")) {
19725          sipdebug |= sip_debug_console;
19726          sipdebug_text = 1;   /*! \note this can be a special debug command - "sip debug text" or something */
19727          memset(&debugaddr, 0, sizeof(debugaddr));
19728          ast_cli(a->fd, "SIP Debugging %senabled\n", oldsipdebug ? "re-" : "");
19729          return CLI_SUCCESS;
19730       } else if (!strcasecmp(what, "off")) {
19731          sipdebug &= ~sip_debug_console;
19732          sipdebug_text = 0;
19733          ast_cli(a->fd, "SIP Debugging Disabled\n");
19734          return CLI_SUCCESS;
19735       }
19736    } else if (a->argc == e->args +1) {/* ip/peer */
19737       if (!strcasecmp(what, "ip"))
19738          return sip_do_debug_ip(a->fd, a->argv[e->args]);
19739       else if (!strcasecmp(what, "peer"))
19740          return sip_do_debug_peer(a->fd, a->argv[e->args]);
19741    }
19742    return CLI_SHOWUSAGE;   /* default, failure */
19743 }
19744 
19745 /*! \brief Cli command to send SIP notify to peer */
19746 static char *sip_cli_notify(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
19747 {
19748    struct ast_variable *varlist;
19749    int i;
19750 
19751    switch (cmd) {
19752    case CLI_INIT:
19753       e->command = "sip notify";
19754       e->usage =
19755          "Usage: sip notify <type> <peer> [<peer>...]\n"
19756          "       Send a NOTIFY message to a SIP peer or peers\n"
19757          "       Message types are defined in sip_notify.conf\n";
19758       return NULL;
19759    case CLI_GENERATE:
19760       return complete_sipnotify(a->line, a->word, a->pos, a->n);
19761    }
19762 
19763    if (a->argc < 4)
19764       return CLI_SHOWUSAGE;
19765 
19766    if (!notify_types) {
19767       ast_cli(a->fd, "No %s file found, or no types listed there\n", notify_config);
19768       return CLI_FAILURE;
19769    }
19770 
19771    varlist = ast_variable_browse(notify_types, a->argv[2]);
19772 
19773    if (!varlist) {
19774       ast_cli(a->fd, "Unable to find notify type '%s'\n", a->argv[2]);
19775       return CLI_FAILURE;
19776    }
19777 
19778    for (i = 3; i < a->argc; i++) {
19779       struct sip_pvt *p;
19780       char buf[512];
19781       struct ast_variable *header, *var;
19782 
19783       if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY, NULL))) {
19784          ast_log(LOG_WARNING, "Unable to build sip pvt data for notify (memory/socket error)\n");
19785          return CLI_FAILURE;
19786       }
19787 
19788       if (create_addr(p, a->argv[i], NULL, 1, NULL)) {
19789          /* Maybe they're not registered, etc. */
19790          dialog_unlink_all(p);
19791          dialog_unref(p, "unref dialog inside for loop" );
19792          /* sip_destroy(p); */
19793          ast_cli(a->fd, "Could not create address for '%s'\n", a->argv[i]);
19794          continue;
19795       }
19796 
19797       /* Notify is outgoing call */
19798       ast_set_flag(&p->flags[0], SIP_OUTGOING);
19799       sip_notify_allocate(p);
19800       p->notify->headers = header = ast_variable_new("Subscription-State", "terminated", "");
19801 
19802       for (var = varlist; var; var = var->next) {
19803          ast_copy_string(buf, var->value, sizeof(buf));
19804          ast_unescape_semicolon(buf);
19805 
19806          if (!strcasecmp(var->name, "Content")) {
19807             if (ast_str_strlen(p->notify->content))
19808                ast_str_append(&p->notify->content, 0, "\r\n");
19809             ast_str_append(&p->notify->content, 0, "%s", buf);
19810          } else if (!strcasecmp(var->name, "Content-Length")) {
19811             ast_log(LOG_WARNING, "it is not necessary to specify Content-Length in sip_notify.conf, ignoring");
19812          } else {
19813             header->next = ast_variable_new(var->name, buf, "");
19814             header = header->next;
19815          }
19816       }
19817 
19818       /* Recalculate our side, and recalculate Call ID */
19819       ast_cli(a->fd, "Sending NOTIFY of type '%s' to '%s'\n", a->argv[2], a->argv[i]);
19820       sip_scheddestroy(p, SIP_TRANS_TIMEOUT);
19821       transmit_invite(p, SIP_NOTIFY, 0, 2, NULL);
19822       dialog_unref(p, "bump down the count of p since we're done with it.");
19823    }
19824 
19825    return CLI_SUCCESS;
19826 }
19827 
19828 /*! \brief Enable/Disable SIP History logging (CLI) */
19829 static char *sip_set_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
19830 {
19831    switch (cmd) {
19832    case CLI_INIT:
19833       e->command = "sip set history {on|off}";
19834       e->usage =
19835          "Usage: sip set history {on|off}\n"
19836          "       Enables/Disables recording of SIP dialog history for debugging purposes.\n"
19837          "       Use 'sip show history' to view the history of a call number.\n";
19838       return NULL;
19839    case CLI_GENERATE:
19840       return NULL;
19841    }
19842 
19843    if (a->argc != e->args)
19844       return CLI_SHOWUSAGE;
19845 
19846    if (!strncasecmp(a->argv[e->args - 1], "on", 2)) {
19847       recordhistory = TRUE;
19848       ast_cli(a->fd, "SIP History Recording Enabled (use 'sip show history')\n");
19849    } else if (!strncasecmp(a->argv[e->args - 1], "off", 3)) {
19850       recordhistory = FALSE;
19851       ast_cli(a->fd, "SIP History Recording Disabled\n");
19852    } else {
19853       return CLI_SHOWUSAGE;
19854    }
19855    return CLI_SUCCESS;
19856 }
19857 
19858 /*! \brief Authenticate for outbound registration */
19859 static int do_register_auth(struct sip_pvt *p, struct sip_request *req, enum sip_auth_type code)
19860 {
19861    char *header, *respheader;
19862    char digest[1024];
19863 
19864    p->authtries++;
19865    sip_auth_headers(code, &header, &respheader);
19866    memset(digest, 0, sizeof(digest));
19867    if (reply_digest(p, req, header, SIP_REGISTER, digest, sizeof(digest))) {
19868       /* There's nothing to use for authentication */
19869       /* No digest challenge in request */
19870       if (sip_debug_test_pvt(p) && p->registry)
19871          ast_verbose("No authentication challenge, sending blank registration to domain/host name %s\n", p->registry->hostname);
19872          /* No old challenge */
19873       return -1;
19874    }
19875    if (p->do_history)
19876       append_history(p, "RegistryAuth", "Try: %d", p->authtries);
19877    if (sip_debug_test_pvt(p) && p->registry)
19878       ast_verbose("Responding to challenge, registration to domain/host name %s\n", p->registry->hostname);
19879    return transmit_register(p->registry, SIP_REGISTER, digest, respheader);
19880 }
19881 
19882 /*! \brief Add authentication on outbound SIP packet */
19883 static int do_proxy_auth(struct sip_pvt *p, struct sip_request *req, enum sip_auth_type code, int sipmethod, int init)
19884 {
19885    char *header, *respheader;
19886    char digest[1024];
19887 
19888    if (!p->options && !(p->options = ast_calloc(1, sizeof(*p->options))))
19889       return -2;
19890 
19891    p->authtries++;
19892    sip_auth_headers(code, &header, &respheader);
19893    ast_debug(2, "Auth attempt %d on %s\n", p->authtries, sip_methods[sipmethod].text);
19894    memset(digest, 0, sizeof(digest));
19895    if (reply_digest(p, req, header, sipmethod, digest, sizeof(digest) )) {
19896       /* No way to authenticate */
19897       return -1;
19898    }
19899    /* Now we have a reply digest */
19900    p->options->auth = digest;
19901    p->options->authheader = respheader;
19902    return transmit_invite(p, sipmethod, sipmethod == SIP_INVITE, init, NULL);
19903 }
19904 
19905 /*! \brief  reply to authentication for outbound registrations
19906 \return  Returns -1 if we have no auth
19907 \note This is used for register= servers in sip.conf, SIP proxies we register
19908    with  for receiving calls from.  */
19909 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod,  char *digest, int digest_len)
19910 {
19911    char tmp[512];
19912    char *c;
19913    char oldnonce[256];
19914 
19915    /* table of recognised keywords, and places where they should be copied */
19916    const struct x {
19917       const char *key;
19918       const ast_string_field *field;
19919    } *i, keys[] = {
19920       { "realm=", &p->realm },
19921       { "nonce=", &p->nonce },
19922       { "opaque=", &p->opaque },
19923       { "qop=", &p->qop },
19924       { "domain=", &p->domain },
19925       { NULL, 0 },
19926    };
19927 
19928    ast_copy_string(tmp, sip_get_header(req, header), sizeof(tmp));
19929    if (ast_strlen_zero(tmp))
19930       return -1;
19931    if (strncasecmp(tmp, "Digest ", strlen("Digest "))) {
19932       ast_log(LOG_WARNING, "missing Digest.\n");
19933       return -1;
19934    }
19935    c = tmp + strlen("Digest ");
19936    ast_copy_string(oldnonce, p->nonce, sizeof(oldnonce));
19937    while (c && *(c = ast_skip_blanks(c))) {  /* lookup for keys */
19938       for (i = keys; i->key != NULL; i++) {
19939          char *src, *separator;
19940          if (strncasecmp(c, i->key, strlen(i->key)) != 0)
19941             continue;
19942          /* Found. Skip keyword, take text in quotes or up to the separator. */
19943          c += strlen(i->key);
19944          if (*c == '"') {
19945             src = ++c;
19946             separator = "\"";
19947          } else {
19948             src = c;
19949             separator = ",";
19950          }
19951          strsep(&c, separator); /* clear separator and move ptr */
19952          ast_string_field_ptr_set(p, i->field, src);
19953          break;
19954       }
19955       if (i->key == NULL) /* not found, try ',' */
19956          strsep(&c, ",");
19957    }
19958    /* Reset nonce count */
19959    if (strcmp(p->nonce, oldnonce))
19960       p->noncecount = 0;
19961 
19962    /* Save auth data for following registrations */
19963    if (p->registry) {
19964       struct sip_registry *r = p->registry;
19965 
19966       if (strcmp(r->nonce, p->nonce)) {
19967          ast_string_field_set(r, realm, p->realm);
19968          ast_string_field_set(r, nonce, p->nonce);
19969          ast_string_field_set(r, authdomain, p->domain);
19970          ast_string_field_set(r, opaque, p->opaque);
19971          ast_string_field_set(r, qop, p->qop);
19972          r->noncecount = 0;
19973       }
19974    }
19975    return build_reply_digest(p, sipmethod, digest, digest_len);
19976 }
19977 
19978 /*! \brief  Build reply digest
19979 \return  Returns -1 if we have no auth
19980 \note Build digest challenge for authentication of registrations and calls
19981    Also used for authentication of BYE
19982 */
19983 static int build_reply_digest(struct sip_pvt *p, int method, char* digest, int digest_len)
19984 {
19985    char a1[256];
19986    char a2[256];
19987    char a1_hash[256];
19988    char a2_hash[256];
19989    char resp[256];
19990    char resp_hash[256];
19991    char uri[256];
19992    char opaque[256] = "";
19993    char cnonce[80];
19994    const char *username;
19995    const char *secret;
19996    const char *md5secret;
19997    struct sip_auth *auth;  /* Realm authentication credential */
19998    struct sip_auth_container *credentials;
19999 
20000    if (!ast_strlen_zero(p->domain))
20001       snprintf(uri, sizeof(uri), "%s:%s", p->socket.type == SIP_TRANSPORT_TLS ? "sips" : "sip", p->domain);
20002    else if (!ast_strlen_zero(p->uri))
20003       ast_copy_string(uri, p->uri, sizeof(uri));
20004    else
20005       snprintf(uri, sizeof(uri), "%s:%s@%s", p->socket.type == SIP_TRANSPORT_TLS ? "sips" : "sip", p->username, ast_sockaddr_stringify_host_remote(&p->sa));
20006 
20007    snprintf(cnonce, sizeof(cnonce), "%08lx", ast_random());
20008 
20009    /* Check if we have peer credentials */
20010    ao2_lock(p);
20011    credentials = p->peerauth;
20012    if (credentials) {
20013       ao2_t_ref(credentials, +1, "Ref peer auth for digest");
20014    }
20015    ao2_unlock(p);
20016    auth = find_realm_authentication(credentials, p->realm);
20017    if (!auth) {
20018       /* If not, check global credentials */
20019       if (credentials) {
20020          ao2_t_ref(credentials, -1, "Unref peer auth for digest");
20021       }
20022       ast_mutex_lock(&authl_lock);
20023       credentials = authl;
20024       if (credentials) {
20025          ao2_t_ref(credentials, +1, "Ref global auth for digest");
20026       }
20027       ast_mutex_unlock(&authl_lock);
20028       auth = find_realm_authentication(credentials, p->realm);
20029    }
20030 
20031    if (auth) {
20032       ast_debug(3, "use realm [%s] from peer [%s][%s]\n", auth->username, p->peername, p->username);
20033       username = auth->username;
20034       secret = auth->secret;
20035       md5secret = auth->md5secret;
20036       if (sipdebug)
20037          ast_debug(1, "Using realm %s authentication for call %s\n", p->realm, p->callid);
20038    } else {
20039       /* No authentication, use peer or register= config */
20040       username = p->authname;
20041       secret = p->relatedpeer 
20042          && !ast_strlen_zero(p->relatedpeer->remotesecret)
20043             ? p->relatedpeer->remotesecret : p->peersecret;
20044       md5secret = p->peermd5secret;
20045    }
20046    if (ast_strlen_zero(username)) {
20047       /* We have no authentication */
20048       if (credentials) {
20049          ao2_t_ref(credentials, -1, "Unref auth for digest");
20050       }
20051       return -1;
20052    }
20053 
20054    /* Calculate SIP digest response */
20055    snprintf(a1, sizeof(a1), "%s:%s:%s", username, p->realm, secret);
20056    snprintf(a2, sizeof(a2), "%s:%s", sip_methods[method].text, uri);
20057    if (!ast_strlen_zero(md5secret))
20058       ast_copy_string(a1_hash, md5secret, sizeof(a1_hash));
20059    else
20060