Thu Apr 28 2011 16:56:44

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         <depend>chan_local</depend>
00166  ***/
00167 
00168 /*!  \page sip_session_timers SIP Session Timers in Asterisk Chan_sip
00169 
00170    The SIP Session-Timers is an extension of the SIP protocol that allows end-points and proxies to
00171    refresh a session periodically. The sessions are kept alive by sending a RE-INVITE or UPDATE
00172    request at a negotiated interval. If a session refresh fails then all the entities that support Session-
00173    Timers clear their internal session state. In addition, UAs generate a BYE request in order to clear
00174    the state in the proxies and the remote UA (this is done for the benefit of SIP entities in the path
00175    that do not support Session-Timers).
00176 
00177    The Session-Timers can be configured on a system-wide, per-user, or per-peer basis. The peruser/
00178    per-peer settings override the global settings. The following new parameters have been
00179    added to the sip.conf file.
00180       session-timers=["accept", "originate", "refuse"]
00181       session-expires=[integer]
00182       session-minse=[integer]
00183       session-refresher=["uas", "uac"]
00184 
00185    The session-timers parameter in sip.conf defines the mode of operation of SIP session-timers feature in
00186    Asterisk. The Asterisk can be configured in one of the following three modes:
00187 
00188    1. Accept :: In the "accept" mode, the Asterisk server honors session-timers requests
00189       made by remote end-points. A remote end-point can request Asterisk to engage
00190       session-timers by either sending it an INVITE request with a "Supported: timer"
00191       header in it or by responding to Asterisk's INVITE with a 200 OK that contains
00192       Session-Expires: header in it. In this mode, the Asterisk server does not 
00193       request session-timers from remote end-points. This is the default mode.
00194    2. Originate :: In the "originate" mode, the Asterisk server requests the remote 
00195       end-points to activate session-timers in addition to honoring such requests
00196       made by the remote end-pints. In order to get as much protection as possible
00197       against hanging SIP channels due to network or end-point failures, Asterisk
00198       resends periodic re-INVITEs even if a remote end-point does not support
00199       the session-timers feature.
00200    3. Refuse :: In the "refuse" mode, Asterisk acts as if it does not support session-
00201       timers for inbound or outbound requests. If a remote end-point requests
00202       session-timers in a dialog, then Asterisk ignores that request unless it's
00203       noted as a requirement (Require: header), in which case the INVITE is 
00204       rejected with a 420 Bad Extension response.
00205 
00206 */
00207 
00208 #include "asterisk.h"
00209 
00210 ASTERISK_FILE_VERSION(__FILE__, "$Revision: 315201 $")
00211 
00212 #include <ctype.h>
00213 #include <sys/ioctl.h>
00214 #include <fcntl.h>
00215 #include <signal.h>
00216 #include <sys/signal.h>
00217 #include <regex.h>
00218 #include <time.h>
00219 
00220 #include "asterisk/network.h"
00221 #include "asterisk/paths.h"   /* need ast_config_AST_SYSTEM_NAME */
00222 
00223 #include "asterisk/lock.h"
00224 #include "asterisk/channel.h"
00225 #include "asterisk/config.h"
00226 #include "asterisk/module.h"
00227 #include "asterisk/pbx.h"
00228 #include "asterisk/sched.h"
00229 #include "asterisk/io.h"
00230 #include "asterisk/rtp.h"
00231 #include "asterisk/udptl.h"
00232 #include "asterisk/acl.h"
00233 #include "asterisk/manager.h"
00234 #include "asterisk/callerid.h"
00235 #include "asterisk/cli.h"
00236 #include "asterisk/app.h"
00237 #include "asterisk/musiconhold.h"
00238 #include "asterisk/dsp.h"
00239 #include "asterisk/features.h"
00240 #include "asterisk/srv.h"
00241 #include "asterisk/astdb.h"
00242 #include "asterisk/causes.h"
00243 #include "asterisk/utils.h"
00244 #include "asterisk/file.h"
00245 #include "asterisk/astobj.h"
00246 /* 
00247    Uncomment the define below,  if you are having refcount related memory leaks.
00248    With this uncommented, this module will generate a file, /tmp/refs, which contains
00249    a history of the ao2_ref() calls. To be useful, all calls to ao2_* functions should
00250    be modified to ao2_t_* calls, and include a tag describing what is happening with 
00251    enough detail, to make pairing up a reference count increment with its corresponding decrement.
00252    The refcounter program in utils/ can be invaluable in highlighting objects that are not
00253    balanced, along with the complete history for that object.
00254    In normal operation, the macros defined will throw away the tags, so they do not 
00255    affect the speed of the program at all. They can be considered to be documentation.
00256 */
00257 /* #define  REF_DEBUG 1 */
00258 #include "asterisk/astobj2.h"
00259 #include "asterisk/dnsmgr.h"
00260 #include "asterisk/devicestate.h"
00261 #include "asterisk/linkedlists.h"
00262 #include "asterisk/stringfields.h"
00263 #include "asterisk/monitor.h"
00264 #include "asterisk/netsock.h"
00265 #include "asterisk/localtime.h"
00266 #include "asterisk/abstract_jb.h"
00267 #include "asterisk/threadstorage.h"
00268 #include "asterisk/translate.h"
00269 #include "asterisk/ast_version.h"
00270 #include "asterisk/event.h"
00271 #include "asterisk/tcptls.h"
00272 #include "asterisk/strings.h"
00273 
00274 /*** DOCUMENTATION
00275    <application name="SIPDtmfMode" language="en_US">
00276       <synopsis>
00277          Change the dtmfmode for a SIP call.
00278       </synopsis>
00279       <syntax>
00280          <parameter name="mode" required="true">
00281             <enumlist>
00282                <enum name="inband" />
00283                <enum name="info" />
00284                <enum name="rfc2833" />
00285             </enumlist>
00286          </parameter>
00287       </syntax>
00288       <description>
00289          <para>Changes the dtmfmode for a SIP call.</para>
00290       </description>
00291    </application>
00292    <application name="SIPAddHeader" language="en_US">
00293       <synopsis>
00294          Add a SIP header to the outbound call.
00295       </synopsis>
00296       <syntax argsep=":">
00297          <parameter name="Header" required="true" />
00298          <parameter name="Content" required="true" />
00299       </syntax>
00300       <description>
00301          <para>Adds a header to a SIP call placed with DIAL.</para>
00302          <para>Remember to use the X-header if you are adding non-standard SIP
00303          headers, like <literal>X-Asterisk-Accountcode:</literal>. Use this with care.
00304          Adding the wrong headers may jeopardize the SIP dialog.</para>
00305          <para>Always returns <literal>0</literal>.</para>
00306       </description>
00307    </application>
00308    <application name="SIPRemoveHeader" language="en_US">
00309       <synopsis>
00310          Remove SIP headers previously added with SIPAddHeader
00311       </synopsis>
00312       <syntax>
00313          <parameter name="Header" required="false" />
00314       </syntax>
00315       <description>
00316          <para>SIPRemoveHeader() allows you to remove headers which were previously 
00317          added with SIPAddHeader(). If no parameter is supplied, all previously added 
00318          headers will be removed. If a parameter is supplied, only the matching headers 
00319          will be removed.</para>
00320          <para>For example you have added these 2 headers:</para>
00321          <para>SIPAddHeader(P-Asserted-Identity: sip:foo@bar);</para>
00322          <para>SIPAddHeader(P-Preferred-Identity: sip:bar@foo);</para>
00323          <para></para>
00324          <para>// remove all headers</para>
00325          <para>SIPRemoveHeader();</para>
00326          <para>// remove all P- headers</para>
00327          <para>SIPRemoveHeader(P-);</para>
00328          <para>// remove only the PAI header (note the : at the end)</para>
00329          <para>SIPRemoveHeader(P-Asserted-Identity:);</para>
00330          <para></para>
00331          <para>Always returns <literal>0</literal>.</para>
00332       </description>
00333    </application>
00334    <function name="SIP_HEADER" language="en_US">
00335       <synopsis>
00336          Gets the specified SIP header.
00337       </synopsis>
00338       <syntax>
00339          <parameter name="name" required="true" />
00340          <parameter name="number">
00341             <para>If not specified, defaults to <literal>1</literal>.</para>
00342          </parameter>
00343       </syntax>
00344       <description>
00345          <para>Since there are several headers (such as Via) which can occur multiple
00346          times, SIP_HEADER takes an optional second argument to specify which header with
00347          that name to retrieve. Headers start at offset <literal>1</literal>.</para>
00348       </description>
00349    </function>
00350    <function name="SIPPEER" language="en_US">
00351       <synopsis>
00352          Gets SIP peer information.
00353       </synopsis>
00354       <syntax>
00355          <parameter name="peername" required="true" />
00356          <parameter name="item">
00357             <enumlist>
00358                <enum name="ip">
00359                   <para>(default) The ip address.</para>
00360                </enum>
00361                <enum name="port">
00362                   <para>The port number.</para>
00363                </enum>
00364                <enum name="mailbox">
00365                   <para>The configured mailbox.</para>
00366                </enum>
00367                <enum name="context">
00368                   <para>The configured context.</para>
00369                </enum>
00370                <enum name="expire">
00371                   <para>The epoch time of the next expire.</para>
00372                </enum>
00373                <enum name="dynamic">
00374                   <para>Is it dynamic? (yes/no).</para>
00375                </enum>
00376                <enum name="callerid_name">
00377                   <para>The configured Caller ID name.</para>
00378                </enum>
00379                <enum name="callerid_num">
00380                   <para>The configured Caller ID number.</para>
00381                </enum>
00382                <enum name="callgroup">
00383                   <para>The configured Callgroup.</para>
00384                </enum>
00385                <enum name="pickupgroup">
00386                   <para>The configured Pickupgroup.</para>
00387                </enum>
00388                <enum name="codecs">
00389                   <para>The configured codecs.</para>
00390                </enum>
00391                <enum name="status">
00392                   <para>Status (if qualify=yes).</para>
00393                </enum>
00394                <enum name="regexten">
00395                   <para>Registration extension.</para>
00396                </enum>
00397                <enum name="limit">
00398                   <para>Call limit (call-limit).</para>
00399                </enum>
00400                <enum name="busylevel">
00401                   <para>Configured call level for signalling busy.</para>
00402                </enum>
00403                <enum name="curcalls">
00404                   <para>Current amount of calls. Only available if call-limit is set.</para>
00405                </enum>
00406                <enum name="language">
00407                   <para>Default language for peer.</para>
00408                </enum>
00409                <enum name="accountcode">
00410                   <para>Account code for this peer.</para>
00411                </enum>
00412                <enum name="useragent">
00413                   <para>Current user agent id for peer.</para>
00414                </enum>
00415                <enum name="chanvar[name]">
00416                   <para>A channel variable configured with setvar for this peer.</para>
00417                </enum>
00418                <enum name="codec[x]">
00419                   <para>Preferred codec index number <replaceable>x</replaceable> (beginning with zero).</para>
00420                </enum>
00421             </enumlist>
00422          </parameter>
00423       </syntax>
00424       <description></description>
00425    </function>
00426    <function name="SIPCHANINFO" language="en_US">
00427       <synopsis>
00428          Gets the specified SIP parameter from the current channel.
00429       </synopsis>
00430       <syntax>
00431          <parameter name="item" required="true">
00432             <enumlist>
00433                <enum name="peerip">
00434                   <para>The IP address of the peer.</para>
00435                </enum>
00436                <enum name="recvip">
00437                   <para>The source IP address of the peer.</para>
00438                </enum>
00439                <enum name="from">
00440                   <para>The URI from the <literal>From:</literal> header.</para>
00441                </enum>
00442                <enum name="uri">
00443                   <para>The URI from the <literal>Contact:</literal> header.</para>
00444                </enum>
00445                <enum name="useragent">
00446                   <para>The useragent.</para>
00447                </enum>
00448                <enum name="peername">
00449                   <para>The name of the peer.</para>
00450                </enum>
00451                <enum name="t38passthrough">
00452                   <para><literal>1</literal> if T38 is offered or enabled in this channel,
00453                   otherwise <literal>0</literal>.</para>
00454                </enum>
00455             </enumlist>
00456          </parameter>
00457       </syntax>
00458       <description></description>
00459    </function>
00460    <function name="CHECKSIPDOMAIN" language="en_US">
00461       <synopsis>
00462          Checks if domain is a local domain.
00463       </synopsis>
00464       <syntax>
00465          <parameter name="domain" required="true" />
00466       </syntax>
00467       <description>
00468          <para>This function checks if the <replaceable>domain</replaceable> in the argument is configured
00469          as a local SIP domain that this Asterisk server is configured to handle.
00470          Returns the domain name if it is locally handled, otherwise an empty string.
00471          Check the <literal>domain=</literal> configuration in <filename>sip.conf</filename>.</para>
00472       </description>
00473    </function>
00474  ***/
00475 
00476 #ifndef FALSE
00477 #define FALSE    0
00478 #endif
00479 
00480 #ifndef TRUE
00481 #define TRUE     1
00482 #endif
00483 
00484 /* Arguments for find_peer */
00485 #define FINDUSERS (1 << 0)
00486 #define FINDPEERS (1 << 1)
00487 #define FINDALLDEVICES (FINDUSERS | FINDPEERS)
00488 
00489 #define  SIPBUFSIZE     512      /*!< Buffer size for many operations */
00490 
00491 #define XMIT_ERROR      -2
00492 
00493 #define SIP_RESERVED ";/?:@&=+$,# "    /*!< Reserved characters in the username part of the URI */
00494 
00495 /* #define VOCAL_DATA_HACK */
00496 
00497 #define DEFAULT_DEFAULT_EXPIRY  120
00498 #define DEFAULT_MIN_EXPIRY      60
00499 #define DEFAULT_MAX_EXPIRY      3600
00500 #define DEFAULT_MWI_EXPIRY      3600
00501 #define DEFAULT_REGISTRATION_TIMEOUT 20
00502 #define DEFAULT_MAX_FORWARDS    "70"
00503 #define DEFAULT_AUTHLIMIT       100
00504 #define DEFAULT_AUTHTIMEOUT     30
00505 
00506 /* guard limit must be larger than guard secs */
00507 /* guard min must be < 1000, and should be >= 250 */
00508 #define EXPIRY_GUARD_SECS       15                /*!< How long before expiry do we reregister */
00509 #define EXPIRY_GUARD_LIMIT      30                /*!< Below here, we use EXPIRY_GUARD_PCT instead of 
00510                                                     EXPIRY_GUARD_SECS */
00511 #define EXPIRY_GUARD_MIN        500                /*!< This is the minimum guard time applied. If 
00512                                                    GUARD_PCT turns out to be lower than this, it 
00513                                                    will use this time instead.
00514                                                    This is in milliseconds. */
00515 #define EXPIRY_GUARD_PCT        0.20                /*!< Percentage of expires timeout to use when 
00516                                                     below EXPIRY_GUARD_LIMIT */
00517 #define DEFAULT_EXPIRY 900                          /*!< Expire slowly */
00518 
00519 static int min_expiry = DEFAULT_MIN_EXPIRY;        /*!< Minimum accepted registration time */
00520 static int max_expiry = DEFAULT_MAX_EXPIRY;        /*!< Maximum accepted registration time */
00521 static int default_expiry = DEFAULT_DEFAULT_EXPIRY;
00522 static int mwi_expiry = DEFAULT_MWI_EXPIRY;
00523 
00524 #define DEFAULT_QUALIFY_GAP   100
00525 #define DEFAULT_QUALIFY_PEERS 1
00526 
00527 
00528 #define CALLERID_UNKNOWN             "Anonymous"
00529 #define FROMDOMAIN_INVALID           "anonymous.invalid"
00530 
00531 #define DEFAULT_MAXMS                2000             /*!< Qualification: Must be faster than 2 seconds by default */
00532 #define DEFAULT_QUALIFYFREQ          60 * 1000        /*!< Qualification: How often to check for the host to be up */
00533 #define DEFAULT_FREQ_NOTOK           10 * 1000        /*!< Qualification: How often to check, if the host is down... */
00534 
00535 #define DEFAULT_RETRANS              1000             /*!< How frequently to retransmit Default: 2 * 500 ms in RFC 3261 */
00536 #define MAX_RETRANS                  6                /*!< Try only 6 times for retransmissions, a total of 7 transmissions */
00537 #define DEFAULT_TIMER_T1                 500              /*!< SIP timer T1 (according to RFC 3261) */
00538 #define SIP_TRANS_TIMEOUT            64 * DEFAULT_TIMER_T1 /*!< SIP request timeout (rfc 3261) 64*T1 
00539                                                       \todo Use known T1 for timeout (peerpoke)
00540                                                       */
00541 #define DEFAULT_TRANS_TIMEOUT        -1               /*!< Use default SIP transaction timeout */
00542 #define PROVIS_KEEPALIVE_TIMEOUT     60000            /*!< How long to wait before retransmitting a provisional response (rfc 3261 13.3.1.1) */
00543 #define MAX_AUTHTRIES                3                /*!< Try authentication three times, then fail */
00544 
00545 #define SIP_MAX_HEADERS              64               /*!< Max amount of SIP headers to read */
00546 #define SIP_MAX_LINES                256              /*!< Max amount of lines in SIP attachment (like SDP) */
00547 #define SIP_MIN_PACKET               4096             /*!< Initialize size of memory to allocate for packets */
00548 #define MAX_HISTORY_ENTRIES        50                /*!< Max entires in the history list for a sip_pvt */
00549 
00550 #define INITIAL_CSEQ                 101              /*!< Our initial sip sequence number */
00551 
00552 #define DEFAULT_MAX_SE               1800             /*!< Session-Timer Default Session-Expires period (RFC 4028) */
00553 #define DEFAULT_MIN_SE               90               /*!< Session-Timer Default Min-SE period (RFC 4028) */
00554 
00555 #define SDP_MAX_RTPMAP_CODECS        32               /*!< Maximum number of codecs allowed in received SDP */
00556 
00557 static int unauth_sessions = 0;
00558 static int authlimit = DEFAULT_AUTHLIMIT;
00559 static int authtimeout = DEFAULT_AUTHTIMEOUT;
00560 
00561 /*! \brief Global jitterbuffer configuration - by default, jb is disabled */
00562 static struct ast_jb_conf default_jbconf =
00563 {
00564    .flags = 0,
00565    .max_size = -1,
00566    .resync_threshold = -1,
00567    .impl = "",
00568    .target_extra = -1,
00569 };
00570 static struct ast_jb_conf global_jbconf;     /*!< Global jitterbuffer configuration */
00571 
00572 static const char config[] = "sip.conf";     /*!< Main configuration file */
00573 static const char notify_config[] = "sip_notify.conf";   /*!< Configuration file for sending Notify with CLI commands to reconfigure or reboot phones */
00574 
00575 #define RTP    1
00576 #define NO_RTP 0
00577 
00578 /*! \brief Authorization scheme for call transfers 
00579 
00580 \note Not a bitfield flag, since there are plans for other modes,
00581    like "only allow transfers for authenticated devices" */
00582 enum transfermodes {
00583    TRANSFER_OPENFORALL,            /*!< Allow all SIP transfers */
00584    TRANSFER_CLOSED,                /*!< Allow no SIP transfers */
00585 };
00586 
00587 
00588 /*! \brief The result of a lot of functions */
00589 enum sip_result {
00590    AST_SUCCESS = 0,     /*!< FALSE means success, funny enough */
00591    AST_FAILURE = -1,    /*!< Failure code */
00592 };
00593 
00594 /*! \brief States for the INVITE transaction, not the dialog 
00595    \note this is for the INVITE that sets up the dialog
00596 */
00597 enum invitestates {
00598    INV_NONE = 0,          /*!< No state at all, maybe not an INVITE dialog */
00599    INV_CALLING = 1,  /*!< Invite sent, no answer */
00600    INV_PROCEEDING = 2,  /*!< We got/sent 1xx message */
00601    INV_EARLY_MEDIA = 3,    /*!< We got 18x message with to-tag back */
00602    INV_COMPLETED = 4,   /*!< Got final response with error. Wait for ACK, then CONFIRMED */
00603    INV_CONFIRMED = 5,   /*!< Confirmed response - we've got an ack (Incoming calls only) */
00604    INV_TERMINATED = 6,  /*!< Transaction done - either successful (AST_STATE_UP) or failed, but done 
00605                  The only way out of this is a BYE from one side */
00606    INV_CANCELLED = 7,   /*!< Transaction cancelled by client or server in non-terminated state */
00607 };
00608 
00609 /*! \brief Readable descriptions of device states.
00610        \note Should be aligned to above table as index */
00611 static const struct invstate2stringtable {
00612    const enum invitestates state;
00613    const char *desc;
00614 } invitestate2string[] = {
00615    {INV_NONE,              "None"  },
00616    {INV_CALLING,           "Calling (Trying)"},
00617    {INV_PROCEEDING,        "Proceeding "},
00618    {INV_EARLY_MEDIA,       "Early media"},
00619    {INV_COMPLETED,         "Completed (done)"},
00620    {INV_CONFIRMED,         "Confirmed (up)"},
00621    {INV_TERMINATED,        "Done"},
00622    {INV_CANCELLED,         "Cancelled"}
00623 };
00624 
00625 /*! \brief When sending a SIP message, we can send with a few options, depending on
00626    type of SIP request. UNRELIABLE is moslty used for responses to repeated requests,
00627    where the original response would be sent RELIABLE in an INVITE transaction */
00628 enum xmittype {
00629    XMIT_CRITICAL = 2,              /*!< Transmit critical SIP message reliably, with re-transmits.
00630                                               If it fails, it's critical and will cause a teardown of the session */
00631    XMIT_RELIABLE = 1,              /*!< Transmit SIP message reliably, with re-transmits */
00632    XMIT_UNRELIABLE = 0,            /*!< Transmit SIP message without bothering with re-transmits */
00633 };
00634 
00635 /*! \brief Results from the parse_register() function */
00636 enum parse_register_result {
00637    PARSE_REGISTER_DENIED,
00638    PARSE_REGISTER_FAILED,
00639    PARSE_REGISTER_UPDATE,
00640    PARSE_REGISTER_QUERY,
00641 };
00642 
00643 /*! \brief Type of subscription, based on the packages we do support, see \ref subscription_types */
00644 enum subscriptiontype { 
00645    NONE = 0,
00646    XPIDF_XML,
00647    DIALOG_INFO_XML,
00648    CPIM_PIDF_XML,
00649    PIDF_XML,
00650    MWI_NOTIFICATION
00651 };
00652 
00653 /*! \brief Subscription types that we support. We support
00654    - dialoginfo updates (really device status, not dialog info as was the original intent of the standard)
00655    - SIMPLE presence used for device status
00656    - Voicemail notification subscriptions
00657 */
00658 static const struct cfsubscription_types {
00659    enum subscriptiontype type;
00660    const char * const event;
00661    const char * const mediatype;
00662    const char * const text;
00663 } subscription_types[] = {
00664    { NONE,        "-",        "unknown",               "unknown" },
00665    /* RFC 4235: SIP Dialog event package */
00666    { DIALOG_INFO_XML, "dialog",   "application/dialog-info+xml", "dialog-info+xml" },
00667    { CPIM_PIDF_XML,   "presence", "application/cpim-pidf+xml",   "cpim-pidf+xml" },  /* RFC 3863 */
00668    { PIDF_XML,        "presence", "application/pidf+xml",        "pidf+xml" },       /* RFC 3863 */
00669    { XPIDF_XML,       "presence", "application/xpidf+xml",       "xpidf+xml" },       /* Pre-RFC 3863 with MS additions */
00670    { MWI_NOTIFICATION,  "message-summary", "application/simple-message-summary", "mwi" } /* RFC 3842: Mailbox notification */
00671 };
00672 
00673 
00674 /*! \brief Authentication types - proxy or www authentication 
00675    \note Endpoints, like Asterisk, should always use WWW authentication to
00676    allow multiple authentications in the same call - to the proxy and
00677    to the end point.
00678 */
00679 enum sip_auth_type {
00680    PROXY_AUTH = 407,
00681    WWW_AUTH = 401,
00682 };
00683 
00684 /*! \brief Authentication result from check_auth* functions */
00685 enum check_auth_result {
00686    AUTH_DONT_KNOW = -100,  /*!< no result, need to check further */
00687       /* XXX maybe this is the same as AUTH_NOT_FOUND */
00688 
00689    AUTH_SUCCESSFUL = 0,
00690    AUTH_CHALLENGE_SENT = 1,
00691    AUTH_SECRET_FAILED = -1,
00692    AUTH_USERNAME_MISMATCH = -2,
00693    AUTH_NOT_FOUND = -3, /*!< returned by register_verify */
00694    AUTH_FAKE_AUTH = -4,
00695    AUTH_UNKNOWN_DOMAIN = -5,
00696    AUTH_PEER_NOT_DYNAMIC = -6,
00697    AUTH_ACL_FAILED = -7,
00698    AUTH_BAD_TRANSPORT = -8,
00699 };
00700 
00701 /*! \brief States for outbound registrations (with register= lines in sip.conf */
00702 enum sipregistrystate {
00703    REG_STATE_UNREGISTERED = 0,   /*!< We are not registered 
00704        *  \note Initial state. We should have a timeout scheduled for the initial
00705        * (or next) registration transmission, calling sip_reregister
00706        */
00707 
00708    REG_STATE_REGSENT,   /*!< Registration request sent 
00709        * \note sent initial request, waiting for an ack or a timeout to
00710        * retransmit the initial request.
00711       */
00712 
00713    REG_STATE_AUTHSENT,  /*!< We have tried to authenticate 
00714        * \note entered after transmit_register with auth info,
00715        * waiting for an ack.
00716        */
00717 
00718    REG_STATE_REGISTERED,   /*!< Registered and done */
00719 
00720    REG_STATE_REJECTED,  /*!< Registration rejected *
00721        * \note only used when the remote party has an expire larger than
00722        * our max-expire. This is a final state from which we do not
00723        * recover (not sure how correctly).
00724        */
00725 
00726    REG_STATE_TIMEOUT,   /*!< Registration timed out *
00727       * \note XXX unused */
00728 
00729    REG_STATE_NOAUTH, /*!< We have no accepted credentials
00730        * \note fatal - no chance to proceed */
00731 
00732    REG_STATE_FAILED, /*!< Registration failed after several tries
00733        * \note fatal - no chance to proceed */
00734 };
00735 
00736 /*! \brief Modes in which Asterisk can be configured to run SIP Session-Timers */
00737 enum st_mode {
00738         SESSION_TIMER_MODE_INVALID = 0, /*!< Invalid value */ 
00739         SESSION_TIMER_MODE_ACCEPT,      /*!< Honor inbound Session-Timer requests */
00740         SESSION_TIMER_MODE_ORIGINATE,   /*!< Originate outbound and honor inbound requests */
00741         SESSION_TIMER_MODE_REFUSE       /*!< Ignore inbound Session-Timers requests */
00742 };
00743 
00744 /*! \brief The entity playing the refresher role for Session-Timers */
00745 enum st_refresher {
00746         SESSION_TIMER_REFRESHER_AUTO,    /*!< Negotiated                      */
00747         SESSION_TIMER_REFRESHER_UAC,     /*!< Session is refreshed by the UAC */
00748         SESSION_TIMER_REFRESHER_UAS      /*!< Session is refreshed by the UAS */
00749 };
00750 
00751 /*! \brief Define some implemented SIP transports 
00752    \note Asterisk does not support SCTP or UDP/DTLS 
00753 */
00754 enum sip_transport {
00755    SIP_TRANSPORT_UDP = 1,     /*!< Unreliable transport for SIP, needs retransmissions */
00756    SIP_TRANSPORT_TCP = 1 << 1,   /*!< Reliable, but unsecure */
00757    SIP_TRANSPORT_TLS = 1 << 2,   /*!< TCP/TLS - reliable and secure transport for signalling */
00758 };
00759 
00760 /*! \brief definition of a sip proxy server
00761  *
00762  * For outbound proxies, a sip_peer will contain a reference to a 
00763  * dynamically allocated instance of a sip_proxy. A sip_pvt may also
00764  * contain a reference to a peer's outboundproxy, or it may contain
00765  * a reference to the sip_cfg.outboundproxy.
00766  */
00767 struct sip_proxy {
00768    char name[MAXHOSTNAMELEN];      /*!< DNS name of domain/host or IP */
00769    struct sockaddr_in ip;          /*!< Currently used IP address and port */
00770    time_t last_dnsupdate;          /*!< When this was resolved */
00771    enum sip_transport transport; 
00772    int force;                      /*!< If it's an outbound proxy, Force use of this outbound proxy for all outbound requests */
00773    /* Room for a SRV record chain based on the name */
00774 };
00775 
00776 /*! \brief argument for the 'show channels|subscriptions' callback. */
00777 struct __show_chan_arg { 
00778    int fd;
00779    int subscriptions;
00780    int numchans;   /* return value */
00781 };
00782 
00783 
00784 /*! \brief States whether a SIP message can create a dialog in Asterisk. */
00785 enum can_create_dialog {
00786    CAN_NOT_CREATE_DIALOG,
00787    CAN_CREATE_DIALOG,
00788    CAN_CREATE_DIALOG_UNSUPPORTED_METHOD,
00789 };
00790 
00791 /*! \brief SIP Request methods known by Asterisk 
00792 
00793    \note Do _NOT_ make any changes to this enum, or the array following it;
00794    if you think you are doing the right thing, you are probably
00795    not doing the right thing. If you think there are changes
00796    needed, get someone else to review them first _before_
00797    submitting a patch. If these two lists do not match properly
00798    bad things will happen.
00799 */
00800 
00801 enum sipmethod {
00802    SIP_UNKNOWN,      /*!< Unknown response */
00803    SIP_RESPONSE,     /*!< Not request, response to outbound request */
00804    SIP_REGISTER,     /*!< Registration to the mothership, tell us where you are located */
00805    SIP_OPTIONS,      /*!< Check capabilities of a device, used for "ping" too */
00806    SIP_NOTIFY,    /*!< Status update, Part of the event package standard, result of a SUBSCRIBE or a REFER */
00807    SIP_INVITE,    /*!< Set up a session */
00808    SIP_ACK,    /*!< End of a three-way handshake started with INVITE. */
00809    SIP_PRACK,     /*!< Reliable pre-call signalling. Not supported in Asterisk. */
00810    SIP_BYE,    /*!< End of a session */
00811    SIP_REFER,     /*!< Refer to another URI (transfer) */
00812    SIP_SUBSCRIBE,    /*!< Subscribe for updates (voicemail, session status, device status, presence) */
00813    SIP_MESSAGE,      /*!< Text messaging */
00814    SIP_UPDATE,    /*!< Update a dialog. We can send UPDATE; but not accept it */
00815    SIP_INFO,      /*!< Information updates during a session */
00816    SIP_CANCEL,    /*!< Cancel an INVITE */
00817    SIP_PUBLISH,      /*!< Not supported in Asterisk */
00818    SIP_PING,      /*!< Not supported at all, no standard but still implemented out there */
00819 };
00820 
00821 /*! \brief Settings for the 'notifycid' option, see sip.conf.sample for details. */
00822 enum notifycid_setting {
00823    DISABLED       = 0,
00824    ENABLED        = 1,
00825    IGNORE_CONTEXT = 2,
00826 };
00827 
00828 /*! \brief The core structure to setup dialogs. We parse incoming messages by using
00829    structure and then route the messages according to the type.
00830 
00831       \note Note that sip_methods[i].id == i must hold or the code breaks */
00832 static const struct  cfsip_methods { 
00833    enum sipmethod id;
00834    int need_rtp;     /*!< when this is the 'primary' use for a pvt structure, does it need RTP? */
00835    char * const text;
00836    enum can_create_dialog can_create;
00837 } sip_methods[] = {
00838    { SIP_UNKNOWN,  RTP,    "-UNKNOWN-",   CAN_CREATE_DIALOG },
00839    { SIP_RESPONSE,    NO_RTP, "SIP/2.0",  CAN_NOT_CREATE_DIALOG },
00840    { SIP_REGISTER,    NO_RTP, "REGISTER",    CAN_CREATE_DIALOG },
00841    { SIP_OPTIONS,  NO_RTP, "OPTIONS",  CAN_CREATE_DIALOG },
00842    { SIP_NOTIFY,   NO_RTP, "NOTIFY",   CAN_CREATE_DIALOG },
00843    { SIP_INVITE,   RTP,    "INVITE",   CAN_CREATE_DIALOG },
00844    { SIP_ACK,   NO_RTP, "ACK",   CAN_NOT_CREATE_DIALOG },
00845    { SIP_PRACK,    NO_RTP, "PRACK",    CAN_NOT_CREATE_DIALOG },
00846    { SIP_BYE,   NO_RTP, "BYE",   CAN_NOT_CREATE_DIALOG },
00847    { SIP_REFER,    NO_RTP, "REFER",    CAN_CREATE_DIALOG },
00848    { SIP_SUBSCRIBE, NO_RTP, "SUBSCRIBE",  CAN_CREATE_DIALOG },
00849    { SIP_MESSAGE,  NO_RTP, "MESSAGE",  CAN_CREATE_DIALOG },
00850    { SIP_UPDATE,   NO_RTP, "UPDATE",   CAN_NOT_CREATE_DIALOG },
00851    { SIP_INFO,  NO_RTP, "INFO",  CAN_NOT_CREATE_DIALOG },
00852    { SIP_CANCEL,   NO_RTP, "CANCEL",   CAN_NOT_CREATE_DIALOG },
00853    { SIP_PUBLISH,  NO_RTP, "PUBLISH",  CAN_CREATE_DIALOG_UNSUPPORTED_METHOD },
00854    { SIP_PING,  NO_RTP, "PING",  CAN_CREATE_DIALOG_UNSUPPORTED_METHOD }
00855 };
00856 
00857 static unsigned int chan_idx;
00858 
00859 /*!  Define SIP option tags, used in Require: and Supported: headers 
00860    We need to be aware of these properties in the phones to use 
00861    the replace: header. We should not do that without knowing
00862    that the other end supports it... 
00863    This is nothing we can configure, we learn by the dialog
00864    Supported: header on the REGISTER (peer) or the INVITE
00865    (other devices)
00866    We are not using many of these today, but will in the future.
00867    This is documented in RFC 3261
00868 */
00869 #define SUPPORTED    1
00870 #define NOT_SUPPORTED      0
00871 
00872 /* SIP options */
00873 #define SIP_OPT_REPLACES   (1 << 0)
00874 #define SIP_OPT_100REL     (1 << 1)
00875 #define SIP_OPT_TIMER      (1 << 2)
00876 #define SIP_OPT_EARLY_SESSION (1 << 3)
00877 #define SIP_OPT_JOIN    (1 << 4)
00878 #define SIP_OPT_PATH    (1 << 5)
00879 #define SIP_OPT_PREF    (1 << 6)
00880 #define SIP_OPT_PRECONDITION  (1 << 7)
00881 #define SIP_OPT_PRIVACY    (1 << 8)
00882 #define SIP_OPT_SDP_ANAT   (1 << 9)
00883 #define SIP_OPT_SEC_AGREE  (1 << 10)
00884 #define SIP_OPT_EVENTLIST  (1 << 11)
00885 #define SIP_OPT_GRUU    (1 << 12)
00886 #define SIP_OPT_TARGET_DIALOG (1 << 13)
00887 #define SIP_OPT_NOREFERSUB (1 << 14)
00888 #define SIP_OPT_HISTINFO   (1 << 15)
00889 #define SIP_OPT_RESPRIORITY   (1 << 16)
00890 #define SIP_OPT_FROMCHANGE (1 << 17)
00891 #define SIP_OPT_RECLISTINV (1 << 18)
00892 #define SIP_OPT_RECLISTSUB (1 << 19)
00893 #define SIP_OPT_OUTBOUND   (1 << 20)
00894 #define SIP_OPT_UNKNOWN    (1 << 21)
00895 
00896 
00897 /*! \brief List of well-known SIP options. If we get this in a require,
00898    we should check the list and answer accordingly. */
00899 static const struct cfsip_options {
00900    int id;        /*!< Bitmap ID */
00901    int supported;    /*!< Supported by Asterisk ? */
00902    char * const text;   /*!< Text id, as in standard */
00903 } sip_options[] = {  /* XXX used in 3 places */
00904    /* RFC3262: PRACK 100% reliability */
00905    { SIP_OPT_100REL, NOT_SUPPORTED, "100rel" }, 
00906    /* RFC3959: SIP Early session support */
00907    { SIP_OPT_EARLY_SESSION, NOT_SUPPORTED,   "early-session" },
00908    /* SIMPLE events:  RFC4662 */
00909    { SIP_OPT_EVENTLIST, NOT_SUPPORTED, "eventlist" },
00910    /* RFC 4916- Connected line ID updates */
00911    { SIP_OPT_FROMCHANGE,   NOT_SUPPORTED, "from-change" },
00912    /* GRUU: Globally Routable User Agent URI's */
00913    { SIP_OPT_GRUU,      NOT_SUPPORTED, "gruu" },
00914    /* RFC4244 History info */
00915    { SIP_OPT_HISTINFO,  NOT_SUPPORTED, "histinfo" },
00916    /* RFC3911: SIP Join header support */
00917    { SIP_OPT_JOIN,      NOT_SUPPORTED, "join" },
00918    /* Disable the REFER subscription, RFC 4488 */
00919    { SIP_OPT_NOREFERSUB,   NOT_SUPPORTED, "norefersub" },
00920    /* SIP outbound - the final NAT battle - draft-sip-outbound */
00921    { SIP_OPT_OUTBOUND,  NOT_SUPPORTED, "outbound" },
00922    /* RFC3327: Path support */
00923    { SIP_OPT_PATH,      NOT_SUPPORTED, "path" },
00924    /* RFC3840: Callee preferences */
00925    { SIP_OPT_PREF,      NOT_SUPPORTED, "pref" },
00926    /* RFC3312: Precondition support */
00927    { SIP_OPT_PRECONDITION, NOT_SUPPORTED, "precondition" },
00928    /* RFC3323: Privacy with proxies*/
00929    { SIP_OPT_PRIVACY,   NOT_SUPPORTED, "privacy" },
00930    /* RFC-ietf-sip-uri-list-conferencing-02.txt conference invite lists */
00931    { SIP_OPT_RECLISTINV,   NOT_SUPPORTED, "recipient-list-invite" },
00932    /* RFC-ietf-sip-uri-list-subscribe-02.txt - subscription lists */
00933    { SIP_OPT_RECLISTSUB,   NOT_SUPPORTED, "recipient-list-subscribe" },
00934    /* RFC3891: Replaces: header for transfer */
00935    { SIP_OPT_REPLACES,  SUPPORTED,  "replaces" },  
00936    /* One version of Polycom firmware has the wrong label */
00937    { SIP_OPT_REPLACES,  SUPPORTED,  "replace" },   
00938    /* RFC4412 Resource priorities */
00939    { SIP_OPT_RESPRIORITY,  NOT_SUPPORTED, "resource-priority" },
00940    /* RFC3329: Security agreement mechanism */
00941    { SIP_OPT_SEC_AGREE, NOT_SUPPORTED, "sec_agree" },
00942    /* RFC4092: Usage of the SDP ANAT Semantics in the SIP */
00943    { SIP_OPT_SDP_ANAT,  NOT_SUPPORTED, "sdp-anat" },
00944    /* RFC4028: SIP Session-Timers */
00945    { SIP_OPT_TIMER,  SUPPORTED,  "timer" },
00946    /* RFC4538: Target-dialog */
00947    { SIP_OPT_TARGET_DIALOG,NOT_SUPPORTED, "tdialog" },
00948 };
00949 
00950 
00951 /*! \brief SIP Methods we support 
00952    \todo This string should be set dynamically. We only support REFER and SUBSCRIBE if we have
00953    allowsubscribe and allowrefer on in sip.conf.
00954 */
00955 #define ALLOWED_METHODS "INVITE, ACK, CANCEL, OPTIONS, BYE, REFER, SUBSCRIBE, NOTIFY, INFO"
00956 
00957 /*! \brief Standard SIP unsecure port for UDP and TCP from RFC 3261. DO NOT CHANGE THIS */
00958 #define STANDARD_SIP_PORT  5060
00959 /*! \brief Standard SIP TLS port from RFC 3261. DO NOT CHANGE THIS */
00960 #define STANDARD_TLS_PORT  5061
00961 
00962 /*! \note in many SIP headers, absence of a port number implies port 5060,
00963  * and this is why we cannot change the above constant.
00964  * There is a limited number of places in asterisk where we could,
00965  * in principle, use a different "default" port number, but
00966  * we do not support this feature at the moment.
00967  * You can run Asterisk with SIP on a different port with a configuration
00968  * option. If you change this value, the signalling will be incorrect.
00969  */
00970 
00971 /*! \name DefaultValues Default values, set and reset in reload_config before reading configuration 
00972 
00973    These are default values in the source. There are other recommended values in the
00974    sip.conf.sample for new installations. These may differ to keep backwards compatibility,
00975    yet encouraging new behaviour on new installations 
00976  */
00977 /*@{*/ 
00978 #define DEFAULT_CONTEXT    "default"   /*!< The default context for [general] section as well as devices */
00979 #define DEFAULT_MOHINTERPRET    "default" /*!< The default music class */
00980 #define DEFAULT_MOHSUGGEST      ""
00981 #define DEFAULT_VMEXTEN    "asterisk"  /*!< Default voicemail extension */
00982 #define DEFAULT_CALLERID   "asterisk"  /*!< Default caller ID */
00983 #define DEFAULT_NOTIFYMIME    "application/simple-message-summary"
00984 #define DEFAULT_ALLOWGUEST TRUE
00985 #define DEFAULT_RTPKEEPALIVE  0     /*!< Default RTPkeepalive setting */
00986 #define DEFAULT_CALLCOUNTER   FALSE
00987 #define DEFAULT_SRVLOOKUP  TRUE     /*!< Recommended setting is ON */
00988 #define DEFAULT_COMPACTHEADERS   FALSE    /*!< Send compact (one-character) SIP headers. Default off */
00989 #define DEFAULT_TOS_SIP         0               /*!< Call signalling packets should be marked as DSCP CS3, but the default is 0 to be compatible with previous versions. */
00990 #define DEFAULT_TOS_AUDIO       0               /*!< Audio packets should be marked as DSCP EF (Expedited Forwarding), but the default is 0 to be compatible with previous versions. */
00991 #define DEFAULT_TOS_VIDEO       0               /*!< Video packets should be marked as DSCP AF41, but the default is 0 to be compatible with previous versions. */
00992 #define DEFAULT_TOS_TEXT        0               /*!< Text packets should be marked as XXXX XXXX, but the default is 0 to be compatible with previous versions. */
00993 #define DEFAULT_COS_SIP         4      /*!< Level 2 class of service for SIP signalling */
00994 #define DEFAULT_COS_AUDIO       5      /*!< Level 2 class of service for audio media  */
00995 #define DEFAULT_COS_VIDEO       6      /*!< Level 2 class of service for video media */
00996 #define DEFAULT_COS_TEXT        5      /*!< Level 2 class of service for text media (T.140) */
00997 #define DEFAULT_ALLOW_EXT_DOM TRUE     /*!< Allow external domains */
00998 #define DEFAULT_REALM      "asterisk"  /*!< Realm for HTTP digest authentication */
00999 #define DEFAULT_NOTIFYRINGING TRUE     /*!< Notify devicestate system on ringing state */
01000 #define DEFAULT_NOTIFYCID     DISABLED /*!< Include CID with ringing notifications */
01001 #define DEFAULT_PEDANTIC   FALSE    /*!< Avoid following SIP standards for dialog matching */
01002 #define DEFAULT_AUTOCREATEPEER   FALSE    /*!< Don't create peers automagically */
01003 #define  DEFAULT_MATCHEXTERNIPLOCALLY FALSE  /*!< Match extern IP locally default setting */
01004 #define DEFAULT_QUALIFY    FALSE    /*!< Don't monitor devices */
01005 #define DEFAULT_CALLEVENTS FALSE    /*!< Extra manager SIP call events */
01006 #define DEFAULT_ALWAYSAUTHREJECT FALSE /*!< Don't reject authentication requests always */
01007 #define DEFAULT_REGEXTENONQUALIFY FALSE
01008 #define DEFAULT_T1MIN      100      /*!< 100 MS for minimal roundtrip time */
01009 #define DEFAULT_MAX_CALL_BITRATE (384)    /*!< Max bitrate for video */
01010 #ifndef DEFAULT_USERAGENT
01011 #define DEFAULT_USERAGENT "Asterisk PBX"  /*!< Default Useragent: header unless re-defined in sip.conf */
01012 #define DEFAULT_SDPSESSION "Asterisk PBX" /*!< Default SDP session name, (s=) header unless re-defined in sip.conf */
01013 #define DEFAULT_SDPOWNER "root"        /*!< Default SDP username field in (o=) header unless re-defined in sip.conf */
01014 #endif
01015 /*@}*/ 
01016 
01017 /*! \name DefaultSettings
01018    Default setttings are used as a channel setting and as a default when
01019    configuring devices 
01020 */
01021 /*@{*/ 
01022 static char default_language[MAX_LANGUAGE];
01023 static char default_callerid[AST_MAX_EXTENSION];
01024 static char default_fromdomain[AST_MAX_EXTENSION];
01025 static char default_notifymime[AST_MAX_EXTENSION];
01026 static int default_qualify;      /*!< Default Qualify= setting */
01027 static char default_vmexten[AST_MAX_EXTENSION];
01028 static char default_mohinterpret[MAX_MUSICCLASS];  /*!< Global setting for moh class to use when put on hold */
01029 static char default_mohsuggest[MAX_MUSICCLASS];    /*!< Global setting for moh class to suggest when putting 
01030                                                     *   a bridged channel on hold */
01031 static char default_parkinglot[AST_MAX_CONTEXT]; /*!< Parkinglot */
01032 static int default_maxcallbitrate;  /*!< Maximum bitrate for call */
01033 static struct ast_codec_pref default_prefs;     /*!< Default codec prefs */
01034 static unsigned int default_transports;         /*!< Default Transports (enum sip_transport) that are acceptable */
01035 static unsigned int default_primary_transport;     /*!< Default primary Transport (enum sip_transport) for outbound connections to devices */
01036 
01037 /*@}*/ 
01038 
01039 /*! \name GlobalSettings
01040    Global settings apply to the channel (often settings you can change in the general section
01041    of sip.conf
01042 */
01043 /*@{*/ 
01044 /*! \brief a place to store all global settings for the sip channel driver 
01045    These are settings that will be possibly to apply on a group level later on.
01046    \note Do not add settings that only apply to the channel itself and can't
01047          be applied to devices (trunks, services, phones)
01048 */
01049 struct sip_settings {
01050    int peer_rtupdate;      /*!< G: Update database with registration data for peer? */
01051    int rtsave_sysname;     /*!< G: Save system name at registration? */
01052    int ignore_regexpire;      /*!< G: Ignore expiration of peer  */
01053    int rtautoclear;     /*!< Realtime ?? */
01054    int directrtpsetup;     /*!< Enable support for Direct RTP setup (no re-invites) */
01055    int pedanticsipchecking;   /*!< Extra checking ?  Default off */
01056    int autocreatepeer;     /*!< Auto creation of peers at registration? Default off. */
01057    int srvlookup;       /*!< SRV Lookup on or off. Default is on */
01058    int allowguest;         /*!< allow unauthenticated peers to connect? */
01059    int alwaysauthreject;      /*!< Send 401 Unauthorized for all failing requests */
01060    int compactheaders;     /*!< send compact sip headers */
01061    int allow_external_domains;   /*!< Accept calls to external SIP domains? */
01062    int callevents;         /*!< Whether we send manager events or not */
01063    int regextenonqualify;     /*!< Whether to add/remove regexten when qualifying peers */
01064    int matchexterniplocally;  /*!< Match externip/externhost setting against localnet setting */
01065    int notifyringing;      /*!< Send notifications on ringing */
01066    int notifyhold;         /*!< Send notifications on hold */
01067    enum notifycid_setting notifycid; /*!< Send CID with ringing notifications */
01068    enum transfermodes allowtransfer;   /*!< SIP Refer restriction scheme */
01069    int allowsubscribe;          /*!< Flag for disabling ALL subscriptions, this is FALSE only if all peers are FALSE 
01070                    the global setting is in globals_flags[1] */
01071    char realm[MAXHOSTNAMELEN];      /*!< Default realm */
01072    struct sip_proxy outboundproxy;  /*!< Outbound proxy */
01073    char default_context[AST_MAX_CONTEXT];
01074    char default_subscribecontext[AST_MAX_CONTEXT];
01075 };
01076 
01077 static struct sip_settings sip_cfg;
01078 
01079 static int global_match_auth_username;    /*!< Match auth username if available instead of From: Default off. */
01080 
01081 static int global_relaxdtmf;     /*!< Relax DTMF */
01082 static int global_prematuremediafilter;   /*!< Enable/disable premature frames in a call (causing 183 early media) */
01083 static int global_relaxdtmf;        /*!< Relax DTMF */
01084 static int global_rtptimeout;    /*!< Time out call if no RTP */
01085 static int global_rtpholdtimeout;   /*!< Time out call if no RTP during hold */
01086 static int global_rtpkeepalive;     /*!< Send RTP keepalives */
01087 static int global_reg_timeout;
01088 static int global_regattempts_max;  /*!< Registration attempts before giving up */
01089 static int global_shrinkcallerid;   /*!< enable or disable shrinking of caller id  */
01090 static int global_callcounter;      /*!< Enable call counters for all devices. This is currently enabled by setting the peer
01091                   call-limit to INT_MAX. When we remove the call-limit from the code, we can make it
01092                   with just a boolean flag in the device structure */
01093 static unsigned int global_tos_sip;    /*!< IP type of service for SIP packets */
01094 static unsigned int global_tos_audio;     /*!< IP type of service for audio RTP packets */
01095 static unsigned int global_tos_video;     /*!< IP type of service for video RTP packets */
01096 static unsigned int global_tos_text;      /*!< IP type of service for text RTP packets */
01097 static unsigned int global_cos_sip;    /*!< 802.1p class of service for SIP packets */
01098 static unsigned int global_cos_audio;     /*!< 802.1p class of service for audio RTP packets */
01099 static unsigned int global_cos_video;     /*!< 802.1p class of service for video RTP packets */
01100 static unsigned int global_cos_text;      /*!< 802.1p class of service for text RTP packets */
01101 static int recordhistory;     /*!< Record SIP history. Off by default */
01102 static int dumphistory;       /*!< Dump history to verbose before destroying SIP dialog */
01103 static char global_regcontext[AST_MAX_CONTEXT];    /*!< Context for auto-extensions */
01104 static char global_useragent[AST_MAX_EXTENSION];   /*!< Useragent for the SIP channel */
01105 static char global_sdpsession[AST_MAX_EXTENSION];  /*!< SDP session name for the SIP channel */
01106 static char global_sdpowner[AST_MAX_EXTENSION]; /*!< SDP owner name for the SIP channel */
01107 static int global_authfailureevents;      /*!< Whether we send authentication failure manager events or not. Default no. */
01108 static int global_t1;         /*!< T1 time */
01109 static int global_t1min;      /*!< T1 roundtrip time minimum */
01110 static int global_timer_b;             /*!< Timer B - RFC 3261 Section 17.1.1.2 */
01111 static int global_autoframing;            /*!< Turn autoframing on or off. */
01112 static int global_qualifyfreq;         /*!< Qualify frequency */
01113 static int global_qualify_gap;              /*!< Time between our group of peer pokes */
01114 static int global_qualify_peers;          /*!< Number of peers to poke at a given time */
01115 
01116 
01117 /*! \brief Codecs that we support by default: */
01118 static int global_capability = AST_FORMAT_ULAW | AST_FORMAT_ALAW | AST_FORMAT_GSM | AST_FORMAT_H263;
01119 
01120 static enum st_mode global_st_mode;           /*!< Mode of operation for Session-Timers           */
01121 static enum st_refresher global_st_refresher; /*!< Session-Timer refresher                        */
01122 static int global_min_se;                     /*!< Lowest threshold for session refresh interval  */
01123 static int global_max_se;                     /*!< Highest threshold for session refresh interval */
01124 
01125 static int global_dynamic_exclude_static = 0;   /*!< Exclude static peers from contact registrations */
01126 /*@}*/
01127 
01128 /*! \brief Global list of addresses dynamic peers are not allowed to use */
01129 static struct ast_ha *global_contact_ha = NULL;
01130 
01131 /*! \name Object counters @{
01132  * \bug These counters are not handled in a thread-safe way ast_atomic_fetchadd_int()
01133  * should be used to modify these values. */
01134 static int speerobjs = 0;                /*!< Static peers */
01135 static int rpeerobjs = 0;                /*!< Realtime peers */
01136 static int apeerobjs = 0;                /*!< Autocreated peer objects */
01137 static int regobjs = 0;                  /*!< Registry objects */
01138 /* }@ */
01139 
01140 static struct ast_flags global_flags[2] = {{0}};        /*!< global SIP_ flags */
01141 static int global_t38_maxdatagram;        /*!< global T.38 FaxMaxDatagram override */
01142 
01143 static char used_context[AST_MAX_CONTEXT];      /*!< name of automatically created context for unloading */
01144 
01145 
01146 AST_MUTEX_DEFINE_STATIC(netlock);
01147 
01148 /*! \brief Protect the monitoring thread, so only one process can kill or start it, and not
01149    when it's doing something critical. */
01150 AST_MUTEX_DEFINE_STATIC(monlock);
01151 
01152 AST_MUTEX_DEFINE_STATIC(sip_reload_lock);
01153 
01154 /*! \brief This is the thread for the monitor which checks for input on the channels
01155    which are not currently in use.  */
01156 static pthread_t monitor_thread = AST_PTHREADT_NULL;
01157 
01158 static int sip_reloading = FALSE;                       /*!< Flag for avoiding multiple reloads at the same time */
01159 static enum channelreloadreason sip_reloadreason;       /*!< Reason for last reload/load of configuration */
01160 
01161 static struct sched_context *sched;     /*!< The scheduling context */
01162 static struct io_context *io;           /*!< The IO context */
01163 static int *sipsock_read_id;            /*!< ID of IO entry for sipsock FD */
01164 
01165 #define DEC_CALL_LIMIT  0
01166 #define INC_CALL_LIMIT  1
01167 #define DEC_CALL_RINGING 2
01168 #define INC_CALL_RINGING 3
01169 
01170 /*! \brief The SIP socket definition */
01171 struct sip_socket {
01172    enum sip_transport type;   /*!< UDP, TCP or TLS */
01173    int fd;           /*!< Filed descriptor, the actual socket */
01174    uint16_t port;
01175    struct ast_tcptls_session_instance *tcptls_session;   /* If tcp or tls, a socket manager */
01176 };
01177 
01178 /*! \brief sip_request: The data grabbed from the UDP socket
01179  *
01180  * \verbatim
01181  * Incoming messages: we first store the data from the socket in data[],
01182  * adding a trailing \0 to make string parsing routines happy.
01183  * Then call parse_request() and req.method = find_sip_method();
01184  * to initialize the other fields. The \r\n at the end of each line is   
01185  * replaced by \0, so that data[] is not a conforming SIP message anymore.
01186  * After this processing, rlPart1 is set to non-NULL to remember
01187  * that we can run get_header() on this kind of packet.
01188  *
01189  * parse_request() splits the first line as follows:
01190  * Requests have in the first line      method uri SIP/2.0
01191  *      rlPart1 = method; rlPart2 = uri;
01192  * Responses have in the first line     SIP/2.0 NNN description
01193  *      rlPart1 = SIP/2.0; rlPart2 = NNN + description;
01194  *
01195  * For outgoing packets, we initialize the fields with init_req() or init_resp()
01196  * (which fills the first line to "METHOD uri SIP/2.0" or "SIP/2.0 code text"),
01197  * and then fill the rest with add_header() and add_content().
01198  * The \r\n at the end of the line are still there, so the get_header()
01199  * and similar functions don't work on these packets. 
01200  * \endverbatim
01201  */
01202 struct sip_request {
01203    ptrdiff_t rlPart1;           /*!< Offset of the SIP Method Name or "SIP/2.0" protocol version */
01204    ptrdiff_t rlPart2;           /*!< Offset of the Request URI or Response Status */
01205    int len;                /*!< bytes used in data[], excluding trailing null terminator. Rarely used. */
01206    int headers;            /*!< # of SIP Headers */
01207    int method;             /*!< Method of this request */
01208    int lines;              /*!< Body Content */
01209    unsigned int sdp_start; /*!< the line number where the SDP begins */
01210    unsigned int sdp_count; /*!< the number of lines of SDP */
01211    char debug;    /*!< print extra debugging if non zero */
01212    char has_to_tag;  /*!< non-zero if packet has To: tag */
01213    char ignore;      /*!< if non-zero This is a re-transmit, ignore it */
01214    char authenticated;     /*!< non-zero if this request was authenticated */
01215    /* Array of offsets into the request string of each SIP header*/
01216    ptrdiff_t header[SIP_MAX_HEADERS];
01217    /* Array of offsets into the request string of each SDP line*/
01218    ptrdiff_t line[SIP_MAX_LINES];
01219    struct ast_str *data;   
01220    struct ast_str *content;
01221    /* XXX Do we need to unref socket.ser when the request goes away? */
01222    struct sip_socket socket;  /*!< The socket used for this request */
01223    AST_LIST_ENTRY(sip_request) next;
01224 };
01225 
01226 /* \brief given a sip_request and an offset, return the char * that resides there
01227  *
01228  * It used to be that rlPart1, rlPart2, and the header and line arrays were character
01229  * pointers. They are now offsets into the ast_str portion of the sip_request structure.
01230  * To avoid adding a bunch of redundant pointer arithmetic to the code, this macro is
01231  * provided to retrieve the string at a particular offset within the request's buffer
01232  */
01233 #define REQ_OFFSET_TO_STR(req,offset) (ast_str_buffer((req)->data) + ((req)->offset))
01234 
01235 /*! \brief structure used in transfers */
01236 struct sip_dual {
01237    struct ast_channel *chan1; /*!< First channel involved */
01238    struct ast_channel *chan2; /*!< Second channel involved */
01239    struct sip_request req;    /*!< Request that caused the transfer (REFER) */
01240    int seqno;        /*!< Sequence number */
01241 };
01242 
01243 struct sip_pkt;
01244 
01245 /*! \brief Parameters to the transmit_invite function */
01246 struct sip_invite_param {
01247    int addsipheaders;      /*!< Add extra SIP headers */
01248    const char *uri_options;   /*!< URI options to add to the URI */
01249    const char *vxml_url;      /*!< VXML url for Cisco phones */
01250    char *auth;       /*!< Authentication */
01251    char *authheader;    /*!< Auth header */
01252    enum sip_auth_type auth_type; /*!< Authentication type */
01253    const char *replaces;      /*!< Replaces header for call transfers */
01254    int transfer;        /*!< Flag - is this Invite part of a SIP transfer? (invite/replaces) */
01255 };
01256 
01257 /*! \brief Structure to save routing information for a SIP session */
01258 struct sip_route {
01259    struct sip_route *next;
01260    char hop[0];
01261 };
01262 
01263 /*! \brief Structure to store Via information */
01264 struct sip_via {
01265    char *via;
01266    const char *protocol;
01267    const char *sent_by;
01268    const char *branch;
01269    const char *maddr;
01270    unsigned int port;
01271    unsigned char ttl;
01272 };
01273 
01274 /*! \brief Modes for SIP domain handling in the PBX */
01275 enum domain_mode {
01276    SIP_DOMAIN_AUTO,     /*!< This domain is auto-configured */
01277    SIP_DOMAIN_CONFIG,      /*!< This domain is from configuration */
01278 };
01279 
01280 /*! \brief Domain data structure. 
01281    \note In the future, we will connect this to a configuration tree specific
01282    for this domain
01283 */
01284 struct domain {
01285    char domain[MAXHOSTNAMELEN];     /*!< SIP domain we are responsible for */
01286    char context[AST_MAX_EXTENSION]; /*!< Incoming context for this domain */
01287    enum domain_mode mode;        /*!< How did we find this domain? */
01288    AST_LIST_ENTRY(domain) list;     /*!< List mechanics */
01289 };
01290 
01291 static AST_LIST_HEAD_STATIC(domain_list, domain);  /*!< The SIP domain list */
01292 
01293 
01294 /*! \brief sip_history: Structure for saving transactions within a SIP dialog */
01295 struct sip_history {
01296    AST_LIST_ENTRY(sip_history) list;
01297    char event[0]; /* actually more, depending on needs */
01298 };
01299 
01300 AST_LIST_HEAD_NOLOCK(sip_history_head, sip_history); /*!< history list, entry in sip_pvt */
01301 
01302 /*! \brief sip_auth: Credentials for authentication to other SIP services */
01303 struct sip_auth {
01304    char realm[AST_MAX_EXTENSION];  /*!< Realm in which these credentials are valid */
01305    char username[256];             /*!< Username */
01306    char secret[256];               /*!< Secret */
01307    char md5secret[256];            /*!< MD5Secret */
01308    struct sip_auth *next;          /*!< Next auth structure in list */
01309 };
01310 
01311 /*! \name SIPflags
01312    Various flags for the flags field in the pvt structure 
01313    Trying to sort these up (one or more of the following):
01314    D: Dialog
01315    P: Peer/user
01316    G: Global flag
01317    When flags are used by multiple structures, it is important that
01318    they have a common layout so it is easy to copy them.
01319 */
01320 /*@{*/ 
01321 #define SIP_OUTGOING    (1 << 0) /*!< D: Direction of the last transaction in this dialog */
01322 #define SIP_RINGING     (1 << 2) /*!< D: Have sent 180 ringing */
01323 #define SIP_PROGRESS_SENT  (1 << 3) /*!< D: Have sent 183 message progress */
01324 #define SIP_NEEDREINVITE   (1 << 4) /*!< D: Do we need to send another reinvite? */
01325 #define SIP_PENDINGBYE     (1 << 5) /*!< D: Need to send bye after we ack? */
01326 #define SIP_GOTREFER    (1 << 6) /*!< D: Got a refer? */
01327 #define SIP_CALL_LIMIT     (1 << 7) /*!< D: Call limit enforced for this call */
01328 #define SIP_INC_COUNT      (1 << 8) /*!< D: Did this dialog increment the counter of in-use calls? */
01329 #define SIP_INC_RINGING    (1 << 9) /*!< D: Did this connection increment the counter of in-use calls? */
01330 #define SIP_DEFER_BYE_ON_TRANSFER   (1 << 10)   /*!< D: Do not hangup at first ast_hangup */
01331 
01332 #define SIP_PROMISCREDIR   (1 << 11)   /*!< DP: Promiscuous redirection */
01333 #define SIP_TRUSTRPID      (1 << 12)   /*!< DP: Trust RPID headers? */
01334 #define SIP_USEREQPHONE    (1 << 13)   /*!< DP: Add user=phone to numeric URI. Default off */
01335 #define SIP_USECLIENTCODE  (1 << 14)   /*!< DP: Trust X-ClientCode info message */
01336 
01337 /* DTMF flags - see str2dtmfmode() and dtmfmode2str() */
01338 #define SIP_DTMF     (7 << 15)   /*!< DP: DTMF Support: five settings, uses three bits */
01339 #define SIP_DTMF_RFC2833   (0 << 15)   /*!< DP: DTMF Support: RTP DTMF - "rfc2833" */
01340 #define SIP_DTMF_INBAND    (1 << 15)   /*!< DP: DTMF Support: Inband audio, only for ULAW/ALAW - "inband" */
01341 #define SIP_DTMF_INFO      (2 << 15)   /*!< DP: DTMF Support: SIP Info messages - "info" */
01342 #define SIP_DTMF_AUTO      (3 << 15)   /*!< DP: DTMF Support: AUTO switch between rfc2833 and in-band DTMF */
01343 #define SIP_DTMF_SHORTINFO      (4 << 15)       /*!< DP: DTMF Support: SIP Info messages - "info" - short variant */
01344 
01345 /* NAT settings - see nat2str() */
01346 #define SIP_NAT         (3 << 18)   /*!< DP: four settings, uses two bits */
01347 #define SIP_NAT_NEVER      (0 << 18)   /*!< DP: No nat support */
01348 #define SIP_NAT_RFC3581    (1 << 18)   /*!< DP: NAT RFC3581 */
01349 #define SIP_NAT_ROUTE      (2 << 18)   /*!< DP: NAT Only ROUTE */
01350 #define SIP_NAT_ALWAYS     (3 << 18)   /*!< DP: NAT Both ROUTE and RFC3581 */
01351 
01352 /* re-INVITE related settings */
01353 #define SIP_REINVITE    (7 << 20)   /*!< DP: four settings, uses three bits */
01354 #define SIP_REINVITE_NONE  (0 << 20)   /*!< DP: no reinvite allowed */
01355 #define SIP_DIRECT_MEDIA   (1 << 20)   /*!< DP: allow peers to be reinvited to send media directly p2p */
01356 #define SIP_DIRECT_MEDIA_NAT  (2 << 20)   /*!< DP: allow media reinvite when new peer is behind NAT */
01357 #define SIP_REINVITE_UPDATE   (4 << 20)   /*!< DP: use UPDATE (RFC3311) when reinviting this peer */
01358 
01359 /* "insecure" settings - see insecure2str() */
01360 #define SIP_INSECURE    (3 << 23)   /*!< DP: three settings, uses two bits */
01361 #define SIP_INSECURE_NONE  (0 << 23)   /*!< DP: secure mode */
01362 #define SIP_INSECURE_PORT  (1 << 23)   /*!< DP: don't require matching port for incoming requests */
01363 #define SIP_INSECURE_INVITE   (1 << 24)   /*!< DP: don't require authentication for incoming INVITEs */
01364 
01365 /* Sending PROGRESS in-band settings */
01366 #define SIP_PROG_INBAND    (3 << 25)   /*!< DP: three settings, uses two bits */
01367 #define SIP_PROG_INBAND_NEVER (0 << 25)
01368 #define SIP_PROG_INBAND_NO (1 << 25)
01369 #define SIP_PROG_INBAND_YES   (2 << 25)
01370 
01371 #define SIP_SENDRPID    (1 << 29)   /*!< DP: Remote Party-ID Support */
01372 #define SIP_G726_NONSTANDARD  (1 << 31)   /*!< DP: Use non-standard packing for G726-32 data */
01373 
01374 /*! \brief Flags to copy from peer/user to dialog */
01375 #define SIP_FLAGS_TO_COPY \
01376    (SIP_PROMISCREDIR | SIP_TRUSTRPID | SIP_SENDRPID | SIP_DTMF | SIP_REINVITE | \
01377     SIP_PROG_INBAND | SIP_USECLIENTCODE | SIP_NAT | SIP_G726_NONSTANDARD | \
01378     SIP_USEREQPHONE | SIP_INSECURE)
01379 /*@}*/ 
01380 
01381 /*! \name SIPflags2
01382    a second page of flags (for flags[1] */
01383 /*@{*/ 
01384 /* realtime flags */
01385 #define SIP_PAGE2_RTCACHEFRIENDS (1 << 0) /*!< GP: Should we keep RT objects in memory for extended time? */
01386 #define SIP_PAGE2_RTAUTOCLEAR    (1 << 2) /*!< GP: Should we clean memory from peers after expiry? */
01387 #define SIP_PAGE2_HAVEPEERCONTEXT   (1 << 3) /*< Are we associated with a configured peer context? */
01388 /* Space for addition of other realtime flags in the future */
01389 #define SIP_PAGE2_FORWARD_LOOP_DETECTED (1 << 8)/*!< 31: Do call forward when receiving 482 Loop Detected */
01390 #define SIP_PAGE2_STATECHANGEQUEUE  (1 << 9) /*!< D: Unsent state pending change exists */
01391 
01392 #define SIP_PAGE2_RPORT_PRESENT         (1 << 10)       /*!< Was rport received in the Via header? */
01393 #define SIP_PAGE2_VIDEOSUPPORT      (1 << 14)   /*!< DP: Video supported if offered? */
01394 #define SIP_PAGE2_TEXTSUPPORT    (1 << 15)   /*!< GDP: Global text enable */
01395 #define SIP_PAGE2_ALLOWSUBSCRIBE (1 << 16)   /*!< GP: Allow subscriptions from this peer? */
01396 #define SIP_PAGE2_ALLOWOVERLAP      (1 << 17)   /*!< DP: Allow overlap dialing ? */
01397 #define SIP_PAGE2_SUBSCRIBEMWIONLY  (1 << 18)   /*!< GP: Only issue MWI notification if subscribed to */
01398 #define SIP_PAGE2_IGNORESDPVERSION  (1 << 19)   /*!< GDP: Ignore the SDP session version number we receive and treat all sessions as new */
01399 
01400 #define SIP_PAGE2_T38SUPPORT             (3 << 20) /*!< GDP: T.38 Fax Support */
01401 #define SIP_PAGE2_T38SUPPORT_UDPTL          (1 << 20) /*!< GDP: T.38 Fax Support (no error correction) */
01402 #define SIP_PAGE2_T38SUPPORT_UDPTL_FEC         (2 << 20) /*!< GDP: T.38 Fax Support (FEC error correction) */
01403 #define SIP_PAGE2_T38SUPPORT_UDPTL_REDUNDANCY   (3 << 20)   /*!< GDP: T.38 Fax Support (redundancy error correction) */
01404 
01405 #define SIP_PAGE2_CALL_ONHOLD    (3 << 23)   /*!< D: Call hold states: */
01406 #define SIP_PAGE2_CALL_ONHOLD_ACTIVE    (1 << 23)       /*!< D: Active hold */
01407 #define SIP_PAGE2_CALL_ONHOLD_ONEDIR   (2 << 23)   /*!< D: One directional hold */
01408 #define SIP_PAGE2_CALL_ONHOLD_INACTIVE (3 << 23)   /*!< D: Inactive hold */
01409 
01410 #define SIP_PAGE2_RFC2833_COMPENSATE    (1 << 25)  /*!< DP: Compensate for buggy RFC2833 implementations */
01411 #define SIP_PAGE2_BUGGY_MWI      (1 << 26)   /*!< DP: Buggy CISCO MWI fix */
01412 #define SIP_PAGE2_DIALOG_ESTABLISHED    (1 << 27)       /*!< 29: Has a dialog been established? */
01413 #define SIP_PAGE2_FAX_DETECT     (3 << 28)   /*!< DP: Fax Detection support */
01414 #define SIP_PAGE2_FAX_DETECT_CNG (1 << 28)   /*!< DP: Fax Detection support - detect CNG in audio */
01415 #define SIP_PAGE2_FAX_DETECT_T38 (2 << 28)   /*!< DP: Fax Detection support - detect T.38 reinvite from peer */
01416 #define SIP_PAGE2_FAX_DETECT_BOTH   (3 << 28)   /*!< DP: Fax Detection support - detect both */
01417 #define SIP_PAGE2_REGISTERTRYING        (1 << 29)       /*!< DP: Send 100 Trying on REGISTER attempts */
01418 #define SIP_PAGE2_UDPTL_DESTINATION     (1 << 30)       /*!< DP: Use source IP of RTP as destination if NAT is enabled */
01419 #define SIP_PAGE2_VIDEOSUPPORT_ALWAYS  (1 << 31)       /*!< DP: Always set up video, even if endpoints don't support it */
01420 
01421 #define SIP_PAGE2_FLAGS_TO_COPY \
01422    (SIP_PAGE2_ALLOWSUBSCRIBE | SIP_PAGE2_ALLOWOVERLAP | SIP_PAGE2_IGNORESDPVERSION | \
01423    SIP_PAGE2_VIDEOSUPPORT | SIP_PAGE2_T38SUPPORT | SIP_PAGE2_RFC2833_COMPENSATE | \
01424    SIP_PAGE2_BUGGY_MWI | SIP_PAGE2_TEXTSUPPORT | SIP_PAGE2_FAX_DETECT | \
01425    SIP_PAGE2_UDPTL_DESTINATION | SIP_PAGE2_VIDEOSUPPORT_ALWAYS | \
01426    SIP_PAGE2_HAVEPEERCONTEXT | SIP_PAGE2_FORWARD_LOOP_DETECTED)
01427 
01428 /*@}*/ 
01429 
01430 /*! \brief debugging state
01431  * We store separately the debugging requests from the config file
01432  * and requests from the CLI. Debugging is enabled if either is set
01433  * (which means that if sipdebug is set in the config file, we can
01434  * only turn it off by reloading the config).
01435  */
01436 enum sip_debug_e {
01437    sip_debug_none = 0,
01438    sip_debug_config = 1,
01439    sip_debug_console = 2,
01440 };
01441 
01442 static enum sip_debug_e sipdebug;
01443 
01444 /*! \brief extra debugging for 'text' related events.
01445  * At the moment this is set together with sip_debug_console.
01446  * \note It should either go away or be implemented properly.
01447  */
01448 static int sipdebug_text;
01449 
01450 /*! \brief T38 States for a call */
01451 enum t38state {
01452    T38_DISABLED = 0,                /*!< Not enabled */
01453    T38_LOCAL_REINVITE,              /*!< Offered from local - REINVITE */
01454    T38_PEER_REINVITE,               /*!< Offered from peer - REINVITE */
01455    T38_ENABLED                      /*!< Negotiated (enabled) */
01456 };
01457 
01458 /*! \brief T.38 channel settings (at some point we need to make this alloc'ed */
01459 struct t38properties {
01460    enum t38state state;    /*!< T.38 state */
01461    struct ast_control_t38_parameters our_parms;
01462    struct ast_control_t38_parameters their_parms;
01463 };
01464 
01465 /*! \brief Parameters to know status of transfer */
01466 enum referstatus {
01467    REFER_IDLE,                    /*!< No REFER is in progress */
01468    REFER_SENT,                    /*!< Sent REFER to transferee */
01469    REFER_RECEIVED,                /*!< Received REFER from transferrer */
01470    REFER_CONFIRMED,               /*!< Refer confirmed with a 100 TRYING (unused) */
01471    REFER_ACCEPTED,                /*!< Accepted by transferee */
01472    REFER_RINGING,                 /*!< Target Ringing */
01473    REFER_200OK,                   /*!< Answered by transfer target */
01474    REFER_FAILED,                  /*!< REFER declined - go on */
01475    REFER_NOAUTH                   /*!< We had no auth for REFER */
01476 };
01477 
01478 /*! \brief generic struct to map between strings and integers.
01479  * Fill it with x-s pairs, terminate with an entry with s = NULL;
01480  * Then you can call map_x_s(...) to map an integer to a string,
01481  * and map_s_x() for the string -> integer mapping.
01482  */
01483 struct _map_x_s {
01484    int x;
01485    const char *s;
01486 };              
01487 
01488 static const struct _map_x_s referstatusstrings[] = {
01489    { REFER_IDLE,     "<none>" },
01490    { REFER_SENT,     "Request sent" },
01491    { REFER_RECEIVED, "Request received" },
01492    { REFER_CONFIRMED,   "Confirmed" },
01493    { REFER_ACCEPTED, "Accepted" },
01494    { REFER_RINGING,  "Target ringing" },
01495    { REFER_200OK,    "Done" },
01496    { REFER_FAILED,      "Failed" },
01497    { REFER_NOAUTH,      "Failed - auth failure" },
01498    { -1,       NULL} /* terminator */
01499 };
01500 
01501 /*! \brief Structure to handle SIP transfers. Dynamically allocated when needed
01502    \note OEJ: Should be moved to string fields */
01503 struct sip_refer {
01504    char refer_to[AST_MAX_EXTENSION];      /*!< Place to store REFER-TO extension */
01505    char refer_to_domain[AST_MAX_EXTENSION];  /*!< Place to store REFER-TO domain */
01506    char refer_to_urioption[AST_MAX_EXTENSION];  /*!< Place to store REFER-TO uri options */
01507    char refer_to_context[AST_MAX_EXTENSION]; /*!< Place to store REFER-TO context */
01508    char referred_by[AST_MAX_EXTENSION];      /*!< Place to store REFERRED-BY extension */
01509    char referred_by_name[AST_MAX_EXTENSION]; /*!< Place to store REFERRED-BY extension */
01510    char refer_contact[AST_MAX_EXTENSION];    /*!< Place to store Contact info from a REFER extension */
01511    char replaces_callid[SIPBUFSIZE];         /*!< Replace info: callid */
01512    char replaces_callid_totag[SIPBUFSIZE/2];    /*!< Replace info: to-tag */
01513    char replaces_callid_fromtag[SIPBUFSIZE/2];     /*!< Replace info: from-tag */
01514    struct sip_pvt *refer_call;         /*!< Call we are referring. This is just a reference to a
01515                       * dialog owned by someone else, so we should not destroy
01516                       * it when the sip_refer object goes.
01517                       */
01518    int attendedtransfer;            /*!< Attended or blind transfer? */
01519    int localtransfer;            /*!< Transfer to local domain? */
01520    enum referstatus status;         /*!< REFER status */
01521 };
01522 
01523 
01524 /*! \brief Structure that encapsulates all attributes related to running 
01525  *   SIP Session-Timers feature on a per dialog basis.
01526  */
01527 struct sip_st_dlg {
01528    int st_active;                          /*!< Session-Timers on/off */ 
01529    int st_interval;                        /*!< Session-Timers negotiated session refresh interval */
01530    int st_schedid;                         /*!< Session-Timers ast_sched scheduler id */
01531    enum st_refresher st_ref;               /*!< Session-Timers session refresher */
01532    int st_expirys;                         /*!< Session-Timers number of expirys */
01533    int st_active_peer_ua;                  /*!< Session-Timers on/off in peer UA */
01534    int st_cached_min_se;                   /*!< Session-Timers cached Min-SE */
01535    int st_cached_max_se;                   /*!< Session-Timers cached Session-Expires */
01536    enum st_mode st_cached_mode;            /*!< Session-Timers cached M.O. */
01537    enum st_refresher st_cached_ref;        /*!< Session-Timers cached refresher */
01538    unsigned char quit_flag:1;              /*!< Stop trying to lock; just quit */
01539 };
01540 
01541 
01542 /*! \brief Structure that encapsulates all attributes related to configuration 
01543  *   of SIP Session-Timers feature on a per user/peer basis.
01544  */
01545 struct sip_st_cfg {
01546    enum st_mode st_mode_oper;      /*!< Mode of operation for Session-Timers           */
01547    enum st_refresher st_ref;       /*!< Session-Timer refresher                        */
01548    int st_min_se;                  /*!< Lowest threshold for session refresh interval  */
01549    int st_max_se;                  /*!< Highest threshold for session refresh interval */
01550 };
01551 
01552 struct offered_media {
01553    int offered;
01554    char text[128];
01555 };
01556 
01557 /*! \brief Structure used for each SIP dialog, ie. a call, a registration, a subscribe.
01558  * Created and initialized by sip_alloc(), the descriptor goes into the list of
01559  * descriptors (dialoglist).
01560  */
01561 struct sip_pvt {
01562    struct sip_pvt *next;         /*!< Next dialog in chain */
01563    enum invitestates invitestate;      /*!< Track state of SIP_INVITEs */
01564    int method;          /*!< SIP method that opened this dialog */
01565    AST_DECLARE_STRING_FIELDS(
01566       AST_STRING_FIELD(callid);  /*!< Global CallID */
01567       AST_STRING_FIELD(randdata);   /*!< Random data */
01568       AST_STRING_FIELD(accountcode);   /*!< Account code */
01569       AST_STRING_FIELD(realm);   /*!< Authorization realm */
01570       AST_STRING_FIELD(nonce);   /*!< Authorization nonce */
01571       AST_STRING_FIELD(opaque);  /*!< Opaque nonsense */
01572       AST_STRING_FIELD(qop);     /*!< Quality of Protection, since SIP wasn't complicated enough yet. */
01573       AST_STRING_FIELD(domain);  /*!< Authorization domain */
01574       AST_STRING_FIELD(from);    /*!< The From: header */
01575       AST_STRING_FIELD(useragent);  /*!< User agent in SIP request */
01576       AST_STRING_FIELD(exten);   /*!< Extension where to start */
01577       AST_STRING_FIELD(context); /*!< Context for this call */
01578       AST_STRING_FIELD(subscribecontext); /*!< Subscribecontext */
01579       AST_STRING_FIELD(subscribeuri); /*!< Subscribecontext */
01580       AST_STRING_FIELD(fromdomain); /*!< Domain to show in the from field */
01581       AST_STRING_FIELD(fromuser);   /*!< User to show in the user field */
01582       AST_STRING_FIELD(fromname);   /*!< Name to show in the user field */
01583       AST_STRING_FIELD(tohost);  /*!< Host we should put in the "to" field */
01584       AST_STRING_FIELD(todnid);  /*!< DNID of this call (overrides host) */
01585       AST_STRING_FIELD(language);   /*!< Default language for this call */
01586       AST_STRING_FIELD(mohinterpret);  /*!< MOH class to use when put on hold */
01587       AST_STRING_FIELD(mohsuggest); /*!< MOH class to suggest when putting a peer on hold */
01588       AST_STRING_FIELD(rdnis);   /*!< Referring DNIS */
01589       AST_STRING_FIELD(redircause); /*!< Referring cause */
01590       AST_STRING_FIELD(theirtag);   /*!< Their tag */
01591       AST_STRING_FIELD(username);   /*!< [user] name */
01592       AST_STRING_FIELD(peername);   /*!< [peer] name, not set if [user] */
01593       AST_STRING_FIELD(authname);   /*!< Who we use for authentication */
01594       AST_STRING_FIELD(uri);     /*!< Original requested URI */
01595       AST_STRING_FIELD(okcontacturi);  /*!< URI from the 200 OK on INVITE */
01596       AST_STRING_FIELD(peersecret); /*!< Password */
01597       AST_STRING_FIELD(peermd5secret);
01598       AST_STRING_FIELD(cid_num); /*!< Caller*ID number */
01599       AST_STRING_FIELD(cid_name);   /*!< Caller*ID name */
01600       AST_STRING_FIELD(fullcontact);   /*!< The Contact: that the UA registers with us */
01601          /* we only store the part in <brackets> in this field. */
01602       AST_STRING_FIELD(our_contact);   /*!< Our contact header */
01603       AST_STRING_FIELD(rpid);    /*!< Our RPID header */
01604       AST_STRING_FIELD(rpid_from);  /*!< Our RPID From header */
01605       AST_STRING_FIELD(url);     /*!< URL to be sent with next message to peer */
01606       AST_STRING_FIELD(parkinglot);    /*!< Parkinglot */
01607    );
01608    char via[128];                          /*!< Via: header */
01609    struct sip_socket socket;     /*!< The socket used for this dialog */
01610    unsigned int ocseq;        /*!< Current outgoing seqno */
01611    unsigned int icseq;        /*!< Current incoming seqno */
01612    ast_group_t callgroup;        /*!< Call group */
01613    ast_group_t pickupgroup;      /*!< Pickup group */
01614    int lastinvite;            /*!< Last Cseq of invite */
01615    struct ast_flags flags[2];    /*!< SIP_ flags */
01616 
01617    /* boolean or small integers that don't belong in flags */
01618    char do_history;        /*!< Set if we want to record history */
01619    char alreadygone;       /*!< already destroyed by our peer */
01620    char needdestroy;       /*!< need to be destroyed by the monitor thread */
01621    char outgoing_call;        /*!< this is an outgoing call */
01622    char answered_elsewhere;      /*!< This call is cancelled due to answer on another channel */
01623    char novideo;           /*!< Didn't get video in invite, don't offer */
01624    char notext;            /*!< Text not supported  (?) */
01625 
01626    int timer_t1;           /*!< SIP timer T1, ms rtt */
01627    int timer_b;                            /*!< SIP timer B, ms */
01628    unsigned int sipoptions;      /*!< Supported SIP options on the other end */
01629    unsigned int reqsipoptions;      /*!< Required SIP options on the other end */
01630    struct ast_codec_pref prefs;     /*!< codec prefs */
01631    int capability;            /*!< Special capability (codec) */
01632    int jointcapability;       /*!< Supported capability at both ends (codecs) */
01633    int peercapability;        /*!< Supported peer capability */
01634    int prefcodec;          /*!< Preferred codec (outbound only) */
01635    int noncodeccapability;       /*!< DTMF RFC2833 telephony-event */
01636    int jointnoncodeccapability;            /*!< Joint Non codec capability */
01637    int redircodecs;        /*!< Redirect codecs */
01638    int maxcallbitrate;        /*!< Maximum Call Bitrate for Video Calls */ 
01639    int t38_maxdatagram;       /*!< T.38 FaxMaxDatagram override */
01640    struct sip_proxy *outboundproxy; /*!< Outbound proxy for this dialog. Use ref_proxy to set this instead of setting it directly*/
01641    struct t38properties t38;     /*!< T38 settings */
01642    struct sockaddr_in udptlredirip; /*!< Where our T.38 UDPTL should be going if not to us */
01643    struct ast_udptl *udptl;      /*!< T.38 UDPTL session */
01644    int callingpres;        /*!< Calling presentation */
01645    int authtries;          /*!< Times we've tried to authenticate */
01646    int expiry;          /*!< How long we take to expire */
01647    long branch;            /*!< The branch identifier of this session */
01648    long invite_branch;        /*!< The branch used when we sent the initial INVITE */
01649    char tag[11];           /*!< Our tag for this session */
01650    int sessionid;          /*!< SDP Session ID */
01651    int sessionversion;        /*!< SDP Session Version */
01652    int64_t sessionversion_remote;      /*!< Remote UA's SDP Session Version */
01653    int session_modify;        /*!< Session modification request true/false  */
01654    unsigned int portinuri:1;     /*!< Non zero if a port has been specified, will also disable srv lookups */
01655    struct sockaddr_in sa;        /*!< Our peer */
01656    struct sockaddr_in redirip;      /*!< Where our RTP should be going if not to us */
01657    struct sockaddr_in vredirip;     /*!< Where our Video RTP should be going if not to us */
01658    struct sockaddr_in tredirip;     /*!< Where our Text RTP should be going if not to us */
01659    time_t lastrtprx;       /*!< Last RTP received */
01660    time_t lastrtptx;       /*!< Last RTP sent */
01661    int rtptimeout;            /*!< RTP timeout time */
01662    struct sockaddr_in recv;      /*!< Received as */
01663    struct sockaddr_in ourip;     /*!< Our IP (as seen from the outside) */
01664    struct ast_channel *owner;    /*!< Who owns us (if we have an owner) */
01665    struct sip_route *route;      /*!< Head of linked list of routing steps (fm Record-Route) */
01666    int route_persistant;         /*!< Is this the "real" route? */
01667    struct ast_variable *notify_headers;    /*!< Custom notify type */
01668    struct sip_auth *peerauth;    /*!< Realm authentication */
01669    int noncecount;            /*!< Nonce-count */
01670    unsigned int stalenonce:1; /*!< Marks the current nonce as responded too */
01671    char lastmsg[256];         /*!< Last Message sent/received */
01672    int amaflags;           /*!< AMA Flags */
01673    int pendinginvite;         /*!< Any pending INVITE or state NOTIFY (in subscribe pvt's) ? (seqno of this) */
01674    int glareinvite;        /*!< A invite received while a pending invite is already present is stored here.  Its seqno is the
01675                   value. Since this glare invite's seqno is not the same as the pending invite's, it must be 
01676                   held in order to properly process acknowledgements for our 491 response. */
01677    struct sip_request initreq;      /*!< Latest request that opened a new transaction
01678                      within this dialog.
01679                      NOT the request that opened the dialog */
01680 
01681    int initid;          /*!< Auto-congest ID if appropriate (scheduler) */
01682    int waitid;          /*!< Wait ID for scheduler after 491 or other delays */
01683    int autokillid;            /*!< Auto-kill ID (scheduler) */
01684    int t38id;                              /*!< T.38 Response ID */
01685    enum transfermodes allowtransfer;   /*!< REFER: restriction scheme */
01686    struct sip_refer *refer;      /*!< REFER: SIP transfer data structure */
01687    enum subscriptiontype subscribed;   /*!< SUBSCRIBE: Is this dialog a subscription?  */
01688    int stateid;            /*!< SUBSCRIBE: ID for devicestate subscriptions */
01689    int laststate;          /*!< SUBSCRIBE: Last known extension state */
01690    int dialogver;          /*!< SUBSCRIBE: Version for subscription dialog-info */
01691 
01692    struct ast_dsp *dsp;       /*!< A DSP for inband DTMF and fax CNG tone detection */
01693 
01694    struct sip_peer *relatedpeer;    /*!< If this dialog is related to a peer, which one 
01695                      Used in peerpoke, mwi subscriptions */
01696    struct sip_registry *registry;      /*!< If this is a REGISTER dialog, to which registry */
01697    struct ast_rtp *rtp;       /*!< RTP Session */
01698    struct ast_rtp *vrtp;         /*!< Video RTP session */
01699    struct ast_rtp *trtp;         /*!< Text RTP session */
01700    struct sip_pkt *packets;      /*!< Packets scheduled for re-transmission */
01701    struct sip_history_head *history;   /*!< History of this SIP dialog */
01702    size_t history_entries;       /*!< Number of entires in the history */
01703    struct ast_variable *chanvars;      /*!< Channel variables to set for inbound call */
01704    AST_LIST_HEAD_NOLOCK(request_queue, sip_request) request_queue; /*!< Requests that arrived but could not be processed immediately */
01705    int request_queue_sched_id;      /*!< Scheduler ID of any scheduled action to process queued requests */
01706    int provisional_keepalive_sched_id; /*!< Scheduler ID for provisional responses that need to be sent out to avoid cancellation */
01707    const char *last_provisional;   /*!< The last successfully transmitted provisonal response message */
01708    struct sip_invite_param *options;   /*!< Options for INVITE */
01709    int autoframing;        /*!< The number of Asters we group in a Pyroflax
01710                      before strolling to the Grokyzpå
01711                      (A bit unsure of this, please correct if
01712                      you know more) */
01713    struct sip_st_dlg *stimer;    /*!< SIP Session-Timers */              
01714   
01715    int red;             /*!< T.140 RTP Redundancy */
01716    int hangupcause;        /*!< Storage of hangupcause copied from our owner before we disconnect from the AST channel (only used at hangup) */
01717 
01718    struct sip_subscription_mwi *mwi;       /*!< If this is a subscription MWI dialog, to which subscription */
01719    /*! When receiving an SDP offer, it is important to take note of what media types were offered.
01720     * By doing this, even if we don't want to answer a particular media stream with something meaningful, we can
01721     * still put an m= line in our answer with the port set to 0.
01722     *
01723     * The reason for the length being 4 is that in this branch of Asterisk, the only media types supported are 
01724     * image, audio, text, and video. Therefore we need to keep track of which types of media were offered.
01725     *
01726     * Note that if we wanted to be 100% correct, we would keep a list of all media streams offered. That way we could respond
01727     * even to unknown media types, and we could respond to multiple streams of the same type. Such large-scale changes
01728     * are not a good idea for released branches, though, so we're compromising by just making sure that for the common cases:
01729     * audio and video, audio and T.38, and audio and text, we give the appropriate response to both media streams.
01730     *
01731     * The large-scale changes would be a good idea for implementing during an SDP rewrite.
01732     */
01733    struct offered_media offered_media[4];
01734 }; 
01735 
01736 
01737 /*! \brief
01738  * Here we implement the container for dialogs (sip_pvt), defining
01739  * generic wrapper functions to ease the transition from the current
01740  * implementation (a single linked list) to a different container.
01741  * In addition to a reference to the container, we need functions to lock/unlock
01742  * the container and individual items, and functions to add/remove
01743  * references to the individual items.
01744  */
01745 struct ao2_container *dialogs;
01746 
01747 #define sip_pvt_lock(x) ao2_lock(x)
01748 #define sip_pvt_trylock(x) ao2_trylock(x)
01749 #define sip_pvt_unlock(x) ao2_unlock(x)
01750 
01751 /*! \brief
01752  * when we create or delete references, make sure to use these
01753  * functions so we keep track of the refcounts.
01754  * To simplify the code, we allow a NULL to be passed to dialog_unref().
01755  */
01756 #ifdef REF_DEBUG
01757 #define dialog_ref(arg1,arg2) dialog_ref_debug((arg1),(arg2), __FILE__, __LINE__, __PRETTY_FUNCTION__)
01758 #define dialog_unref(arg1,arg2) dialog_unref_debug((arg1),(arg2), __FILE__, __LINE__, __PRETTY_FUNCTION__)
01759 
01760 static struct sip_pvt *dialog_ref_debug(struct sip_pvt *p, char *tag, char *file, int line, const char *func)
01761 {
01762    if (p)
01763       _ao2_ref_debug(p, 1, tag, file, line, func);
01764    else
01765       ast_log(LOG_ERROR, "Attempt to Ref a null pointer\n");
01766    return p;
01767 }
01768 
01769 static struct sip_pvt *dialog_unref_debug(struct sip_pvt *p, char *tag, char *file, int line, const char *func)
01770 {
01771    if (p)
01772       _ao2_ref_debug(p, -1, tag, file, line, func);
01773    return NULL;
01774 }
01775 #else
01776 static struct sip_pvt *dialog_ref(struct sip_pvt *p, char *tag)
01777 {
01778    if (p)
01779       ao2_ref(p, 1);
01780    else
01781       ast_log(LOG_ERROR, "Attempt to Ref a null pointer\n");
01782    return p;
01783 }
01784 
01785 static struct sip_pvt *dialog_unref(struct sip_pvt *p, char *tag)
01786 {
01787    if (p)
01788       ao2_ref(p, -1);
01789    return NULL;
01790 }
01791 #endif
01792 
01793 /*! \brief sip packet - raw format for outbound packets that are sent or scheduled for transmission
01794  * Packets are linked in a list, whose head is in the struct sip_pvt they belong to.
01795  * Each packet holds a reference to the parent struct sip_pvt.
01796  * This structure is allocated in __sip_reliable_xmit() and only for packets that
01797  * require retransmissions.
01798  */
01799 struct sip_pkt {
01800    struct sip_pkt *next;         /*!< Next packet in linked list */
01801    int retrans;            /*!< Retransmission number */
01802    int method;          /*!< SIP method for this packet */
01803    int seqno;           /*!< Sequence number */
01804    char is_resp;           /*!< 1 if this is a response packet (e.g. 200 OK), 0 if it is a request */
01805    char is_fatal;          /*!< non-zero if there is a fatal error */
01806    int response_code;      /*!< If this is a response, the response code */
01807    struct sip_pvt *owner;        /*!< Owner AST call */
01808    int retransid;          /*!< Retransmission ID */
01809    int timer_a;            /*!< SIP timer A, retransmission timer */
01810    int timer_t1;           /*!< SIP Timer T1, estimated RTT or 500 ms */
01811    int packetlen;          /*!< Length of packet */
01812    struct ast_str *data;
01813 }; 
01814 
01815 /*!
01816  * \brief A peer's mailbox
01817  *
01818  * We could use STRINGFIELDS here, but for only two strings, it seems like
01819  * too much effort ...
01820  */
01821 struct sip_mailbox {
01822    char *mailbox;
01823    char *context;
01824    unsigned int delme:1;
01825    /*! Associated MWI subscription */
01826    struct ast_event_sub *event_sub;
01827    AST_LIST_ENTRY(sip_mailbox) entry;
01828 };
01829 
01830 enum sip_peer_type {
01831    SIP_TYPE_PEER = (1 << 0),
01832    SIP_TYPE_USER = (1 << 1),
01833 };
01834 
01835 /*! \brief Structure for SIP peer data, we place calls to peers if registered  or fixed IP address (host) 
01836 */
01837 /* XXX field 'name' must be first otherwise sip_addrcmp() will fail, as will astobj2 hashing of the structure */
01838 struct sip_peer {
01839    char name[80];             /*!< the unique name of this object */
01840    AST_DECLARE_STRING_FIELDS(
01841       AST_STRING_FIELD(secret);     /*!< Password for inbound auth */
01842       AST_STRING_FIELD(md5secret);     /*!< Password in MD5 */
01843       AST_STRING_FIELD(remotesecret);     /*!< Remote secret (trunks, remote devices) */
01844       AST_STRING_FIELD(context);    /*!< Default context for incoming calls */
01845       AST_STRING_FIELD(subscribecontext); /*!< Default context for subscriptions */
01846       AST_STRING_FIELD(username);      /*!< Temporary username until registration */ 
01847       AST_STRING_FIELD(accountcode);      /*!< Account code */
01848       AST_STRING_FIELD(tohost);     /*!< If not dynamic, IP address */
01849       AST_STRING_FIELD(regexten);      /*!< Extension to register (if regcontext is used) */
01850       AST_STRING_FIELD(fromuser);      /*!< From: user when calling this peer */
01851       AST_STRING_FIELD(fromdomain);    /*!< From: domain when calling this peer */
01852       AST_STRING_FIELD(fullcontact);      /*!< Contact registered with us (not in sip.conf) */
01853       AST_STRING_FIELD(cid_num);    /*!< Caller ID num */
01854       AST_STRING_FIELD(cid_name);      /*!< Caller ID name */
01855       AST_STRING_FIELD(vmexten);       /*!< Dialplan extension for MWI notify message*/
01856       AST_STRING_FIELD(language);      /*!<  Default language for prompts */
01857       AST_STRING_FIELD(mohinterpret);     /*!<  Music on Hold class */
01858       AST_STRING_FIELD(mohsuggest);    /*!<  Music on Hold class */
01859       AST_STRING_FIELD(parkinglot);    /*!<  Parkinglot */
01860       AST_STRING_FIELD(useragent);     /*!<  User agent in SIP request (saved from registration) */
01861       );
01862    struct sip_socket socket;  /*!< Socket used for this peer */
01863    enum sip_transport default_outbound_transport;    /*!< Peer Registration may change the default outbound transport.
01864                                     If register expires, default should be reset. to this value */
01865    unsigned int transports:3;      /*!< Transports (enum sip_transport) that are acceptable for this peer */
01866    struct sip_auth *auth;     /*!< Realm authentication list */
01867    int amaflags;        /*!< AMA Flags (for billing) */
01868    int callingpres;     /*!< Calling id presentation */
01869    int inUse;        /*!< Number of calls in use */
01870    int inRinging;       /*!< Number of calls ringing */
01871    int onHold;                     /*!< Peer has someone on hold */
01872    int call_limit;         /*!< Limit of concurrent calls */
01873    int t38_maxdatagram;    /*!< T.38 FaxMaxDatagram override */
01874    int busy_level;         /*!< Level of active channels where we signal busy */
01875    enum transfermodes allowtransfer;   /*! SIP Refer restriction scheme */
01876    struct ast_codec_pref prefs;  /*!<  codec prefs */
01877    int lastmsgssent;
01878    unsigned int sipoptions;   /*!<  Supported SIP options */
01879    struct ast_flags flags[2]; /*!<  SIP_ flags */
01880 
01881    /*! Mailboxes that this peer cares about */
01882    AST_LIST_HEAD_NOLOCK(, sip_mailbox) mailboxes;
01883 
01884    /* things that don't belong in flags */
01885    char is_realtime;    /*!< this is a 'realtime' peer */
01886    char rt_fromcontact;    /*!< copy fromcontact from realtime */
01887    char host_dynamic;      /*!< Dynamic Peers register with Asterisk */
01888    char selfdestruct;      /*!< Automatic peers need to destruct themselves */
01889    char the_mark;       /*!< moved out of ASTOBJ into struct proper; That which bears the_mark should be deleted! */
01890 
01891    int expire;       /*!<  When to expire this peer registration */
01892    int capability;         /*!<  Codec capability */
01893    int rtptimeout;         /*!<  RTP timeout */
01894    int rtpholdtimeout;     /*!<  RTP Hold Timeout */
01895    int rtpkeepalive;    /*!<  Send RTP packets for keepalive */
01896    ast_group_t callgroup;     /*!<  Call group */
01897    ast_group_t pickupgroup;   /*!<  Pickup group */
01898    struct sip_proxy *outboundproxy; /*!< Outbound proxy for this peer */
01899    struct ast_dnsmgr_entry *dnsmgr;/*!<  DNS refresh manager for peer */
01900    struct sockaddr_in addr;   /*!<  IP address of peer */
01901    int maxcallbitrate;     /*!< Maximum Bitrate for a video call */
01902    unsigned int portinuri:1;  /*!< Whether the port should be included in the URI */
01903 
01904    /* Qualification */
01905    struct sip_pvt *call;      /*!<  Call pointer */
01906    int pokeexpire;         /*!<  When to expire poke (qualify= checking) */
01907    int lastms;       /*!<  How long last response took (in ms), or -1 for no response */
01908    int maxms;        /*!<  Max ms we will accept for the host to be up, 0 to not monitor */
01909    int qualifyfreq;     /*!<  Qualification: How often to check for the host to be up */
01910    struct timeval ps;      /*!<  Time for sending SIP OPTION in sip_pke_peer() */
01911    struct sockaddr_in defaddr;   /*!<  Default IP address, used until registration */
01912    struct ast_ha *ha;      /*!<  Access control list */
01913    struct ast_ha *contactha;       /*!<  Restrict what IPs are allowed in the Contact header (for registration) */
01914    struct ast_variable *chanvars;   /*!<  Variables to set for channel created by user */
01915    struct sip_pvt *mwipvt;    /*!<  Subscription for MWI */
01916    int autoframing;
01917    struct sip_st_cfg stimer;  /*!<  SIP Session-Timers */
01918    int timer_t1;        /*!<  The maximum T1 value for the peer */
01919    int timer_b;         /*!<  The maximum timer B (transaction timeouts) */
01920    int deprecated_username; /*!< If it's a realtime peer, are they using the deprecated "username" instead of "defaultuser" */
01921    
01922    /*XXX Seems like we suddenly have two flags with the same content. Why? To be continued... */
01923    enum sip_peer_type type; /*!< Distinguish between "user" and "peer" types. This is used solely for CLI and manager commands */
01924 };
01925 
01926 
01927 /*! 
01928  * \brief Registrations with other SIP proxies
01929  *
01930  * Created by sip_register(), the entry is linked in the 'regl' list,
01931  * and never deleted (other than at 'sip reload' or module unload times).
01932  * The entry always has a pending timeout, either waiting for an ACK to
01933  * the REGISTER message (in which case we have to retransmit the request),
01934  * or waiting for the next REGISTER message to be sent (either the initial one,
01935  * or once the previously completed registration one expires).
01936  * The registration can be in one of many states, though at the moment
01937  * the handling is a bit mixed.
01938  */
01939 struct sip_registry {
01940    ASTOBJ_COMPONENTS_FULL(struct sip_registry,1,1);
01941    AST_DECLARE_STRING_FIELDS(
01942       AST_STRING_FIELD(callid);  /*!< Global Call-ID */
01943       AST_STRING_FIELD(realm);   /*!< Authorization realm */
01944       AST_STRING_FIELD(nonce);   /*!< Authorization nonce */
01945       AST_STRING_FIELD(opaque);  /*!< Opaque nonsense */
01946       AST_STRING_FIELD(qop);     /*!< Quality of Protection, since SIP wasn't complicated enough yet. */
01947       AST_STRING_FIELD(domain);  /*!< Authorization domain */
01948       AST_STRING_FIELD(username);   /*!< Who we are registering as */
01949       AST_STRING_FIELD(authuser);   /*!< Who we *authenticate* as */
01950       AST_STRING_FIELD(hostname);   /*!< Domain or host we register to */
01951       AST_STRING_FIELD(secret);  /*!< Password in clear text */   
01952       AST_STRING_FIELD(md5secret);  /*!< Password in md5 */
01953       AST_STRING_FIELD(callback);   /*!< Contact extension */
01954       AST_STRING_FIELD(random);
01955       AST_STRING_FIELD(peername);   /*!< Peer registering to */
01956    );
01957    enum sip_transport transport; /*!< Transport for this registration UDP, TCP or TLS */
01958    int portno;       /*!<  Optional port override */
01959    int expire;       /*!< Sched ID of expiration */
01960    int configured_expiry;     /*!< Configured value to use for the Expires header */
01961    int expiry;       /*!< Negotiated value used for the Expires header */
01962    int regattempts;     /*!< Number of attempts (since the last success) */
01963    int timeout;         /*!< sched id of sip_reg_timeout */
01964    int refresh;         /*!< How often to refresh */
01965    struct sip_pvt *call;      /*!< create a sip_pvt structure for each outbound "registration dialog" in progress */
01966    enum sipregistrystate regstate;  /*!< Registration state (see above) */
01967    struct timeval regtime;    /*!< Last successful registration time */
01968    int callid_valid;    /*!< 0 means we haven't chosen callid for this registry yet. */
01969    unsigned int ocseq;     /*!< Sequence number we got to for REGISTERs for this registry */
01970    struct ast_dnsmgr_entry *dnsmgr; /*!<  DNS refresh manager for register */
01971    struct sockaddr_in us;     /*!< Who the server thinks we are */
01972    int noncecount;         /*!< Nonce-count */
01973    char lastmsg[256];      /*!< Last Message sent/received */
01974 };
01975 
01976 enum sip_tcptls_alert {
01977    /*! \brief There is new data to be sent out */
01978    TCPTLS_ALERT_DATA,
01979    /*! \brief A request to stop the tcp_handler thread */
01980    TCPTLS_ALERT_STOP,
01981 };
01982 
01983 struct tcptls_packet {
01984    AST_LIST_ENTRY(tcptls_packet) entry;
01985    struct ast_str *data;
01986    size_t len;
01987 };
01988 /*! \brief Definition of a thread that handles a socket */
01989 struct sip_threadinfo {
01990    int stop;
01991    int alert_pipe[2]; /*! Used to alert tcptls thread when packet is ready to be written */
01992    pthread_t threadid;
01993    struct ast_tcptls_session_instance *tcptls_session;
01994    enum sip_transport type;   /*!< We keep a copy of the type here so we can display it in the connection list */
01995    AST_LIST_HEAD_NOLOCK(, tcptls_packet) packet_q;
01996 };
01997 
01998 /*! \brief Definition of an MWI subscription to another server */
01999 struct sip_subscription_mwi {
02000    ASTOBJ_COMPONENTS_FULL(struct sip_subscription_mwi,1,1);
02001    AST_DECLARE_STRING_FIELDS(
02002       AST_STRING_FIELD(username);     /*!< Who we are sending the subscription as */
02003       AST_STRING_FIELD(authuser);     /*!< Who we *authenticate* as */
02004       AST_STRING_FIELD(hostname);     /*!< Domain or host we subscribe to */
02005       AST_STRING_FIELD(secret);       /*!< Password in clear text */
02006       AST_STRING_FIELD(mailbox);      /*!< Mailbox store to put MWI into */
02007       );
02008    enum sip_transport transport;    /*!< Transport to use */
02009    int portno;                      /*!< Optional port override */
02010    int resub;                       /*!< Sched ID of resubscription */
02011    unsigned int subscribed:1;       /*!< Whether we are currently subscribed or not */
02012    struct sip_pvt *call;            /*!< Outbound subscription dialog */
02013    struct ast_dnsmgr_entry *dnsmgr; /*!< DNS refresh manager for subscription */
02014    struct sockaddr_in us;           /*!< Who the server thinks we are */
02015 };
02016 
02017 /* --- Hash tables of various objects --------*/
02018 #ifdef LOW_MEMORY
02019 static const int HASH_PEER_SIZE = 17;
02020 static const int HASH_DIALOG_SIZE = 17;
02021 #else
02022 static const int HASH_PEER_SIZE = 563; /*!< Size of peer hash table, prime number preferred! */
02023 static const int HASH_DIALOG_SIZE = 563;
02024 #endif
02025 static struct ao2_container *threadt;
02026 
02027 /*! \brief  The peer list: Users, Peers and Friends */
02028 struct ao2_container *peers;
02029 struct ao2_container *peers_by_ip;
02030 
02031 /*! \brief  The register list: Other SIP proxies we register with and place calls to */
02032 static struct ast_register_list {
02033    ASTOBJ_CONTAINER_COMPONENTS(struct sip_registry);
02034    int recheck;
02035 } regl;
02036 
02037 /*! \brief  The MWI subscription list */
02038 static struct ast_subscription_mwi_list {
02039    ASTOBJ_CONTAINER_COMPONENTS(struct sip_subscription_mwi);
02040 } submwil;
02041 
02042 /*! \brief
02043  * \note The only member of the peer used here is the name field
02044  */
02045 static int peer_hash_cb(const void *obj, const int flags)
02046 {
02047    const struct sip_peer *peer = obj;
02048 
02049    return ast_str_case_hash(peer->name);
02050 }
02051 
02052 /*!
02053  * \note The only member of the peer used here is the name field
02054  */
02055 static int peer_cmp_cb(void *obj, void *arg, int flags)
02056 {
02057    struct sip_peer *peer = obj, *peer2 = arg;
02058 
02059    return !strcasecmp(peer->name, peer2->name) ? CMP_MATCH | CMP_STOP : 0;
02060 }
02061 
02062 /*!
02063  * \note the peer's ip address field is used to create key.
02064  */
02065 static int peer_iphash_cb(const void *obj, const int flags)
02066 {
02067    const struct sip_peer *peer = obj;
02068    int ret1 = peer->addr.sin_addr.s_addr;
02069    if (ret1 < 0)
02070       ret1 = -ret1;
02071 
02072    return ret1;
02073 }
02074 
02075 /*!
02076  * Match Peers by IP and Port number.
02077  *
02078  * This function has two modes.
02079  *  - If the peer arg does not have INSECURE_PORT set, then we will only return
02080  *    a match for a peer that matches both the IP and port.
02081  *  - If the peer arg does have the INSECURE_PORT flag set, then we will only
02082  *    return a match for a peer that matches the IP and has insecure=port
02083  *    in its configuration.
02084  *
02085  * This callback will be used twice when doing peer matching.  There is a first
02086  * pass for full IP+port matching, and a second pass in case there is a match
02087  * that meets the insecure=port criteria.
02088  *
02089  * \note Connections coming in over TCP or TLS should never be matched by port.
02090  *
02091  * \note the peer's addr struct provides to fields combined to make a key: the sin_addr.s_addr and sin_port fields.
02092  */
02093 static int peer_ipcmp_cb(void *obj, void *arg, int flags)
02094 {
02095    struct sip_peer *peer = obj, *peer2 = arg;
02096 
02097    if (peer->addr.sin_addr.s_addr != peer2->addr.sin_addr.s_addr) {
02098       /* IP doesn't match */
02099       return 0;
02100    }
02101 
02102    /* We matched the IP, check to see if we need to match by port as well. */
02103    if ((peer->transports & peer2->transports) & (SIP_TRANSPORT_TLS | SIP_TRANSPORT_TCP)) {
02104       /* peer matching on port is not possible with TCP/TLS */
02105       return CMP_MATCH | CMP_STOP;
02106    } else if (ast_test_flag(&peer2->flags[0], SIP_INSECURE_PORT)) {
02107       /* We are allowing match without port for peers configured that
02108        * way in this pass through the peers. */
02109       return ast_test_flag(&peer->flags[0], SIP_INSECURE_PORT) ?
02110             (CMP_MATCH | CMP_STOP) : 0;
02111    }
02112 
02113    /* Now only return a match if the port matches, as well. */
02114    return peer->addr.sin_port == peer2->addr.sin_port ? (CMP_MATCH | CMP_STOP) : 0;
02115 }
02116 
02117 
02118 static int threadt_hash_cb(const void *obj, const int flags)
02119 {
02120    const struct sip_threadinfo *th = obj;
02121 
02122    return (int) th->tcptls_session->remote_address.sin_addr.s_addr;
02123 }
02124 
02125 static int threadt_cmp_cb(void *obj, void *arg, int flags)
02126 {
02127    struct sip_threadinfo *th = obj, *th2 = arg;
02128 
02129    return (th->tcptls_session == th2->tcptls_session) ? CMP_MATCH | CMP_STOP : 0;
02130 }
02131 
02132 /*!
02133  * \note The only member of the dialog used here callid string
02134  */
02135 static int dialog_hash_cb(const void *obj, const int flags)
02136 {
02137    const struct sip_pvt *pvt = obj;
02138 
02139    return ast_str_case_hash(pvt->callid);
02140 }
02141 
02142 /*!
02143  * \note The only member of the dialog used here callid string
02144  */
02145 static int dialog_cmp_cb(void *obj, void *arg, int flags)
02146 {
02147    struct sip_pvt *pvt = obj, *pvt2 = arg;
02148    
02149    return !strcasecmp(pvt->callid, pvt2->callid) ? CMP_MATCH | CMP_STOP : 0;
02150 }
02151 
02152 static int temp_pvt_init(void *);
02153 static void temp_pvt_cleanup(void *);
02154 
02155 /*! \brief A per-thread temporary pvt structure */
02156 AST_THREADSTORAGE_CUSTOM(ts_temp_pvt, temp_pvt_init, temp_pvt_cleanup);
02157 
02158 #ifdef LOW_MEMORY
02159 static void ts_ast_rtp_destroy(void *);
02160 
02161 AST_THREADSTORAGE_CUSTOM(ts_audio_rtp, NULL, ts_ast_rtp_destroy);
02162 AST_THREADSTORAGE_CUSTOM(ts_video_rtp, NULL, ts_ast_rtp_destroy);
02163 AST_THREADSTORAGE_CUSTOM(ts_text_rtp, NULL, ts_ast_rtp_destroy);
02164 #endif
02165 
02166 /*! \brief Authentication list for realm authentication 
02167  * \todo Move the sip_auth list to AST_LIST */
02168 static struct sip_auth *authl = NULL;
02169 
02170 
02171 /* --- Sockets and networking --------------*/
02172 
02173 /*! \brief Main socket for UDP SIP communication.
02174  *
02175  * sipsock is shared between the SIP manager thread (which handles reload
02176  * requests), the udp io handler (sipsock_read()) and the user routines that
02177  * issue udp writes (using __sip_xmit()).
02178  * The socket is -1 only when opening fails (this is a permanent condition),
02179  * or when we are handling a reload() that changes its address (this is
02180  * a transient situation during which we might have a harmless race, see
02181  * below). Because the conditions for the race to be possible are extremely
02182  * rare, we don't want to pay the cost of locking on every I/O.
02183  * Rather, we remember that when the race may occur, communication is
02184  * bound to fail anyways, so we just live with this event and let
02185  * the protocol handle this above us.
02186  */
02187 static int sipsock  = -1;
02188 
02189 static struct sockaddr_in bindaddr; /*!< UDP: The address we bind to */
02190 
02191 /*! \brief our (internal) default address/port to put in SIP/SDP messages
02192  *  internip is initialized picking a suitable address from one of the
02193  * interfaces, and the same port number we bind to. It is used as the
02194  * default address/port in SIP messages, and as the default address
02195  * (but not port) in SDP messages.
02196  */
02197 static struct sockaddr_in internip;
02198 
02199 /*! \brief our external IP address/port for SIP sessions.
02200  * externip.sin_addr is only set when we know we might be behind
02201  * a NAT, and this is done using a variety of (mutually exclusive)
02202  * ways from the config file:
02203  *
02204  * + with "externip = host[:port]" we specify the address/port explicitly.
02205  *   The address is looked up only once when (re)loading the config file;
02206  * 
02207  * + with "externhost = host[:port]" we do a similar thing, but the
02208  *   hostname is stored in externhost, and the hostname->IP mapping
02209  *   is refreshed every 'externrefresh' seconds;
02210  * 
02211  * + with "stunaddr = host[:port]" we run queries every externrefresh seconds
02212  *   to the specified server, and store the result in externip.
02213  *
02214  * Other variables (externhost, externexpire, externrefresh) are used
02215  * to support the above functions.
02216  */
02217 static struct sockaddr_in externip;    /*!< External IP address if we are behind NAT */
02218 
02219 static char externhost[MAXHOSTNAMELEN];      /*!< External host name */
02220 static time_t externexpire;         /*!< Expiration counter for re-resolving external host name in dynamic DNS */
02221 static int externrefresh = 10;
02222 static struct sockaddr_in stunaddr;    /*!< stun server address */
02223 
02224 /*! \brief  List of local networks
02225  * We store "localnet" addresses from the config file into an access list,
02226  * marked as 'DENY', so the call to ast_apply_ha() will return
02227  * AST_SENSE_DENY for 'local' addresses, and AST_SENSE_ALLOW for 'non local'
02228  * (i.e. presumably public) addresses.
02229  */
02230 static struct ast_ha *localaddr;    /*!< List of local networks, on the same side of NAT as this Asterisk */
02231 
02232 static int ourport_tcp;          /*!< The port used for TCP connections */
02233 static int ourport_tls;          /*!< The port used for TCP/TLS connections */
02234 static struct sockaddr_in debugaddr;
02235 
02236 static struct ast_config *notify_types = NULL;     /*!< The list of manual NOTIFY types we know how to send */
02237 
02238 /*! some list management macros. */
02239  
02240 #define UNLINK(element, head, prev) do {  \
02241    if (prev)            \
02242       (prev)->next = (element)->next;  \
02243    else              \
02244       (head) = (element)->next;  \
02245    } while (0)
02246 
02247 enum t38_action_flag {
02248    SDP_T38_NONE = 0, /*!< Do not modify T38 information at all */
02249    SDP_T38_INITIATE, /*!< Remote side has requested T38 with us */
02250    SDP_T38_ACCEPT,   /*!< Remote side accepted our T38 request */
02251 };
02252 
02253 /*---------------------------- Forward declarations of functions in chan_sip.c */
02254 /* Note: This is added to help splitting up chan_sip.c into several files
02255    in coming releases. */
02256 
02257 /*--- PBX interface functions */
02258 static struct ast_channel *sip_request_call(const char *type, int format, void *data, int *cause);
02259 static int sip_devicestate(void *data);
02260 static int sip_sendtext(struct ast_channel *ast, const char *text);
02261 static int sip_call(struct ast_channel *ast, char *dest, int timeout);
02262 static int sip_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen);
02263 static int sip_hangup(struct ast_channel *ast);
02264 static int sip_answer(struct ast_channel *ast);
02265 static struct ast_frame *sip_read(struct ast_channel *ast);
02266 static int sip_write(struct ast_channel *ast, struct ast_frame *frame);
02267 static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen);
02268 static int sip_transfer(struct ast_channel *ast, const char *dest);
02269 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
02270 static int sip_senddigit_begin(struct ast_channel *ast, char digit);
02271 static int sip_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration);
02272 static int sip_queryoption(struct ast_channel *chan, int option, void *data, int *datalen);
02273 static const char *sip_get_callid(struct ast_channel *chan);
02274 
02275 static int handle_request_do(struct sip_request *req, struct sockaddr_in *sin);
02276 static int sip_standard_port(enum sip_transport type, int port);
02277 static int sip_prepare_socket(struct sip_pvt *p);
02278 static int sip_parse_host(char *line, int lineno, char **hostname, int *portnum, enum sip_transport *transport);
02279 
02280 /*--- Transmitting responses and requests */
02281 static int sipsock_read(int *id, int fd, short events, void *ignore);
02282 static int __sip_xmit(struct sip_pvt *p, struct ast_str *data, int len);
02283 static int __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, struct ast_str *data, int len, int fatal, int sipmethod);
02284 static int __transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
02285 static int retrans_pkt(const void *data);
02286 static int transmit_response_using_temp(ast_string_field callid, struct sockaddr_in *sin, int useglobal_nat, const int intended_method, const struct sip_request *req, const char *msg);
02287 static int transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req);
02288 static int transmit_response_reliable(struct sip_pvt *p, const char *msg, const struct sip_request *req);
02289 static int transmit_response_with_date(struct sip_pvt *p, const char *msg, const struct sip_request *req);
02290 static int transmit_response_with_sdp(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable, int oldsdp);
02291 static int transmit_response_with_unsupported(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *unsupported);
02292 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);
02293 static int transmit_provisional_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, int with_sdp);
02294 static int transmit_response_with_allow(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
02295 static void transmit_fake_auth_response(struct sip_pvt *p, int sipmethod, struct sip_request *req, enum xmittype reliable);
02296 static int transmit_request(struct sip_pvt *p, int sipmethod, int inc, enum xmittype reliable, int newbranch);
02297 static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, int seqno, enum xmittype reliable, int newbranch);
02298 static int transmit_invite(struct sip_pvt *p, int sipmethod, int sdp, int init);
02299 static int transmit_reinvite_with_sdp(struct sip_pvt *p, int t38version, int oldsdp);
02300 static int transmit_info_with_digit(struct sip_pvt *p, const char digit, unsigned int duration);
02301 static int transmit_info_with_vidupdate(struct sip_pvt *p);
02302 static int transmit_message_with_text(struct sip_pvt *p, const char *text);
02303 static int transmit_refer(struct sip_pvt *p, const char *dest);
02304 static int transmit_notify_with_mwi(struct sip_pvt *p, int newmsgs, int oldmsgs, const char *vmexten);
02305 static int transmit_notify_with_sipfrag(struct sip_pvt *p, int cseq, char *message, int terminate);
02306 static int transmit_notify_custom(struct sip_pvt *p, struct ast_variable *vars);
02307 static int transmit_register(struct sip_registry *r, int sipmethod, const char *auth, const char *authheader);
02308 static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno);
02309 static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno);
02310 static void copy_request(struct sip_request *dst, const struct sip_request *src);
02311 static void receive_message(struct sip_pvt *p, struct sip_request *req);
02312 static void parse_moved_contact(struct sip_pvt *p, struct sip_request *req);
02313 static int sip_send_mwi_to_peer(struct sip_peer *peer, const struct ast_event *event, int cache_only);
02314 
02315 /*--- Dialog management */
02316 static struct sip_pvt *sip_alloc(ast_string_field callid, struct sockaddr_in *sin,
02317              int useglobal_nat, const int intended_method, struct sip_request *req);
02318 static int __sip_autodestruct(const void *data);
02319 static void sip_scheddestroy(struct sip_pvt *p, int ms);
02320 static int sip_cancel_destroy(struct sip_pvt *p);
02321 static struct sip_pvt *sip_destroy(struct sip_pvt *p);
02322 static void *dialog_unlink_all(struct sip_pvt *dialog, int lockowner, int lockdialoglist);
02323 static void *registry_unref(struct sip_registry *reg, char *tag);
02324 static void __sip_destroy(struct sip_pvt *p, int lockowner, int lockdialoglist);
02325 static int __sip_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod);
02326 static void __sip_pretend_ack(struct sip_pvt *p);
02327 static int __sip_semi_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod);
02328 static int auto_congest(const void *arg);
02329 static int update_call_counter(struct sip_pvt *fup, int event);
02330 static int hangup_sip2cause(int cause);
02331 static const char *hangup_cause2sip(int cause);
02332 static struct sip_pvt *find_call(struct sip_request *req, struct sockaddr_in *sin, const int intended_method);
02333 static void free_old_route(struct sip_route *route);
02334 static void list_route(struct sip_route *route);
02335 static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards);
02336 static enum check_auth_result register_verify(struct sip_pvt *p, struct sockaddr_in *sin,
02337                      struct sip_request *req, char *uri);
02338 static struct sip_pvt *get_sip_pvt_byid_locked(const char *callid, const char *totag, const char *fromtag);
02339 static void check_pendings(struct sip_pvt *p);
02340 static void *sip_park_thread(void *stuff);
02341 static int sip_park(struct ast_channel *chan1, struct ast_channel *chan2, struct sip_request *req, int seqno);
02342 static int sip_sipredirect(struct sip_pvt *p, const char *dest);
02343 
02344 /*--- Codec handling / SDP */
02345 static void try_suggested_sip_codec(struct sip_pvt *p);
02346 static const char *get_sdp_iterate(int* start, struct sip_request *req, const char *name);
02347 static char get_sdp_line(int *start, int stop, struct sip_request *req, const char **value);
02348 static int find_sdp(struct sip_request *req);
02349 static int process_sdp(struct sip_pvt *p, struct sip_request *req, int t38action);
02350 static int process_sdp_o(const char *o, struct sip_pvt *p);
02351 static int process_sdp_c(const char *c, struct ast_hostent *hp);
02352 static int process_sdp_a_sendonly(const char *a, int *sendonly);
02353 static int process_sdp_a_audio(const char *a, struct sip_pvt *p, struct ast_rtp *newaudiortp, int *last_rtpmap_codec);
02354 static int process_sdp_a_video(const char *a, struct sip_pvt *p, struct ast_rtp *newvideortp, int *last_rtpmap_codec);
02355 static int process_sdp_a_text(const char *a, struct sip_pvt *p, struct ast_rtp *newtextrtp, char *red_fmtp, int *red_num_gen, int *red_data_pt, int *last_rtpmap_codec);
02356 static int process_sdp_a_image(const char *a, struct sip_pvt *p);
02357 static void add_codec_to_sdp(const struct sip_pvt *p, int codec,
02358               struct ast_str **m_buf, struct ast_str **a_buf,
02359               int debug, int *min_packet_size);
02360 static void add_noncodec_to_sdp(const struct sip_pvt *p, int format,
02361             struct ast_str **m_buf, struct ast_str **a_buf,
02362             int debug);
02363 static enum sip_result add_sdp(struct sip_request *resp, struct sip_pvt *p, int oldsdp, int add_audio, int add_t38);
02364 static void do_setnat(struct sip_pvt *p, int natflags);
02365 static void stop_media_flows(struct sip_pvt *p);
02366 
02367 /*--- Authentication stuff */
02368 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod, char *digest, int digest_len);
02369 static int build_reply_digest(struct sip_pvt *p, int method, char *digest, int digest_len);
02370 static enum check_auth_result check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
02371                 const char *secret, const char *md5secret, int sipmethod,
02372                 char *uri, enum xmittype reliable, int ignore);
02373 static enum check_auth_result check_user_full(struct sip_pvt *p, struct sip_request *req,
02374                      int sipmethod, char *uri, enum xmittype reliable,
02375                      struct sockaddr_in *sin, struct sip_peer **authpeer);
02376 static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, char *uri, enum xmittype reliable, struct sockaddr_in *sin);
02377 
02378 /*--- Domain handling */
02379 static int check_sip_domain(const char *domain, char *context, size_t len); /* Check if domain is one of our local domains */
02380 static int add_sip_domain(const char *domain, const enum domain_mode mode, const char *context);
02381 static void clear_sip_domains(void);
02382 
02383 /*--- SIP realm authentication */
02384 static struct sip_auth *add_realm_authentication(struct sip_auth *authlist, const char *configuration, int lineno);
02385 static int clear_realm_authentication(struct sip_auth *authlist); /* Clear realm authentication list (at reload) */
02386 static struct sip_auth *find_realm_authentication(struct sip_auth *authlist, const char *realm);
02387 
02388 /*--- Misc functions */
02389 static void check_rtp_timeout(struct sip_pvt *dialog, time_t t);
02390 static int sip_do_reload(enum channelreloadreason reason);
02391 static int reload_config(enum channelreloadreason reason);
02392 static int expire_register(const void *data);
02393 static void *do_monitor(void *data);
02394 static int restart_monitor(void);
02395 static void peer_mailboxes_to_str(struct ast_str **mailbox_str, struct sip_peer *peer);
02396 static struct ast_variable *copy_vars(struct ast_variable *src);
02397 /* static int sip_addrcmp(char *name, struct sockaddr_in *sin);   Support for peer matching */
02398 static int sip_refer_allocate(struct sip_pvt *p);
02399 static void ast_quiet_chan(struct ast_channel *chan);
02400 static int attempt_transfer(struct sip_dual *transferer, struct sip_dual *target);
02401 static int do_magic_pickup(struct ast_channel *channel, const char *extension, const char *context);
02402 
02403 /*!
02404  * \brief generic function for determining if a correct transport is being 
02405  * used to contact a peer
02406  *
02407  * this is done as a macro so that the "tmpl" var can be passed either a 
02408  * sip_request or a sip_peer 
02409  */
02410 #define check_request_transport(peer, tmpl) ({ \
02411    int ret = 0; \
02412    if (peer->socket.type == tmpl->socket.type) \
02413       ; \
02414    else if (!(peer->transports & tmpl->socket.type)) {\
02415       ast_log(LOG_ERROR, \
02416          "'%s' is not a valid transport for '%s'. we only use '%s'! ending call.\n", \
02417          get_transport(tmpl->socket.type), peer->name, get_transport_list(peer->transports) \
02418          ); \
02419       ret = 1; \
02420    } else if (peer->socket.type & SIP_TRANSPORT_TLS) { \
02421       ast_log(LOG_WARNING, \
02422          "peer '%s' HAS NOT USED (OR SWITCHED TO) TLS in favor of '%s' (but this was allowed in sip.conf)!\n", \
02423          peer->name, get_transport(tmpl->socket.type) \
02424       ); \
02425    } else { \
02426       ast_debug(1, \
02427          "peer '%s' has contacted us over %s even though we prefer %s.\n", \
02428          peer->name, get_transport(tmpl->socket.type), get_transport(peer->socket.type) \
02429       ); \
02430    }\
02431    (ret); \
02432 })
02433 
02434 
02435 /*--- Device monitoring and Device/extension state/event handling */
02436 static int cb_extensionstate(char *context, char* exten, int state, void *data);
02437 static int sip_devicestate(void *data);
02438 static int sip_poke_noanswer(const void *data);
02439 static int sip_poke_peer(struct sip_peer *peer, int force);
02440 static void sip_poke_all_peers(void);
02441 static void sip_peer_hold(struct sip_pvt *p, int hold);
02442 static void mwi_event_cb(const struct ast_event *, void *);
02443 
02444 /*--- Applications, functions, CLI and manager command helpers */
02445 static const char *sip_nat_mode(const struct sip_pvt *p);
02446 static char *sip_show_inuse(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02447 static char *transfermode2str(enum transfermodes mode) attribute_const;
02448 static const char *nat2str(int nat) attribute_const;
02449 static int peer_status(struct sip_peer *peer, char *status, int statuslen);
02450 static char *sip_show_sched(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02451 static char * _sip_show_peers(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char *argv[]);
02452 static char *sip_show_peers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02453 static char *sip_show_objects(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02454 static void  print_group(int fd, ast_group_t group, int crlf);
02455 static const char *dtmfmode2str(int mode) attribute_const;
02456 static int str2dtmfmode(const char *str) attribute_unused;
02457 static const char *insecure2str(int mode) attribute_const;
02458 static void cleanup_stale_contexts(char *new, char *old);
02459 static void print_codec_to_cli(int fd, struct ast_codec_pref *pref);
02460 static const char *domain_mode_to_text(const enum domain_mode mode);
02461 static char *sip_show_domains(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02462 static char *_sip_show_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[]);
02463 static char *sip_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02464 static char *_sip_qualify_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[]);
02465 static char *sip_qualify_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02466 static char *sip_show_registry(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02467 static char *sip_unregister(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02468 static char *sip_show_settings(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02469 static char *sip_show_mwi(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02470 static const char *subscription_type2str(enum subscriptiontype subtype) attribute_pure;
02471 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
02472 static char *complete_sip_peer(const char *word, int state, int flags2);
02473 static char *complete_sip_registered_peer(const char *word, int state, int flags2);
02474 static char *complete_sip_show_history(const char *line, const char *word, int pos, int state);
02475 static char *complete_sip_show_peer(const char *line, const char *word, int pos, int state);
02476 static char *complete_sip_unregister(const char *line, const char *word, int pos, int state);
02477 static char *complete_sipnotify(const char *line, const char *word, int pos, int state);
02478 static char *sip_show_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02479 static char *sip_show_channelstats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02480 static char *sip_show_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02481 static char *sip_do_debug_ip(int fd, char *arg);
02482 static char *sip_do_debug_peer(int fd, char *arg);
02483 static char *sip_do_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02484 static char *sip_cli_notify(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02485 static char *sip_set_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02486 static int sip_dtmfmode(struct ast_channel *chan, void *data);
02487 static int sip_addheader(struct ast_channel *chan, void *data);
02488 static int sip_do_reload(enum channelreloadreason reason);
02489 static char *sip_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02490 static int acf_channel_read(struct ast_channel *chan, const char *funcname, char *preparse, char *buf, size_t buflen);
02491 
02492 /*--- Debugging 
02493    Functions for enabling debug per IP or fully, or enabling history logging for
02494    a SIP dialog
02495 */
02496 static void sip_dump_history(struct sip_pvt *dialog); /* Dump history to debuglog at end of dialog, before destroying data */
02497 static inline int sip_debug_test_addr(const struct sockaddr_in *addr);
02498 static inline int sip_debug_test_pvt(struct sip_pvt *p);
02499 
02500 
02501 /*! \brief Append to SIP dialog history 
02502    \return Always returns 0 */
02503 #define append_history(p, event, fmt , args... )   append_history_full(p, "%-15s " fmt, event, ## args)
02504 static void append_history_full(struct sip_pvt *p, const char *fmt, ...);
02505 static void sip_dump_history(struct sip_pvt *dialog);
02506 
02507 /*--- Device object handling */
02508 static struct sip_peer *temp_peer(const char *name);
02509 static struct sip_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime, int devstate_only);
02510 static int update_call_counter(struct sip_pvt *fup, int event);
02511 static void sip_destroy_peer(struct sip_peer *peer);
02512 static void sip_destroy_peer_fn(void *peer);
02513 static void set_peer_defaults(struct sip_peer *peer);
02514 static struct sip_peer *temp_peer(const char *name);
02515 static void register_peer_exten(struct sip_peer *peer, int onoff);
02516 static struct sip_peer *find_peer(const char *peer, struct sockaddr_in *sin, int realtime, int forcenamematch, int devstate_only, int transport);
02517 static int sip_poke_peer_s(const void *data);
02518 static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *p, struct sip_request *req);
02519 static void reg_source_db(struct sip_peer *peer);
02520 static void destroy_association(struct sip_peer *peer);
02521 static void set_insecure_flags(struct ast_flags *flags, const char *value, int lineno);
02522 static int handle_common_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v);
02523 static void set_socket_transport(struct sip_socket *socket, int transport);
02524 
02525 /* Realtime device support */
02526 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, const char *username, const char *fullcontact, const char *useragent, int expirey, int deprecated_username, int lastms);
02527 static void update_peer(struct sip_peer *p, int expire);
02528 static struct ast_variable *get_insecure_variable_from_config(struct ast_config *config);
02529 static const char *get_name_from_variable(struct ast_variable *var, const char *newpeername);
02530 static struct sip_peer *realtime_peer(const char *peername, struct sockaddr_in *sin, int devstate_only);
02531 static char *sip_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02532 
02533 /*--- Internal UA client handling (outbound registrations) */
02534 static void ast_sip_ouraddrfor(struct in_addr *them, struct sockaddr_in *us, struct sip_pvt *p);
02535 static void sip_registry_destroy(struct sip_registry *reg);
02536 static int sip_register(const char *value, int lineno);
02537 static const char *regstate2str(enum sipregistrystate regstate) attribute_const;
02538 static int sip_reregister(const void *data);
02539 static int __sip_do_register(struct sip_registry *r);
02540 static int sip_reg_timeout(const void *data);
02541 static void sip_send_all_registers(void);
02542 static int sip_reinvite_retry(const void *data);
02543 
02544 /*--- Parsing SIP requests and responses */
02545 static void append_date(struct sip_request *req);  /* Append date to SIP packet */
02546 static int determine_firstline_parts(struct sip_request *req);
02547 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
02548 static const char *gettag(const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize);
02549 static int find_sip_method(const char *msg);
02550 static unsigned int parse_sip_options(struct sip_pvt *pvt, const char *supported);
02551 static int parse_request(struct sip_request *req);
02552 static const char *get_header(const struct sip_request *req, const char *name);
02553 static const char *referstatus2str(enum referstatus rstatus) attribute_pure;
02554 static int method_match(enum sipmethod id, const char *name);
02555 static void parse_copy(struct sip_request *dst, const struct sip_request *src);
02556 static char *get_in_brackets(char *tmp);
02557 static const char *find_alias(const char *name, const char *_default);
02558 static const char *__get_header(const struct sip_request *req, const char *name, int *start);
02559 static int lws2sws(char *msgbuf, int len);
02560 static void extract_uri(struct sip_pvt *p, struct sip_request *req);
02561 static char *remove_uri_parameters(char *uri);
02562 static int get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req);
02563 static int get_also_info(struct sip_pvt *p, struct sip_request *oreq);
02564 static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req);
02565 static int set_address_from_contact(struct sip_pvt *pvt);
02566 static void check_via(struct sip_pvt *p, struct sip_request *req);
02567 static char *get_calleridname(const char *input, char *output, size_t outputsize);
02568 static int get_rpid_num(const char *input, char *output, int maxlen);
02569 static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq);
02570 static int get_destination(struct sip_pvt *p, struct sip_request *oreq);
02571 static int get_msg_text(char *buf, int len, struct sip_request *req, int addnewline);
02572 static int transmit_state_notify(struct sip_pvt *p, int state, int full, int timeout);
02573 static struct sip_via *parse_via(const char *header);
02574 static void free_via(struct sip_via *v);
02575 
02576 /*-- TCP connection handling ---*/
02577 static void *_sip_tcp_helper_thread(struct sip_pvt *pvt, struct ast_tcptls_session_instance *tcptls_session);
02578 static void *sip_tcp_worker_fn(void *);
02579 
02580 /*--- Constructing requests and responses */
02581 static void initialize_initreq(struct sip_pvt *p, struct sip_request *req);
02582 static int init_req(struct sip_request *req, int sipmethod, const char *recip);
02583 static void deinit_req(struct sip_request *req);
02584 static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, int seqno, int newbranch);
02585 static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod);
02586 static int init_resp(struct sip_request *resp, const char *msg);
02587 static inline int resp_needs_contact(const char *msg, enum sipmethod method);
02588 static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req);
02589 static const struct sockaddr_in *sip_real_dst(const struct sip_pvt *p);
02590 static void build_via(struct sip_pvt *p);
02591 static int create_addr_from_peer(struct sip_pvt *r, struct sip_peer *peer);
02592 static int create_addr(struct sip_pvt *dialog, const char *opeer, struct sockaddr_in *sin, int newdialog);
02593 static char *generate_random_string(char *buf, size_t size);
02594 static void build_callid_pvt(struct sip_pvt *pvt);
02595 static void build_callid_registry(struct sip_registry *reg, struct in_addr ourip, const char *fromdomain);
02596 static void make_our_tag(char *tagbuf, size_t len);
02597 static int add_header(struct sip_request *req, const char *var, const char *value);
02598 static int add_content(struct sip_request *req, const char *line);
02599 static int finalize_content(struct sip_request *req);
02600 static int add_text(struct sip_request *req, const char *text);
02601 static int add_digit(struct sip_request *req, char digit, unsigned int duration, int mode);
02602 static int add_vidupdate(struct sip_request *req);
02603 static void add_route(struct sip_request *req, struct sip_route *route);
02604 static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field);
02605 static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field);
02606 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field);
02607 static void set_destination(struct sip_pvt *p, char *uri);
02608 static void append_date(struct sip_request *req);
02609 static void build_contact(struct sip_pvt *p);
02610 static void build_rpid(struct sip_pvt *p);
02611 
02612 /*------Request handling functions */
02613 static int handle_incoming(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int *recount, int *nounlock);
02614 static int handle_request_invite(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, struct sockaddr_in *sin, int *recount, char *e, int *nounlock);
02615 static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, int *nounlock);
02616 static int handle_request_bye(struct sip_pvt *p, struct sip_request *req);
02617 static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, char *e);
02618 static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req);
02619 static int handle_request_message(struct sip_pvt *p, struct sip_request *req);
02620 static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e);
02621 static void handle_request_info(struct sip_pvt *p, struct sip_request *req);
02622 static int handle_request_options(struct sip_pvt *p, struct sip_request *req);
02623 static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, struct sockaddr_in *sin, int *nounlock);
02624 static int handle_request_notify(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e);
02625 static int local_attended_transfer(struct sip_pvt *transferer, struct sip_dual *current, struct sip_request *req, int seqno);
02626 
02627 /*------Response handling functions */
02628 static void handle_response_invite(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
02629 static void handle_response_notify(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
02630 static void handle_response_refer(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
02631 static void handle_response_subscribe(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
02632 static int handle_response_register(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
02633 static void handle_response(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
02634 
02635 /*----- RTP interface functions */
02636 static int sip_set_rtp_peer(struct ast_channel *chan, struct ast_rtp *rtp, struct ast_rtp *vrtp,  struct ast_rtp *trtp, int codecs, int nat_active);
02637 static enum ast_rtp_get_result sip_get_rtp_peer(struct ast_channel *chan, struct ast_rtp **rtp);
02638 static enum ast_rtp_get_result sip_get_vrtp_peer(struct ast_channel *chan, struct ast_rtp **rtp);
02639 static enum ast_rtp_get_result sip_get_trtp_peer(struct ast_channel *chan, struct ast_rtp **rtp);
02640 static int sip_get_codec(struct ast_channel *chan);
02641 static struct ast_frame *sip_rtp_read(struct ast_channel *ast, struct sip_pvt *p, int *faxdetect);
02642 
02643 /*------ T38 Support --------- */
02644 static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans);
02645 static struct ast_udptl *sip_get_udptl_peer(struct ast_channel *chan);
02646 static int sip_set_udptl_peer(struct ast_channel *chan, struct ast_udptl *udptl);
02647 static void change_t38_state(struct sip_pvt *p, int state);
02648 
02649 /*------ Session-Timers functions --------- */
02650 static void proc_422_rsp(struct sip_pvt *p, struct sip_request *rsp);
02651 static int  proc_session_timer(const void *vp);
02652 static void stop_session_timer(struct sip_pvt *p);
02653 static void start_session_timer(struct sip_pvt *p);
02654 static void restart_session_timer(struct sip_pvt *p);
02655 static const char *strefresher2str(enum st_refresher r);
02656 static int parse_session_expires(const char *p_hdrval, int *const p_interval, enum st_refresher *const p_ref);
02657 static int parse_minse(const char *p_hdrval, int *const p_interval);
02658 static int st_get_se(struct sip_pvt *, int max);
02659 static enum st_refresher st_get_refresher(struct sip_pvt *);
02660 static enum st_mode st_get_mode(struct sip_pvt *);
02661 static struct sip_st_dlg* sip_st_alloc(struct sip_pvt *const p);
02662 
02663 /*!--- SIP MWI Subscription support */
02664 static int sip_subscribe_mwi(const char *value, int lineno);
02665 static void sip_subscribe_mwi_destroy(struct sip_subscription_mwi *mwi);
02666 static void sip_send_all_mwi_subscriptions(void);
02667 static int sip_subscribe_mwi_do(const void *data);
02668 static int __sip_subscribe_mwi_do(struct sip_subscription_mwi *mwi);
02669 
02670 /*! \brief Definition of this channel for PBX channel registration */
02671 static const struct ast_channel_tech sip_tech = {
02672    .type = "SIP",
02673    .description = "Session Initiation Protocol (SIP)",
02674    .capabilities = AST_FORMAT_AUDIO_MASK, /* all audio formats */
02675    .properties = AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER,
02676    .requester = sip_request_call,         /* called with chan unlocked */
02677    .devicestate = sip_devicestate,        /* called with chan unlocked (not chan-specific) */
02678    .call = sip_call,       /* called with chan locked */
02679    .send_html = sip_sendhtml,
02680    .hangup = sip_hangup,         /* called with chan locked */
02681    .answer = sip_answer,         /* called with chan locked */
02682    .read = sip_read,       /* called with chan locked */
02683    .write = sip_write,        /* called with chan locked */
02684    .write_video = sip_write,     /* called with chan locked */
02685    .write_text = sip_write,
02686    .indicate = sip_indicate,     /* called with chan locked */
02687    .transfer = sip_transfer,     /* called with chan locked */
02688    .fixup = sip_fixup,        /* called with chan locked */
02689    .send_digit_begin = sip_senddigit_begin,  /* called with chan unlocked */
02690    .send_digit_end = sip_senddigit_end,
02691    .bridge = ast_rtp_bridge,        /* XXX chan unlocked ? */
02692    .early_bridge = ast_rtp_early_bridge,
02693    .send_text = sip_sendtext,    /* called with chan locked */
02694    .func_channel_read = acf_channel_read,
02695    .queryoption = sip_queryoption,
02696    .get_pvt_uniqueid = sip_get_callid,
02697 };
02698 
02699 /*! \brief This version of the sip channel tech has no send_digit_begin
02700  * callback so that the core knows that the channel does not want
02701  * DTMF BEGIN frames.
02702  * The struct is initialized just before registering the channel driver,
02703  * and is for use with channels using SIP INFO DTMF.
02704  */
02705 static struct ast_channel_tech sip_tech_info;
02706 
02707 
02708 /*! \brief Working TLS connection configuration */
02709 static struct ast_tls_config sip_tls_cfg;
02710 
02711 /*! \brief Default TLS connection configuration */
02712 static struct ast_tls_config default_tls_cfg;
02713 
02714 /*! \brief The TCP server definition */
02715 static struct ast_tcptls_session_args sip_tcp_desc = {
02716    .accept_fd = -1,
02717    .master = AST_PTHREADT_NULL,
02718    .tls_cfg = NULL,
02719    .poll_timeout = -1,
02720    .name = "SIP TCP server",
02721    .accept_fn = ast_tcptls_server_root,
02722    .worker_fn = sip_tcp_worker_fn,
02723 };
02724 
02725 /*! \brief The TCP/TLS server definition */
02726 static struct ast_tcptls_session_args sip_tls_desc = {
02727    .accept_fd = -1,
02728    .master = AST_PTHREADT_NULL,
02729    .tls_cfg = &sip_tls_cfg,
02730    .poll_timeout = -1,
02731    .name = "SIP TLS server",
02732    .accept_fn = ast_tcptls_server_root,
02733    .worker_fn = sip_tcp_worker_fn,
02734 };
02735 
02736 /* wrapper macro to tell whether t points to one of the sip_tech descriptors */
02737 #define IS_SIP_TECH(t)  ((t) == &sip_tech || (t) == &sip_tech_info)
02738 
02739 /*! \brief map from an integer value to a string.
02740  * If no match is found, return errorstring
02741  */
02742 static const char *map_x_s(const struct _map_x_s *table, int x, const char *errorstring)
02743 {
02744    const struct _map_x_s *cur;
02745 
02746    for (cur = table; cur->s; cur++)
02747       if (cur->x == x)
02748          return cur->s;
02749    return errorstring;
02750 }
02751 
02752 /*! \brief map from a string to an integer value, case insensitive.
02753  * If no match is found, return errorvalue.
02754  */
02755 static int map_s_x(const struct _map_x_s *table, const char *s, int errorvalue)
02756 {
02757    const struct _map_x_s *cur;
02758 
02759    for (cur = table; cur->s; cur++)
02760       if (!strcasecmp(cur->s, s))
02761          return cur->x;
02762    return errorvalue;
02763 }
02764 
02765 
02766 /*! \brief Interface structure with callbacks used to connect to RTP module */
02767 static struct ast_rtp_protocol sip_rtp = {
02768    .type = "SIP",
02769    .get_rtp_info = sip_get_rtp_peer,
02770    .get_vrtp_info = sip_get_vrtp_peer,
02771    .get_trtp_info = sip_get_trtp_peer,
02772    .set_rtp_peer = sip_set_rtp_peer,
02773    .get_codec = sip_get_codec,
02774 };
02775 
02776 /*!
02777  * duplicate a list of channel variables, \return the copy.
02778  */
02779 static struct ast_variable *copy_vars(struct ast_variable *src)
02780 {
02781    struct ast_variable *res = NULL, *tmp, *v = NULL;
02782 
02783    for (v = src ; v ; v = v->next) {
02784       if ((tmp = ast_variable_new(v->name, v->value, v->file))) {
02785          tmp->next = res;
02786          res = tmp;
02787       }
02788    }
02789    return res;
02790 }
02791 
02792 static void tcptls_packet_destructor(void *obj)
02793 {
02794    struct tcptls_packet *packet = obj;
02795 
02796    ast_free(packet->data);
02797 }
02798 
02799 static void sip_tcptls_client_args_destructor(void *obj)
02800 {
02801    struct ast_tcptls_session_args *args = obj;
02802    if (args->tls_cfg) {
02803       ast_free(args->tls_cfg->certfile);
02804       ast_free(args->tls_cfg->cipher);
02805       ast_free(args->tls_cfg->cafile);
02806       ast_free(args->tls_cfg->capath);
02807    }
02808    ast_free(args->tls_cfg);
02809    ast_free((char *) args->name);
02810 }
02811 
02812 static void sip_threadinfo_destructor(void *obj)
02813 {
02814    struct sip_threadinfo *th = obj;
02815    struct tcptls_packet *packet;
02816    if (th->alert_pipe[1] > -1) {
02817       close(th->alert_pipe[0]);
02818    }
02819    if (th->alert_pipe[1] > -1) {
02820       close(th->alert_pipe[1]);
02821    }
02822    th->alert_pipe[0] = th->alert_pipe[1] = -1;
02823 
02824    while ((packet = AST_LIST_REMOVE_HEAD(&th->packet_q, entry))) {
02825       ao2_t_ref(packet, -1, "thread destruction, removing packet from frame queue");
02826    }
02827 
02828    if (th->tcptls_session) {
02829       ao2_t_ref(th->tcptls_session, -1, "remove tcptls_session for sip_threadinfo object");
02830    }
02831 }
02832 
02833 /*! \brief creates a sip_threadinfo object and links it into the threadt table. */
02834 static struct sip_threadinfo *sip_threadinfo_create(struct ast_tcptls_session_instance *tcptls_session, int transport)
02835 {
02836    struct sip_threadinfo *th;
02837 
02838    if (!tcptls_session || !(th = ao2_alloc(sizeof(*th), sip_threadinfo_destructor))) {
02839       return NULL;
02840    }
02841 
02842    th->alert_pipe[0] = th->alert_pipe[1] = -1;
02843 
02844    if (pipe(th->alert_pipe) == -1) {
02845       ao2_t_ref(th, -1, "Failed to open alert pipe on sip_threadinfo");
02846       ast_log(LOG_ERROR, "Could not create sip alert pipe in tcptls thread, error %s\n", strerror(errno));
02847       return NULL;
02848    }
02849    ao2_t_ref(tcptls_session, +1, "tcptls_session ref for sip_threadinfo object");
02850    th->tcptls_session = tcptls_session;
02851    th->type = transport ? transport : (tcptls_session->ssl ? SIP_TRANSPORT_TLS: SIP_TRANSPORT_TCP);
02852    ao2_t_link(threadt, th, "Adding new tcptls helper thread");
02853    ao2_t_ref(th, -1, "Decrementing threadinfo ref from alloc, only table ref remains");
02854    return th;
02855 }
02856 
02857 /*! \brief used to indicate to a tcptls thread that data is ready to be written */
02858 static int sip_tcptls_write(struct ast_tcptls_session_instance *tcptls_session, const void *buf, size_t len)
02859 {
02860    int res = len;
02861    struct sip_threadinfo *th = NULL;
02862    struct tcptls_packet *packet = NULL;
02863    struct sip_threadinfo tmp = {
02864       .tcptls_session = tcptls_session,
02865    };
02866    enum sip_tcptls_alert alert = TCPTLS_ALERT_DATA;
02867 
02868    if (!tcptls_session) {
02869       return XMIT_ERROR;
02870    }
02871 
02872    ast_mutex_lock(&tcptls_session->lock);
02873 
02874    if ((tcptls_session->fd == -1) ||
02875       !(th = ao2_t_find(threadt, &tmp, OBJ_POINTER, "ao2_find, getting sip_threadinfo in tcp helper thread")) ||
02876       !(packet = ao2_alloc(sizeof(*packet), tcptls_packet_destructor)) ||
02877       !(packet->data = ast_str_create(len))) {
02878       goto tcptls_write_setup_error;
02879    }
02880 
02881    /* goto tcptls_write_error should _NOT_ be used beyond this point */
02882    ast_str_set(&packet->data, 0, "%s", (char *) buf);
02883    packet->len = len;
02884 
02885    /* alert tcptls thread handler that there is a packet to be sent.
02886     * must lock the thread info object to guarantee control of the
02887     * packet queue */
02888    ao2_lock(th);
02889    if (write(th->alert_pipe[1], &alert, sizeof(alert)) == -1) {
02890       ast_log(LOG_ERROR, "write() to alert pipe failed: %s\n", strerror(errno));
02891       ao2_t_ref(packet, -1, "could not write to alert pipe, remove packet");
02892       packet = NULL;
02893       res = XMIT_ERROR;
02894    } else { /* it is safe to queue the frame after issuing the alert when we hold the threadinfo lock */
02895       AST_LIST_INSERT_TAIL(&th->packet_q, packet, entry);
02896    }
02897    ao2_unlock(th);
02898 
02899    ast_mutex_unlock(&tcptls_session->lock);
02900    ao2_t_ref(th, -1, "In sip_tcptls_write, unref threadinfo object after finding it");
02901    return res;
02902 
02903 tcptls_write_setup_error:
02904    if (th) {
02905       ao2_t_ref(th, -1, "In sip_tcptls_write, unref threadinfo obj, could not create packet");
02906    }
02907    if (packet) {
02908       ao2_t_ref(packet, -1, "could not allocate packet's data");
02909    }
02910    ast_mutex_unlock(&tcptls_session->lock);
02911 
02912    return XMIT_ERROR;
02913 }
02914 
02915 /*! \brief SIP TCP connection handler */
02916 static void *sip_tcp_worker_fn(void *data)
02917 {
02918    struct ast_tcptls_session_instance *tcptls_session = data;
02919 
02920    return _sip_tcp_helper_thread(NULL, tcptls_session);
02921 }
02922 
02923 /*! \brief Check if the authtimeout has expired.
02924  * \param start the time when the session started
02925  *
02926  * \retval 0 the timeout has expired
02927  * \retval -1 error
02928  * \return the number of milliseconds until the timeout will expire
02929  */
02930 static int sip_check_authtimeout(time_t start)
02931 {
02932    int timeout;
02933    time_t now;
02934    if(time(&now) == -1) {
02935       ast_log(LOG_ERROR, "error executing time(): %s\n", strerror(errno));
02936       return -1;
02937    }
02938 
02939    timeout = (authtimeout - (now - start)) * 1000;
02940    if (timeout < 0) {
02941       /* we have timed out */
02942       return 0;
02943    }
02944 
02945    return timeout;
02946 }
02947 
02948 /*! \brief SIP TCP thread management function 
02949    This function reads from the socket, parses the packet into a request
02950 */
02951 static void *_sip_tcp_helper_thread(struct sip_pvt *pvt, struct ast_tcptls_session_instance *tcptls_session) 
02952 {
02953    int res, cl, timeout = -1, authenticated = 0, flags;
02954    time_t start;
02955    struct sip_request req = { 0, } , reqcpy = { 0, };
02956    struct sip_threadinfo *me = NULL;
02957    char buf[1024] = "";
02958    struct pollfd fds[2] = { { 0 }, { 0 }, };
02959    struct ast_tcptls_session_args *ca = NULL;
02960 
02961    /* If this is a server session, then the connection has already been
02962     * setup. Check if the authlimit has been reached and if not create the
02963     * threadinfo object so we can access this thread for writing.
02964     *
02965     * if this is a client connection more work must be done.
02966     * 1. We own the parent session args for a client connection.  This pointer needs
02967     *    to be held on to so we can decrement it's ref count on thread destruction.
02968     * 2. The threadinfo object was created before this thread was launched, however
02969     *    it must be found within the threadt table.
02970     * 3. Last, the tcptls_session must be started.
02971     */
02972    if (!tcptls_session->client) {
02973       if (ast_atomic_fetchadd_int(&unauth_sessions, +1) >= authlimit) {
02974          /* unauth_sessions is decremented in the cleanup code */
02975          goto cleanup;
02976       }
02977 
02978       if ((flags = fcntl(tcptls_session->fd, F_GETFL)) == -1) {
02979          ast_log(LOG_ERROR, "error setting socket to non blocking mode, fcntl() failed: %s\n", strerror(errno));
02980          goto cleanup;
02981       }
02982 
02983       flags |= O_NONBLOCK;
02984       if (fcntl(tcptls_session->fd, F_SETFL, flags) == -1) {
02985          ast_log(LOG_ERROR, "error setting socket to non blocking mode, fcntl() failed: %s\n", strerror(errno));
02986          goto cleanup;
02987       }
02988 
02989       if (!(me = sip_threadinfo_create(tcptls_session, tcptls_session->ssl ? SIP_TRANSPORT_TLS : SIP_TRANSPORT_TCP))) {
02990          goto cleanup;
02991       }
02992       ao2_t_ref(me, +1, "Adding threadinfo ref for tcp_helper_thread");
02993    } else {
02994       struct sip_threadinfo tmp = {
02995          .tcptls_session = tcptls_session,
02996       };
02997 
02998       if ((!(ca = tcptls_session->parent)) ||
02999          (!(me = ao2_t_find(threadt, &tmp, OBJ_POINTER, "ao2_find, getting sip_threadinfo in tcp helper thread"))) ||
03000          (!(tcptls_session = ast_tcptls_client_start(tcptls_session)))) {
03001          goto cleanup;
03002       }
03003    }
03004 
03005    me->threadid = pthread_self();
03006    ast_debug(2, "Starting thread for %s server\n", tcptls_session->ssl ? "SSL" : "TCP");
03007 
03008    /* set up pollfd to watch for reads on both the socket and the alert_pipe */
03009    fds[0].fd = tcptls_session->fd;
03010    fds[1].fd = me->alert_pipe[0];
03011    fds[0].events = fds[1].events = POLLIN | POLLPRI;
03012 
03013    if (!(req.data = ast_str_create(SIP_MIN_PACKET)))
03014       goto cleanup;
03015    if (!(reqcpy.data = ast_str_create(SIP_MIN_PACKET)))
03016       goto cleanup;
03017 
03018    if(time(&start) == -1) {
03019       ast_log(LOG_ERROR, "error executing time(): %s\n", strerror(errno));
03020       goto cleanup;
03021    }
03022 
03023    for (;;) {
03024       struct ast_str *str_save;
03025 
03026       if (!tcptls_session->client && req.authenticated && !authenticated) {
03027          authenticated = 1;
03028          ast_atomic_fetchadd_int(&unauth_sessions, -1);
03029       }
03030 
03031       /* calculate the timeout for unauthenticated server sessions */
03032       if (!tcptls_session->client && !authenticated ) {
03033          if ((timeout = sip_check_authtimeout(start)) < 0) {
03034             goto cleanup;
03035          }
03036 
03037          if (timeout == 0) {
03038             ast_debug(2, "SIP %s server timed out\n", tcptls_session->ssl ? "SSL": "TCP");
03039             goto cleanup;
03040          }
03041       } else {
03042          timeout = -1;
03043       }
03044 
03045       res = ast_poll(fds, 2, timeout); /* polls for both socket and alert_pipe */
03046       if (res < 0) {
03047          ast_debug(2, "SIP %s server :: ast_wait_for_input returned %d\n", tcptls_session->ssl ? "SSL": "TCP", res);
03048          goto cleanup;
03049       } else if (res == 0) {
03050          /* timeout */
03051          ast_debug(2, "SIP %s server timed out\n", tcptls_session->ssl ? "SSL": "TCP");
03052          goto cleanup;
03053       }
03054 
03055       /* handle the socket event, check for both reads from the socket fd,
03056        * and writes from alert_pipe fd */
03057       if (fds[0].revents) { /* there is data on the socket to be read */
03058 
03059          fds[0].revents = 0;
03060 
03061          /* clear request structure */
03062          str_save = req.data;
03063          memset(&req, 0, sizeof(req));
03064          req.data = str_save;
03065          ast_str_reset(req.data);
03066 
03067          str_save = reqcpy.data;
03068          memset(&reqcpy, 0, sizeof(reqcpy));
03069          reqcpy.data = str_save;
03070          ast_str_reset(reqcpy.data);
03071 
03072          memset(buf, 0, sizeof(buf));
03073 
03074          if (tcptls_session->ssl) {
03075             set_socket_transport(&req.socket, SIP_TRANSPORT_TLS);
03076             req.socket.port = htons(ourport_tls);
03077          } else {
03078             set_socket_transport(&req.socket, SIP_TRANSPORT_TCP);
03079             req.socket.port = htons(ourport_tcp);
03080          }
03081          req.socket.fd = tcptls_session->fd;
03082 
03083          /* Read in headers one line at a time */
03084          while (req.len < 4 || strncmp(REQ_OFFSET_TO_STR(&req, len - 4), "\r\n\r\n", 4)) {
03085             if (!tcptls_session->client && !authenticated ) {
03086                if ((timeout = sip_check_authtimeout(start)) < 0) {
03087                   goto cleanup;
03088                }
03089 
03090                if (timeout == 0) {
03091                   ast_debug(2, "SIP %s server timed out\n", tcptls_session->ssl ? "SSL": "TCP");
03092                   goto cleanup;
03093                }
03094             } else {
03095                timeout = -1;
03096             }
03097 
03098             res = ast_wait_for_input(tcptls_session->fd, timeout);
03099             if (res < 0) {
03100                ast_debug(2, "SIP %s server :: ast_wait_for_input returned %d\n", tcptls_session->ssl ? "SSL": "TCP", res);
03101                goto cleanup;
03102             } else if (res == 0) {
03103                /* timeout */
03104                ast_debug(2, "SIP %s server timed out\n", tcptls_session->ssl ? "SSL": "TCP");
03105                goto cleanup;
03106             }
03107 
03108             ast_mutex_lock(&tcptls_session->lock);
03109             if (!fgets(buf, sizeof(buf), tcptls_session->f)) {
03110                ast_mutex_unlock(&tcptls_session->lock);
03111                goto cleanup;
03112             }
03113             ast_mutex_unlock(&tcptls_session->lock);
03114             if (me->stop)
03115                 goto cleanup;
03116             ast_str_append(&req.data, 0, "%s", buf);
03117             req.len = req.data->used;
03118          }
03119          copy_request(&reqcpy, &req);
03120          parse_request(&reqcpy);
03121          /* In order to know how much to read, we need the content-length header */
03122          if (sscanf(get_header(&reqcpy, "Content-Length"), "%30d", &cl)) {
03123             while (cl > 0) {
03124                size_t bytes_read;
03125                if (!tcptls_session->client && !authenticated ) {
03126                   if ((timeout = sip_check_authtimeout(start)) < 0) {
03127                      goto cleanup;
03128                   }
03129 
03130                   if (timeout == 0) {
03131                      ast_debug(2, "SIP %s server timed out", tcptls_session->ssl ? "SSL": "TCP");
03132                      goto cleanup;
03133                   }
03134                } else {
03135                   timeout = -1;
03136                }
03137 
03138                res = ast_wait_for_input(tcptls_session->fd, timeout);
03139                if (res < 0) {
03140                   ast_debug(2, "SIP %s server :: ast_wait_for_input returned %d\n", tcptls_session->ssl ? "SSL": "TCP", res);
03141                   goto cleanup;
03142                } else if (res == 0) {
03143                   /* timeout */
03144                   ast_debug(2, "SIP %s server timed out", tcptls_session->ssl ? "SSL": "TCP");
03145                   goto cleanup;
03146                }
03147 
03148                ast_mutex_lock(&tcptls_session->lock);
03149                if (!(bytes_read = fread(buf, 1, MIN(sizeof(buf) - 1, cl), tcptls_session->f))) {
03150                   ast_mutex_unlock(&tcptls_session->lock);
03151                   goto cleanup;
03152                }
03153                buf[bytes_read] = '\0';
03154                ast_mutex_unlock(&tcptls_session->lock);
03155                if (me->stop)
03156                   goto cleanup;
03157                cl -= strlen(buf);
03158                ast_str_append(&req.data, 0, "%s", buf);
03159                req.len = req.data->used;
03160             }
03161          }
03162          /*! \todo XXX If there's no Content-Length or if the content-length and what
03163                we receive is not the same - we should generate an error */
03164 
03165          req.socket.tcptls_session = tcptls_session;
03166          handle_request_do(&req, &tcptls_session->remote_address);
03167       }
03168 
03169       if (fds[1].revents) { /* alert_pipe indicates there is data in the send queue to be sent */
03170          enum sip_tcptls_alert alert;
03171          struct tcptls_packet *packet;
03172 
03173          fds[1].revents = 0;
03174 
03175          if (read(me->alert_pipe[0], &alert, sizeof(alert)) == -1) {
03176             ast_log(LOG_ERROR, "read() failed: %s\n", strerror(errno));
03177             continue;
03178          }
03179 
03180          switch (alert) {
03181          case TCPTLS_ALERT_STOP:
03182             goto cleanup;
03183          case TCPTLS_ALERT_DATA:
03184             ao2_lock(me);
03185             if (!(packet = AST_LIST_REMOVE_HEAD(&me->packet_q, entry))) {
03186                ast_log(LOG_WARNING, "TCPTLS thread alert_pipe indicated packet should be sent, but frame_q is empty");
03187             } else if (ast_tcptls_server_write(tcptls_session, ast_str_buffer(packet->data), packet->len) == -1) {
03188                ast_log(LOG_WARNING, "Failure to write to tcp/tls socket\n");
03189             }
03190 
03191             if (packet) {
03192                ao2_t_ref(packet, -1, "tcptls packet sent, this is no longer needed");
03193             }
03194             ao2_unlock(me);
03195             break;
03196          default:
03197             ast_log(LOG_ERROR, "Unknown tcptls thread alert '%d'\n", alert);
03198          }
03199       }
03200    }
03201 
03202    ast_debug(2, "Shutting down thread for %s server\n", tcptls_session->ssl ? "SSL" : "TCP");
03203 
03204 cleanup:
03205    if (!tcptls_session->client && !authenticated) {
03206       ast_atomic_fetchadd_int(&unauth_sessions, -1);
03207    }
03208 
03209    if (me) {
03210       ao2_t_unlink(threadt, me, "Removing tcptls helper thread, thread is closing");
03211       ao2_t_ref(me, -1, "Removing tcp_helper_threads threadinfo ref");
03212    }
03213    deinit_req(&reqcpy);
03214    deinit_req(&req);
03215 
03216    /* if client, we own the parent session arguments and must decrement ref */
03217    if (ca) {
03218       ao2_t_ref(ca, -1, "closing tcptls thread, getting rid of client tcptls_session arguments");
03219    }
03220 
03221    if (tcptls_session) {
03222       ast_mutex_lock(&tcptls_session->lock);
03223       if (tcptls_session->f) {
03224          fclose(tcptls_session->f);
03225          tcptls_session->f = NULL;
03226       }
03227       if (tcptls_session->fd != -1) {
03228          close(tcptls_session->fd);
03229          tcptls_session->fd = -1;
03230       }
03231       tcptls_session->parent = NULL;
03232       ast_mutex_unlock(&tcptls_session->lock);
03233 
03234       ao2_ref(tcptls_session, -1);
03235       tcptls_session = NULL;
03236    }
03237    return NULL;
03238 }
03239 
03240 /* this func is used with ao2_callback to unlink/delete all marked
03241    peers */
03242 static int peer_is_marked(void *peerobj, void *arg, int flags)
03243 {
03244    struct sip_peer *peer = peerobj;
03245    if (peer->the_mark && peer->pokeexpire != -1) {
03246       AST_SCHED_DEL(sched, peer->pokeexpire);
03247    }
03248    return peer->the_mark ? CMP_MATCH : 0;
03249 }
03250 
03251 
03252 /* \brief Unlink all marked peers from ao2 containers */
03253 static void unlink_marked_peers_from_tables(void)
03254 {
03255    ao2_t_callback(peers, OBJ_NODATA | OBJ_UNLINK | OBJ_MULTIPLE, peer_is_marked, NULL,
03256                   "initiating callback to remove marked peers");
03257    ao2_t_callback(peers_by_ip, OBJ_NODATA | OBJ_UNLINK | OBJ_MULTIPLE, peer_is_marked, NULL,
03258                   "initiating callback to remove marked peers");
03259 }
03260 
03261 /* \brief Unlink single peer from all ao2 containers */
03262 static void unlink_peer_from_tables(struct sip_peer *peer)
03263 {
03264    ao2_t_unlink(peers, peer, "ao2_unlink of peer from peers table");
03265    if (peer->addr.sin_addr.s_addr) {
03266       ao2_t_unlink(peers_by_ip, peer, "ao2_unlink of peer from peers_by_ip table");
03267    }
03268 }
03269 
03270 /*!
03271  * helper functions to unreference various types of objects.
03272  * By handling them this way, we don't have to declare the
03273  * destructor on each call, which removes the chance of errors.
03274  */
03275 static void *unref_peer(struct sip_peer *peer, char *tag)
03276 {
03277    ao2_t_ref(peer, -1, tag);
03278    return NULL;
03279 }
03280 
03281 static struct sip_peer *ref_peer(struct sip_peer *peer, char *tag)
03282 {
03283    ao2_t_ref(peer, 1, tag);
03284    return peer;
03285 }
03286 
03287 /*! \brief maintain proper refcounts for a sip_pvt's outboundproxy
03288  *
03289  * This function sets pvt's outboundproxy pointer to the one referenced
03290  * by the proxy parameter. Because proxy may be a refcounted object, and
03291  * because pvt's old outboundproxy may also be a refcounted object, we need
03292  * to maintain the proper refcounts.
03293  *
03294  * \param pvt The sip_pvt for which we wish to set the outboundproxy
03295  * \param proxy The sip_proxy which we will point pvt towards.
03296  * \return Returns void
03297  */
03298 static void ref_proxy(struct sip_pvt *pvt, struct sip_proxy *proxy)
03299 {
03300    struct sip_proxy *old_obproxy = pvt->outboundproxy;
03301    /* The sip_cfg.outboundproxy is statically allocated, and so
03302     * we don't ever need to adjust refcounts for it
03303     */
03304    if (proxy && proxy != &sip_cfg.outboundproxy) {
03305       ao2_ref(proxy, +1);
03306    }
03307    pvt->outboundproxy = proxy;
03308    if (old_obproxy && old_obproxy != &sip_cfg.outboundproxy) {
03309       ao2_ref(old_obproxy, -1);
03310    }
03311 }
03312 
03313 /*!
03314  * \brief Unlink a dialog from the dialogs container, as well as any other places
03315  * that it may be currently stored.
03316  *
03317  * \note A reference to the dialog must be held before calling this function, and this
03318  * function does not release that reference.
03319  */
03320 static void *dialog_unlink_all(struct sip_pvt *dialog, int lockowner, int lockdialoglist)
03321 {
03322    struct sip_pkt *cp;
03323 
03324    dialog_ref(dialog, "Let's bump the count in the unlink so it doesn't accidentally become dead before we are done");
03325 
03326    ao2_t_unlink(dialogs, dialog, "unlinking dialog via ao2_unlink");
03327 
03328    /* Unlink us from the owner (channel) if we have one */
03329    if (dialog->owner) {
03330       if (lockowner)
03331          ast_channel_lock(dialog->owner);
03332       ast_debug(1, "Detaching from channel %s\n", dialog->owner->name);
03333       dialog->owner->tech_pvt = dialog_unref(dialog->owner->tech_pvt, "resetting channel dialog ptr in unlink_all");
03334       if (lockowner)
03335          ast_channel_unlock(dialog->owner);
03336    }
03337    if (dialog->registry) {
03338       if (dialog->registry->call == dialog)
03339          dialog->registry->call = dialog_unref(dialog->registry->call, "nulling out the registry's call dialog field in unlink_all");
03340       dialog->registry = registry_unref(dialog->registry, "delete dialog->registry");
03341    }
03342    if (dialog->stateid > -1) {
03343       ast_extension_state_del(dialog->stateid, NULL);
03344       dialog_unref(dialog, "removing extension_state, should unref the associated dialog ptr that was stored there.");
03345       dialog->stateid = -1; /* shouldn't we 'zero' this out? */
03346    }
03347    /* Remove link from peer to subscription of MWI */
03348    if (dialog->relatedpeer && dialog->relatedpeer->mwipvt == dialog)
03349       dialog->relatedpeer->mwipvt = dialog_unref(dialog->relatedpeer->mwipvt, "delete ->relatedpeer->mwipvt");
03350    if (dialog->relatedpeer && dialog->relatedpeer->call == dialog)
03351       dialog->relatedpeer->call = dialog_unref(dialog->relatedpeer->call, "unset the relatedpeer->call field in tandem with relatedpeer field itself");
03352 
03353    /* remove all current packets in this dialog */
03354    while((cp = dialog->packets)) {
03355       dialog->packets = dialog->packets->next;
03356       AST_SCHED_DEL(sched, cp->retransid);
03357       dialog_unref(cp->owner, "remove all current packets in this dialog, and the pointer to the dialog too as part of __sip_destroy");
03358       if (cp->data) {
03359          ast_free(cp->data);
03360       }
03361       ast_free(cp);
03362    }
03363 
03364    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"));
03365 
03366    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"));
03367    
03368    if (dialog->autokillid > -1)
03369       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"));
03370 
03371    if (dialog->request_queue_sched_id > -1) {
03372       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"));
03373    }
03374 
03375    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"));
03376 
03377    if (dialog->t38id > -1) {
03378       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"));
03379    }
03380 
03381    dialog_unref(dialog, "Let's unbump the count in the unlink so the poor pvt can disappear if it is time");
03382    return NULL;
03383 }
03384 
03385 static void *registry_unref(struct sip_registry *reg, char *tag)
03386 {
03387    ast_debug(3, "SIP Registry %s: refcount now %d\n", reg->hostname, reg->refcount - 1);
03388    ASTOBJ_UNREF(reg, sip_registry_destroy);
03389    return NULL;
03390 }
03391 
03392 /*! \brief Add object reference to SIP registry */
03393 static struct sip_registry *registry_addref(struct sip_registry *reg, char *tag)
03394 {
03395    ast_debug(3, "SIP Registry %s: refcount now %d\n", reg->hostname, reg->refcount + 1);
03396    return ASTOBJ_REF(reg); /* Add pointer to registry in packet */
03397 }
03398 
03399 /*! \brief Interface structure with callbacks used to connect to UDPTL module*/
03400 static struct ast_udptl_protocol sip_udptl = {
03401    type: "SIP",
03402    get_udptl_info: sip_get_udptl_peer,
03403    set_udptl_peer: sip_set_udptl_peer,
03404 };
03405 
03406 static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
03407    __attribute__((format(printf, 2, 3)));
03408 
03409 
03410 /*! \brief Convert transfer status to string */
03411 static const char *referstatus2str(enum referstatus rstatus)
03412 {
03413    return map_x_s(referstatusstrings, rstatus, "");
03414 }
03415 
03416 static inline void pvt_set_needdestroy(struct sip_pvt *pvt, const char *reason)
03417 {
03418    append_history(pvt, "NeedDestroy", "Setting needdestroy because %s", reason);
03419    pvt->needdestroy = 1;
03420 }
03421 
03422 /*! \brief Initialize the initital request packet in the pvt structure.
03423    This packet is used for creating replies and future requests in
03424    a dialog */
03425 static void initialize_initreq(struct sip_pvt *p, struct sip_request *req)
03426 {
03427    if (p->initreq.headers)
03428       ast_debug(1, "Initializing already initialized SIP dialog %s (presumably reinvite)\n", p->callid);
03429    else
03430       ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
03431    /* Use this as the basis */
03432    copy_request(&p->initreq, req);
03433    parse_request(&p->initreq);
03434    if (req->debug)
03435       ast_verbose("Initreq: %d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
03436 }
03437 
03438 /*! \brief Encapsulate setting of SIP_ALREADYGONE to be able to trace it with debugging */
03439 static void sip_alreadygone(struct sip_pvt *dialog)
03440 {
03441    ast_debug(3, "Setting SIP_ALREADYGONE on dialog %s\n", dialog->callid);
03442    dialog->alreadygone = 1;
03443 }
03444 
03445 /*! Resolve DNS srv name or host name in a sip_proxy structure */
03446 static int proxy_update(struct sip_proxy *proxy)
03447 {
03448    /* if it's actually an IP address and not a name,
03449            there's no need for a managed lookup */
03450    if (!inet_aton(proxy->name, &proxy->ip.sin_addr)) {
03451       /* Ok, not an IP address, then let's check if it's a domain or host */
03452       /* XXX Todo - if we have proxy port, don't do SRV */
03453       if (ast_get_ip_or_srv(&proxy->ip, proxy->name, sip_cfg.srvlookup ? "_sip._udp" : NULL) < 0) {
03454          ast_log(LOG_WARNING, "Unable to locate host '%s'\n", proxy->name);
03455          return FALSE;
03456       }
03457    }
03458    proxy->last_dnsupdate = time(NULL);
03459    return TRUE;
03460 }
03461 
03462 /*! \brief converts ascii port to int representation. If no
03463  *  pt buffer is provided or the pt has errors when being converted
03464  *  to an int value, the port provided as the standard is used.
03465  */
03466 static int port_str2int(const char *pt, unsigned int standard)
03467 {
03468    int port = standard;
03469    if (ast_strlen_zero(pt) || (sscanf(pt, "%30d", &port) != 1) || (port < 1) || (port > 65535)) {
03470       port = standard;
03471    }
03472 
03473    return port;
03474 }
03475 
03476 /*! \brief Allocate and initialize sip proxy */
03477 static struct sip_proxy *proxy_allocate(char *name, char *port, int force)
03478 {
03479    struct sip_proxy *proxy;
03480 
03481    if (ast_strlen_zero(name)) {
03482       return NULL;
03483    }
03484 
03485    proxy = ao2_alloc(sizeof(*proxy), NULL);
03486    if (!proxy)
03487       return NULL;
03488    proxy->force = force;
03489    ast_copy_string(proxy->name, name, sizeof(proxy->name));
03490    proxy->ip.sin_port = htons(port_str2int(port, STANDARD_SIP_PORT));
03491    proxy->ip.sin_family = AF_INET;
03492    proxy_update(proxy);
03493    return proxy;
03494 }
03495 
03496 /*! \brief Get default outbound proxy or global proxy */
03497 static struct sip_proxy *obproxy_get(struct sip_pvt *dialog, struct sip_peer *peer)
03498 {
03499    if (peer && peer->outboundproxy) {
03500       if (sipdebug)
03501          ast_debug(1, "OBPROXY: Applying peer OBproxy to this call\n");
03502       append_history(dialog, "OBproxy", "Using peer obproxy %s", peer->outboundproxy->name);
03503       return peer->outboundproxy;
03504    }
03505    if (sip_cfg.outboundproxy.name[0]) {
03506       if (sipdebug)
03507          ast_debug(1, "OBPROXY: Applying global OBproxy to this call\n");
03508       append_history(dialog, "OBproxy", "Using global obproxy %s", sip_cfg.outboundproxy.name);
03509       return &sip_cfg.outboundproxy;
03510    }
03511    if (sipdebug)
03512       ast_debug(1, "OBPROXY: Not applying OBproxy to this call\n");
03513    return NULL;
03514 }
03515 
03516 /*! \brief returns true if 'name' (with optional trailing whitespace)
03517  * matches the sip method 'id'.
03518  * Strictly speaking, SIP methods are case SENSITIVE, but we do
03519  * a case-insensitive comparison to be more tolerant.
03520  * following Jon Postel's rule: Be gentle in what you accept, strict with what you send
03521  */
03522 static int method_match(enum sipmethod id, const char *name)
03523 {
03524    int len = strlen(sip_methods[id].text);
03525    int l_name = name ? strlen(name) : 0;
03526    /* true if the string is long enough, and ends with whitespace, and matches */
03527    return (l_name >= len && name[len] < 33 &&
03528       !strncasecmp(sip_methods[id].text, name, len));
03529 }
03530 
03531 /*! \brief  find_sip_method: Find SIP method from header */
03532 static int find_sip_method(const char *msg)
03533 {
03534    int i, res = 0;
03535    
03536    if (ast_strlen_zero(msg))
03537       return 0;
03538    for (i = 1; i < ARRAY_LEN(sip_methods) && !res; i++) {
03539       if (method_match(i, msg))
03540          res = sip_methods[i].id;
03541    }
03542    return res;
03543 }
03544 
03545 /*! \brief Parse supported header in incoming packet */
03546 static unsigned int parse_sip_options(struct sip_pvt *pvt, const char *supported)
03547 {
03548    char *next, *sep;
03549    char *temp;
03550    unsigned int profile = 0;
03551    int i, found;
03552 
03553    if (ast_strlen_zero(supported) )
03554       return 0;
03555    temp = ast_strdupa(supported);
03556 
03557    if (sipdebug)
03558       ast_debug(3, "Begin: parsing SIP \"Supported: %s\"\n", supported);
03559 
03560    for (next = temp; next; next = sep) {
03561       found = FALSE;
03562       if ( (sep = strchr(next, ',')) != NULL)
03563          *sep++ = '\0';
03564       next = ast_skip_blanks(next);
03565       if (sipdebug)
03566          ast_debug(3, "Found SIP option: -%s-\n", next);
03567       for (i = 0; i < ARRAY_LEN(sip_options); i++) {
03568          if (!strcasecmp(next, sip_options[i].text)) {
03569             profile |= sip_options[i].id;
03570             found = TRUE;
03571             if (sipdebug)
03572                ast_debug(3, "Matched SIP option: %s\n", next);
03573             break;
03574          }
03575       }
03576 
03577       /* This function is used to parse both Suported: and Require: headers.
03578       Let the caller of this function know that an unknown option tag was 
03579       encountered, so that if the UAC requires it then the request can be 
03580       rejected with a 420 response. */
03581       if (!found)
03582          profile |= SIP_OPT_UNKNOWN;
03583 
03584       if (!found && sipdebug) {
03585          if (!strncasecmp(next, "x-", 2))
03586             ast_debug(3, "Found private SIP option, not supported: %s\n", next);
03587          else
03588             ast_debug(3, "Found no match for SIP option: %s (Please file bug report!)\n", next);
03589       }
03590    }
03591 
03592    if (pvt)
03593       pvt->sipoptions = profile;
03594    return profile;
03595 }
03596 
03597 /*! \brief See if we pass debug IP filter */
03598 static inline int sip_debug_test_addr(const struct sockaddr_in *addr) 
03599 {
03600    if (!sipdebug)
03601       return 0;
03602    if (debugaddr.sin_addr.s_addr) {
03603       if (((ntohs(debugaddr.sin_port) != 0)
03604          && (debugaddr.sin_port != addr->sin_port))
03605          || (debugaddr.sin_addr.s_addr != addr->sin_addr.s_addr))
03606          return 0;
03607    }
03608    return 1;
03609 }
03610 
03611 /*! \brief The real destination address for a write */
03612 static const struct sockaddr_in *sip_real_dst(const struct sip_pvt *p)
03613 {
03614    if (p->outboundproxy)
03615       return &p->outboundproxy->ip;
03616 
03617    return ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE ? &p->recv : &p->sa;
03618 }
03619 
03620 /*! \brief Display SIP nat mode */
03621 static const char *sip_nat_mode(const struct sip_pvt *p)
03622 {
03623    return ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE ? "NAT" : "no NAT";
03624 }
03625 
03626 /*! \brief Test PVT for debugging output */
03627 static inline int sip_debug_test_pvt(struct sip_pvt *p) 
03628 {
03629    if (!sipdebug)
03630       return 0;
03631    return sip_debug_test_addr(sip_real_dst(p));
03632 }
03633 
03634 /*! \brief Return int representing a bit field of transport types found in const char *transport */
03635 static int get_transport_str2enum(const char *transport)
03636 {
03637    int res = 0;
03638 
03639    if (ast_strlen_zero(transport)) {
03640       return res;
03641    }
03642 
03643    if (!strcasecmp(transport, "udp")) {
03644       res |= SIP_TRANSPORT_UDP;
03645    }
03646    if (!strcasecmp(transport, "tcp")) {
03647       res |= SIP_TRANSPORT_TCP;
03648    }
03649    if (!strcasecmp(transport, "tls")) {
03650       res |= SIP_TRANSPORT_TLS;
03651    }
03652 
03653    return res;
03654 }
03655 
03656 /*! \brief Return configuration of transports for a device */
03657 static inline const char *get_transport_list(unsigned int transports) {
03658    switch (transports) {
03659       case SIP_TRANSPORT_UDP:
03660          return "UDP";
03661       case SIP_TRANSPORT_TCP:
03662          return "TCP";
03663       case SIP_TRANSPORT_TLS:
03664          return "TLS";
03665       case SIP_TRANSPORT_UDP | SIP_TRANSPORT_TCP:
03666          return "TCP,UDP";
03667       case SIP_TRANSPORT_UDP | SIP_TRANSPORT_TLS:
03668          return "TLS,UDP";
03669       case SIP_TRANSPORT_TCP | SIP_TRANSPORT_TLS:
03670          return "TLS,TCP";
03671       default:
03672          return transports ? 
03673             "TLS,TCP,UDP" : "UNKNOWN"; 
03674    }
03675 }
03676 
03677 /*! \brief Return transport as string */
03678 static inline const char *get_transport(enum sip_transport t)
03679 {
03680    switch (t) {
03681    case SIP_TRANSPORT_UDP:
03682       return "UDP";
03683    case SIP_TRANSPORT_TCP:
03684       return "TCP";
03685    case SIP_TRANSPORT_TLS:
03686       return "TLS";
03687    }
03688 
03689    return "UNKNOWN";
03690 }
03691 
03692 /*! \brief Return protocol string for srv dns query */
03693 static inline const char *get_srv_protocol(enum sip_transport t)
03694 {
03695    switch (t) {
03696    case SIP_TRANSPORT_UDP:
03697       return "udp";
03698    case SIP_TRANSPORT_TLS:
03699    case SIP_TRANSPORT_TCP:
03700       return "tcp";
03701    }
03702 
03703    return "udp";
03704 }
03705 
03706 /*! \brief Return service string for srv dns query */
03707 static inline const char *get_srv_service(enum sip_transport t)
03708 {
03709    switch (t) {
03710    case SIP_TRANSPORT_TCP:
03711    case SIP_TRANSPORT_UDP:
03712       return "sip";
03713    case SIP_TRANSPORT_TLS:
03714       return "sips";
03715    }
03716    return "sip";
03717 }
03718 
03719 /*! \brief Return transport of dialog.
03720    \note this is based on a false assumption. We don't always use the
03721    outbound proxy for all requests in a dialog. It depends on the
03722    "force" parameter. The FIRST request is always sent to the ob proxy.
03723    \todo Fix this function to work correctly
03724 */
03725 static inline const char *get_transport_pvt(struct sip_pvt *p)
03726 {
03727    if (p->outboundproxy && p->outboundproxy->transport) {
03728       set_socket_transport(&p->socket, p->outboundproxy->transport);
03729    }
03730 
03731    return get_transport(p->socket.type);
03732 }
03733 
03734 /*! \brief Transmit SIP message 
03735    Sends a SIP request or response on a given socket (in the pvt)
03736    Called by retrans_pkt, send_request, send_response and 
03737    __sip_reliable_xmit
03738 */
03739 static int __sip_xmit(struct sip_pvt *p, struct ast_str *data, int len)
03740 {
03741    int res = 0;
03742    const struct sockaddr_in *dst = sip_real_dst(p);
03743 
03744    ast_debug(2, "Trying to put '%.11s' onto %s socket destined for %s:%d\n", data->str, get_transport_pvt(p), ast_inet_ntoa(dst->sin_addr), htons(dst->sin_port));
03745 
03746    if (sip_prepare_socket(p) < 0)
03747       return XMIT_ERROR;
03748 
03749    if (p->socket.type == SIP_TRANSPORT_UDP) {
03750       res = sendto(p->socket.fd, data->str, len, 0, (const struct sockaddr *)dst, sizeof(struct sockaddr_in));
03751    } else if (p->socket.tcptls_session) {
03752       res = sip_tcptls_write(p->socket.tcptls_session, data->str, len);
03753    } else {
03754       ast_debug(2, "Socket type is TCP but no tcptls_session is present to write to\n");
03755       return XMIT_ERROR;
03756    }
03757 
03758    if (res == -1) {
03759       switch (errno) {
03760       case EBADF:       /* Bad file descriptor - seems like this is generated when the host exist, but doesn't accept the UDP packet */
03761       case EHOSTUNREACH:   /* Host can't be reached */
03762       case ENETDOWN:       /* Inteface down */
03763       case ENETUNREACH: /* Network failure */
03764       case ECONNREFUSED:      /* ICMP port unreachable */ 
03765          res = XMIT_ERROR; /* Don't bother with trying to transmit again */
03766       }
03767    }
03768    if (res != len)
03769       ast_log(LOG_WARNING, "sip_xmit of %p (len %d) to %s:%d returned %d: %s\n", data, len, ast_inet_ntoa(dst->sin_addr), ntohs(dst->sin_port), res, strerror(errno));
03770 
03771    return res;
03772 }
03773 
03774 /*! \brief Build a Via header for a request */
03775 static void build_via(struct sip_pvt *p)
03776 {
03777    /* Work around buggy UNIDEN UIP200 firmware */
03778    const char *rport = ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_RFC3581 ? ";rport" : "";
03779 
03780    /* z9hG4bK is a magic cookie.  See RFC 3261 section 8.1.1.7 */
03781    snprintf(p->via, sizeof(p->via), "SIP/2.0/%s %s:%d;branch=z9hG4bK%08x%s",
03782        get_transport_pvt(p),
03783        ast_inet_ntoa(p->ourip.sin_addr),
03784        ntohs(p->ourip.sin_port), (int) p->branch, rport);
03785 }
03786 
03787 /*! \brief NAT fix - decide which IP address to use for Asterisk server?
03788  *
03789  * Using the localaddr structure built up with localnet statements in sip.conf
03790  * apply it to their address to see if we need to substitute our
03791  * externip or can get away with our internal bindaddr
03792  * 'us' is always overwritten.
03793  */
03794 static void ast_sip_ouraddrfor(struct in_addr *them, struct sockaddr_in *us, struct sip_pvt *p)
03795 {
03796    struct sockaddr_in theirs;
03797    /* Set want_remap to non-zero if we want to remap 'us' to an externally
03798     * reachable IP address and port. This is done if:
03799     * 1. we have a localaddr list (containing 'internal' addresses marked
03800     *    as 'deny', so ast_apply_ha() will return AST_SENSE_DENY on them,
03801     *    and AST_SENSE_ALLOW on 'external' ones);
03802     * 2. either stunaddr or externip is set, so we know what to use as the
03803     *    externally visible address;
03804     * 3. the remote address, 'them', is external;
03805     * 4. the address returned by ast_ouraddrfor() is 'internal' (AST_SENSE_DENY
03806     *    when passed to ast_apply_ha() so it does need to be remapped.
03807     *    This fourth condition is checked later.
03808     */
03809    int want_remap;
03810 
03811    *us = internip;      /* starting guess for the internal address */
03812    /* now ask the system what would it use to talk to 'them' */
03813    ast_ouraddrfor(them, &us->sin_addr);
03814    theirs.sin_addr = *them;
03815 
03816    want_remap = localaddr &&
03817       (externip.sin_addr.s_addr || stunaddr.sin_addr.s_addr) &&
03818       ast_apply_ha(localaddr, &theirs) == AST_SENSE_ALLOW ;
03819 
03820    if (want_remap &&
03821        (!sip_cfg.matchexterniplocally || !ast_apply_ha(localaddr, us)) ) {
03822       /* if we used externhost or stun, see if it is time to refresh the info */
03823       if (externexpire && time(NULL) >= externexpire) {
03824          if (stunaddr.sin_addr.s_addr) {
03825             ast_stun_request(sipsock, &stunaddr, NULL, &externip);
03826          } else {
03827             if (ast_parse_arg(externhost, PARSE_INADDR, &externip))
03828                ast_log(LOG_NOTICE, "Warning: Re-lookup of '%s' failed!\n", externhost);
03829          }
03830          externexpire = time(NULL) + externrefresh;
03831       }
03832       if (externip.sin_addr.s_addr)
03833          *us = externip;
03834       else
03835          ast_log(LOG_WARNING, "stun failed\n");
03836       ast_debug(1, "Target address %s is not local, substituting externip\n", 
03837          ast_inet_ntoa(*(struct in_addr *)&them->s_addr));
03838    } else if (p) {
03839       /* no remapping, but we bind to a specific address, so use it. */
03840       switch (p->socket.type) {
03841       case SIP_TRANSPORT_TCP:
03842          if (sip_tcp_desc.local_address.sin_addr.s_addr) {
03843             *us = sip_tcp_desc.local_address;
03844          } else {
03845             us->sin_port = sip_tcp_desc.local_address.sin_port;
03846          }
03847          break;
03848       case SIP_TRANSPORT_TLS:
03849          if (sip_tls_desc.local_address.sin_addr.s_addr) {
03850             *us = sip_tls_desc.local_address;
03851          } else {
03852             us->sin_port = sip_tls_desc.local_address.sin_port;
03853          }
03854             break;
03855       case SIP_TRANSPORT_UDP:
03856          /* fall through on purpose */
03857       default:
03858          if (bindaddr.sin_addr.s_addr) {
03859             *us = bindaddr;
03860          }
03861       }
03862    } else if (bindaddr.sin_addr.s_addr) {
03863       *us = bindaddr;
03864    }
03865    ast_debug(3, "Setting SIP_TRANSPORT_%s with address %s:%d\n", get_transport(p->socket.type), ast_inet_ntoa(us->sin_addr), ntohs(us->sin_port));
03866 }
03867 
03868 /*! \brief Append to SIP dialog history with arg list  */
03869 static __attribute__((format(printf, 2, 0))) void append_history_va(struct sip_pvt *p, const char *fmt, va_list ap)
03870 {
03871    char buf[80], *c = buf; /* max history length */
03872    struct sip_history *hist;
03873    int l;
03874 
03875    vsnprintf(buf, sizeof(buf), fmt, ap);
03876    strsep(&c, "\r\n"); /* Trim up everything after \r or \n */
03877    l = strlen(buf) + 1;
03878    if (!(hist = ast_calloc(1, sizeof(*hist) + l)))
03879       return;
03880    if (!p->history && !(p->history = ast_calloc(1, sizeof(*p->history)))) {
03881       ast_free(hist);
03882       return;
03883    }
03884    memcpy(hist->event, buf, l);
03885    if (p->history_entries == MAX_HISTORY_ENTRIES) {
03886       struct sip_history *oldest;
03887       oldest = AST_LIST_REMOVE_HEAD(p->history, list);
03888       p->history_entries--;
03889       ast_free(oldest);
03890    }
03891    AST_LIST_INSERT_TAIL(p->history, hist, list);
03892    p->history_entries++;
03893 }
03894 
03895 /*! \brief Append to SIP dialog history with arg list  */
03896 static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
03897 {
03898    va_list ap;
03899 
03900    if (!p)
03901       return;
03902 
03903    if (!p->do_history && !recordhistory && !dumphistory)
03904       return;
03905 
03906    va_start(ap, fmt);
03907    append_history_va(p, fmt, ap);
03908    va_end(ap);
03909 
03910    return;
03911 }
03912 
03913 /*! \brief Retransmit SIP message if no answer (Called from scheduler) */
03914 static int retrans_pkt(const void *data)
03915 {
03916    struct sip_pkt *pkt = (struct sip_pkt *)data, *prev, *cur = NULL;
03917    int reschedule = DEFAULT_RETRANS;
03918    int xmitres = 0;
03919 
03920    /* Lock channel PVT */
03921    sip_pvt_lock(pkt->owner);
03922 
03923    if (pkt->retrans < MAX_RETRANS) {
03924       pkt->retrans++;
03925       if (!pkt->timer_t1) {   /* Re-schedule using timer_a and timer_t1 */
03926          if (sipdebug)
03927             ast_debug(4, "SIP TIMER: Not rescheduling id #%d:%s (Method %d) (No timer T1)\n", pkt->retransid, sip_methods[pkt->method].text, pkt->method);
03928       } else {
03929          int siptimer_a;
03930 
03931          if (sipdebug)
03932             ast_debug(4, "SIP TIMER: Rescheduling retransmission #%d (%d) %s - %d\n", pkt->retransid, pkt->retrans, sip_methods[pkt->method].text, pkt->method);
03933          if (!pkt->timer_a)
03934             pkt->timer_a = 2 ;
03935          else
03936             pkt->timer_a = 2 * pkt->timer_a;
03937 
03938          /* For non-invites, a maximum of 4 secs */
03939          siptimer_a = pkt->timer_t1 * pkt->timer_a;   /* Double each time */
03940          if (pkt->method != SIP_INVITE && siptimer_a > 4000)
03941             siptimer_a = 4000;
03942 
03943          /* Reschedule re-transmit */
03944          reschedule = siptimer_a;
03945          ast_debug(4, "** SIP timers: Rescheduling retransmission %d to %d ms (t1 %d ms (Retrans id #%d)) \n", pkt->retrans +1, siptimer_a, pkt->timer_t1, pkt->retransid);
03946       }
03947 
03948       if (sip_debug_test_pvt(pkt->owner)) {
03949          const struct sockaddr_in *dst = sip_real_dst(pkt->owner);
03950          ast_verbose("Retransmitting #%d (%s) to %s:%d:\n%s\n---\n",
03951             pkt->retrans, sip_nat_mode(pkt->owner),
03952             ast_inet_ntoa(dst->sin_addr),
03953             ntohs(dst->sin_port), pkt->data->str);
03954       }
03955 
03956       append_history(pkt->owner, "ReTx", "%d %s", reschedule, pkt->data->str);
03957       xmitres = __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
03958       if (xmitres == XMIT_ERROR) {
03959          ast_log(LOG_WARNING, "Network error on retransmit in dialog %s\n", pkt->owner->callid);
03960       } else {
03961          sip_pvt_unlock(pkt->owner);
03962          return  reschedule;
03963       }
03964    }
03965    /* Too many retries */
03966    if (pkt->owner && pkt->method != SIP_OPTIONS && xmitres == 0) {
03967       if (pkt->is_fatal || sipdebug)   /* Tell us if it's critical or if we're debugging */
03968          ast_log(LOG_WARNING, "Maximum retries exceeded on transmission %s for seqno %d (%s %s) -- See https://wiki.asterisk.org/wiki/display/AST/SIP+Retransmissions \n",
03969             pkt->owner->callid, pkt->seqno,
03970             pkt->is_fatal ? "Critical" : "Non-critical", pkt->is_resp ? "Response" : "Request");
03971    } else if (pkt->method == SIP_OPTIONS && sipdebug) {
03972          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);
03973 
03974    }
03975    if (xmitres == XMIT_ERROR) {
03976       ast_log(LOG_WARNING, "Transmit error :: Cancelling transmission on Call ID %s\n", pkt->owner->callid);
03977       append_history(pkt->owner, "XmitErr", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
03978    } else {
03979       append_history(pkt->owner, "MaxRetries", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
03980    }
03981    pkt->retransid = -1;
03982 
03983    if (pkt->is_fatal) {
03984       while(pkt->owner->owner && ast_channel_trylock(pkt->owner->owner)) {
03985          sip_pvt_unlock(pkt->owner);   /* SIP_PVT, not channel */
03986          usleep(1);
03987          sip_pvt_lock(pkt->owner);
03988       }
03989 
03990       if (pkt->owner->owner && !pkt->owner->owner->hangupcause)
03991          pkt->owner->owner->hangupcause = AST_CAUSE_NO_USER_RESPONSE;
03992 
03993       if (pkt->owner->owner) {
03994          sip_alreadygone(pkt->owner);
03995          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);
03996          ast_queue_hangup_with_cause(pkt->owner->owner, AST_CAUSE_PROTOCOL_ERROR);
03997          ast_channel_unlock(pkt->owner->owner);
03998       } else {
03999          /* If no channel owner, destroy now */
04000 
04001          /* Let the peerpoke system expire packets when the timer expires for poke_noanswer */
04002          if (pkt->method != SIP_OPTIONS && pkt->method != SIP_REGISTER) {
04003             pvt_set_needdestroy(pkt->owner, "no response to critical packet");
04004             sip_alreadygone(pkt->owner);
04005             append_history(pkt->owner, "DialogKill", "Killing this failed dialog immediately");
04006          }
04007       }
04008    }
04009 
04010    if (pkt->method == SIP_BYE) {
04011       /* We're not getting answers on SIP BYE's.  Tear down the call anyway. */
04012       sip_alreadygone(pkt->owner);
04013       if (pkt->owner->owner)
04014          ast_channel_unlock(pkt->owner->owner);
04015       append_history(pkt->owner, "ByeFailure", "Remote peer doesn't respond to bye. Destroying call anyway.");
04016       pvt_set_needdestroy(pkt->owner, "no response to BYE");
04017    }
04018 
04019    /* Remove the packet */
04020    for (prev = NULL, cur = pkt->owner->packets; cur; prev = cur, cur = cur->next) {
04021       if (cur == pkt) {
04022          UNLINK(cur, pkt->owner->packets, prev);
04023          sip_pvt_unlock(pkt->owner);
04024          if (pkt->owner)
04025             pkt->owner = dialog_unref(pkt->owner,"pkt is being freed, its dialog ref is dead now");
04026          if (pkt->data)
04027             ast_free(pkt->data);
04028          pkt->data = NULL;
04029          ast_free(pkt);
04030          return 0;
04031       }
04032    }
04033    /* error case */
04034    ast_log(LOG_WARNING, "Weird, couldn't find packet owner!\n");
04035    sip_pvt_unlock(pkt->owner);
04036    return 0;
04037 }
04038 
04039 /*! \brief Transmit packet with retransmits 
04040    \return 0 on success, -1 on failure to allocate packet 
04041 */
04042 static enum sip_result __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, struct ast_str *data, int len, int fatal, int sipmethod)
04043 {
04044    struct sip_pkt *pkt = NULL;
04045    int siptimer_a = DEFAULT_RETRANS;
04046    int xmitres = 0;
04047    int respid;
04048 
04049    if (sipmethod == SIP_INVITE) {
04050       /* Note this is a pending invite */
04051       p->pendinginvite = seqno;
04052    }
04053 
04054    /* If the transport is something reliable (TCP or TLS) then don't really send this reliably */
04055    /* I removed the code from retrans_pkt that does the same thing so it doesn't get loaded into the scheduler */
04056    /*! \todo According to the RFC some packets need to be retransmitted even if its TCP, so this needs to get revisited */
04057    if (!(p->socket.type & SIP_TRANSPORT_UDP)) {
04058       xmitres = __sip_xmit(p, data, len); /* Send packet */
04059       if (xmitres == XMIT_ERROR) {  /* Serious network trouble, no need to try again */
04060          append_history(p, "XmitErr", "%s", fatal ? "(Critical)" : "(Non-critical)");
04061          return AST_FAILURE;
04062       } else {
04063          return AST_SUCCESS;
04064       }
04065    }
04066 
04067    if (!(pkt = ast_calloc(1, sizeof(*pkt) + len + 1)))
04068       return AST_FAILURE;
04069    /* copy data, add a terminator and save length */
04070    if (!(pkt->data = ast_str_create(len))) {
04071       ast_free(pkt);
04072       return AST_FAILURE;
04073    }
04074    ast_str_set(&pkt->data, 0, "%s%s", data->str, "\0");
04075    pkt->packetlen = len;
04076    /* copy other parameters from the caller */
04077    pkt->method = sipmethod;
04078    pkt->seqno = seqno;
04079    pkt->is_resp = resp;
04080    pkt->is_fatal = fatal;
04081    pkt->owner = dialog_ref(p, "__sip_reliable_xmit: setting pkt->owner");
04082    pkt->next = p->packets;
04083    p->packets = pkt; /* Add it to the queue */
04084    if (resp) {
04085       /* Parse out the response code */
04086       if (sscanf(ast_str_buffer(pkt->data), "SIP/2.0 %30u", &respid) == 1) {
04087          pkt->response_code = respid;
04088       }
04089    }
04090    pkt->timer_t1 = p->timer_t1;  /* Set SIP timer T1 */
04091    pkt->retransid = -1;
04092    if (pkt->timer_t1)
04093       siptimer_a = pkt->timer_t1 * 2;
04094 
04095    /* Schedule retransmission */
04096    AST_SCHED_REPLACE_VARIABLE(pkt->retransid, sched, siptimer_a, retrans_pkt, pkt, 1);
04097    if (sipdebug)
04098       ast_debug(4, "*** SIP TIMER: Initializing retransmit timer on packet: Id  #%d\n", pkt->retransid);
04099 
04100    xmitres = __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);   /* Send packet */
04101 
04102    if (xmitres == XMIT_ERROR) {  /* Serious network trouble, no need to try again */
04103       append_history(pkt->owner, "XmitErr", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
04104       ast_log(LOG_ERROR, "Serious Network Trouble; __sip_xmit returns error for pkt data\n");
04105       AST_SCHED_DEL(sched, pkt->retransid);
04106       p->packets = pkt->next;
04107       pkt->owner = dialog_unref(pkt->owner,"pkt is being freed, its dialog ref is dead now");
04108       ast_free(pkt->data);
04109       ast_free(pkt);
04110       return AST_FAILURE;
04111    } else {
04112       return AST_SUCCESS;
04113    }
04114 }
04115 
04116 /*! \brief Kill a SIP dialog (called only by the scheduler)
04117  * The scheduler has a reference to this dialog when p->autokillid != -1,
04118  * and we are called using that reference. So if the event is not
04119  * rescheduled, we need to call dialog_unref().
04120  */
04121 static int __sip_autodestruct(const void *data)
04122 {
04123    struct sip_pvt *p = (struct sip_pvt *)data;
04124 
04125    /* If this is a subscription, tell the phone that we got a timeout */
04126    if (p->subscribed) {
04127       transmit_state_notify(p, AST_EXTENSION_DEACTIVATED, 1, TRUE);  /* Send last notification */
04128       p->subscribed = NONE;
04129       append_history(p, "Subscribestatus", "timeout");
04130       ast_debug(3, "Re-scheduled destruction of SIP subscription %s\n", p->callid ? p->callid : "<unknown>");
04131       return 10000;  /* Reschedule this destruction so that we know that it's gone */
04132    }
04133 
04134    /* If there are packets still waiting for delivery, delay the destruction */
04135    if (p->packets) {
04136       if (!p->needdestroy) {
04137          char method_str[31];
04138          ast_debug(3, "Re-scheduled destruction of SIP call %s\n", p->callid ? p->callid : "<unknown>");
04139          append_history(p, "ReliableXmit", "timeout");
04140          if (sscanf(p->lastmsg, "Tx: %30s", method_str) == 1 || sscanf(p->lastmsg, "Rx: %30s", method_str) == 1) {
04141             if (method_match(SIP_CANCEL, method_str) || method_match(SIP_BYE, method_str)) {
04142                pvt_set_needdestroy(p, "autodestruct");
04143             }
04144          }
04145          return 10000;
04146       } else {
04147          /* They've had their chance to respond. Time to bail */
04148          __sip_pretend_ack(p);
04149       }
04150    }
04151 
04152    /* Reset schedule ID */
04153    p->autokillid = -1;
04154 
04155 
04156    /*
04157     * Lock both the pvt and the channel safely so that we can queue up a frame.
04158     */
04159    sip_pvt_lock(p);
04160    while (p->owner && ast_channel_trylock(p->owner)) {
04161       sip_pvt_unlock(p);
04162       sched_yield();
04163       sip_pvt_lock(p);
04164    }
04165 
04166    if (p->owner) {
04167       ast_log(LOG_WARNING, "Autodestruct on dialog '%s' with owner in place (Method: %s)\n", p->callid, sip_methods[p->method].text);
04168       ast_queue_hangup_with_cause(p->owner, AST_CAUSE_PROTOCOL_ERROR);
04169       ast_channel_unlock(p->owner);
04170    } else if (p->refer && !p->alreadygone) {
04171       ast_debug(3, "Finally hanging up channel after transfer: %s\n", p->callid);
04172       transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
04173       append_history(p, "ReferBYE", "Sending BYE on transferer call leg %s", p->callid);
04174       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
04175    } else {
04176       append_history(p, "AutoDestroy", "%s", p->callid);
04177       ast_debug(3, "Auto destroying SIP dialog '%s'\n", p->callid);
04178       dialog_unlink_all(p, TRUE, TRUE); /* once it's unlinked and unrefd everywhere, it'll be freed automagically */
04179       /* dialog_unref(p, "unref dialog-- no other matching conditions"); -- unlink all now should finish off the dialog's references and free it. */
04180       /* sip_destroy(p); */      /* Go ahead and destroy dialog. All attempts to recover is done */
04181       /* sip_destroy also absorbs the reference */
04182    }
04183 
04184    sip_pvt_unlock(p);
04185 
04186    dialog_unref(p, "The ref to a dialog passed to this sched callback is going out of scope; unref it.");
04187 
04188    return 0;
04189 }
04190 
04191 /*! \brief Schedule destruction of SIP dialog */
04192 static void sip_scheddestroy(struct sip_pvt *p, int ms)
04193 {
04194    if (ms < 0) {
04195       if (p->timer_t1 == 0) {
04196          p->timer_t1 = global_t1;   /* Set timer T1 if not set (RFC 3261) */
04197          p->timer_b = global_timer_b;  /* Set timer B if not set (RFC 3261) */
04198       }
04199       ms = p->timer_t1 * 64;
04200    }
04201    if (sip_debug_test_pvt(p))
04202       ast_verbose("Scheduling destruction of SIP dialog '%s' in %d ms (Method: %s)\n", p->callid, ms, sip_methods[p->method].text);
04203    if (sip_cancel_destroy(p))
04204       ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
04205 
04206    if (p->do_history)
04207       append_history(p, "SchedDestroy", "%d ms", ms);
04208    p->autokillid = ast_sched_add(sched, ms, __sip_autodestruct, dialog_ref(p, "setting ref as passing into ast_sched_add for __sip_autodestruct"));
04209 
04210    if (p->stimer && p->stimer->st_active == TRUE && p->stimer->st_schedid > 0)
04211       stop_session_timer(p);
04212 }
04213 
04214 /*! \brief Cancel destruction of SIP dialog.
04215  * Be careful as this also absorbs the reference - if you call it
04216  * from within the scheduler, this might be the last reference.
04217  */
04218 static int sip_cancel_destroy(struct sip_pvt *p)
04219 {
04220    int res = 0;
04221    if (p->autokillid > -1) {
04222       int res3;
04223 
04224       if (!(res3 = ast_sched_del(sched, p->autokillid))) {
04225          append_history(p, "CancelDestroy", "");
04226          p->autokillid = -1;
04227          dialog_unref(p, "dialog unrefd because autokillid is de-sched'd");
04228       }
04229    }
04230    return res;
04231 }
04232 
04233 /*! \brief Acknowledges receipt of a packet and stops retransmission 
04234  * called with p locked*/
04235 static int __sip_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod)
04236 {
04237    struct sip_pkt *cur, *prev = NULL;
04238    const char *msg = "Not Found";   /* used only for debugging */
04239    int res = FALSE;
04240 
04241    /* If we have an outbound proxy for this dialog, then delete it now since
04242      the rest of the requests in this dialog needs to follow the routing.
04243      If obforcing is set, we will keep the outbound proxy during the whole
04244      dialog, regardless of what the SIP rfc says
04245    */
04246    if (p->outboundproxy && !p->outboundproxy->force){
04247       ref_proxy(p, NULL);
04248    }
04249 
04250    for (cur = p->packets; cur; prev = cur, cur = cur->next) {
04251       if (cur->seqno != seqno || cur->is_resp != resp)
04252          continue;
04253       if (cur->is_resp || cur->method == sipmethod) {
04254          res = TRUE;
04255          msg = "Found";
04256          if (!resp && (seqno == p->pendinginvite)) {
04257             ast_debug(1, "Acked pending invite %d\n", p->pendinginvite);
04258             p->pendinginvite = 0;
04259          }
04260          if (cur->retransid > -1) {
04261             if (sipdebug)
04262                ast_debug(4, "** SIP TIMER: Cancelling retransmit of packet (reply received) Retransid #%d\n", cur->retransid);
04263          }
04264          /* This odd section is designed to thwart a 
04265           * race condition in the packet scheduler. There are
04266           * two conditions under which deleting the packet from the
04267           * scheduler can fail.
04268           *
04269           * 1. The packet has been removed from the scheduler because retransmission
04270           * is being attempted. The problem is that if the packet is currently attempting
04271           * retransmission and we are at this point in the code, then that MUST mean
04272           * that retrans_pkt is waiting on p's lock. Therefore we will relinquish the
04273           * lock temporarily to allow retransmission.
04274           *
04275           * 2. The packet has reached its maximum number of retransmissions and has
04276           * been permanently removed from the packet scheduler. If this is the case, then
04277           * the packet's retransid will be set to -1. The atomicity of the setting and checking
04278           * of the retransid to -1 is ensured since in both cases p's lock is held.
04279           */
04280          while (cur->retransid > -1 && ast_sched_del(sched, cur->retransid)) {
04281             sip_pvt_unlock(p);
04282             usleep(1);
04283             sip_pvt_lock(p);
04284          }
04285          UNLINK(cur, p->packets, prev);
04286          dialog_unref(cur->owner, "unref pkt cur->owner dialog from sip ack before freeing pkt");
04287          if (cur->data)
04288             ast_free(cur->data);
04289          ast_free(cur);
04290          break;
04291       }
04292    }
04293    ast_debug(1, "Stopping retransmission on '%s' of %s %d: Match %s\n",
04294       p->callid, resp ? "Response" : "Request", seqno, msg);
04295    return res;
04296 }
04297 
04298 /*! \brief Pretend to ack all packets
04299  * called with p locked */
04300 static void __sip_pretend_ack(struct sip_pvt *p)
04301 {
04302    struct sip_pkt *cur = NULL;
04303 
04304    while (p->packets) {
04305       int method;
04306       if (cur == p->packets) {
04307          ast_log(LOG_WARNING, "Have a packet that doesn't want to give up! %s\n", sip_methods[cur->method].text);
04308          return;
04309       }
04310       cur = p->packets;
04311       method = (cur->method) ? cur->method : find_sip_method(cur->data->str);
04312       __sip_ack(p, cur->seqno, cur->is_resp, method);
04313    }
04314 }
04315 
04316 /*! \brief Acks receipt of packet, keep it around (used for provisional responses) */
04317 static int __sip_semi_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod)
04318 {
04319    struct sip_pkt *cur;
04320    int res = FALSE;
04321 
04322    for (cur = p->packets; cur; cur = cur->next) {
04323       if (cur->seqno == seqno && cur->is_resp == resp &&
04324          (cur->is_resp || method_match(sipmethod, cur->data->str))) {
04325          /* this is our baby */
04326          if (cur->retransid > -1) {
04327             if (sipdebug)
04328                ast_debug(4, "*** SIP TIMER: Cancelling retransmission #%d - %s (got response)\n", cur->retransid, sip_methods[sipmethod].text);
04329          }
04330          AST_SCHED_DEL(sched, cur->retransid);
04331          res = TRUE;
04332          break;
04333       }
04334    }
04335    ast_debug(1, "(Provisional) Stopping retransmission (but retaining packet) on '%s' %s %d: %s\n", p->callid, resp ? "Response" : "Request", seqno, res == -1 ? "Not Found" : "Found");
04336    return res;
04337 }
04338 
04339 
04340 /*! \brief Copy SIP request, parse it */
04341 static void parse_copy(struct sip_request *dst, const struct sip_request *src)
04342 {
04343    copy_request(dst, src);
04344    parse_request(dst);
04345 }
04346 
04347 /*! \brief add a blank line if no body */
04348 static void add_blank(struct sip_request *req)
04349 {
04350    if (!req->lines) {
04351       /* Add extra empty return. add_header() reserves 4 bytes so cannot be truncated */
04352       ast_str_append(&req->data, 0, "\r\n");
04353       req->len = ast_str_strlen(req->data);
04354    }
04355 }
04356 
04357 static int send_provisional_keepalive_full(struct sip_pvt *pvt, int with_sdp)
04358 {
04359    const char *msg = NULL;
04360 
04361    if (!pvt->last_provisional || !strncasecmp(pvt->last_provisional, "100", 3)) {
04362       msg = "183 Session Progress";
04363    }
04364 
04365    if (pvt->invitestate < INV_COMPLETED) {
04366       if (with_sdp) {
04367          transmit_response_with_sdp(pvt, S_OR(msg, pvt->last_provisional), &pvt->initreq, XMIT_UNRELIABLE, FALSE);
04368       } else {
04369          transmit_response(pvt, S_OR(msg, pvt->last_provisional), &pvt->initreq);
04370       }
04371       return PROVIS_KEEPALIVE_TIMEOUT;
04372    }
04373 
04374    return 0;
04375 }
04376 
04377 static int send_provisional_keepalive(const void *data) {
04378    struct sip_pvt *pvt = (struct sip_pvt *) data;
04379 
04380    return send_provisional_keepalive_full(pvt, 0);
04381 }
04382 
04383 static int send_provisional_keepalive_with_sdp(const void *data) {
04384    struct sip_pvt *pvt = (void *)data;
04385 
04386    return send_provisional_keepalive_full(pvt, 1);
04387 }
04388 
04389 static void update_provisional_keepalive(struct sip_pvt *pvt, int with_sdp)
04390 {
04391    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"));
04392 
04393    pvt->provisional_keepalive_sched_id = ast_sched_add(sched, PROVIS_KEEPALIVE_TIMEOUT,
04394       with_sdp ? send_provisional_keepalive_with_sdp : send_provisional_keepalive, dialog_ref(pvt, "Increment refcount to pass dialog pointer to sched callback"));
04395 }
04396 
04397 /*! \brief Transmit response on SIP request*/
04398 static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno)
04399 {
04400    int res;
04401 
04402    finalize_content(req);
04403    add_blank(req);
04404    if (sip_debug_test_pvt(p)) {
04405       const struct sockaddr_in *dst = sip_real_dst(p);
04406 
04407       ast_verbose("\n<--- %sTransmitting (%s) to %s:%d --->\n%s\n<------------>\n",
04408          reliable ? "Reliably " : "", sip_nat_mode(p),
04409          ast_inet_ntoa(dst->sin_addr),
04410          ntohs(dst->sin_port), req->data->str);
04411    }
04412    if (p->do_history) {
04413       struct sip_request tmp = { .rlPart1 = 0, };
04414       parse_copy(&tmp, req);
04415       append_history(p, reliable ? "TxRespRel" : "TxResp", "%s / %s - %s", tmp.data->str, get_header(&tmp, "CSeq"), 
04416          (tmp.method == SIP_RESPONSE || tmp.method == SIP_UNKNOWN) ? REQ_OFFSET_TO_STR(&tmp, rlPart2) : sip_methods[tmp.method].text);
04417       deinit_req(&tmp);
04418    }
04419 
04420    /* If we are sending a final response to an INVITE, stop retransmitting provisional responses */
04421    if (p->initreq.method == SIP_INVITE && reliable == XMIT_CRITICAL) {
04422       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"));
04423    }
04424 
04425    res = (reliable) ?
04426        __sip_reliable_xmit(p, seqno, 1, req->data, req->len, (reliable == XMIT_CRITICAL), req->method) :
04427       __sip_xmit(p, req->data, req->len);
04428    deinit_req(req);
04429    if (res > 0)
04430       return 0;
04431    return res;
04432 }
04433 
04434 /*! \brief Send SIP Request to the other part of the dialogue */
04435 static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno)
04436 {
04437    int res;
04438 
04439    /* If we have an outbound proxy, reset peer address 
04440       Only do this once.
04441    */
04442    if (p->outboundproxy) {
04443       p->sa = p->outboundproxy->ip;
04444    }
04445 
04446    finalize_content(req);
04447    add_blank(req);
04448    if (sip_debug_test_pvt(p)) {
04449       if (ast_test_flag(&p->flags[0], SIP_NAT_ROUTE))
04450          ast_verbose("%sTransmitting (NAT) to %s:%d:\n%s\n---\n", reliable ? "Reliably " : "", ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port), req->data->str);
04451       else
04452          ast_verbose("%sTransmitting (no NAT) to %s:%d:\n%s\n---\n", reliable ? "Reliably " : "", ast_inet_ntoa(p->sa.sin_addr), ntohs(p->sa.sin_port), req->data->str);
04453    }
04454    if (p->do_history) {
04455       struct sip_request tmp = { .rlPart1 = 0, };
04456       parse_copy(&tmp, req);
04457       append_history(p, reliable ? "TxReqRel" : "TxReq", "%s / %s - %s", tmp.data->str, get_header(&tmp, "CSeq"), sip_methods[tmp.method].text);
04458       deinit_req(&tmp);
04459    }
04460    res = (reliable) ?
04461       __sip_reliable_xmit(p, seqno, 0, req->data, req->len, (reliable == XMIT_CRITICAL), req->method) :
04462       __sip_xmit(p, req->data, req->len);
04463    deinit_req(req);
04464    return res;
04465 }
04466 
04467 /*! \brief Query an option on a SIP dialog */
04468 static int sip_queryoption(struct ast_channel *chan, int option, void *data, int *datalen)
04469 {
04470    int res = -1;
04471    enum ast_t38_state state = T38_STATE_UNAVAILABLE;
04472    struct sip_pvt *p = (struct sip_pvt *) chan->tech_pvt;
04473 
04474    switch (option) {
04475    case AST_OPTION_T38_STATE:
04476       /* Make sure we got an ast_t38_state enum passed in */
04477       if (*datalen != sizeof(enum ast_t38_state)) {
04478          ast_log(LOG_ERROR, "Invalid datalen for AST_OPTION_T38_STATE option. Expected %d, got %d\n", (int)sizeof(enum ast_t38_state), *datalen);
04479          return -1;
04480       }
04481 
04482       sip_pvt_lock(p);
04483 
04484       /* 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 */
04485       if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT)) {
04486          switch (p->t38.state) {
04487          case T38_LOCAL_REINVITE:
04488          case T38_PEER_REINVITE:
04489             state = T38_STATE_NEGOTIATING;
04490             break;
04491          case T38_ENABLED:
04492             state = T38_STATE_NEGOTIATED;
04493             break;
04494          default:
04495             state = T38_STATE_UNKNOWN;
04496          }
04497       }
04498 
04499       sip_pvt_unlock(p);
04500 
04501       *((enum ast_t38_state *) data) = state;
04502       res = 0;
04503 
04504       break;
04505    default:
04506       break;
04507    }
04508 
04509    return res;
04510 }
04511 
04512 /*! \brief Locate closing quote in a string, skipping escaped quotes.
04513  * optionally with a limit on the search.
04514  * start must be past the first quote.
04515  */
04516 static const char *find_closing_quote(const char *start, const char *lim)
04517 {
04518    char last_char = '\0';
04519    const char *s;
04520    for (s = start; *s && s != lim; last_char = *s++) {
04521       if (*s == '"' && last_char != '\\')
04522          break;
04523    }
04524    return s;
04525 }
04526 
04527 /*! \brief Pick out text in brackets from character string
04528    \return pointer to terminated stripped string
04529    \param tmp input string that will be modified
04530    Examples:
04531 \verbatim
04532    "foo" <bar> valid input, returns bar
04533    foo      returns the whole string
04534    < "foo ... >   returns the string between brackets
04535    < "foo...   bogus (missing closing bracket), returns the whole string
04536          XXX maybe should still skip the opening bracket
04537 \endverbatim
04538  */
04539 static char *get_in_brackets(char *tmp)
04540 {
04541    const char *parse = tmp;
04542    char *first_bracket;
04543 
04544    /*
04545     * Skip any quoted text until we find the part in brackets.
04546    * On any error give up and return the full string.
04547    */
04548    while ( (first_bracket = strchr(parse, '<')) ) {
04549       char *first_quote = strchr(parse, '"');
04550 
04551       if (!first_quote || first_quote > first_bracket)
04552          break; /* no need to look at quoted part */
04553       /* the bracket is within quotes, so ignore it */
04554       parse = find_closing_quote(first_quote + 1, NULL);
04555       if (!*parse) { /* not found, return full string ? */
04556          /* XXX or be robust and return in-bracket part ? */
04557          ast_log(LOG_WARNING, "No closing quote found in '%s'\n", tmp);
04558          break;
04559       }
04560       parse++;
04561    }
04562    if (first_bracket) {
04563       char *second_bracket = strchr(first_bracket + 1, '>');
04564       if (second_bracket) {
04565          *second_bracket = '\0';
04566          tmp = first_bracket + 1;
04567       } else {
04568          ast_log(LOG_WARNING, "No closing bracket found in '%s'\n", tmp);
04569       }
04570    }
04571    
04572    return tmp;
04573 }
04574 
04575 /*! \brief * parses a URI in its components.
04576  *
04577  * \note 
04578  * - If scheme is specified, drop it from the top.
04579  * - If a component is not requested, do not split around it.
04580  * - Multiple scheme's can be specified ',' delimited. ex: "sip:,sips:"
04581  *
04582  * This means that if we don't have domain, we cannot split
04583  * name:pass and domain:port.
04584  * It is safe to call with ret_name, pass, domain, port
04585  * pointing all to the same place.
04586  * Init pointers to empty string so we never get NULL dereferencing.
04587  * Overwrites the string.
04588  * return 0 on success, other values on error.
04589  * \verbatim 
04590  * general form we are expecting is sip[s]:username[:password][;parameter]@host[:port][;...] 
04591  * \endverbatim
04592  * 
04593  */
04594 static int parse_uri(char *uri, const char *scheme,
04595    char **ret_name, char **pass, char **domain, char **port, char **options, char **transport)
04596 {
04597    char *name = NULL;
04598    int error = 0;
04599 
04600    /* init field as required */
04601    if (pass)
04602       *pass = "";
04603    if (port)
04604       *port = "";
04605    if (scheme) {
04606       int l;
04607       char *scheme2 = ast_strdupa(scheme);
04608       char *cur = strsep(&scheme2, ",");
04609       for (; !ast_strlen_zero(cur); cur = strsep(&scheme2, ",")) {
04610          l = strlen(cur);
04611          if (!strncasecmp(uri, cur, l)) {
04612             uri += l;
04613             break;
04614          }
04615       }
04616       if (ast_strlen_zero(cur)) {
04617          ast_debug(1, "No supported scheme found in '%s' using the scheme[s] %s\n", uri, scheme);
04618          error = -1;
04619       }
04620    }
04621    if (transport) {
04622       char *t, *type = "";
04623       *transport = "";
04624       if ((t = strstr(uri, "transport="))) {
04625          strsep(&t, "=");
04626          if ((type = strsep(&t, ";"))) {
04627             *transport = type;
04628          }
04629       }
04630    }
04631 
04632    if (!domain) {
04633       /* if we don't want to split around domain, keep everything as a name,
04634        * so we need to do nothing here, except remember why.
04635        */
04636    } else {
04637       /* store the result in a temp. variable to avoid it being
04638        * overwritten if arguments point to the same place.
04639        */
04640       char *c, *dom = "";
04641 
04642       if ((c = strchr(uri, '@')) == NULL) {
04643          /* domain-only URI, according to the SIP RFC. */
04644          dom = uri;
04645          name = "";
04646       } else {
04647          *c++ = '\0';
04648          dom = c;
04649          name = uri;
04650       }
04651 
04652       /* Remove options in domain and name */
04653       dom = strsep(&dom, ";");
04654       name = strsep(&name, ";");
04655 
04656       if (port && (c = strchr(dom, ':'))) { /* Remove :port */
04657          *c++ = '\0';
04658          *port = c;
04659       }
04660       if (pass && (c = strchr(name, ':'))) { /* user:password */
04661          *c++ = '\0';
04662          *pass = c;
04663       }
04664       *domain = dom;
04665    }
04666    if (ret_name)  /* same as for domain, store the result only at the end */
04667       *ret_name = name;
04668    if (options)
04669       *options = uri ? uri : "";
04670 
04671    return error;
04672 }
04673 
04674 /*! \brief Send message with Access-URL header, if this is an HTML URL only! */
04675 static int sip_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen)
04676 {
04677    struct sip_pvt *p = chan->tech_pvt;
04678 
04679    if (subclass != AST_HTML_URL)
04680       return -1;
04681 
04682    ast_string_field_build(p, url, "<%s>;mode=active", data);
04683 
04684    if (sip_debug_test_pvt(p))
04685       ast_debug(1, "Send URL %s, state = %d!\n", data, chan->_state);
04686 
04687    switch (chan->_state) {
04688    case AST_STATE_RING:
04689       transmit_response(p, "100 Trying", &p->initreq);
04690       break;
04691    case AST_STATE_RINGING:
04692       transmit_response(p, "180 Ringing", &p->initreq);
04693       break;
04694    case AST_STATE_UP:
04695       if (!p->pendinginvite) {      /* We are up, and have no outstanding invite */
04696          transmit_reinvite_with_sdp(p, FALSE, FALSE);
04697       } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
04698          ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);   
04699       }  
04700       break;
04701    default:
04702       ast_log(LOG_WARNING, "Don't know how to send URI when state is %d!\n", chan->_state);
04703    }
04704 
04705    return 0;
04706 }
04707 
04708 /*! \brief Deliver SIP call ID for the call */
04709 static const char *sip_get_callid(struct ast_channel *chan)
04710 {
04711    return chan->tech_pvt ? ((struct sip_pvt *) chan->tech_pvt)->callid : "";
04712 }
04713 
04714 /*! \brief Send SIP MESSAGE text within a call
04715    Called from PBX core sendtext() application */
04716 static int sip_sendtext(struct ast_channel *ast, const char *text)
04717 {
04718    struct sip_pvt *p = ast->tech_pvt;
04719    int debug = sip_debug_test_pvt(p);
04720 
04721    if (debug)
04722       ast_verbose("Sending text %s on %s\n", text, ast->name);
04723    if (!p)
04724       return -1;
04725    /* NOT ast_strlen_zero, because a zero-length message is specifically
04726     * allowed by RFC 3428 (See section 10, Examples) */
04727    if (!text)
04728       return 0;
04729    if (debug)
04730       ast_verbose("Really sending text %s on %s\n", text, ast->name);
04731    transmit_message_with_text(p, text);
04732    return 0;   
04733 }
04734 
04735 /*! \brief Update peer object in realtime storage 
04736    If the Asterisk system name is set in asterisk.conf, we will use
04737    that name and store that in the "regserver" field in the sippeers
04738    table to facilitate multi-server setups.
04739 */
04740 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, const char *defaultuser, const char *fullcontact, const char *useragent, int expirey, int deprecated_username, int lastms)
04741 {
04742    char port[10];
04743    char ipaddr[INET_ADDRSTRLEN];
04744    char regseconds[20];
04745    char *tablename = NULL;
04746    char str_lastms[20];
04747 
04748    const char *sysname = ast_config_AST_SYSTEM_NAME;
04749    char *syslabel = NULL;
04750 
04751    time_t nowtime = time(NULL) + expirey;
04752    const char *fc = fullcontact ? "fullcontact" : NULL;
04753 
04754    int realtimeregs = ast_check_realtime("sipregs");
04755 
04756    tablename = realtimeregs ? "sipregs" : "sippeers";
04757    
04758 
04759    snprintf(str_lastms, sizeof(str_lastms), "%d", lastms);
04760    snprintf(regseconds, sizeof(regseconds), "%d", (int)nowtime);  /* Expiration time */
04761    ast_copy_string(ipaddr, ast_inet_ntoa(sin->sin_addr), sizeof(ipaddr));
04762    snprintf(port, sizeof(port), "%d", ntohs(sin->sin_port));
04763    
04764    if (ast_strlen_zero(sysname)) /* No system name, disable this */
04765       sysname = NULL;
04766    else if (sip_cfg.rtsave_sysname)
04767       syslabel = "regserver";
04768 
04769    /* XXX IMPORTANT: Anytime you add a new parameter to be updated, you
04770          *  must also add it to contrib/scripts/asterisk.ldap-schema,
04771          *  contrib/scripts/asterisk.ldif,
04772          *  and to configs/res_ldap.conf.sample as described in
04773          *  bugs 15156 and 15895 
04774          */
04775    if (fc) {
04776       ast_update_realtime(tablename, "name", peername, "ipaddr", ipaddr,
04777          "port", port, "regseconds", regseconds,
04778          deprecated_username ? "username" : "defaultuser", defaultuser,
04779          "useragent", useragent, "lastms", str_lastms,
04780          fc, fullcontact, syslabel, sysname, SENTINEL); /* note fc and syslabel _can_ be NULL */
04781    } else {
04782       ast_update_realtime(tablename, "name", peername, "ipaddr", ipaddr,
04783          "port", port, "regseconds", regseconds,
04784          "useragent", useragent, "lastms", str_lastms,
04785          deprecated_username ? "username" : "defaultuser", defaultuser,
04786          syslabel, sysname, SENTINEL); /* note syslabel _can_ be NULL */
04787    }
04788 }
04789 
04790 /*! \brief Automatically add peer extension to dial plan */
04791 static void register_peer_exten(struct sip_peer *peer, int onoff)
04792 {
04793    char multi[256];
04794    char *stringp, *ext, *context;
04795    struct pbx_find_info q = { .stacklen = 0 };
04796 
04797    /* XXX note that global_regcontext is both a global 'enable' flag and
04798     * the name of the global regexten context, if not specified
04799     * individually.
04800     */
04801    if (ast_strlen_zero(global_regcontext))
04802       return;
04803 
04804    ast_copy_string(multi, S_OR(peer->regexten, peer->name), sizeof(multi));
04805    stringp = multi;
04806    while ((ext = strsep(&stringp, "&"))) {
04807       if ((context = strchr(ext, '@'))) {
04808          *context++ = '\0';   /* split ext@context */
04809          if (!ast_context_find(context)) {
04810             ast_log(LOG_WARNING, "Context %s must exist in regcontext= in sip.conf!\n", context);
04811             continue;
04812          }
04813       } else {
04814          context = global_regcontext;
04815       }
04816       if (onoff) {
04817          if (!ast_exists_extension(NULL, context, ext, 1, NULL)) {
04818             ast_add_extension(context, 1, ext, 1, NULL, NULL, "Noop",
04819                 ast_strdup(peer->name), ast_free_ptr, "SIP");
04820          }
04821       } else if (pbx_find_extension(NULL, NULL, &q, context, ext, 1, NULL, "", E_MATCH)) {
04822          ast_context_remove_extension(context, ext, 1, NULL);
04823       }
04824    }
04825 }
04826 
04827 /*! Destroy mailbox subscriptions */
04828 static void destroy_mailbox(struct sip_mailbox *mailbox)
04829 {
04830    if (mailbox->mailbox)
04831       ast_free(mailbox->mailbox);
04832    if (mailbox->context)
04833       ast_free(mailbox->context);
04834    if (mailbox->event_sub)
04835       ast_event_unsubscribe(mailbox->event_sub);
04836    ast_free(mailbox);
04837 }
04838 
04839 /*! Destroy all peer-related mailbox subscriptions */
04840 static void clear_peer_mailboxes(struct sip_peer *peer)
04841 {
04842    struct sip_mailbox *mailbox;
04843 
04844    while ((mailbox = AST_LIST_REMOVE_HEAD(&peer->mailboxes, entry)))
04845       destroy_mailbox(mailbox);
04846 }
04847 
04848 static void sip_destroy_peer_fn(void *peer)
04849 {
04850    sip_destroy_peer(peer);
04851 }
04852 
04853 /*! \brief Destroy peer object from memory */
04854 static void sip_destroy_peer(struct sip_peer *peer)
04855 {
04856    ast_debug(3, "Destroying SIP peer %s\n", peer->name);
04857    if (peer->outboundproxy)
04858       ao2_ref(peer->outboundproxy, -1);
04859    peer->outboundproxy = NULL;
04860 
04861    /* Delete it, it needs to disappear */
04862    if (peer->call) {
04863       dialog_unlink_all(peer->call, TRUE, TRUE);
04864       peer->call = dialog_unref(peer->call, "peer->call is being unset");
04865    }
04866    
04867 
04868    if (peer->mwipvt) {  /* We have an active subscription, delete it */
04869       dialog_unlink_all(peer->mwipvt, TRUE, TRUE);
04870       peer->mwipvt = dialog_unref(peer->mwipvt, "unreffing peer->mwipvt");
04871    }
04872    
04873    if (peer->chanvars) {
04874       ast_variables_destroy(peer->chanvars);
04875       peer->chanvars = NULL;
04876    }
04877    
04878    register_peer_exten(peer, FALSE);
04879    ast_free_ha(peer->ha);
04880    if (peer->selfdestruct)
04881       ast_atomic_fetchadd_int(&apeerobjs, -1);
04882    else if (peer->is_realtime) {
04883       ast_atomic_fetchadd_int(&rpeerobjs, -1);
04884       ast_debug(3, "-REALTIME- peer Destroyed. Name: %s. Realtime Peer objects: %d\n", peer->name, rpeerobjs);
04885    } else
04886       ast_atomic_fetchadd_int(&speerobjs, -1);
04887    clear_realm_authentication(peer->auth);
04888    peer->auth = NULL;
04889    if (peer->dnsmgr)
04890       ast_dnsmgr_release(peer->dnsmgr);
04891    clear_peer_mailboxes(peer);
04892 
04893    if (peer->socket.tcptls_session) {
04894       ao2_ref(peer->socket.tcptls_session, -1);
04895       peer->socket.tcptls_session = NULL;
04896    }
04897 
04898    ast_string_field_free_memory(peer);
04899 }
04900 
04901 /*! \brief Update peer data in database (if used) */
04902 static void update_peer(struct sip_peer *p, int expire)
04903 {
04904    int rtcachefriends = ast_test_flag(&p->flags[1], SIP_PAGE2_RTCACHEFRIENDS);
04905    if (sip_cfg.peer_rtupdate &&
04906        (p->is_realtime || rtcachefriends)) {
04907       realtime_update_peer(p->name, &p->addr, p->username, rtcachefriends ? p->fullcontact : NULL, p->useragent, expire, p->deprecated_username, p->lastms);
04908    }
04909 }
04910 
04911 static struct ast_variable *get_insecure_variable_from_config(struct ast_config *cfg)
04912 {
04913    struct ast_variable *var = NULL;
04914    struct ast_flags flags = {0};
04915    char *cat = NULL;
04916    const char *insecure;
04917    while ((cat = ast_category_browse(cfg, cat))) {
04918       insecure = ast_variable_retrieve(cfg, cat, "insecure");
04919       set_insecure_flags(&flags, insecure, -1);
04920       if (ast_test_flag(&flags, SIP_INSECURE_PORT)) {
04921          var = ast_category_root(cfg, cat);
04922          break;
04923       }
04924    }
04925    return var;
04926 }
04927 
04928 static const char *get_name_from_variable(struct ast_variable *var, const char *newpeername)
04929 {
04930    struct ast_variable *tmp;
04931    for (tmp = var; tmp; tmp = tmp->next) {
04932       if (!newpeername && !strcasecmp(tmp->name, "name"))
04933          newpeername = tmp->value;
04934    }
04935    return newpeername;
04936 }
04937 
04938 /*! \brief  realtime_peer: Get peer from realtime storage
04939  * Checks the "sippeers" realtime family from extconfig.conf 
04940  * Checks the "sipregs" realtime family from extconfig.conf if it's configured.
04941  * This returns a pointer to a peer and because we use build_peer, we can rest
04942  * assured that the refcount is bumped.
04943 */
04944 static struct sip_peer *realtime_peer(const char *newpeername, struct sockaddr_in *sin, int devstate_only)
04945 {
04946    struct sip_peer *peer;
04947    struct ast_variable *var = NULL;
04948    struct ast_variable *varregs = NULL;
04949    struct ast_variable *tmp;
04950    struct ast_config *peerlist = NULL;
04951    char ipaddr[INET_ADDRSTRLEN];
04952    char portstring[6]; /*up to 5 digits plus null terminator*/
04953    char *cat = NULL;
04954    unsigned short portnum;
04955    int realtimeregs = ast_check_realtime("sipregs");
04956 
04957    /* First check on peer name */
04958    if (newpeername) {
04959       if (realtimeregs)
04960          varregs = ast_load_realtime("sipregs", "name", newpeername, SENTINEL);
04961 
04962       var = ast_load_realtime("sippeers", "name", newpeername, "host", "dynamic", SENTINEL);
04963       if (!var && sin)
04964          var = ast_load_realtime("sippeers", "name", newpeername, "host", ast_inet_ntoa(sin->sin_addr), SENTINEL);
04965       if (!var) {
04966          var = ast_load_realtime("sippeers", "name", newpeername, SENTINEL);
04967          /*!\note
04968           * If this one loaded something, then we need to ensure that the host
04969           * field matched.  The only reason why we can't have this as a criteria
04970           * is because we only have the IP address and the host field might be
04971           * set as a name (and the reverse PTR might not match).
04972           */
04973          if (var && sin) {
04974             for (tmp = var; tmp; tmp = tmp->next) {
04975                if (!strcasecmp(tmp->name, "host")) {
04976                   struct hostent *hp;
04977                   struct ast_hostent ahp;
04978                   if (!(hp = ast_gethostbyname(tmp->value, &ahp)) || (memcmp(hp->h_addr, &sin->sin_addr, sizeof(hp->h_addr)))) {
04979                      /* No match */
04980                      ast_variables_destroy(var);
04981                      var = NULL;
04982                   }
04983                   break;
04984                }
04985             }
04986          }
04987       }
04988    }
04989 
04990    if (!var && sin) {   /* Then check on IP address for dynamic peers */
04991       ast_copy_string(ipaddr, ast_inet_ntoa(sin->sin_addr), sizeof(ipaddr));
04992       portnum = ntohs(sin->sin_port);
04993       sprintf(portstring, "%u", portnum);
04994       var = ast_load_realtime("sippeers", "host", ipaddr, "port", portstring, SENTINEL);  /* First check for fixed IP hosts */
04995       if (var) {
04996          if (realtimeregs) {
04997             newpeername = get_name_from_variable(var, newpeername);
04998             varregs = ast_load_realtime("sipregs", "name", newpeername, SENTINEL);
04999          }
05000       } else {
05001          if (realtimeregs)
05002             varregs = ast_load_realtime("sipregs", "ipaddr", ipaddr, "port", portstring, SENTINEL); /* Then check for registered hosts */
05003          else
05004             var = ast_load_realtime("sippeers", "ipaddr", ipaddr, "port", portstring, SENTINEL); /* Then check for registered hosts */
05005          if (varregs) {
05006             newpeername = get_name_from_variable(varregs, newpeername);
05007             var = ast_load_realtime("sippeers", "name", newpeername, SENTINEL);
05008          }
05009       }
05010       if (!var) { /*We couldn't match on ipaddress and port, so we need to check if port is insecure*/
05011          peerlist = ast_load_realtime_multientry("sippeers", "host", ipaddr, SENTINEL);
05012          if (peerlist) {
05013             var = get_insecure_variable_from_config(peerlist);
05014             if(var) {
05015                if (realtimeregs) {
05016                   newpeername = get_name_from_variable(var, newpeername);
05017                   varregs = ast_load_realtime("sipregs", "name", newpeername, SENTINEL);
05018                }
05019             } else { /*var wasn't found in the list of "hosts", so try "ipaddr"*/
05020                peerlist = NULL;
05021                cat = NULL;
05022                peerlist = ast_load_realtime_multientry("sippeers", "ipaddr", ipaddr, SENTINEL);
05023                if(peerlist) {
05024                   var = get_insecure_variable_from_config(peerlist);
05025                   if(var) {
05026                      if (realtimeregs) {
05027                         newpeername = get_name_from_variable(var, newpeername);
05028                         varregs = ast_load_realtime("sipregs", "name", newpeername, SENTINEL);
05029                      }
05030                   }
05031                }
05032             }
05033          } else {
05034             if (realtimeregs) {
05035                peerlist = ast_load_realtime_multientry("sipregs", "ipaddr", ipaddr, SENTINEL);
05036                if (peerlist) {
05037                   varregs = get_insecure_variable_from_config(peerlist);
05038                   if (varregs) {
05039                      newpeername = get_name_from_variable(varregs, newpeername);
05040                      var = ast_load_realtime("sippeers", "name", newpeername, SENTINEL);
05041                   }
05042                }
05043             } else {
05044                peerlist = ast_load_realtime_multientry("sippeers", "ipaddr", ipaddr, SENTINEL);
05045                if (peerlist) {
05046                   var = get_insecure_variable_from_config(peerlist);
05047                   if (var) {
05048                      newpeername = get_name_from_variable(var, newpeername);
05049                      varregs = ast_load_realtime("sipregs", "name", newpeername, SENTINEL);
05050                   }
05051                }
05052             }
05053          }
05054       }
05055    }
05056 
05057    if (!var) {
05058       if (peerlist)
05059          ast_config_destroy(peerlist);
05060       return NULL;
05061    }
05062 
05063    for (tmp = var; tmp; tmp = tmp->next) {
05064       if (!newpeername && !strcasecmp(tmp->name, "name")) {
05065          newpeername = tmp->value;
05066       }
05067    }
05068    
05069    if (!newpeername) {  /* Did not find peer in realtime */
05070       ast_log(LOG_WARNING, "Cannot Determine peer name ip=%s\n", ipaddr);
05071       if(peerlist)
05072          ast_config_destroy(peerlist);
05073       else
05074          ast_variables_destroy(var);
05075       return NULL;
05076    }
05077 
05078 
05079    /* Peer found in realtime, now build it in memory */
05080    peer = build_peer(newpeername, var, varregs, TRUE, devstate_only);
05081    if (!peer) {
05082       if(peerlist)
05083          ast_config_destroy(peerlist);
05084       else {
05085          ast_variables_destroy(var);
05086          ast_variables_destroy(varregs);
05087       }
05088       return NULL;
05089    }
05090 
05091    ast_debug(3, "-REALTIME- loading peer from database to memory. Name: %s. Peer objects: %d\n", peer->name, rpeerobjs);
05092 
05093    if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) && !devstate_only) {
05094       /* Cache peer */
05095       ast_copy_flags(&peer->flags[1], &global_flags[1], SIP_PAGE2_RTAUTOCLEAR|SIP_PAGE2_RTCACHEFRIENDS);
05096       if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTAUTOCLEAR)) {
05097          AST_SCHED_REPLACE_UNREF(peer->expire, sched, sip_cfg.rtautoclear * 1000, expire_register, peer,
05098                unref_peer(_data, "remove registration ref"),
05099                unref_peer(peer, "remove registration ref"),
05100                ref_peer(peer, "add registration ref"));
05101       }
05102       ao2_t_link(peers, peer, "link peer into peers table");
05103       if (peer->addr.sin_addr.s_addr) {
05104          ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
05105       }
05106    }
05107    peer->is_realtime = 1;
05108    if (peerlist)
05109       ast_config_destroy(peerlist);
05110    else {
05111       ast_variables_destroy(var);
05112       ast_variables_destroy(varregs);
05113    }
05114 
05115    return peer;
05116 }
05117 
05118 /* Function to assist finding peers by name only */
05119 static int find_by_name(void *obj, void *arg, void *data, int flags)
05120 {
05121    struct sip_peer *search = obj, *match = arg;
05122    int *which_objects = data;
05123 
05124    /* Usernames in SIP uri's are case sensitive. Domains are not */
05125    if (strcmp(search->name, match->name)) {
05126       return 0;
05127    }
05128 
05129    switch (*which_objects) {
05130    case FINDUSERS:
05131       if (!(search->type & SIP_TYPE_USER)) {
05132          return 0;
05133       }
05134       break;
05135    case FINDPEERS:
05136       if (!(search->type & SIP_TYPE_PEER)) {
05137          return 0;
05138       }
05139       break;
05140    case FINDALLDEVICES:
05141       break;
05142    }
05143 
05144    return CMP_MATCH | CMP_STOP;
05145 }
05146 
05147 /*! 
05148  * \brief Locate device by name or ip address 
05149  *
05150  * \param which_objects Define which objects should be matched when doing a lookup
05151  *        by name.  Valid options are FINDUSERS, FINDPEERS, or FINDALLDEVICES.
05152  *        Note that this option is not used at all when doing a lookup by IP.
05153  *
05154  * This is used on find matching device on name or ip/port.
05155  * If the device was declared as type=peer, we don't match on peer name on incoming INVITEs.
05156  *
05157  * \note Avoid using this function in new functions if there is a way to avoid it,
05158  * since it might cause a database lookup.
05159  */
05160 static struct sip_peer *find_peer(const char *peer, struct sockaddr_in *sin, int realtime, int which_objects, int devstate_only, int transport)
05161 {
05162    struct sip_peer *p = NULL;
05163    struct sip_peer tmp_peer;
05164 
05165    if (peer) {
05166       ast_copy_string(tmp_peer.name, peer, sizeof(tmp_peer.name));
05167       p = ao2_t_callback_data(peers, OBJ_POINTER, find_by_name, &tmp_peer, &which_objects, "ao2_find in peers table");
05168    } else if (sin) { /* search by addr? */
05169       tmp_peer.addr.sin_addr.s_addr = sin->sin_addr.s_addr;
05170       tmp_peer.addr.sin_port = sin->sin_port;
05171       tmp_peer.flags[0].flags = 0;
05172       tmp_peer.transports = transport;
05173       p = ao2_t_find(peers_by_ip, &tmp_peer, OBJ_POINTER, "ao2_find in peers_by_ip table"); /* WAS:  p = ASTOBJ_CONTAINER_FIND_FULL(&peerl, sin, name, sip_addr_hashfunc, 1, sip_addrcmp); */
05174       if (!p) {
05175          ast_set_flag(&tmp_peer.flags[0], SIP_INSECURE_PORT);
05176          p = ao2_t_find(peers_by_ip, &tmp_peer, OBJ_POINTER, "ao2_find in peers_by_ip table 2"); /* WAS:  p = ASTOBJ_CONTAINER_FIND_FULL(&peerl, sin, name, sip_addr_hashfunc, 1, sip_addrcmp); */
05177          if (p) {
05178             return p;
05179          }
05180       }
05181    }
05182 
05183    if (!p && (realtime || devstate_only)) {
05184       p = realtime_peer(peer, sin, devstate_only);
05185       if (p) {
05186          switch (which_objects) {
05187          case FINDUSERS:
05188             if (!(p->type & SIP_TYPE_USER)) {
05189                unref_peer(p, "Wrong type of realtime SIP endpoint");
05190                return NULL;
05191             }
05192             break;
05193          case FINDPEERS:
05194             if (!(p->type & SIP_TYPE_PEER)) {
05195                unref_peer(p, "Wrong type of realtime SIP endpoint");
05196                return NULL;
05197             }
05198             break;
05199          case FINDALLDEVICES:
05200             break;
05201          }
05202       }
05203    }
05204 
05205    return p;
05206 }
05207 
05208 /*! \brief Set nat mode on the various data sockets */
05209 static void do_setnat(struct sip_pvt *p, int natflags)
05210 {
05211    const char *mode = natflags ? "On" : "Off";
05212 
05213    if (p->rtp) {
05214       ast_debug(1, "Setting NAT on RTP to %s\n", mode);
05215       ast_rtp_setnat(p->rtp, natflags);
05216    }
05217    if (p->vrtp) {
05218       ast_debug(1, "Setting NAT on VRTP to %s\n", mode);
05219       ast_rtp_setnat(p->vrtp, natflags);
05220    }
05221    if (p->udptl) {
05222       ast_debug(1, "Setting NAT on UDPTL to %s\n", mode);
05223       ast_udptl_setnat(p->udptl, natflags);
05224    }
05225    if (p->trtp) {
05226       ast_debug(1, "Setting NAT on TRTP to %s\n", mode);
05227       ast_rtp_setnat(p->trtp, natflags);
05228    }
05229 }
05230 
05231 /*! \brief Change the T38 state on a SIP dialog */
05232 static void change_t38_state(struct sip_pvt *p, int state)
05233 {
05234    int old = p->t38.state;
05235    struct ast_channel *chan = p->owner;
05236    struct ast_control_t38_parameters parameters = { .request_response = 0 };
05237 
05238    /* Don't bother changing if we are already in the state wanted */
05239    if (old == state)
05240       return;
05241 
05242    p->t38.state = state;
05243    ast_debug(2, "T38 state changed to %d on channel %s\n", p->t38.state, chan ? chan->name : "<none>");
05244 
05245    /* If no channel was provided we can't send off a control frame */
05246    if (!chan)
05247       return;
05248 
05249    /* Given the state requested and old state determine what control frame we want to queue up */
05250    switch (state) {
05251    case T38_PEER_REINVITE:
05252       parameters = p->t38.their_parms;
05253       parameters.max_ifp = ast_udptl_get_far_max_ifp(p->udptl);
05254       parameters.request_response = AST_T38_REQUEST_NEGOTIATE;
05255       ast_udptl_set_tag(p->udptl, "SIP/%s", p->username);
05256       break;
05257    case T38_ENABLED:
05258       parameters = p->t38.their_parms;
05259       parameters.max_ifp = ast_udptl_get_far_max_ifp(p->udptl);
05260       parameters.request_response = AST_T38_NEGOTIATED;
05261       ast_udptl_set_tag(p->udptl, "SIP/%s", p->username);
05262       break;
05263    case T38_DISABLED:
05264       if (old == T38_ENABLED) {
05265          parameters.request_response = AST_T38_TERMINATED;
05266       } else if (old == T38_LOCAL_REINVITE) {
05267          parameters.request_response = AST_T38_REFUSED;
05268       }
05269       break;
05270    case T38_LOCAL_REINVITE:
05271       /* wait until we get a peer response before responding to local reinvite */
05272       break;
05273    }
05274 
05275    /* Woot we got a message, create a control frame and send it on! */
05276    if (parameters.request_response)
05277       ast_queue_control_data(chan, AST_CONTROL_T38_PARAMETERS, &parameters, sizeof(parameters));
05278 }
05279 
05280 /*! \brief Set the global T38 capabilities on a SIP dialog structure */
05281 static void set_t38_capabilities(struct sip_pvt *p)
05282 {
05283    if (p->udptl) {
05284       if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) == SIP_PAGE2_T38SUPPORT_UDPTL_REDUNDANCY) {
05285                         ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_REDUNDANCY);
05286       } else if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) == SIP_PAGE2_T38SUPPORT_UDPTL_FEC) {
05287          ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_FEC);
05288       } else if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) == SIP_PAGE2_T38SUPPORT_UDPTL) {
05289          ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_NONE);
05290       }
05291    }
05292 }
05293 
05294 static void copy_socket_data(struct sip_socket *to_sock, const struct sip_socket *from_sock)
05295 {
05296    if (to_sock->tcptls_session) {
05297       ao2_ref(to_sock->tcptls_session, -1);
05298       to_sock->tcptls_session = NULL;
05299    }
05300 
05301    if (from_sock->tcptls_session) {
05302       ao2_ref(from_sock->tcptls_session, +1);
05303    }
05304 
05305    *to_sock = *from_sock;
05306 }
05307 
05308 /*! \brief Create address structure from peer reference.
05309  * This function copies data from peer to the dialog, so we don't have to look up the peer
05310  * again from memory or database during the life time of the dialog.
05311  *
05312  * \return -1 on error, 0 on success.
05313  *
05314  */
05315 static int create_addr_from_peer(struct sip_pvt *dialog, struct sip_peer *peer)
05316 {
05317 
05318    /* this checks that the dialog is contacting the peer on a valid
05319     * transport type based on the peers transport configuration,
05320     * otherwise, this function bails out */
05321    if (dialog->socket.type && check_request_transport(peer, dialog))
05322       return -1;
05323    copy_socket_data(&dialog->socket, &peer->socket);
05324 
05325    if ((peer->addr.sin_addr.s_addr || peer->defaddr.sin_addr.s_addr) &&
05326        (!peer->maxms || ((peer->lastms >= 0)  && (peer->lastms <= peer->maxms)))) {
05327       dialog->sa = (peer->addr.sin_addr.s_addr) ? peer->addr : peer->defaddr;
05328       dialog->recv = dialog->sa;
05329    } else 
05330       return -1;
05331 
05332    ast_copy_flags(&dialog->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
05333    ast_copy_flags(&dialog->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
05334    dialog->capability = peer->capability;
05335    if (!ast_test_flag(&dialog->flags[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS) &&
05336          (!ast_test_flag(&dialog->flags[1], SIP_PAGE2_VIDEOSUPPORT) ||
05337             !(dialog->capability & AST_FORMAT_VIDEO_MASK)) &&
05338          dialog->vrtp) {
05339       ast_rtp_destroy(dialog->vrtp);
05340       dialog->vrtp = NULL;
05341    }
05342    if (!ast_test_flag(&dialog->flags[1], SIP_PAGE2_TEXTSUPPORT) && dialog->trtp) {
05343       ast_rtp_destroy(dialog->trtp);
05344       dialog->trtp = NULL;
05345    }
05346    dialog->prefs = peer->prefs;
05347    if (ast_test_flag(&dialog->flags[1], SIP_PAGE2_T38SUPPORT)) {
05348       /* t38pt_udptl was enabled in the peer and not in [general] */
05349       if (dialog->udptl || (!dialog->udptl && (dialog->udptl = ast_udptl_new_with_bindaddr(sched, io, 0, bindaddr.sin_addr)))) {
05350          dialog->t38_maxdatagram = peer->t38_maxdatagram;
05351          set_t38_capabilities(dialog);
05352       } else {
05353          /* It is impossible to support T38 without udptl */
05354          ast_debug(1, "UDPTL creation failed on dialog.\n");
05355          ast_clear_flag(&dialog->flags[1], SIP_PAGE2_T38SUPPORT);
05356       }
05357    } else if (dialog->udptl) {
05358       ast_udptl_destroy(dialog->udptl);
05359       dialog->udptl = NULL;
05360    }
05361    do_setnat(dialog, ast_test_flag(&dialog->flags[0], SIP_NAT) & SIP_NAT_ROUTE);
05362 
05363    if (dialog->rtp) { /* Audio */
05364       ast_rtp_setdtmf(dialog->rtp, ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
05365       ast_rtp_setdtmfcompensate(dialog->rtp, ast_test_flag(&dialog->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
05366       ast_rtp_set_rtptimeout(dialog->rtp, peer->rtptimeout);
05367       ast_rtp_set_rtpholdtimeout(dialog->rtp, peer->rtpholdtimeout);
05368       ast_rtp_set_rtpkeepalive(dialog->rtp, peer->rtpkeepalive);
05369       /* Set Frame packetization */
05370       ast_rtp_codec_setpref(dialog->rtp, &dialog->prefs);
05371       dialog->autoframing = peer->autoframing;
05372    }
05373    if (dialog->vrtp) { /* Video */
05374       ast_rtp_setdtmf(dialog->vrtp, 0);
05375       ast_rtp_setdtmfcompensate(dialog->vrtp, 0);
05376       ast_rtp_set_rtptimeout(dialog->vrtp, peer->rtptimeout);
05377       ast_rtp_set_rtpholdtimeout(dialog->vrtp, peer->rtpholdtimeout);
05378       ast_rtp_set_rtpkeepalive(dialog->vrtp, peer->rtpkeepalive);
05379    }
05380    if (dialog->trtp) { /* Realtime text */
05381       ast_rtp_setdtmf(dialog->trtp, 0);
05382       ast_rtp_setdtmfcompensate(dialog->trtp, 0);
05383       ast_rtp_set_rtptimeout(dialog->trtp, peer->rtptimeout);
05384       ast_rtp_set_rtpholdtimeout(dialog->trtp, peer->rtpholdtimeout);
05385       ast_rtp_set_rtpkeepalive(dialog->trtp, peer->rtpkeepalive);
05386    }
05387 
05388    ast_string_field_set(dialog, peername, peer->name);
05389    ast_string_field_set(dialog, authname, peer->username);
05390    ast_string_field_set(dialog, username, peer->username);
05391    ast_string_field_set(dialog, peersecret, peer->secret);
05392    ast_string_field_set(dialog, peermd5secret, peer->md5secret);
05393    ast_string_field_set(dialog, mohsuggest, peer->mohsuggest);
05394    ast_string_field_set(dialog, mohinterpret, peer->mohinterpret);
05395    ast_string_field_set(dialog, tohost, peer->tohost);
05396    ast_string_field_set(dialog, fullcontact, peer->fullcontact);
05397    ast_string_field_set(dialog, context, peer->context);
05398    ast_string_field_set(dialog, parkinglot, peer->parkinglot);
05399    ref_proxy(dialog, obproxy_get(dialog, peer));
05400    dialog->callgroup = peer->callgroup;
05401    dialog->pickupgroup = peer->pickupgroup;
05402    dialog->allowtransfer = peer->allowtransfer;
05403    dialog->jointnoncodeccapability = dialog->noncodeccapability;
05404    dialog->rtptimeout = peer->rtptimeout;
05405    dialog->peerauth = peer->auth;
05406    dialog->maxcallbitrate = peer->maxcallbitrate;
05407    if (ast_strlen_zero(dialog->tohost))
05408       ast_string_field_set(dialog, tohost, ast_inet_ntoa(dialog->sa.sin_addr));
05409    if (!ast_strlen_zero(peer->fromdomain)) {
05410       ast_string_field_set(dialog, fromdomain, peer->fromdomain);
05411       if (!dialog->initreq.headers) {
05412          char *c;
05413          char *tmpcall = ast_strdupa(dialog->callid);
05414          /* this sure looks to me like we are going to change the callid on this dialog!! */
05415          c = strchr(tmpcall, '@');
05416          if (c) {
05417             *c = '\0';
05418             ao2_t_unlink(dialogs, dialog, "About to change the callid -- remove the old name");
05419             ast_string_field_build(dialog, callid, "%s@%s", tmpcall, peer->fromdomain);
05420             ao2_t_link(dialogs, dialog, "New dialog callid -- inserted back into table");
05421          }
05422       }
05423    }
05424    if (!ast_strlen_zero(peer->fromuser)) 
05425       ast_string_field_set(dialog, fromuser, peer->fromuser);
05426    if (!ast_strlen_zero(peer->language))
05427       ast_string_field_set(dialog, language, peer->language);
05428    /* Set timer T1 to RTT for this peer (if known by qualify=) */
05429    /* Minimum is settable or default to 100 ms */
05430    /* If there is a maxms and lastms from a qualify use that over a manual T1
05431       value. Otherwise, use the peer's T1 value. */
05432    if (peer->maxms && peer->lastms)
05433       dialog->timer_t1 = peer->lastms < global_t1min ? global_t1min : peer->lastms;
05434    else
05435       dialog->timer_t1 = peer->timer_t1;
05436 
05437    /* Set timer B to control transaction timeouts, the peer setting is the default and overrides
05438       the known timer */
05439    if (peer->timer_b)
05440       dialog->timer_b = peer->timer_b;
05441    else
05442       dialog->timer_b = 64 * dialog->timer_t1;
05443 
05444    if ((ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
05445        (ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
05446       dialog->noncodeccapability |= AST_RTP_DTMF;
05447    else
05448       dialog->noncodeccapability &= ~AST_RTP_DTMF;
05449    if (peer->call_limit)
05450       ast_set_flag(&dialog->flags[0], SIP_CALL_LIMIT);
05451    if (!dialog->portinuri)
05452       dialog->portinuri = peer->portinuri;
05453    
05454    dialog->chanvars = copy_vars(peer->chanvars);
05455 
05456    return 0;
05457 }
05458 
05459 /*! \brief create address structure from device name
05460  *      Or, if peer not found, find it in the global DNS 
05461  *      returns TRUE (-1) on failure, FALSE on success */
05462 static int create_addr(struct sip_pvt *dialog, const char *opeer, struct sockaddr_in *sin, int newdialog)
05463 {
05464    struct hostent *hp;
05465    struct ast_hostent ahp;
05466    struct sip_peer *peer;
05467    char *port;
05468    int portno = 0;
05469    char host[MAXHOSTNAMELEN], *hostn;
05470    char peername[256];
05471    int srv_ret = 0;
05472 
05473    ast_copy_string(peername, opeer, sizeof(peername));
05474    port = strchr(peername, ':');
05475    if (port) {
05476       *port++ = '\0';
05477       dialog->portinuri = 1;
05478    }
05479    dialog->sa.sin_family = AF_INET;
05480    dialog->timer_t1 = global_t1; /* Default SIP retransmission timer T1 (RFC 3261) */
05481    dialog->timer_b = global_timer_b; /* Default SIP transaction timer B (RFC 3261) */
05482    peer = find_peer(peername, NULL, TRUE, FINDPEERS, FALSE, 0);
05483 
05484    if (peer) {
05485       int res;
05486       if (newdialog) {
05487          set_socket_transport(&dialog->socket, 0);
05488       }
05489       res = create_addr_from_peer(dialog, peer);
05490       if (!ast_strlen_zero(port)) {
05491          if ((portno = atoi(port))) {
05492             dialog->sa.sin_port = dialog->recv.sin_port = htons(portno);
05493          }
05494       }
05495       unref_peer(peer, "create_addr: unref peer from find_peer hashtab lookup");
05496       return res;
05497    }
05498 
05499    do_setnat(dialog, ast_test_flag(&dialog->flags[0], SIP_NAT) & SIP_NAT_ROUTE);
05500 
05501    ast_string_field_set(dialog, tohost, peername);
05502 
05503    /* Get the outbound proxy information */
05504    ref_proxy(dialog, obproxy_get(dialog, NULL));
05505 
05506    if (sin) {
05507       /* This address should be updated using dnsmgr */
05508       memcpy(&dialog->sa.sin_addr, &sin->sin_addr, sizeof(dialog->sa.sin_addr));
05509       if (!sin->sin_port) {
05510          portno = port_str2int(port, (dialog->socket.type == SIP_TRANSPORT_TLS) ? STANDARD_TLS_PORT : STANDARD_SIP_PORT);
05511       } else {
05512          portno = ntohs(sin->sin_port);
05513       }
05514    } else {
05515 
05516       /* Let's see if we can find the host in DNS. First try DNS SRV records,
05517          then hostname lookup */
05518       /*! \todo Fix this function. When we ask for SRV, we should check all transports 
05519            In the future, we should first check NAPTR to find out transport preference
05520        */
05521       hostn = peername;
05522       /* Section 4.2 of RFC 3263 specifies that if a port number is specified, then
05523        * an A record lookup should be used instead of SRV.
05524        */
05525       if (!port && sip_cfg.srvlookup) {
05526          char service[MAXHOSTNAMELEN];
05527          int tportno;
05528          snprintf(service, sizeof(service), "_%s._%s.%s",
05529              get_srv_service(dialog->socket.type),
05530              get_srv_protocol(dialog->socket.type), peername);
05531          srv_ret = ast_get_srv(NULL, host, sizeof(host), &tportno, service);
05532          if (srv_ret > 0) {
05533             hostn = host;
05534             portno = tportno;
05535          }
05536       }
05537       if (!portno)
05538          portno = port_str2int(port, (dialog->socket.type == SIP_TRANSPORT_TLS) ? STANDARD_TLS_PORT : STANDARD_SIP_PORT);
05539       hp = ast_gethostbyname(hostn, &ahp);
05540       if (!hp) {
05541          ast_log(LOG_WARNING, "No such host: %s\n", peername);
05542          return -1;
05543       }
05544       memcpy(&dialog->sa.sin_addr, hp->h_addr, sizeof(dialog->sa.sin_addr));
05545    }
05546 
05547    if (!dialog->socket.type)
05548       set_socket_transport(&dialog->socket, SIP_TRANSPORT_UDP);
05549    if (!dialog->socket.port)
05550       dialog->socket.port = bindaddr.sin_port;
05551    dialog->sa.sin_port = htons(portno);
05552    dialog->recv = dialog->sa;
05553    return 0;
05554 }
05555 
05556 /*! \brief Scheduled congestion on a call.
05557  * Only called by the scheduler, must return the reference when done.
05558  */
05559 static int auto_congest(const void *arg)
05560 {
05561    struct sip_pvt *p = (struct sip_pvt *)arg;
05562 
05563    sip_pvt_lock(p);
05564    p->initid = -1;   /* event gone, will not be rescheduled */
05565    if (p->owner) {
05566       /* XXX fails on possible deadlock */
05567       if (!ast_channel_trylock(p->owner)) {
05568          append_history(p, "Cong", "Auto-congesting (timer)");
05569          ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
05570          ast_channel_unlock(p->owner);
05571       }
05572 
05573       /* Give the channel a chance to act before we proceed with destruction */
05574       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
05575    }
05576    sip_pvt_unlock(p);
05577    dialog_unref(p, "unreffing arg passed into auto_congest callback (p->initid)");
05578    return 0;
05579 }
05580 
05581 
05582 /*! \brief Initiate SIP call from PBX 
05583  *      used from the dial() application      */
05584 static int sip_call(struct ast_channel *ast, char *dest, int timeout)
05585 {
05586    int res;
05587    struct sip_pvt *p = ast->tech_pvt;  /* chan is locked, so the reference cannot go away */
05588    struct varshead *headp;
05589    struct ast_var_t *current;
05590    const char *referer = NULL;   /* SIP referrer */
05591 
05592    if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
05593       ast_log(LOG_WARNING, "sip_call called on %s, neither down nor reserved\n", ast->name);
05594       return -1;
05595    }
05596 
05597    /* Check whether there is vxml_url, distinctive ring variables */
05598    headp=&ast->varshead;
05599    AST_LIST_TRAVERSE(headp, current, entries) {
05600       /* Check whether there is a VXML_URL variable */
05601       if (!p->options->vxml_url && !strcasecmp(ast_var_name(current), "VXML_URL")) {
05602          p->options->vxml_url = ast_var_value(current);
05603       } else if (!p->options->uri_options && !strcasecmp(ast_var_name(current), "SIP_URI_OPTIONS")) {
05604          p->options->uri_options = ast_var_value(current);
05605       } else if (!p->options->addsipheaders && !strncasecmp(ast_var_name(current), "SIPADDHEADER", strlen("SIPADDHEADER"))) {
05606          /* Check whether there is a variable with a name starting with SIPADDHEADER */
05607          p->options->addsipheaders = 1;
05608       } else if (!strcasecmp(ast_var_name(current), "SIPFROMDOMAIN")) {
05609          ast_string_field_set(p, fromdomain, ast_var_value(current));
05610       } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER")) {
05611          /* This is a transfered call */
05612          p->options->transfer = 1;
05613       } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER_REFERER")) {
05614          /* This is the referrer */
05615          referer = ast_var_value(current);
05616       } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER_REPLACES")) {
05617          /* We're replacing a call. */
05618          p->options->replaces = ast_var_value(current);
05619       }
05620    }
05621 
05622    res = 0;
05623    ast_set_flag(&p->flags[0], SIP_OUTGOING);
05624 
05625    /* T.38 re-INVITE FAX detection should never be done for outgoing calls,
05626     * so ensure it is disabled.
05627     */
05628    ast_clear_flag(&p->flags[1], SIP_PAGE2_FAX_DETECT_T38);
05629 
05630    if (p->options->transfer) {
05631       char buf[SIPBUFSIZE/2];
05632 
05633       if (referer) {
05634          if (sipdebug)
05635             ast_debug(3, "Call for %s transfered by %s\n", p->username, referer);
05636          snprintf(buf, sizeof(buf)-1, "-> %s (via %s)", p->cid_name, referer);
05637       } else 
05638          snprintf(buf, sizeof(buf)-1, "-> %s", p->cid_name);
05639       ast_string_field_set(p, cid_name, buf);
05640    } 
05641    ast_debug(1, "Outgoing Call for %s\n", p->username);
05642 
05643    res = update_call_counter(p, INC_CALL_RINGING);
05644 
05645    if (res == -1) {
05646       ast->hangupcause = AST_CAUSE_USER_BUSY;
05647       return res;
05648    }
05649    p->callingpres = ast->cid.cid_pres;
05650    p->jointcapability = ast_translate_available_formats(p->capability, p->prefcodec);
05651    p->jointnoncodeccapability = p->noncodeccapability;
05652 
05653    /* If there are no audio formats left to offer, punt */
05654    if (!(p->jointcapability & AST_FORMAT_AUDIO_MASK)) {
05655       ast_log(LOG_WARNING, "No audio format found to offer. Cancelling call to %s\n", p->username);
05656       res = -1;
05657    } else {
05658       int xmitres;
05659 
05660       xmitres = transmit_invite(p, SIP_INVITE, 1, 2);
05661       if (xmitres == XMIT_ERROR)
05662          return -1;
05663       p->invitestate = INV_CALLING;
05664    
05665       /* Initialize auto-congest time */
05666       AST_SCHED_REPLACE_UNREF(p->initid, sched, p->timer_b, auto_congest, p, 
05667                         dialog_unref(_data, "dialog ptr dec when SCHED_REPLACE del op succeeded"), 
05668                         dialog_unref(p, "dialog ptr dec when SCHED_REPLACE add failed"),
05669                         dialog_ref(p, "dialog ptr inc when SCHED_REPLACE add succeeded") );
05670    }
05671    return res;
05672 }
05673 
05674 /*! \brief Destroy registry object
05675    Objects created with the register= statement in static configuration */
05676 static void sip_registry_destroy(struct sip_registry *reg)
05677 {
05678    /* Really delete */
05679    ast_debug(3, "Destroying registry entry for %s@%s\n", reg->username, reg->hostname);
05680 
05681    if (reg->call) {
05682       /* Clear registry before destroying to ensure
05683          we don't get reentered trying to grab the registry lock */
05684       reg->call->registry = registry_unref(reg->call->registry, "destroy reg->call->registry");
05685       ast_debug(3, "Destroying active SIP dialog for registry %s@%s\n", reg->username, reg->hostname);
05686       dialog_unlink_all(reg->call, TRUE, TRUE);
05687       reg->call = dialog_unref(reg->call, "unref reg->call");
05688       /* reg->call = sip_destroy(reg->call); */
05689    }
05690    AST_SCHED_DEL(sched, reg->expire);  
05691    AST_SCHED_DEL(sched, reg->timeout);
05692    
05693    ast_string_field_free_memory(reg);
05694    ast_atomic_fetchadd_int(&regobjs, -1);
05695    ast_dnsmgr_release(reg->dnsmgr);
05696    ast_free(reg);
05697 }
05698 
05699 /*! \brief Destroy MWI subscription object */
05700 static void sip_subscribe_mwi_destroy(struct sip_subscription_mwi *mwi)
05701 {
05702    if (mwi->call) {
05703       mwi->call->mwi = NULL;
05704       sip_destroy(mwi->call);
05705    }
05706    
05707    AST_SCHED_DEL(sched, mwi->resub);
05708    ast_string_field_free_memory(mwi);
05709    ast_dnsmgr_release(mwi->dnsmgr);
05710    ast_free(mwi);
05711 }
05712 
05713 /*! \brief Execute destruction of SIP dialog structure, release memory */
05714 static void __sip_destroy(struct sip_pvt *p, int lockowner, int lockdialoglist)
05715 {
05716    struct sip_request *req;
05717 
05718    if (p->stimer) {
05719       ast_free(p->stimer);
05720       p->stimer = NULL;
05721    }
05722 
05723    if (sip_debug_test_pvt(p))
05724       ast_verbose("Really destroying SIP dialog '%s' Method: %s\n", p->callid, sip_methods[p->method].text);
05725 
05726    if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
05727       update_call_counter(p, DEC_CALL_LIMIT);
05728       ast_debug(2, "This call did not properly clean up call limits. Call ID %s\n", p->callid);
05729    }
05730 
05731    /* Unlink us from the owner if we have one */
05732    if (p->owner) {
05733       if (lockowner)
05734          ast_channel_lock(p->owner);
05735       if (option_debug)
05736          ast_log(LOG_DEBUG, "Detaching from %s\n", p->owner->name);
05737       p->owner->tech_pvt = NULL;
05738       /* Make sure that the channel knows its backend is going away */
05739       p->owner->_softhangup |= AST_SOFTHANGUP_DEV;
05740       if (lockowner)
05741          ast_channel_unlock(p->owner);
05742       /* Give the channel a chance to react before deallocation */
05743       usleep(1);
05744    }
05745 
05746    /* Remove link from peer to subscription of MWI */
05747    if (p->relatedpeer && p->relatedpeer->mwipvt)
05748       p->relatedpeer->mwipvt = dialog_unref(p->relatedpeer->mwipvt, "delete ->relatedpeer->mwipvt");
05749    if (p->relatedpeer && p->relatedpeer->call == p)
05750       p->relatedpeer->call = dialog_unref(p->relatedpeer->call, "unset the relatedpeer->call field in tandem with relatedpeer field itself");
05751    
05752    if (p->relatedpeer)
05753       p->relatedpeer = unref_peer(p->relatedpeer,"unsetting a dialog relatedpeer field in sip_destroy");
05754    
05755    if (p->registry) {
05756       if (p->registry->call == p)
05757          p->registry->call = dialog_unref(p->registry->call, "nulling out the registry's call dialog field in unlink_all");
05758       p->registry = registry_unref(p->registry, "delete p->registry");
05759    }
05760    
05761    if (p->mwi) {
05762       p->mwi->call = NULL;
05763    }
05764 
05765    if (dumphistory)
05766       sip_dump_history(p);
05767 
05768    if (p->options)
05769       ast_free(p->options);
05770 
05771    if (p->notify_headers) {
05772       ast_variables_destroy(p->notify_headers);
05773       p->notify_headers = NULL;
05774    }
05775    if (p->rtp) {
05776       ast_rtp_destroy(p->rtp);
05777    }
05778    if (p->vrtp) {
05779       ast_rtp_destroy(p->vrtp);
05780    }
05781    if (p->trtp) {
05782       while (ast_rtp_get_bridged(p->trtp))
05783          usleep(1);
05784       ast_rtp_destroy(p->trtp);
05785    }
05786    if (p->udptl)
05787       ast_udptl_destroy(p->udptl);
05788    if (p->refer)
05789       ast_free(p->refer);
05790    if (p->route) {
05791       free_old_route(p->route);
05792       p->route = NULL;
05793    }
05794    deinit_req(&p->initreq);
05795 
05796    /* Destroy Session-Timers if allocated */
05797    if (p->stimer) {
05798       p->stimer->quit_flag = 1;
05799       if (p->stimer->st_active == TRUE && p->stimer->st_schedid > -1) {
05800          AST_SCHED_DEL_UNREF(sched, p->stimer->st_schedid,
05801                dialog_unref(p, "removing session timer ref"));
05802       }
05803       ast_free(p->stimer);
05804       p->stimer = NULL;
05805    }
05806 
05807    /* Clear history */
05808    if (p->history) {
05809       struct sip_history *hist;
05810       while ( (hist = AST_LIST_REMOVE_HEAD(p->history, list)) ) {
05811          ast_free(hist);
05812          p->history_entries--;
05813       }
05814       ast_free(p->history);
05815       p->history = NULL;
05816    }
05817 
05818    while ((req = AST_LIST_REMOVE_HEAD(&p->request_queue, next))) {
05819       ast_free(req);
05820    }
05821 
05822    if (p->chanvars) {
05823       ast_variables_destroy(p->chanvars);
05824       p->chanvars = NULL;
05825    }
05826 
05827    ast_string_field_free_memory(p);
05828 
05829    if (p->socket.tcptls_session) {
05830       ao2_ref(p->socket.tcptls_session, -1);
05831       p->socket.tcptls_session = NULL;
05832    }
05833 }
05834 
05835 /*! \brief  update_call_counter: Handle call_limit for SIP devices
05836  * Setting a call-limit will cause calls above the limit not to be accepted.
05837  *
05838  * Remember that for a type=friend, there's one limit for the user and
05839  * another for the peer, not a combined call limit.
05840  * This will cause unexpected behaviour in subscriptions, since a "friend"
05841  * is *two* devices in Asterisk, not one.
05842  *
05843  * Thought: For realtime, we should probably update storage with inuse counter... 
05844  *
05845  * \return 0 if call is ok (no call limit, below threshold)
05846  * -1 on rejection of call
05847  *    
05848  */
05849 static int update_call_counter(struct sip_pvt *fup, int event)
05850 {
05851    char name[256];
05852    int *inuse = NULL, *call_limit = NULL, *inringing = NULL;
05853    int outgoing = fup->outgoing_call;
05854    struct sip_peer *p = NULL;
05855 
05856    ast_debug(3, "Updating call counter for %s call\n", outgoing ? "outgoing" : "incoming");
05857 
05858 
05859    /* Test if we need to check call limits, in order to avoid 
05860       realtime lookups if we do not need it */
05861    if (!ast_test_flag(&fup->flags[0], SIP_CALL_LIMIT) && !ast_test_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD))
05862       return 0;
05863 
05864    ast_copy_string(name, fup->username, sizeof(name));
05865 
05866    /* Check the list of devices */
05867    if ((p = find_peer(ast_strlen_zero(fup->peername) ? name : fup->peername, NULL, TRUE, FINDALLDEVICES, FALSE, 0))) { 
05868       inuse = &p->inUse;
05869       call_limit = &p->call_limit;
05870       inringing = &p->inRinging;
05871       ast_copy_string(name, fup->peername, sizeof(name));
05872    }
05873    if (!p) {
05874       ast_debug(2, "%s is not a local device, no call limit\n", name);
05875       return 0;
05876    }
05877 
05878    switch(event) {
05879    /* incoming and outgoing affects the inUse counter */
05880    case DEC_CALL_LIMIT:
05881       /* Decrement inuse count if applicable */
05882       if (inuse) {
05883          sip_pvt_lock(fup);
05884          ao2_lock(p);
05885          if (*inuse > 0) {
05886             if (ast_test_flag(&fup->flags[0], SIP_INC_COUNT)) {
05887                (*inuse)--;
05888                ast_clear_flag(&fup->flags[0], SIP_INC_COUNT);
05889             }
05890          } else {
05891             *inuse = 0;
05892          }
05893          ao2_unlock(p);
05894          sip_pvt_unlock(fup);
05895       }
05896 
05897       /* Decrement ringing count if applicable */
05898       if (inringing) {
05899          sip_pvt_lock(fup);
05900          ao2_lock(p);
05901          if (*inringing > 0) {
05902             if (ast_test_flag(&fup->flags[0], SIP_INC_RINGING)) {
05903                (*inringing)--;
05904                ast_clear_flag(&fup->flags[0], SIP_INC_RINGING);
05905             }
05906          } else {
05907             *inringing = 0;
05908          }
05909          ao2_unlock(p);
05910          sip_pvt_unlock(fup);
05911       }
05912 
05913       /* Decrement onhold count if applicable */
05914       sip_pvt_lock(fup);
05915       ao2_lock(p);
05916       if (ast_test_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD) && sip_cfg.notifyhold) {
05917          ast_clear_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD);
05918          ao2_unlock(p);
05919          sip_pvt_unlock(fup);
05920          sip_peer_hold(fup, FALSE);
05921       } else {
05922          ao2_unlock(p);
05923          sip_pvt_unlock(fup);
05924       }
05925       if (sipdebug)
05926          ast_debug(2, "Call %s %s '%s' removed from call limit %d\n", outgoing ? "to" : "from", "peer", name, *call_limit);
05927       break;
05928 
05929    case INC_CALL_RINGING:
05930    case INC_CALL_LIMIT:
05931       /* If call limit is active and we have reached the limit, reject the call */
05932       if (*call_limit > 0 ) {
05933          if (*inuse >= *call_limit) {
05934             ast_log(LOG_NOTICE, "Call %s %s '%s' rejected due to usage limit of %d\n", outgoing ? "to" : "from", "peer", name, *call_limit);
05935             unref_peer(p, "update_call_counter: unref peer p, call limit exceeded");
05936             return -1; 
05937          }
05938       }
05939       if (inringing && (event == INC_CALL_RINGING)) {
05940          sip_pvt_lock(fup);
05941          ao2_lock(p);
05942          if (!ast_test_flag(&fup->flags[0], SIP_INC_RINGING)) {
05943             (*inringing)++;
05944             ast_set_flag(&fup->flags[0], SIP_INC_RINGING);
05945          }
05946          ao2_unlock(p);
05947          sip_pvt_unlock(fup);
05948       }
05949       if (inuse) {
05950          sip_pvt_lock(fup);
05951          ao2_lock(p);
05952          if (!ast_test_flag(&fup->flags[0], SIP_INC_COUNT)) {
05953             (*inuse)++;
05954             ast_set_flag(&fup->flags[0], SIP_INC_COUNT);
05955          }
05956          ao2_unlock(p);
05957          sip_pvt_unlock(fup);
05958       }
05959       if (sipdebug) {
05960          ast_debug(2, "Call %s %s '%s' is %d out of %d\n", outgoing ? "to" : "from", "peer", name, *inuse, *call_limit);
05961       }
05962       break;
05963 
05964    case DEC_CALL_RINGING:
05965       if (inringing) {
05966          sip_pvt_lock(fup);
05967          ao2_lock(p);
05968          if (ast_test_flag(&fup->flags[0], SIP_INC_RINGING)) {
05969             if (*inringing > 0) {
05970                (*inringing)--;
05971             }
05972             ast_clear_flag(&fup->flags[0], SIP_INC_RINGING);
05973          }
05974          ao2_unlock(p);
05975          sip_pvt_unlock(fup);
05976       }
05977       break;
05978 
05979    default:
05980       ast_log(LOG_ERROR, "update_call_counter(%s, %d) called with no event!\n", name, event);
05981    }
05982 
05983    if (p) {
05984       ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", p->name);
05985       unref_peer(p, "update_call_counter: unref_peer from call counter");
05986    } 
05987    return 0;
05988 }
05989 
05990 
05991 static void sip_destroy_fn(void *p)
05992 {
05993    sip_destroy(p);
05994 }
05995 
05996 /*! \brief Destroy SIP call structure.
05997  * Make it return NULL so the caller can do things like
05998  * foo = sip_destroy(foo);
05999  * and reduce the chance of bugs due to dangling pointers.
06000  */
06001 static struct sip_pvt * sip_destroy(struct sip_pvt *p)
06002 {
06003    ast_debug(3, "Destroying SIP dialog %s\n", p->callid);
06004    __sip_destroy(p, TRUE, TRUE);
06005    return NULL;
06006 }
06007 
06008 /*! \brief Convert SIP hangup causes to Asterisk hangup causes */
06009 static int hangup_sip2cause(int cause)
06010 {
06011    /* Possible values taken from causes.h */
06012 
06013    switch(cause) {
06014       case 401:   /* Unauthorized */
06015          return AST_CAUSE_CALL_REJECTED;
06016       case 403:   /* Not found */
06017          return AST_CAUSE_CALL_REJECTED;
06018       case 404:   /* Not found */
06019          return AST_CAUSE_UNALLOCATED;
06020       case 405:   /* Method not allowed */
06021          return AST_CAUSE_INTERWORKING;
06022       case 407:   /* Proxy authentication required */
06023          return AST_CAUSE_CALL_REJECTED;
06024       case 408:   /* No reaction */
06025          return AST_CAUSE_NO_USER_RESPONSE;
06026       case 409:   /* Conflict */
06027          return AST_CAUSE_NORMAL_TEMPORARY_FAILURE;
06028       case 410:   /* Gone */
06029          return AST_CAUSE_NUMBER_CHANGED;
06030       case 411:   /* Length required */
06031          return AST_CAUSE_INTERWORKING;
06032       case 413:   /* Request entity too large */
06033          return AST_CAUSE_INTERWORKING;
06034       case 414:   /* Request URI too large */
06035          return AST_CAUSE_INTERWORKING;
06036       case 415:   /* Unsupported media type */
06037          return AST_CAUSE_INTERWORKING;
06038       case 420:   /* Bad extension */
06039          return AST_CAUSE_NO_ROUTE_DESTINATION;
06040       case 480:   /* No answer */
06041          return AST_CAUSE_NO_ANSWER;
06042       case 481:   /* No answer */
06043          return AST_CAUSE_INTERWORKING;
06044       case 482:   /* Loop detected */
06045          return AST_CAUSE_INTERWORKING;
06046       case 483:   /* Too many hops */
06047          return AST_CAUSE_NO_ANSWER;
06048       case 484:   /* Address incomplete */
06049          return AST_CAUSE_INVALID_NUMBER_FORMAT;
06050       case 485:   /* Ambiguous */
06051          return AST_CAUSE_UNALLOCATED;
06052       case 486:   /* Busy everywhere */
06053          return AST_CAUSE_BUSY;
06054       case 487:   /* Request terminated */
06055          return AST_CAUSE_INTERWORKING;
06056       case 488:   /* No codecs approved */
06057          return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
06058       case 491:   /* Request pending */
06059          return AST_CAUSE_INTERWORKING;
06060       case 493:   /* Undecipherable */
06061          return AST_CAUSE_INTERWORKING;
06062       case 500:   /* Server internal failure */
06063          return AST_CAUSE_FAILURE;
06064       case 501:   /* Call rejected */
06065          return AST_CAUSE_FACILITY_REJECTED;
06066       case 502:   
06067          return AST_CAUSE_DESTINATION_OUT_OF_ORDER;
06068       case 503:   /* Service unavailable */
06069          return AST_CAUSE_CONGESTION;
06070       case 504:   /* Gateway timeout */
06071          return AST_CAUSE_RECOVERY_ON_TIMER_EXPIRE;
06072       case 505:   /* SIP version not supported */
06073          return AST_CAUSE_INTERWORKING;
06074       case 600:   /* Busy everywhere */
06075          return AST_CAUSE_USER_BUSY;
06076       case 603:   /* Decline */
06077          return AST_CAUSE_CALL_REJECTED;
06078       case 604:   /* Does not exist anywhere */
06079          return AST_CAUSE_UNALLOCATED;
06080       case 606:   /* Not acceptable */
06081          return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
06082       default:
06083          return AST_CAUSE_NORMAL;
06084    }
06085    /* Never reached */
06086    return 0;
06087 }
06088 
06089 /*! \brief Convert Asterisk hangup causes to SIP codes 
06090 \verbatim
06091  Possible values from causes.h
06092         AST_CAUSE_NOTDEFINED    AST_CAUSE_NORMAL        AST_CAUSE_BUSY
06093         AST_CAUSE_FAILURE       AST_CAUSE_CONGESTION    AST_CAUSE_UNALLOCATED
06094 
06095    In addition to these, a lot of PRI codes is defined in causes.h 
06096    ...should we take care of them too ?
06097    
06098    Quote RFC 3398
06099 
06100    ISUP Cause value                        SIP response
06101    ----------------                        ------------
06102    1  unallocated number                   404 Not Found
06103    2  no route to network                  404 Not found
06104    3  no route to destination              404 Not found
06105    16 normal call clearing                 --- (*)
06106    17 user busy                            486 Busy here
06107    18 no user responding                   408 Request Timeout
06108    19 no answer from the user              480 Temporarily unavailable
06109    20 subscriber absent                    480 Temporarily unavailable
06110    21 call rejected                        403 Forbidden (+)
06111    22 number changed (w/o diagnostic)      410 Gone
06112    22 number changed (w/ diagnostic)       301 Moved Permanently
06113    23 redirection to new destination       410 Gone
06114    26 non-selected user clearing           404 Not Found (=)
06115    27 destination out of order             502 Bad Gateway
06116    28 address incomplete                   484 Address incomplete
06117    29 facility rejected                    501 Not implemented
06118    31 normal unspecified                   480 Temporarily unavailable
06119 \endverbatim
06120 */
06121 static const char *hangup_cause2sip(int cause)
06122 {
06123    switch (cause) {
06124       case AST_CAUSE_UNALLOCATED:      /* 1 */
06125       case AST_CAUSE_NO_ROUTE_DESTINATION:   /* 3 IAX2: Can't find extension in context */
06126       case AST_CAUSE_NO_ROUTE_TRANSIT_NET:   /* 2 */
06127          return "404 Not Found";
06128       case AST_CAUSE_CONGESTION:    /* 34 */
06129       case AST_CAUSE_SWITCH_CONGESTION:   /* 42 */
06130          return "503 Service Unavailable";
06131       case AST_CAUSE_NO_USER_RESPONSE: /* 18 */
06132          return "408 Request Timeout";
06133       case AST_CAUSE_NO_ANSWER:     /* 19 */
06134       case AST_CAUSE_UNREGISTERED:        /* 20 */
06135          return "480 Temporarily unavailable";
06136       case AST_CAUSE_CALL_REJECTED:    /* 21 */
06137          return "403 Forbidden";
06138       case AST_CAUSE_NUMBER_CHANGED:      /* 22 */
06139          return "410 Gone";
06140       case AST_CAUSE_NORMAL_UNSPECIFIED:  /* 31 */
06141          return "480 Temporarily unavailable";
06142       case AST_CAUSE_INVALID_NUMBER_FORMAT:
06143          return "484 Address incomplete";
06144       case AST_CAUSE_USER_BUSY:
06145          return "486 Busy here";
06146       case AST_CAUSE_FAILURE:
06147          return "500 Server internal failure";
06148       case AST_CAUSE_FACILITY_REJECTED:   /* 29 */
06149          return "501 Not Implemented";
06150       case AST_CAUSE_CHAN_NOT_IMPLEMENTED:
06151          return "503 Service Unavailable";
06152       /* Used in chan_iax2 */
06153       case AST_CAUSE_DESTINATION_OUT_OF_ORDER:
06154          return "502 Bad Gateway";
06155       case AST_CAUSE_BEARERCAPABILITY_NOTAVAIL: /* Can't find codec to connect to host */
06156          return "488 Not Acceptable Here";
06157          
06158       case AST_CAUSE_NOTDEFINED:
06159       default:
06160          ast_debug(1, "AST hangup cause %d (no match found in SIP)\n", cause);
06161          return NULL;
06162    }
06163 
06164    /* Never reached */
06165    return 0;
06166 }
06167 
06168 
06169 /*! \brief  sip_hangup: Hangup SIP call
06170  * Part of PBX interface, called from ast_hangup */
06171 static int sip_hangup(struct ast_channel *ast)
06172 {
06173    struct sip_pvt *p = ast->tech_pvt;
06174    int needcancel = FALSE;
06175    int needdestroy = 0;
06176    struct ast_channel *oldowner = ast;
06177 
06178    if (!p) {
06179       ast_debug(1, "Asked to hangup channel that was not connected\n");
06180       return 0;
06181    }
06182    if (ast_test_flag(ast, AST_FLAG_ANSWERED_ELSEWHERE) || ast->hangupcause == AST_CAUSE_ANSWERED_ELSEWHERE) {
06183       ast_debug(1, "This call was answered elsewhere");
06184       if (ast->hangupcause == AST_CAUSE_ANSWERED_ELSEWHERE) {
06185          ast_debug(1, "####### It's the cause code, buddy. The cause code!!!\n");
06186       }
06187       append_history(p, "Cancel", "Call answered elsewhere");
06188       p->answered_elsewhere = TRUE;
06189    }
06190 
06191    /* Store hangupcause locally in PVT so we still have it before disconnect */
06192    if (p->owner)
06193       p->hangupcause = p->owner->hangupcause;
06194 
06195    if (ast_test_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER)) {
06196       if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
06197          if (sipdebug)
06198             ast_debug(1, "update_call_counter(%s) - decrement call limit counter on hangup\n", p->username);
06199          update_call_counter(p, DEC_CALL_LIMIT);
06200       }
06201       ast_debug(4, "SIP Transfer: Not hanging up right now... Rescheduling hangup for %s.\n", p->callid);
06202       if (p->autokillid > -1 && sip_cancel_destroy(p))
06203          ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
06204       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
06205       ast_clear_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER); /* Really hang up next time */
06206       p->needdestroy = 0;
06207       p->owner->tech_pvt = dialog_unref(p->owner->tech_pvt, "unref p->owner->tech_pvt");
06208       sip_pvt_lock(p);
06209       p->owner = NULL;  /* Owner will be gone after we return, so take it away */
06210       sip_pvt_unlock(p);
06211       ast_module_unref(ast_module_info->self);
06212       return 0;
06213    }
06214 
06215    if (ast_test_flag(ast, AST_FLAG_ZOMBIE)) {
06216       if (p->refer)
06217          ast_debug(1, "SIP Transfer: Hanging up Zombie channel %s after transfer ... Call-ID: %s\n", ast->name, p->callid);
06218       else
06219          ast_debug(1, "Hanging up zombie call. Be scared.\n");
06220    } else
06221       ast_debug(1, "Hangup call %s, SIP callid %s\n", ast->name, p->callid);
06222 
06223    sip_pvt_lock(p);
06224    if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
06225       if (sipdebug)
06226          ast_debug(1, "update_call_counter(%s) - decrement call limit counter on hangup\n", p->username);
06227       update_call_counter(p, DEC_CALL_LIMIT);
06228    }
06229 
06230    /* Determine how to disconnect */
06231    if (p->owner != ast) {
06232       ast_log(LOG_WARNING, "Huh?  We aren't the owner? Can't hangup call.\n");
06233       sip_pvt_unlock(p);
06234       return 0;
06235    }
06236    /* If the call is not UP, we need to send CANCEL instead of BYE */
06237    /* In case of re-invites, the call might be UP even though we have an incomplete invite transaction */
06238    if (p->invitestate < INV_COMPLETED && p->owner->_state != AST_STATE_UP) {
06239       needcancel = TRUE;
06240       ast_debug(4, "Hanging up channel in state %s (not UP)\n", ast_state2str(ast->_state));
06241    }
06242 
06243    stop_media_flows(p); /* Immediately stop RTP, VRTP and UDPTL as applicable */
06244 
06245    append_history(p, needcancel ? "Cancel" : "Hangup", "Cause %s", p->owner ? ast_cause2str(p->hangupcause) : "Unknown");
06246 
06247    /* Disconnect */
06248    if (p->dsp)
06249       ast_dsp_free(p->dsp);
06250 
06251    p->owner = NULL;
06252    ast->tech_pvt = dialog_unref(ast->tech_pvt, "unref ast->tech_pvt");
06253 
06254    ast_module_unref(ast_module_info->self);
06255    /* Do not destroy this pvt until we have timeout or
06256       get an answer to the BYE or INVITE/CANCEL 
06257       If we get no answer during retransmit period, drop the call anyway.
06258       (Sorry, mother-in-law, you can't deny a hangup by sending
06259       603 declined to BYE...)
06260    */
06261    if (p->alreadygone)
06262       needdestroy = 1;  /* Set destroy flag at end of this function */
06263    else if (p->invitestate != INV_CALLING)
06264       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
06265 
06266    /* Start the process if it's not already started */
06267    if (!p->alreadygone && p->initreq.data && !ast_strlen_zero(p->initreq.data->str)) {
06268       if (needcancel) { /* Outgoing call, not up */
06269          if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06270             /* stop retransmitting an INVITE that has not received a response */
06271             /* if we can't send right now, mark it pending */
06272             if (p->invitestate == INV_CALLING) {
06273                /* We can't send anything in CALLING state */
06274                ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
06275                /* 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. */
06276                sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
06277                append_history(p, "DELAY", "Not sending cancel, waiting for timeout");
06278             } else {
06279                struct sip_pkt *cur;
06280 
06281                for (cur = p->packets; cur; cur = cur->next) {
06282                   __sip_semi_ack(p, cur->seqno, cur->is_resp, cur->method ? cur->method : find_sip_method(cur->data->str));
06283                }
06284                p->invitestate = INV_CANCELLED;
06285                /* Send a new request: CANCEL */
06286                transmit_request(p, SIP_CANCEL, p->lastinvite, XMIT_RELIABLE, FALSE);
06287                /* Actually don't destroy us yet, wait for the 487 on our original 
06288                   INVITE, but do set an autodestruct just in case we never get it. */
06289                needdestroy = 0;
06290                sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
06291             }
06292          } else { /* Incoming call, not up */
06293             const char *res;
06294             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"));
06295             if (p->hangupcause && (res = hangup_cause2sip(p->hangupcause)))
06296                transmit_response_reliable(p, res, &p->initreq);
06297             else 
06298                transmit_response_reliable(p, "603 Declined", &p->initreq);
06299             p->invitestate = INV_TERMINATED;
06300          }
06301       } else { /* Call is in UP state, send BYE */
06302          if (p->stimer->st_active == TRUE) {
06303             stop_session_timer(p);
06304          }
06305 
06306          if (!p->pendinginvite) {
06307             struct ast_channel *bridge = ast_bridged_channel(oldowner);
06308             char *audioqos = "";
06309             char *videoqos = "";
06310             char *textqos = "";
06311 
06312             /* We need to get the lock on bridge because ast_rtp_set_vars will attempt
06313              * to lock the bridge. This may get hairy...
06314              */
06315             while (bridge && ast_channel_trylock(bridge)) {
06316                sip_pvt_unlock(p);
06317                do {
06318                   /* Use oldowner since p->owner is already NULL */
06319                   CHANNEL_DEADLOCK_AVOIDANCE(oldowner);
06320                } while (sip_pvt_trylock(p));
06321                bridge = ast_bridged_channel(oldowner);
06322             }
06323 
06324             if (p->rtp)
06325                ast_rtp_set_vars(oldowner, p->rtp);
06326 
06327             if (bridge) {
06328                struct sip_pvt *q = bridge->tech_pvt;
06329 
06330                if (IS_SIP_TECH(bridge->tech) && q && q->rtp)
06331                   ast_rtp_set_vars(bridge, q->rtp);
06332                ast_channel_unlock(bridge);
06333             }
06334 
06335             if (p->vrtp)
06336                videoqos = ast_rtp_get_quality(p->vrtp, NULL, RTPQOS_SUMMARY);
06337             if (p->trtp)
06338                textqos = ast_rtp_get_quality(p->trtp, NULL, RTPQOS_SUMMARY);
06339             /* Send a hangup */
06340             if (oldowner->_state == AST_STATE_UP) {
06341                transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
06342             }
06343 
06344             /* Get RTCP quality before end of call */
06345             if (p->do_history) {
06346                if (p->rtp)
06347                   append_history(p, "RTCPaudio", "Quality:%s", audioqos);
06348                if (p->vrtp)
06349                   append_history(p, "RTCPvideo", "Quality:%s", videoqos);
06350                if (p->trtp)
06351                   append_history(p, "RTCPtext", "Quality:%s", textqos);
06352             }
06353             if (p->rtp && oldowner)
06354                pbx_builtin_setvar_helper(oldowner, "RTPAUDIOQOS", audioqos);
06355             if (p->vrtp && oldowner)
06356                pbx_builtin_setvar_helper(oldowner, "RTPVIDEOQOS", videoqos);
06357             if (p->trtp && oldowner)
06358                pbx_builtin_setvar_helper(oldowner, "RTPTEXTQOS", textqos);
06359          } else {
06360             /* Note we will need a BYE when this all settles out
06361                but we can't send one while we have "INVITE" outstanding. */
06362             ast_set_flag(&p->flags[0], SIP_PENDINGBYE);  
06363             ast_clear_flag(&p->flags[0], SIP_NEEDREINVITE); 
06364             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"));
06365             if (sip_cancel_destroy(p))
06366                ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
06367          }
06368       }
06369    }
06370    if (needdestroy) {
06371       pvt_set_needdestroy(p, "hangup");
06372    }
06373    sip_pvt_unlock(p);
06374    return 0;
06375 }
06376 
06377 /*! \brief Try setting codec suggested by the SIP_CODEC channel variable */
06378 static void try_suggested_sip_codec(struct sip_pvt *p)
06379 {
06380    int fmt;
06381    const char *codec;
06382 
06383    codec = pbx_builtin_getvar_helper(p->owner, "SIP_CODEC");
06384    if (!codec) 
06385       return;
06386 
06387    fmt = ast_getformatbyname(codec);
06388    if (fmt) {
06389       ast_log(LOG_NOTICE, "Changing codec to '%s' for this call because of ${SIP_CODEC} variable\n", codec);
06390       if (p->jointcapability & fmt) {
06391          p->jointcapability &= fmt;
06392          p->capability &= fmt;
06393       } else
06394          ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because it is not shared by both ends.\n");
06395    } else
06396       ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because of unrecognized/not configured codec (check allow/disallow in sip.conf): %s\n", codec);
06397    return;  
06398 }
06399 
06400 /*! \brief  sip_answer: Answer SIP call , send 200 OK on Invite 
06401  * Part of PBX interface */
06402 static int sip_answer(struct ast_channel *ast)
06403 {
06404    int res = 0;
06405    struct sip_pvt *p = ast->tech_pvt;
06406 
06407    sip_pvt_lock(p);
06408    if (ast->_state != AST_STATE_UP) {
06409       try_suggested_sip_codec(p);   
06410 
06411       ast_setstate(ast, AST_STATE_UP);
06412       ast_debug(1, "SIP answering channel: %s\n", ast->name);
06413       ast_rtp_new_source(p->rtp);
06414       res = transmit_response_with_sdp(p, "200 OK", &p->initreq, XMIT_CRITICAL, FALSE);
06415       ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
06416    }
06417    sip_pvt_unlock(p);
06418    return res;
06419 }
06420 
06421 /*! \brief Send frame to media channel (rtp) */
06422 static int sip_write(struct ast_channel *ast, struct ast_frame *frame)
06423 {
06424    struct sip_pvt *p = ast->tech_pvt;
06425    int res = 0;
06426 
06427    switch (frame->frametype) {
06428    case AST_FRAME_VOICE:
06429       if (!(frame->subclass & ast->nativeformats)) {
06430          char s1[512], s2[512], s3[512];
06431          ast_log(LOG_WARNING, "Asked to transmit frame type %d, while native formats is %s(%d) read/write = %s(%d)/%s(%d)\n",
06432             frame->subclass, 
06433             ast_getformatname_multiple(s1, sizeof(s1) - 1, ast->nativeformats & AST_FORMAT_AUDIO_MASK),
06434             ast->nativeformats & AST_FORMAT_AUDIO_MASK,
06435             ast_getformatname_multiple(s2, sizeof(s2) - 1, ast->readformat),
06436             ast->readformat,
06437             ast_getformatname_multiple(s3, sizeof(s3) - 1, ast->writeformat),
06438             ast->writeformat);
06439          return 0;
06440       }
06441       if (p) {
06442          sip_pvt_lock(p);
06443          if (p->rtp) {
06444             /* If channel is not up, activate early media session */
06445             if ((ast->_state != AST_STATE_UP) &&
06446                 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
06447                 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06448                ast_rtp_new_source(p->rtp);
06449                if (!global_prematuremediafilter) {
06450                   p->invitestate = INV_EARLY_MEDIA;
06451                   transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
06452                   ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
06453                }
06454             } else if (p->t38.state == T38_ENABLED) {
06455                /* drop frame, can't sent VOICE frames while in T.38 mode */
06456             } else {
06457                p->lastrtptx = time(NULL);
06458                res = ast_rtp_write(p->rtp, frame);
06459             }
06460          }
06461          sip_pvt_unlock(p);
06462       }
06463       break;
06464    case AST_FRAME_VIDEO:
06465       if (p) {
06466          sip_pvt_lock(p);
06467          if (p->vrtp) {
06468             /* Activate video early media */
06469             if ((ast->_state != AST_STATE_UP) &&
06470                 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
06471                 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06472                p->invitestate = INV_EARLY_MEDIA;
06473                transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
06474                ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
06475             }
06476             p->lastrtptx = time(NULL);
06477             res = ast_rtp_write(p->vrtp, frame);
06478          }
06479          sip_pvt_unlock(p);
06480       }
06481       break;
06482    case AST_FRAME_TEXT:
06483       if (p) {
06484          sip_pvt_lock(p);
06485          if (p->red) {
06486             red_buffer_t140(p->trtp, frame);
06487          } else {
06488             if (p->trtp) {
06489                /* Activate text early media */
06490                if ((ast->_state != AST_STATE_UP) &&
06491                    !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
06492                    !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06493                   p->invitestate = INV_EARLY_MEDIA;
06494                   transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
06495                   ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
06496                }
06497                p->lastrtptx = time(NULL);
06498                res = ast_rtp_write(p->trtp, frame);
06499             }
06500          }
06501          sip_pvt_unlock(p);
06502       }
06503       break;
06504    case AST_FRAME_IMAGE:
06505       return 0;
06506       break;
06507    case AST_FRAME_MODEM:
06508       if (p) {
06509          sip_pvt_lock(p);
06510          /* UDPTL requires two-way communication, so early media is not needed here.
06511             we simply forget the frames if we get modem frames before the bridge is up.
06512             Fax will re-transmit.
06513          */
06514          if ((ast->_state == AST_STATE_UP) &&
06515              p->udptl &&
06516              (p->t38.state == T38_ENABLED)) {
06517             res = ast_udptl_write(p->udptl, frame);
06518          }
06519          sip_pvt_unlock(p);
06520       }
06521       break;
06522    default: 
06523       ast_log(LOG_WARNING, "Can't send %d type frames with SIP write\n", frame->frametype);
06524       return 0;
06525    }
06526 
06527    return res;
06528 }
06529 
06530 /*! \brief  sip_fixup: Fix up a channel:  If a channel is consumed, this is called.
06531         Basically update any ->owner links */
06532 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
06533 {
06534    int ret = -1;
06535    struct sip_pvt *p;
06536 
06537    if (newchan && ast_test_flag(newchan, AST_FLAG_ZOMBIE))
06538       ast_debug(1, "New channel is zombie\n");
06539    if (oldchan && ast_test_flag(oldchan, AST_FLAG_ZOMBIE))
06540       ast_debug(1, "Old channel is zombie\n");
06541 
06542    if (!newchan || !newchan->tech_pvt) {
06543       if (!newchan)
06544          ast_log(LOG_WARNING, "No new channel! Fixup of %s failed.\n", oldchan->name);
06545       else
06546          ast_log(LOG_WARNING, "No SIP tech_pvt! Fixup of %s failed.\n", oldchan->name);
06547       return -1;
06548    }
06549    p = newchan->tech_pvt;
06550 
06551    sip_pvt_lock(p);
06552    append_history(p, "Masq", "Old channel: %s\n", oldchan->name);
06553    append_history(p, "Masq (cont)", "...new owner: %s\n", newchan->name);
06554    if (p->owner != oldchan)
06555       ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, p->owner);
06556    else {
06557       p->owner = newchan;
06558       /* Re-invite RTP back to Asterisk. Needed if channel is masqueraded out of a native
06559          RTP bridge (i.e., RTP not going through Asterisk): RTP bridge code might not be
06560          able to do this if the masquerade happens before the bridge breaks (e.g., AMI
06561          redirect of both channels). Note that a channel can not be masqueraded *into*
06562          a native bridge. So there is no danger that this breaks a native bridge that
06563          should stay up. */
06564       sip_set_rtp_peer(newchan, NULL, NULL, 0, 0, 0);
06565       ret = 0;
06566    }
06567    ast_debug(3, "SIP Fixup: New owner for dialogue %s: %s (Old parent: %s)\n", p->callid, p->owner->name, oldchan->name);
06568 
06569    sip_pvt_unlock(p);
06570    return ret;
06571 }
06572 
06573 static int sip_senddigit_begin(struct ast_channel *ast, char digit)
06574 {
06575    struct sip_pvt *p = ast->tech_pvt;
06576    int res = 0;
06577 
06578    sip_pvt_lock(p);
06579    switch (ast_test_flag(&p->flags[0], SIP_DTMF)) {
06580    case SIP_DTMF_INBAND:
06581       res = -1; /* Tell Asterisk to generate inband indications */
06582       break;
06583    case SIP_DTMF_RFC2833:
06584       if (p->rtp)
06585          ast_rtp_senddigit_begin(p->rtp, digit);
06586       break;
06587    default:
06588       break;
06589    }
06590    sip_pvt_unlock(p);
06591 
06592    return res;
06593 }
06594 
06595 /*! \brief Send DTMF character on SIP channel
06596    within one call, we're able to transmit in many methods simultaneously */
06597 static int sip_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration)
06598 {
06599    struct sip_pvt *p = ast->tech_pvt;
06600    int res = 0;
06601 
06602    sip_pvt_lock(p);
06603    switch (ast_test_flag(&p->flags[0], SIP_DTMF)) {
06604    case SIP_DTMF_INFO:
06605    case SIP_DTMF_SHORTINFO:
06606       transmit_info_with_digit(p, digit, duration);
06607       break;
06608    case SIP_DTMF_RFC2833:
06609       if (p->rtp)
06610          ast_rtp_senddigit_end_with_duration(p->rtp, digit, duration);
06611       break;
06612    case SIP_DTMF_INBAND:
06613       res = -1; /* Tell Asterisk to stop inband indications */
06614       break;
06615    }
06616    sip_pvt_unlock(p);
06617 
06618    return res;
06619 }
06620 
06621 /*! \brief Transfer SIP call */
06622 static int sip_transfer(struct ast_channel *ast, const char *dest)
06623 {
06624    struct sip_pvt *p = ast->tech_pvt;
06625    int res;
06626 
06627    if (dest == NULL) /* functions below do not take a NULL */
06628       dest = "";
06629    sip_pvt_lock(p);
06630    if (ast->_state == AST_STATE_RING)
06631       res = sip_sipredirect(p, dest);
06632    else
06633       res = transmit_refer(p, dest);
06634    sip_pvt_unlock(p);
06635    return res;
06636 }
06637 
06638 /*! \brief Helper function which updates T.38 capability information and triggers a reinvite */
06639 static int interpret_t38_parameters(struct sip_pvt *p, const struct ast_control_t38_parameters *parameters)
06640 {
06641    int res = 0;
06642 
06643    if (!ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) || !p->udptl) {
06644       return -1;
06645    }
06646    switch (parameters->request_response) {
06647    case AST_T38_NEGOTIATED:
06648    case AST_T38_REQUEST_NEGOTIATE:         /* Request T38 */
06649       /* Negotiation can not take place without a valid max_ifp value. */
06650       if (!parameters->max_ifp) {
06651          change_t38_state(p, T38_DISABLED);
06652          if (p->t38.state == T38_PEER_REINVITE) {
06653             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"));
06654             transmit_response_reliable(p, "488 Not acceptable here", &p->initreq);
06655          }
06656          break;
06657       } else if (p->t38.state == T38_PEER_REINVITE) {
06658          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"));
06659          p->t38.our_parms = *parameters;
06660          /* modify our parameters to conform to the peer's parameters,
06661           * based on the rules in the ITU T.38 recommendation
06662           */
06663          if (!p->t38.their_parms.fill_bit_removal) {
06664             p->t38.our_parms.fill_bit_removal = FALSE;
06665          }
06666          if (!p->t38.their_parms.transcoding_mmr) {
06667             p->t38.our_parms.transcoding_mmr = FALSE;
06668          }
06669          if (!p->t38.their_parms.transcoding_jbig) {
06670             p->t38.our_parms.transcoding_jbig = FALSE;
06671          }
06672          p->t38.our_parms.version = MIN(p->t38.our_parms.version, p->t38.their_parms.version);
06673          p->t38.our_parms.rate_management = p->t38.their_parms.rate_management;
06674          ast_udptl_set_local_max_ifp(p->udptl, p->t38.our_parms.max_ifp);
06675          change_t38_state(p, T38_ENABLED);
06676          transmit_response_with_t38_sdp(p, "200 OK", &p->initreq, XMIT_CRITICAL);
06677       } else if (p->t38.state != T38_ENABLED) {
06678          p->t38.our_parms = *parameters;
06679          ast_udptl_set_local_max_ifp(p->udptl, p->t38.our_parms.max_ifp);
06680          change_t38_state(p, T38_LOCAL_REINVITE);
06681          if (!p->pendinginvite) {
06682             transmit_reinvite_with_sdp(p, TRUE, FALSE);
06683          } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
06684             ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
06685          }
06686       }
06687       break;
06688    case AST_T38_TERMINATED:
06689    case AST_T38_REFUSED:
06690    case AST_T38_REQUEST_TERMINATE:         /* Shutdown T38 */
06691       if (p->t38.state == T38_PEER_REINVITE) {
06692          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"));
06693          change_t38_state(p, T38_DISABLED);
06694          transmit_response_reliable(p, "488 Not acceptable here", &p->initreq);
06695       } else if (p->t38.state == T38_ENABLED)
06696          transmit_reinvite_with_sdp(p, FALSE, FALSE);
06697       break;
06698    case AST_T38_REQUEST_PARMS: {    /* Application wants remote's parameters re-sent */
06699       struct ast_control_t38_parameters parameters = p->t38.their_parms;
06700 
06701       if (p->t38.state == T38_PEER_REINVITE) {
06702          AST_SCHED_DEL(sched, p->t38id);
06703          parameters.max_ifp = ast_udptl_get_far_max_ifp(p->udptl);
06704          parameters.request_response = AST_T38_REQUEST_NEGOTIATE;
06705          ast_queue_control_data(p->owner, AST_CONTROL_T38_PARAMETERS, &parameters, sizeof(parameters));
06706          /* we need to return a positive value here, so that applications that
06707           * send this request can determine conclusively whether it was accepted or not...
06708           * older versions of chan_sip would just silently accept it and return zero.
06709           */
06710          res = AST_T38_REQUEST_PARMS;
06711       }
06712       break;
06713    }
06714    default:
06715       res = -1;
06716       break;
06717    }
06718 
06719    return res;
06720 }
06721 
06722 /*! \brief Play indication to user 
06723  * With SIP a lot of indications is sent as messages, letting the device play
06724    the indication - busy signal, congestion etc 
06725    \return -1 to force ast_indicate to send indication in audio, 0 if SIP can handle the indication by sending a message
06726 */
06727 static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen)
06728 {
06729    struct sip_pvt *p = ast->tech_pvt;
06730    int res = 0;
06731 
06732    sip_pvt_lock(p);
06733    switch(condition) {
06734    case AST_CONTROL_RINGING:
06735       if (ast->_state == AST_STATE_RING) {
06736          p->invitestate = INV_EARLY_MEDIA;
06737          if (!ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) ||
06738              (ast_test_flag(&p->flags[0], SIP_PROG_INBAND) == SIP_PROG_INBAND_NEVER)) {            
06739             /* Send 180 ringing if out-of-band seems reasonable */
06740             transmit_provisional_response(p, "180 Ringing", &p->initreq, 0);
06741             ast_set_flag(&p->flags[0], SIP_RINGING);
06742             if (ast_test_flag(&p->flags[0], SIP_PROG_INBAND) != SIP_PROG_INBAND_YES)
06743                break;
06744          } else {
06745             /* Well, if it's not reasonable, just send in-band */
06746          }
06747       }
06748       res = -1;
06749       break;
06750    case AST_CONTROL_BUSY:
06751       if (ast->_state != AST_STATE_UP) {
06752          transmit_response_reliable(p, "486 Busy Here", &p->initreq);
06753          p->invitestate = INV_COMPLETED;
06754          sip_alreadygone(p);
06755          ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
06756          break;
06757       }
06758       res = -1;
06759       break;
06760    case AST_CONTROL_CONGESTION:
06761       if (ast->_state != AST_STATE_UP) {
06762          transmit_response_reliable(p, "503 Service Unavailable", &p->initreq);
06763          p->invitestate = INV_COMPLETED;
06764          sip_alreadygone(p);
06765          ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
06766          break;
06767       }
06768       res = -1;
06769       break;
06770    case AST_CONTROL_PROCEEDING:
06771       if ((ast->_state != AST_STATE_UP) &&
06772           !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
06773           !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06774          transmit_response(p, "100 Trying", &p->initreq);
06775          p->invitestate = INV_PROCEEDING;  
06776          break;
06777       }
06778       res = -1;
06779       break;
06780    case AST_CONTROL_PROGRESS:
06781       if ((ast->_state != AST_STATE_UP) &&
06782           !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
06783           !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06784          p->invitestate = INV_EARLY_MEDIA;
06785          transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
06786          ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
06787          break;
06788       }
06789       res = -1;
06790       break;
06791    case AST_CONTROL_HOLD:
06792       ast_rtp_new_source(p->rtp);
06793       ast_moh_start(ast, data, p->mohinterpret);
06794       break;
06795    case AST_CONTROL_UNHOLD:
06796       ast_rtp_new_source(p->rtp);
06797       ast_moh_stop(ast);
06798       break;
06799    case AST_CONTROL_VIDUPDATE:   /* Request a video frame update */
06800       if (p->vrtp && !p->novideo) {
06801          transmit_info_with_vidupdate(p);
06802          /* ast_rtcp_send_h261fur(p->vrtp); */
06803       } else
06804          res = -1;
06805       break;
06806    case AST_CONTROL_T38_PARAMETERS:
06807       if (datalen != sizeof(struct ast_control_t38_parameters)) {
06808          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);
06809          res = -1;
06810       } else {
06811          const struct ast_control_t38_parameters *parameters = data;
06812          res = interpret_t38_parameters(p, parameters);
06813       }
06814       break;
06815    case AST_CONTROL_SRCUPDATE:
06816       ast_rtp_new_source(p->rtp);
06817       break;
06818    case AST_CONTROL_SRCCHANGE:
06819       ast_rtp_change_source(p->rtp);
06820       break;
06821    case -1:
06822       res = -1;
06823       break;
06824    default:
06825       ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", condition);
06826       res = -1;
06827       break;
06828    }
06829    sip_pvt_unlock(p);
06830    return res;
06831 }
06832 
06833 
06834 /*! \brief Initiate a call in the SIP channel
06835    called from sip_request_call (calls from the pbx ) for outbound channels
06836    and from handle_request_invite for inbound channels
06837    
06838 */
06839 static struct ast_channel *sip_new(struct sip_pvt *i, int state, const char *title)
06840 {
06841    struct ast_channel *tmp;
06842    struct ast_variable *v = NULL;
06843    int fmt;
06844    int what;
06845    int video;
06846    int text;
06847    int needvideo = 0;
06848    int needtext = 0;
06849    char buf[SIPBUFSIZE];
06850    char *decoded_exten;
06851 
06852    {
06853       const char *my_name; /* pick a good name */
06854    
06855       if (title) {
06856          my_name = title;
06857       } else {
06858          char *port = NULL;
06859          my_name = ast_strdupa(i->fromdomain);
06860          if ((port = strchr(i->fromdomain, ':'))) {
06861             *port = '\0';
06862          }
06863       }
06864 
06865       sip_pvt_unlock(i);
06866       /* Don't hold a sip pvt lock while we allocate a channel */
06867       tmp = ast_channel_alloc(1, state, i->cid_num, i->cid_name, i->accountcode, i->exten, i->context, i->amaflags, "SIP/%s-%08x", my_name, ast_atomic_fetchadd_int((int *)&chan_idx, +1));
06868 
06869    }
06870    if (!tmp) {
06871       ast_log(LOG_WARNING, "Unable to allocate AST channel structure for SIP channel\n");
06872       sip_pvt_lock(i);
06873       return NULL;
06874    }
06875    sip_pvt_lock(i);
06876 
06877    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;
06878 
06879    /* Select our native format based on codec preference until we receive
06880       something from another device to the contrary. */
06881    if (i->jointcapability) {  /* The joint capabilities of us and peer */
06882       what = i->jointcapability;
06883       video = i->jointcapability & AST_FORMAT_VIDEO_MASK;
06884       text = i->jointcapability & AST_FORMAT_TEXT_MASK;
06885    } else if (i->capability) {      /* Our configured capability for this peer */
06886       what = i->capability;
06887       video = i->capability & AST_FORMAT_VIDEO_MASK;
06888       text = i->capability & AST_FORMAT_TEXT_MASK;
06889    } else {
06890       what = global_capability;  /* Global codec support */
06891       video = global_capability & AST_FORMAT_VIDEO_MASK;
06892       text = global_capability & AST_FORMAT_TEXT_MASK;
06893    }
06894 
06895    /* Set the native formats for audio  and merge in video */
06896    tmp->nativeformats = ast_codec_choose(&i->prefs, what, 1) | video | text;
06897    ast_debug(3, "*** Our native formats are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, tmp->nativeformats));
06898    ast_debug(3, "*** Joint capabilities are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, i->jointcapability));
06899    ast_debug(3, "*** Our capabilities are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, i->capability));
06900    ast_debug(3, "*** AST_CODEC_CHOOSE formats are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, ast_codec_choose(&i->prefs, what, 1)));
06901    if (i->prefcodec)
06902       ast_debug(3, "*** Our preferred formats from the incoming channel are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, i->prefcodec));
06903 
06904    /* XXX Why are we choosing a codec from the native formats?? */
06905    fmt = ast_best_codec(tmp->nativeformats);
06906 
06907    /* If we have a prefcodec setting, we have an inbound channel that set a 
06908       preferred format for this call. Otherwise, we check the jointcapability
06909       We also check for vrtp. If it's not there, we are not allowed do any video anyway.
06910     */
06911    if (i->vrtp) {
06912       if (ast_test_flag(&i->flags[1], SIP_PAGE2_VIDEOSUPPORT))
06913          needvideo = AST_FORMAT_VIDEO_MASK;
06914       else if (i->prefcodec)
06915          needvideo = i->prefcodec & AST_FORMAT_VIDEO_MASK;  /* Outbound call */
06916       else
06917          needvideo = i->jointcapability & AST_FORMAT_VIDEO_MASK;  /* Inbound call */
06918    }
06919 
06920    if (i->trtp) {
06921       if (i->prefcodec)
06922          needtext = i->prefcodec & AST_FORMAT_TEXT_MASK; /* Outbound call */
06923       else
06924          needtext = i->jointcapability & AST_FORMAT_TEXT_MASK; /* Inbound call */
06925    }
06926 
06927    if (needvideo) 
06928       ast_debug(3, "This channel can handle video! HOLLYWOOD next!\n");
06929    else
06930       ast_debug(3, "This channel will not be able to handle video.\n");
06931 
06932    if ((ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) || (ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_AUTO) ||
06933        (ast_test_flag(&i->flags[1], SIP_PAGE2_FAX_DETECT))) {
06934       int features = 0;
06935 
06936       if ((ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) || (ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_AUTO)) {
06937          features |= DSP_FEATURE_DIGIT_DETECT;
06938       }
06939 
06940       if (ast_test_flag(&i->flags[1], SIP_PAGE2_FAX_DETECT)) {
06941          features |= DSP_FEATURE_FAX_DETECT;
06942       }
06943 
06944       i->dsp = ast_dsp_new();
06945       ast_dsp_set_features(i->dsp, features);
06946       if (global_relaxdtmf)
06947          ast_dsp_set_digitmode(i->dsp, DSP_DIGITMODE_DTMF | DSP_DIGITMODE_RELAXDTMF);
06948          }
06949 
06950    /* Set file descriptors for audio, video, realtime text and UDPTL as needed */
06951    if (i->rtp) {
06952       ast_channel_set_fd(tmp, 0, ast_rtp_fd(i->rtp));
06953       ast_channel_set_fd(tmp, 1, ast_rtcp_fd(i->rtp));
06954    }
06955    if (needvideo && i->vrtp) {
06956       ast_channel_set_fd(tmp, 2, ast_rtp_fd(i->vrtp));
06957       ast_channel_set_fd(tmp, 3, ast_rtcp_fd(i->vrtp));
06958    }
06959    if (needtext && i->trtp) 
06960       ast_channel_set_fd(tmp, 4, ast_rtp_fd(i->trtp));
06961    if (i->udptl)
06962       ast_channel_set_fd(tmp, 5, ast_udptl_fd(i->udptl));
06963 
06964    if (state == AST_STATE_RING)
06965       tmp->rings = 1;
06966    tmp->adsicpe = AST_ADSI_UNAVAILABLE;
06967    tmp->writeformat = fmt;
06968    tmp->rawwriteformat = fmt;
06969    tmp->readformat = fmt;
06970    tmp->rawreadformat = fmt;
06971    tmp->tech_pvt = dialog_ref(i, "sip_new: set chan->tech_pvt to i");
06972 
06973    tmp->callgroup = i->callgroup;
06974    tmp->pickupgroup = i->pickupgroup;
06975    tmp->cid.cid_pres = i->callingpres;
06976    if (!ast_strlen_zero(i->parkinglot))
06977       ast_string_field_set(tmp, parkinglot, i->parkinglot);
06978    if (!ast_strlen_zero(i->accountcode))
06979       ast_string_field_set(tmp, accountcode, i->accountcode);
06980    if (i->amaflags)
06981       tmp->amaflags = i->amaflags;
06982    if (!ast_strlen_zero(i->language))
06983       ast_string_field_set(tmp, language, i->language);
06984    i->owner = tmp;
06985    ast_module_ref(ast_module_info->self);
06986    ast_copy_string(tmp->context, i->context, sizeof(tmp->context));
06987    /*Since it is valid to have extensions in the dialplan that have unescaped characters in them
06988     * we should decode the uri before storing it in the channel, but leave it encoded in the sip_pvt
06989     * structure so that there aren't issues when forming URI's
06990     */
06991    if (ast_exists_extension(NULL, i->context, i->exten, 1, i->cid_num)) {
06992       /* encoded in dialplan, so keep extension encoded */
06993       ast_copy_string(tmp->exten, i->exten, sizeof(tmp->exten));
06994    } else {
06995       decoded_exten = ast_strdupa(i->exten);
06996       ast_uri_decode(decoded_exten);
06997       ast_copy_string(tmp->exten, decoded_exten, sizeof(tmp->exten));
06998    }
06999 
07000    /* Don't use ast_set_callerid() here because it will
07001     * generate an unnecessary NewCallerID event  */
07002    tmp->cid.cid_ani = ast_strdup(i->cid_num);
07003    if (!ast_strlen_zero(i->rdnis))
07004       tmp->cid.cid_rdnis = ast_strdup(i->rdnis);
07005    
07006    if (!ast_strlen_zero(i->exten) && strcmp(i->exten, "s"))
07007       tmp->cid.cid_dnid = ast_strdup(i->exten);
07008 
07009    tmp->priority = 1;
07010    if (!ast_strlen_zero(i->uri))
07011       pbx_builtin_setvar_helper(tmp, "SIPURI", i->uri);
07012    if (!ast_strlen_zero(i->domain))
07013       pbx_builtin_setvar_helper(tmp, "SIPDOMAIN", i->domain);
07014    if (!ast_strlen_zero(i->callid))
07015       pbx_builtin_setvar_helper(tmp, "SIPCALLID", i->callid);
07016    if (i->rtp)
07017       ast_jb_configure(tmp, &global_jbconf);
07018 
07019    /* Set channel variables for this call from configuration */
07020    for (v = i->chanvars ; v ; v = v->next) {
07021       char valuebuf[1024];
07022       pbx_builtin_setvar_helper(tmp, v->name, ast_get_encoded_str(v->value, valuebuf, sizeof(valuebuf)));
07023    }
07024 
07025    if (state != AST_STATE_DOWN && ast_pbx_start(tmp)) {
07026       ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
07027       tmp->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
07028       ast_hangup(tmp);
07029       tmp = NULL;
07030    }
07031 
07032    if (i->do_history)
07033       append_history(i, "NewChan", "Channel %s - from %s", tmp->name, i->callid);
07034 
07035    /* Inform manager user about new channel and their SIP call ID */
07036    if (sip_cfg.callevents)
07037       manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
07038          "Channel: %s\r\nUniqueid: %s\r\nChanneltype: %s\r\nSIPcallid: %s\r\nSIPfullcontact: %s\r\n",
07039          tmp->name, tmp->uniqueid, "SIP", i->callid, i->fullcontact);
07040 
07041    return tmp;
07042 }
07043 
07044 /*! \brief Reads one line of SIP message body */
07045 static char *get_body_by_line(const char *line, const char *name, int nameLen, char delimiter)
07046 {
07047    if (!strncasecmp(line, name, nameLen) && line[nameLen] == delimiter)
07048       return ast_skip_blanks(line + nameLen + 1);
07049 
07050    return "";
07051 }
07052 
07053 /*! \brief Lookup 'name' in the SDP starting
07054  * at the 'start' line. Returns the matching line, and 'start'
07055  * is updated with the next line number.
07056  */
07057 static const char *get_sdp_iterate(int *start, struct sip_request *req, const char *name)
07058 {
07059    int len = strlen(name);
07060 
07061    while (*start < (req->sdp_start + req->sdp_count)) {
07062       const char *r = get_body_by_line(REQ_OFFSET_TO_STR(req, line[(*start)++]), name, len, '=');
07063       if (r[0] != '\0')
07064          return r;
07065    }
07066 
07067    /* if the line was not found, ensure that *start points past the SDP */
07068    (*start)++;
07069 
07070    return "";
07071 }
07072 
07073 /*! \brief Fetches the next valid SDP line between the 'start' line
07074  * (inclusive) and the 'stop' line (exclusive). Returns the type
07075  * ('a', 'c', ...) and matching line in reference 'start' is updated
07076  * with the next line number.
07077  */
07078 static char get_sdp_line(int *start, int stop, struct sip_request *req, const char **value)
07079 {
07080    char type = '\0';
07081    const char *line = NULL;
07082 
07083    if (stop > (req->sdp_start + req->sdp_count)) {
07084       stop = req->sdp_start + req->sdp_count;
07085    }
07086 
07087    while (*start < stop) {
07088       line = REQ_OFFSET_TO_STR(req, line[(*start)++]);
07089       if (line[1] == '=') {
07090          type = line[0];
07091          *value = ast_skip_blanks(line + 2);
07092          break;
07093       }
07094    }
07095 
07096    return type;
07097 }
07098 
07099 /*! \brief Get a specific line from the message body */
07100 static char *get_body(struct sip_request *req, char *name, char delimiter) 
07101 {
07102    int x;
07103    int len = strlen(name);
07104    char *r;
07105 
07106    for (x = 0; x < req->lines; x++) {
07107       r = get_body_by_line(REQ_OFFSET_TO_STR(req, line[x]), name, len, delimiter);
07108       if (r[0] != '\0')
07109          return r;
07110    }
07111 
07112    return "";
07113 }
07114 
07115 /*! \brief Find compressed SIP alias */
07116 static const char *find_alias(const char *name, const char *_default)
07117 {
07118    /*! \brief Structure for conversion between compressed SIP and "normal" SIP */
07119    static const struct cfalias {
07120       char * const fullname;
07121       char * const shortname;
07122    } aliases[] = {
07123       { "Content-Type",  "c" },
07124       { "Content-Encoding",    "e" },
07125       { "From",       "f" },
07126       { "Call-ID",       "i" },
07127       { "Contact",       "m" },
07128       { "Content-Length",   "l" },
07129       { "Subject",       "s" },
07130       { "To",         "t" },
07131       { "Supported",     "k" },
07132       { "Refer-To",      "r" },
07133       { "Referred-By",   "b" },
07134       { "Allow-Events",  "u" },
07135       { "Event",      "o" },
07136       { "Via",     "v" },
07137       { "Accept-Contact",      "a" },
07138       { "Reject-Contact",      "j" },
07139       { "Request-Disposition", "d" },
07140       { "Session-Expires",     "x" },
07141       { "Identity",            "y" },
07142       { "Identity-Info",       "n" },
07143    };
07144    int x;
07145 
07146    for (x = 0; x < ARRAY_LEN(aliases); x++) {
07147       if (!strcasecmp(aliases[x].fullname, name))
07148          return aliases[x].shortname;
07149    }
07150 
07151    return _default;
07152 }
07153 
07154 static const char *__get_header(const struct sip_request *req, const char *name, int *start)
07155 {
07156    int pass;
07157 
07158    /*
07159     * Technically you can place arbitrary whitespace both before and after the ':' in
07160     * a header, although RFC3261 clearly says you shouldn't before, and place just
07161     * one afterwards.  If you shouldn't do it, what absolute idiot decided it was 
07162     * a good idea to say you can do it, and if you can do it, why in the hell would.
07163     * you say you shouldn't.
07164     * Anyways, pedanticsipchecking controls whether we allow spaces before ':',
07165     * and we always allow spaces after that for compatibility.
07166     */
07167    for (pass = 0; name && pass < 2;pass++) {
07168       int x, len = strlen(name);
07169       for (x = *start; x < req->headers; x++) {
07170          char *header = REQ_OFFSET_TO_STR(req, header[x]);
07171          if (!strncasecmp(header, name, len)) {
07172             char *r = header + len; /* skip name */
07173             if (sip_cfg.pedanticsipchecking)
07174                r = ast_skip_blanks(r);
07175 
07176             if (*r == ':') {
07177                *start = x+1;
07178                return ast_skip_blanks(r+1);
07179             }
07180          }
07181       }
07182       if (pass == 0) /* Try aliases */
07183          name = find_alias(name, NULL);
07184    }
07185 
07186    /* Don't return NULL, so get_header is always a valid pointer */
07187    return "";
07188 }
07189 
07190 /*! \brief Get header from SIP request 
07191    \return Always return something, so don't check for NULL because it won't happen :-)
07192 */
07193 static const char *get_header(const struct sip_request *req, const char *name)
07194 {
07195    int start = 0;
07196    return __get_header(req, name, &start);
07197 }
07198 
07199 /*! \brief Read RTP from network */
07200 static struct ast_frame *sip_rtp_read(struct ast_channel *ast, struct sip_pvt *p, int *faxdetect)
07201 {
07202    /* Retrieve audio/etc from channel.  Assumes p->lock is already held. */
07203    struct ast_frame *f;
07204    
07205    if (!p->rtp) {
07206       /* We have no RTP allocated for this channel */
07207       return &ast_null_frame;
07208    }
07209 
07210    switch(ast->fdno) {
07211    case 0:
07212       f = ast_rtp_read(p->rtp);  /* RTP Audio */
07213       break;
07214    case 1:
07215       f = ast_rtcp_read(p->rtp); /* RTCP Control Channel */
07216       break;
07217    case 2:
07218       f = ast_rtp_read(p->vrtp); /* RTP Video */
07219       break;
07220    case 3:
07221       f = ast_rtcp_read(p->vrtp);   /* RTCP Control Channel for video */
07222       break;
07223    case 4:
07224       f = ast_rtp_read(p->trtp); /* RTP Text */
07225       if (sipdebug_text) {
07226          int i;
07227          unsigned char* arr = f->data.ptr;
07228          for (i=0; i < f->datalen; i++)
07229             ast_verbose("%c", (arr[i] > ' ' && arr[i] < '}') ? arr[i] : '.');
07230          ast_verbose(" -> ");
07231          for (i=0; i < f->datalen; i++)
07232             ast_verbose("%02X ", arr[i]);
07233          ast_verbose("\n");
07234       }
07235       break;
07236    case 5:
07237       f = ast_udptl_read(p->udptl); /* UDPTL for T.38 */
07238       break;
07239    default:
07240       f = &ast_null_frame;
07241    }
07242    /* Don't forward RFC2833 if we're not supposed to */
07243    if (f && (f->frametype == AST_FRAME_DTMF_BEGIN || f->frametype == AST_FRAME_DTMF_END) &&
07244        (ast_test_flag(&p->flags[0], SIP_DTMF) != SIP_DTMF_RFC2833)) {
07245       ast_debug(1, "Ignoring DTMF (%c) RTP frame because dtmfmode is not RFC2833\n", f->subclass);
07246       return &ast_null_frame;
07247    }
07248 
07249    /* We already hold the channel lock */
07250    if (!p->owner || (f && f->frametype != AST_FRAME_VOICE))
07251       return f;
07252 
07253    if (f && f->subclass != (p->owner->nativeformats & AST_FORMAT_AUDIO_MASK)) {
07254       if (!(f->subclass & p->jointcapability)) {
07255          ast_debug(1, "Bogus frame of format '%s' received from '%s'!\n",
07256             ast_getformatname(f->subclass), p->owner->name);
07257          return &ast_null_frame;
07258       }
07259       ast_debug(1, "Oooh, format changed to %d %s\n",
07260          f->subclass, ast_getformatname(f->subclass));
07261       p->owner->nativeformats = (p->owner->nativeformats & (AST_FORMAT_VIDEO_MASK | AST_FORMAT_TEXT_MASK)) | f->subclass;
07262       ast_set_read_format(p->owner, p->owner->readformat);
07263       ast_set_write_format(p->owner, p->owner->writeformat);
07264    }
07265 
07266    if (f && ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) || ast_test_flag(&p->flags[1], SIP_PAGE2_FAX_DETECT)) && p->dsp) {
07267       f = ast_dsp_process(p->owner, p->dsp, f);
07268                 if (f && f->frametype == AST_FRAME_DTMF) {
07269          if (f->subclass == 'f') {
07270                                 if (option_debug)
07271                                         ast_log(LOG_DEBUG, "Fax CNG detected on %s\n", ast->name);
07272                                 *faxdetect = 1;
07273             /* If we only needed this DSP for fax detection purposes we can just drop it now */
07274             if (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) {
07275                ast_dsp_set_features(p->dsp, DSP_FEATURE_DIGIT_DETECT);
07276             } else {
07277                ast_dsp_free(p->dsp);
07278                p->dsp = NULL;
07279             }
07280          } else {
07281             ast_debug(1, "* Detected inband DTMF '%c'\n", f->subclass);
07282          }
07283       }
07284    }
07285    
07286    return f;
07287 }
07288 
07289 /*! \brief Read SIP RTP from channel */
07290 static struct ast_frame *sip_read(struct ast_channel *ast)
07291 {
07292    struct ast_frame *fr;
07293    struct sip_pvt *p = ast->tech_pvt;
07294    int faxdetected = FALSE;
07295 
07296    sip_pvt_lock(p);
07297    fr = sip_rtp_read(ast, p, &faxdetected);
07298    p->lastrtprx = time(NULL);
07299 
07300    /* If we detect a CNG tone and fax detection is enabled then send us off to the fax extension */
07301    if (faxdetected && ast_test_flag(&p->flags[1], SIP_PAGE2_FAX_DETECT_CNG)) {
07302       ast_channel_lock(ast);
07303       if (strcmp(ast->exten, "fax")) {
07304          const char *target_context = S_OR(ast->macrocontext, ast->context);
07305          ast_channel_unlock(ast);
07306          if (ast_exists_extension(ast, target_context, "fax", 1, ast->cid.cid_num)) {
07307             ast_verbose(VERBOSE_PREFIX_2 "Redirecting '%s' to fax extension due to CNG detection\n", ast->name);
07308             pbx_builtin_setvar_helper(ast, "FAXEXTEN", ast->exten);
07309             if (ast_async_goto(ast, target_context, "fax", 1)) {
07310                ast_log(LOG_NOTICE, "Failed to async goto '%s' into fax of '%s'\n", ast->name, target_context);
07311             }
07312             fr = &ast_null_frame;
07313          } else {
07314             ast_log(LOG_NOTICE, "FAX CNG detected but no fax extension\n");
07315                         }
07316       } else {
07317          ast_channel_unlock(ast);
07318                 }
07319         }
07320 
07321    /* Only allow audio through if they sent progress with SDP, or if the channel is actually answered */
07322    if (fr && fr->frametype == AST_FRAME_VOICE && p->invitestate != INV_EARLY_MEDIA && ast->_state != AST_STATE_UP) {
07323       fr = &ast_null_frame;
07324    }
07325 
07326    sip_pvt_unlock(p);
07327 
07328    return fr;
07329 }
07330 
07331 
07332 /*! \brief Generate 32 byte random string for callid's etc */
07333 static char *generate_random_string(char *buf, size_t size)
07334 {
07335    long val[4];
07336    int x;
07337 
07338    for (x=0; x<4; x++)
07339       val[x] = ast_random();
07340    snprintf(buf, size, "%08lx%08lx%08lx%08lx", val[0], val[1], val[2], val[3]);
07341 
07342    return buf;
07343 }
07344 
07345 /*! \brief Build SIP Call-ID value for a non-REGISTER transaction */
07346 static void build_callid_pvt(struct sip_pvt *pvt)
07347 {
07348    char buf[33];
07349 
07350    const char *host = S_OR(pvt->fromdomain, ast_inet_ntoa(pvt->ourip.sin_addr));
07351    
07352    ast_string_field_build(pvt, callid, "%s@%s", generate_random_string(buf, sizeof(buf)), host);
07353 
07354 }
07355 
07356 /*! \brief Build SIP Call-ID value for a REGISTER transaction */
07357 static void build_callid_registry(struct sip_registry *reg, struct in_addr ourip, const char *fromdomain)
07358 {
07359    char buf[33];
07360 
07361    const char *host = S_OR(fromdomain, ast_inet_ntoa(ourip));
07362 
07363    ast_string_field_build(reg, callid, "%s@%s", generate_random_string(buf, sizeof(buf)), host);
07364 }
07365 
07366 /*! \brief Make our SIP dialog tag */
07367 static void make_our_tag(char *tagbuf, size_t len)
07368 {
07369    snprintf(tagbuf, len, "as%08lx", ast_random());
07370 }
07371 
07372 /*! \brief Allocate Session-Timers struct w/in dialog */
07373 static struct sip_st_dlg* sip_st_alloc(struct sip_pvt *const p)
07374 {
07375    struct sip_st_dlg *stp;
07376 
07377    if (p->stimer) {
07378       ast_log(LOG_ERROR, "Session-Timer struct already allocated\n");
07379       return p->stimer;
07380    }
07381 
07382    if (!(stp = ast_calloc(1, sizeof(struct sip_st_dlg))))
07383       return NULL;
07384 
07385    p->stimer = stp;
07386 
07387    stp->st_schedid = -1;           /* Session-Timers ast_sched scheduler id */
07388 
07389    return p->stimer;
07390 }
07391 
07392 /*! \brief Allocate sip_pvt structure, set defaults and link in the container.
07393  * Returns a reference to the object so whoever uses it later must
07394  * remember to release the reference.
07395  */
07396 static struct sip_pvt *sip_alloc(ast_string_field callid, struct sockaddr_in *sin,
07397              int useglobal_nat, const int intended_method, struct sip_request *req)
07398 {
07399    struct sip_pvt *p;
07400 
07401    if (!(p = ao2_t_alloc(sizeof(*p), sip_destroy_fn, "allocate a dialog(pvt) struct")))
07402       return NULL;
07403 
07404    if (ast_string_field_init(p, 512)) {
07405       ao2_t_ref(p, -1, "failed to string_field_init, drop p");
07406       return NULL;
07407    }
07408 
07409    if (req) {
07410       set_socket_transport(&p->socket, req->socket.type); /* Later in ast_sip_ouraddrfor we need this to choose the right ip and port for the specific transport */
07411    } else {
07412       set_socket_transport(&p->socket, SIP_TRANSPORT_UDP);
07413    }
07414 
07415    p->socket.fd = -1;
07416    p->method = intended_method;
07417    p->initid = -1;
07418    p->waitid = -1;
07419    p->autokillid = -1;
07420    p->request_queue_sched_id = -1;
07421    p->provisional_keepalive_sched_id = -1;
07422    p->t38id = -1;
07423    p->subscribed = NONE;
07424    p->stateid = -1;
07425    p->sessionversion_remote = -1;
07426    p->session_modify = TRUE;
07427    p->stimer = NULL;
07428    p->prefs = default_prefs;     /* Set default codecs for this call */
07429 
07430    if (intended_method != SIP_OPTIONS) {  /* Peerpoke has it's own system */
07431       p->timer_t1 = global_t1;   /* Default SIP retransmission timer T1 (RFC 3261) */
07432       p->timer_b = global_timer_b;  /* Default SIP transaction timer B (RFC 3261) */
07433    }
07434 
07435    if (!sin)
07436       p->ourip = internip;
07437    else {
07438       p->sa = *sin;
07439       ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
07440    }
07441 
07442    /* Copy global flags to this PVT at setup. */
07443    ast_copy_flags(&p->flags[0], &global_flags[0], SIP_FLAGS_TO_COPY);
07444    ast_copy_flags(&p->flags[1], &global_flags[1], SIP_PAGE2_FLAGS_TO_COPY);
07445 
07446    p->do_history = recordhistory;
07447 
07448    p->branch = ast_random();  
07449    make_our_tag(p->tag, sizeof(p->tag));
07450    p->ocseq = INITIAL_CSEQ;
07451 
07452    if (sip_methods[intended_method].need_rtp) {
07453       p->rtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
07454       /* If the global videosupport flag is on, we always create a RTP interface for video */
07455       if (ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT) ||
07456             ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS))
07457          p->vrtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
07458       if (ast_test_flag(&p->flags[1], SIP_PAGE2_TEXTSUPPORT))
07459          p->trtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
07460       if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT)) {
07461          if (!(p->udptl = ast_udptl_new_with_bindaddr(sched, io, 0, bindaddr.sin_addr))) {
07462             /* udptl creation failed, T38 can not be supported on this dialog */
07463             ast_log(LOG_ERROR, "UDPTL creation failed\n");
07464             ast_clear_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT);
07465          }
07466       }
07467       if (!p->rtp|| (ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT) && !p->vrtp) 
07468             || (ast_test_flag(&p->flags[1], SIP_PAGE2_TEXTSUPPORT) && !p->trtp)) {
07469          ast_log(LOG_WARNING, "Unable to create RTP audio %s%ssession: %s\n",
07470             ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT) ? "and video " : "",
07471             ast_test_flag(&p->flags[1], SIP_PAGE2_TEXTSUPPORT) ? "and text " : "", strerror(errno));
07472          if (p->chanvars) {
07473             ast_variables_destroy(p->chanvars);
07474             p->chanvars = NULL;
07475          }
07476          ao2_t_ref(p, -1, "failed to create RTP audio session, drop p");
07477          return NULL;
07478          p->t38_maxdatagram = global_t38_maxdatagram;
07479       }
07480       ast_rtp_setqos(p->rtp, global_tos_audio, global_cos_audio, "SIP RTP");
07481       ast_rtp_setdtmf(p->rtp, ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
07482       ast_rtp_setdtmfcompensate(p->rtp, ast_test_flag(&p->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
07483       ast_rtp_set_rtptimeout(p->rtp, global_rtptimeout);
07484       ast_rtp_set_rtpholdtimeout(p->rtp, global_rtpholdtimeout);
07485       ast_rtp_set_rtpkeepalive(p->rtp, global_rtpkeepalive);
07486       if (p->vrtp) {
07487          ast_rtp_setqos(p->vrtp, global_tos_video, global_cos_video, "SIP VRTP");
07488          ast_rtp_setdtmf(p->vrtp, 0);
07489          ast_rtp_setdtmfcompensate(p->vrtp, 0);
07490          ast_rtp_set_rtptimeout(p->vrtp, global_rtptimeout);
07491          ast_rtp_set_rtpholdtimeout(p->vrtp, global_rtpholdtimeout);
07492          ast_rtp_set_rtpkeepalive(p->vrtp, global_rtpkeepalive);
07493       }
07494       if (p->trtp) {
07495          ast_rtp_setqos(p->trtp, global_tos_text, global_cos_text, "SIP TRTP");
07496          ast_rtp_setdtmf(p->trtp, 0);
07497          ast_rtp_setdtmfcompensate(p->trtp, 0);
07498       }
07499       if (p->udptl)
07500          ast_udptl_setqos(p->udptl, global_tos_audio, global_cos_audio);
07501       p->maxcallbitrate = default_maxcallbitrate;
07502       p->autoframing = global_autoframing;
07503       ast_rtp_codec_setpref(p->rtp, &p->prefs);
07504    }
07505 
07506    if (useglobal_nat && sin) {
07507       /* Setup NAT structure according to global settings if we have an address */
07508       ast_copy_flags(&p->flags[0], &global_flags[0], SIP_NAT);
07509       p->recv = *sin;
07510       do_setnat(p, ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE);
07511    }
07512 
07513    if (p->method != SIP_REGISTER)
07514       ast_string_field_set(p, fromdomain, default_fromdomain);
07515    build_via(p);
07516    if (!callid)
07517       build_callid_pvt(p);
07518    else
07519       ast_string_field_set(p, callid, callid);
07520    /* Assign default music on hold class */
07521    ast_string_field_set(p, mohinterpret, default_mohinterpret);
07522    ast_string_field_set(p, mohsuggest, default_mohsuggest);
07523    p->capability = global_capability;
07524    p->allowtransfer = sip_cfg.allowtransfer;
07525    if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
07526        (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
07527       p->noncodeccapability |= AST_RTP_DTMF;
07528    if (p->udptl) {
07529       p->t38_maxdatagram = global_t38_maxdatagram;
07530       set_t38_capabilities(p);
07531    }
07532    ast_string_field_set(p, context, sip_cfg.default_context);
07533    ast_string_field_set(p, parkinglot, default_parkinglot);
07534 
07535    AST_LIST_HEAD_INIT_NOLOCK(&p->request_queue);
07536 
07537    /* Add to active dialog list */
07538 
07539    ao2_t_link(dialogs, p, "link pvt into dialogs table");
07540    
07541    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");
07542    return p;
07543 }
07544 
07545 static void free_via(struct sip_via *v)
07546 {
07547    if (!v) {
07548       return;
07549    }
07550 
07551    if (v->via) {
07552       ast_free(v->via);
07553    }
07554 
07555    ast_free(v);
07556 }
07557 
07558 /*!
07559  * \brief Parse a Via header
07560  *
07561  * This function parses the Via header and processes it according to section
07562  * 18.2 of RFC 3261 and RFC 3581. Since we don't have a transport layer, we
07563  * only care about the maddr and ttl parms.  The received and rport params are
07564  * not parsed.
07565  *
07566  * \note This function fails to parse some odd combinations of SWS in parameter
07567  * lists.
07568  *
07569  * \code
07570  * VIA syntax. RFC 3261 section 25.1
07571  * Via               =  ( "Via" / "v" ) HCOLON via-parm *(COMMA via-parm)
07572  * via-parm          =  sent-protocol LWS sent-by *( SEMI via-params )
07573  * via-params        =  via-ttl / via-maddr
07574  *                   / via-received / via-branch
07575  *                   / via-extension
07576  * via-ttl           =  "ttl" EQUAL ttl
07577  * via-maddr         =  "maddr" EQUAL host
07578  * via-received      =  "received" EQUAL (IPv4address / IPv6address)
07579  * via-branch        =  "branch" EQUAL token
07580  * via-extension     =  generic-param
07581  * sent-protocol     =  protocol-name SLASH protocol-version
07582  *                   SLASH transport
07583  * protocol-name     =  "SIP" / token
07584  * protocol-version  =  token
07585  * transport         =  "UDP" / "TCP" / "TLS" / "SCTP"
07586  *                   / other-transport
07587  * sent-by           =  host [ COLON port ]
07588  * ttl               =  1*3DIGIT ; 0 to 255
07589  * \endcode
07590  */
07591 static struct sip_via *parse_via(const char *header)
07592 {
07593    struct sip_via *v = ast_calloc(1, sizeof(*v));
07594    char *via, *parm;
07595 
07596    if (!v) {
07597       return NULL;
07598    }
07599 
07600    v->via = ast_strdup(header);
07601    v->ttl = 1;
07602 
07603    via = v->via;
07604 
07605    if (ast_strlen_zero(via)) {
07606       ast_log(LOG_ERROR, "received request without a Via header\n");
07607       free_via(v);
07608       return NULL;
07609    }
07610 
07611    /* seperate the first via-parm */
07612    via = strsep(&via, ",");
07613 
07614    /* chop off sent-protocol */
07615    v->protocol = strsep(&via, " \t\r\n");
07616    if (ast_strlen_zero(v->protocol)) {
07617       ast_log(LOG_ERROR, "missing sent-protocol in Via header\n");
07618       free_via(v);
07619       return NULL;
07620    }
07621    v->protocol = ast_skip_blanks(v->protocol);
07622 
07623    if (via) {
07624       via = ast_skip_blanks(via);
07625    }
07626 
07627    /* chop off sent-by */
07628    v->sent_by = strsep(&via, "; \t\r\n");
07629    if (ast_strlen_zero(v->sent_by)) {
07630       ast_log(LOG_ERROR, "missing sent-by in Via header\n");
07631       free_via(v);
07632       return NULL;
07633    }
07634    v->sent_by = ast_skip_blanks(v->sent_by);
07635 
07636    /* store the port */
07637    if ((parm = strchr(v->sent_by, ':'))) {
07638       char *endptr;
07639 
07640       v->port = strtol(++parm, &endptr, 10);
07641    }
07642 
07643    /* evaluate any via-parms */
07644    while ((parm = strsep(&via, "; \t\r\n"))) {
07645       char *c;
07646       if ((c = strstr(parm, "maddr="))) {
07647          v->maddr = ast_skip_blanks(c + sizeof("maddr=") - 1);
07648       } else if ((c = strstr(parm, "branch="))) {
07649          v->branch = ast_skip_blanks(c + sizeof("branch=") - 1);
07650       } else if ((c = strstr(parm, "ttl="))) {
07651          char *endptr;
07652          c = ast_skip_blanks(c + sizeof("ttl=") - 1);
07653          v->ttl = strtol(c, &endptr, 10);
07654 
07655          /* make sure we got a valid ttl value */
07656          if (c == endptr) {
07657             v->ttl = 1;
07658          }
07659       }
07660    }
07661 
07662    return v;
07663 }
07664 
07665 /*!
07666  * \brief Check if an ip is an multicast IP.
07667  * \parm addr the address to check
07668  *
07669  * This function checks if an address is in the 224.0.0.0/4 network block.
07670  * \return non-zero if this is a multicast address
07671  */
07672 static int addr_is_multicast(struct in_addr *addr)
07673 {
07674    return ((ntohl(addr->s_addr) & 0xf0000000) == 0xe0000000);
07675 }
07676 
07677 static int process_via(struct sip_pvt *p, const struct sip_request *req)
07678 {
07679    struct sip_via *via = parse_via(get_header(req, "Via"));
07680 
07681    if (!via) {
07682       ast_log(LOG_ERROR, "error processing via header\n");
07683       return -1;
07684    }
07685 
07686    if (via->maddr) {
07687       struct hostent *hp;
07688       struct ast_hostent ahp;
07689 
07690       hp = ast_gethostbyname(via->maddr, &ahp);
07691       if (hp == NULL)  {
07692          ast_log(LOG_WARNING, "Can't find address for maddr '%s'\n", via->maddr);
07693          ast_log(LOG_ERROR, "error processing via header\n");
07694          free_via(via);
07695          return -1;
07696       }
07697 
07698       p->sa.sin_family = AF_INET;
07699       memcpy(&p->sa.sin_addr, hp->h_addr, sizeof(p->sa.sin_addr));
07700 
07701       if (via->port) {
07702          p->sa.sin_port = via->port;
07703       } else {
07704          p->sa.sin_port = STANDARD_SIP_PORT;
07705       }
07706 
07707       if (addr_is_multicast(&p->sa.sin_addr)) {
07708          setsockopt(sipsock, IPPROTO_IP, IP_MULTICAST_TTL, &via->ttl, sizeof(via->ttl));
07709       }
07710    }
07711 
07712    free_via(via);
07713    return 0;
07714 }
07715 
07716 /*! \brief argument to the helper function to identify a call */
07717 struct find_call_cb_arg {
07718    enum sipmethod method;
07719    const char *callid;
07720    const char *fromtag;
07721    const char *totag;
07722    const char *tag;
07723 };
07724 
07725 /*!
07726  * code to determine whether this is the pvt that we are looking for.
07727  * Return FALSE if not found, true otherwise. p is unlocked.
07728  */
07729 static int find_call_cb(void *__pvt, void *__arg, int flags)
07730 {
07731    struct sip_pvt *p = __pvt;
07732    struct find_call_cb_arg *arg = __arg;
07733    /* In pedantic, we do not want packets with bad syntax to be connected to a PVT */
07734    int found = FALSE;
07735    
07736    if (!ast_strlen_zero(p->callid)) { /* XXX double check, do we allow match on empty p->callid ? */
07737       if (arg->method == SIP_REGISTER)
07738          found = (!strcmp(p->callid, arg->callid));
07739       else {
07740          found = !strcmp(p->callid, arg->callid);
07741          if (sip_cfg.pedanticsipchecking && found) {
07742             found = ast_strlen_zero(arg->tag) || ast_strlen_zero(p->theirtag) || !ast_test_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED) || !strcmp(p->theirtag, arg->tag);
07743          } 
07744       }
07745       
07746       ast_debug(5, "= %s Their Call ID: %s Their Tag %s Our tag: %s\n", found ? "Found" : "No match", p->callid, p->theirtag, p->tag);
07747       
07748       /* If we get a new request within an existing to-tag - check the to tag as well */
07749       if (sip_cfg.pedanticsipchecking && found && arg->method != SIP_RESPONSE) { /* SIP Request */
07750          if (p->tag[0] == '\0' && arg->totag[0]) {
07751             /* We have no to tag, but they have. Wrong dialog */
07752             found = FALSE;
07753          } else if (arg->totag[0]) { /* Both have tags, compare them */
07754             if (strcmp(arg->totag, p->tag)) {
07755                found = FALSE; /* This is not our packet */
07756             }
07757          }
07758          if (!found)
07759             ast_debug(5, "= Being pedantic: This is not our match on request: Call ID: %s Ourtag <null> Totag %s Method %s\n", p->callid, arg->totag, sip_methods[arg->method].text);
07760       }
07761    }
07762    return found;
07763 }
07764 
07765 /*! \brief find or create a dialog structure for an incoming SIP message.
07766  * Connect incoming SIP message to current dialog or create new dialog structure
07767  * Returns a reference to the sip_pvt object, remember to give it back once done.
07768  *     Called by handle_incoming(), sipsock_read
07769  */
07770 static struct sip_pvt *find_call(struct sip_request *req, struct sockaddr_in *sin, const int intended_method)
07771 {
07772    struct sip_pvt *p = NULL;
07773    char *tag = "";   /* note, tag is never NULL */
07774    char totag[128];
07775    char fromtag[128];
07776    struct find_call_cb_arg arg;
07777    const char *callid = get_header(req, "Call-ID");
07778    const char *from = get_header(req, "From");
07779    const char *to = get_header(req, "To");
07780    const char *cseq = get_header(req, "Cseq");
07781    struct sip_pvt *sip_pvt_ptr;
07782 
07783    /* Call-ID, to, from and Cseq are required by RFC 3261. (Max-forwards and via too - ignored now) */
07784    /* get_header always returns non-NULL so we must use ast_strlen_zero() */
07785    if (ast_strlen_zero(callid) || ast_strlen_zero(to) ||
07786          ast_strlen_zero(from) || ast_strlen_zero(cseq))
07787       return NULL;   /* Invalid packet */
07788 
07789    arg.method = req->method;
07790    arg.callid = callid;
07791    arg.fromtag = fromtag;
07792    arg.totag = totag;
07793    arg.tag = ""; /* make sure tag is never NULL */
07794 
07795    if (sip_cfg.pedanticsipchecking) {
07796       /* In principle Call-ID's uniquely identify a call, but with a forking SIP proxy
07797          we need more to identify a branch - so we have to check branch, from
07798          and to tags to identify a call leg.
07799          For Asterisk to behave correctly, you need to turn on pedanticsipchecking
07800          in sip.conf
07801          */
07802       if (gettag(req, "To", totag, sizeof(totag)))
07803          req->has_to_tag = 1; /* Used in handle_request/response */
07804       gettag(req, "From", fromtag, sizeof(fromtag));
07805 
07806       tag = (req->method == SIP_RESPONSE) ? totag : fromtag;
07807 
07808       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);
07809 
07810       /* All messages must always have From: tag */
07811       if (ast_strlen_zero(fromtag)) {
07812          ast_debug(5, "%s request has no from tag, dropping callid: %s from: %s\n", sip_methods[req->method].text , callid, from );
07813          return NULL;
07814       }
07815       /* reject requests that must always have a To: tag */
07816       if (ast_strlen_zero(totag) && (req->method == SIP_ACK || req->method == SIP_BYE || req->method == SIP_INFO )) {
07817          ast_debug(5, "%s must have a to tag. dropping callid: %s from: %s\n", sip_methods[req->method].text , callid, from );
07818          return NULL;
07819       }
07820    }
07821 
07822 restartsearch:
07823    if (!sip_cfg.pedanticsipchecking) {
07824       struct sip_pvt tmp_dialog = {
07825          .callid = callid,
07826       };       
07827       sip_pvt_ptr = ao2_t_find(dialogs, &tmp_dialog, OBJ_POINTER, "ao2_find in dialogs");
07828       if (sip_pvt_ptr) {  /* well, if we don't find it-- what IS in there? */
07829          /* Found the call */
07830          sip_pvt_lock(sip_pvt_ptr);
07831          return sip_pvt_ptr;
07832       }
07833    } else { /* in pedantic mode! -- do the fancy linear search */
07834       ao2_lock(dialogs);
07835       p = ao2_t_callback(dialogs, 0 /* single, data */, find_call_cb, &arg, "pedantic linear search for dialog");
07836       if (p) {
07837          if (sip_pvt_trylock(p)) {
07838             ao2_unlock(dialogs);
07839             usleep(1);
07840             goto restartsearch;
07841          }
07842          ao2_unlock(dialogs);
07843          return p;
07844       }
07845       ao2_unlock(dialogs);
07846    }
07847  
07848    /* See if the method is capable of creating a dialog */
07849    if (sip_methods[intended_method].can_create == CAN_CREATE_DIALOG) {
07850       if (intended_method == SIP_REFER) {
07851          /* We do support REFER, but not outside of a dialog yet */
07852          transmit_response_using_temp(callid, sin, 1, intended_method, req, "603 Declined (no dialog)");
07853       } else if (intended_method == SIP_NOTIFY) {
07854          /* We do not support out-of-dialog NOTIFY either,
07855             like voicemail notification, so cancel that early */
07856          transmit_response_using_temp(callid, sin, 1, intended_method, req, "481 No subscription");
07857       } else {
07858          /* Ok, time to create a new SIP dialog object, a pvt */
07859          if ((p = sip_alloc(callid, sin, 1, intended_method, req)))  {
07860             /* Ok, we've created a dialog, let's go and process it */
07861             sip_pvt_lock(p);
07862          } else {
07863             /* We have a memory or file/socket error (can't allocate RTP sockets or something) so we're not
07864                getting a dialog from sip_alloc. 
07865    
07866                Without a dialog we can't retransmit and handle ACKs and all that, but at least
07867                send an error message.
07868    
07869                Sorry, we apologize for the inconvienience
07870             */
07871             transmit_response_using_temp(callid, sin, 1, intended_method, req, "500 Server internal error");
07872             ast_debug(4, "Failed allocating SIP dialog, sending 500 Server internal error and giving up\n");
07873          }
07874       }
07875       return p; /* can be NULL */
07876    } else if( sip_methods[intended_method].can_create == CAN_CREATE_DIALOG_UNSUPPORTED_METHOD) {
07877       /* A method we do not support, let's take it on the volley */
07878       transmit_response_using_temp(callid, sin, 1, intended_method, req, "501 Method Not Implemented");
07879       ast_debug(2, "Got a request with unsupported SIP method.\n");
07880    } else if (intended_method != SIP_RESPONSE && intended_method != SIP_ACK) {
07881       /* This is a request outside of a dialog that we don't know about */
07882       transmit_response_using_temp(callid, sin, 1, intended_method, req, "481 Call leg/transaction does not exist");
07883       ast_debug(2, "That's odd...  Got a request in unknown dialog. Callid %s\n", callid ? callid : "<unknown>");
07884    }
07885    /* We do not respond to responses for dialogs that we don't know about, we just drop
07886       the session quickly */
07887    if (intended_method == SIP_RESPONSE)
07888       ast_debug(2, "That's odd...  Got a response on a call we don't know about. Callid %s\n", callid ? callid : "<unknown>");
07889 
07890    return NULL;
07891 }
07892 
07893 /*! \brief Parse register=> line in sip.conf and add to registry */
07894 static int sip_register(const char *value, int lineno)
07895 {
07896    struct sip_registry *reg;
07897    int portnum = 0;
07898    enum sip_transport transport = SIP_TRANSPORT_UDP;
07899    char buf[256] = "";
07900    char *userpart = NULL, *hostpart = NULL;
07901    /* register => [peer?][transport://]user[@domain][:secret[:authuser]]@host[:port][/extension][~expiry] */
07902    AST_DECLARE_APP_ARGS(pre1,
07903       AST_APP_ARG(peer);
07904       AST_APP_ARG(userpart);
07905    );
07906    AST_DECLARE_APP_ARGS(pre2,
07907       AST_APP_ARG(transport);
07908       AST_APP_ARG(blank);
07909       AST_APP_ARG(userpart);
07910    );
07911    AST_DECLARE_APP_ARGS(user1,
07912       AST_APP_ARG(userpart);
07913       AST_APP_ARG(secret);
07914       AST_APP_ARG(authuser);
07915    );
07916    AST_DECLARE_APP_ARGS(host1,
07917       AST_APP_ARG(hostpart);
07918       AST_APP_ARG(expiry);
07919    );
07920    AST_DECLARE_APP_ARGS(host2,
07921       AST_APP_ARG(hostpart);
07922       AST_APP_ARG(extension);
07923    );
07924    AST_DECLARE_APP_ARGS(host3,
07925       AST_APP_ARG(host);
07926       AST_APP_ARG(port);
07927    );
07928 
07929    if (!value)
07930       return -1;
07931    ast_copy_string(buf, value, sizeof(buf));
07932 
07933    /*! register => [peer?][transport://]user[@domain][:secret[:authuser]]@host[:port][/extension][~expiry]
07934     * becomes
07935     *   userpart => [peer?][transport://]user[@domain][:secret[:authuser]]
07936     *   hostpart => host[:port][/extension][~expiry]
07937     */
07938    if ((hostpart = strrchr(buf, '@'))) {
07939       *hostpart++ = '\0';
07940       userpart = buf;
07941    }
07942 
07943    if (ast_strlen_zero(userpart) || ast_strlen_zero(hostpart)) {
07944       ast_log(LOG_WARNING, "Format for registration is [peer?][transport://]user[@domain][:secret[:authuser]]@host[:port][/extension][~expiry] at line %d\n", lineno);
07945       return -1;
07946    }
07947 
07948    /*!
07949     * pre1.peer => peer
07950     * pre1.userpart => [transport://]user[@domain][:secret[:authuser]]
07951     * hostpart => host[:port][/extension][~expiry]
07952     */
07953    AST_NONSTANDARD_RAW_ARGS(pre1, userpart, '?');
07954    if (ast_strlen_zero(pre1.userpart)) {
07955       pre1.userpart = pre1.peer;
07956       pre1.peer = NULL;
07957    }
07958 
07959    /*!
07960     * pre1.peer => peer
07961     * pre2.transport = transport
07962     * pre2.userpart => user[@domain][:secret[:authuser]]
07963     * hostpart => host[:port][/extension][~expiry]
07964     */
07965    AST_NONSTANDARD_RAW_ARGS(pre2, pre1.userpart, '/');
07966    if (ast_strlen_zero(pre2.userpart)) {
07967       pre2.userpart = pre2.transport;
07968       pre2.transport = NULL;
07969    } else {
07970       pre2.transport[strlen(pre2.transport) - 1] = '\0'; /* Remove trailing : */
07971    }
07972 
07973    if (!ast_strlen_zero(pre2.blank)) {
07974       ast_log(LOG_WARNING, "Format for registration is [peer?][transport://]user[@domain][:secret[:authuser]]@host[:port][/extension][~expiry] at line %d\n", lineno);
07975       return -1;
07976    }
07977 
07978    /*!
07979     * pre1.peer => peer
07980     * pre2.transport = transport
07981     * user1.userpart => user[@domain]
07982     * user1.secret => secret
07983     * user1.authuser => authuser
07984     * hostpart => host[:port][/extension][~expiry]
07985     */
07986    AST_NONSTANDARD_RAW_ARGS(user1, pre2.userpart, ':');
07987 
07988    /*!
07989     * pre1.peer => peer
07990     * pre2.transport = transport
07991     * user1.userpart => user[@domain]
07992     * user1.secret => secret
07993     * user1.authuser => authuser
07994     * host1.hostpart => host[:port][/extension]
07995     * host1.expiry => [expiry]
07996     */
07997    AST_NONSTANDARD_RAW_ARGS(host1, hostpart, '~');
07998 
07999    /*!
08000     * pre1.peer => peer
08001     * pre2.transport = transport
08002     * user1.userpart => user[@domain]
08003     * user1.secret => secret
08004     * user1.authuser => authuser
08005     * host2.hostpart => host[:port]
08006     * host2.extension => [extension]
08007     * host1.expiry => [expiry]
08008     */
08009    AST_NONSTANDARD_RAW_ARGS(host2, host1.hostpart, '/');
08010 
08011    /*!
08012     * pre1.peer => peer
08013     * pre2.transport = transport
08014     * user1.userpart => user[@domain]
08015     * user1.secret => secret
08016     * user1.authuser => authuser
08017     * host3.host => host
08018     * host3.port => port
08019     * host2.extension => extension
08020     * host1.expiry => expiry
08021     */
08022    AST_NONSTANDARD_RAW_ARGS(host3, host2.hostpart, ':');
08023 
08024    if (host3.port) {
08025       if (!(portnum = port_str2int(host3.port, 0))) {
08026          ast_log(LOG_NOTICE, "'%s' is not a valid port number on line %d of sip.conf. using default.\n", host3.port, lineno);
08027       }
08028    }
08029 
08030    /* set transport type */
08031    if (!pre2.transport) {
08032       transport = SIP_TRANSPORT_UDP;
08033    } else if (!strncasecmp(pre2.transport, "tcp", 3)) {
08034       transport = SIP_TRANSPORT_TCP;
08035    } else if (!strncasecmp(pre2.transport, "tls", 3)) {
08036       transport = SIP_TRANSPORT_TLS;
08037    } else if (!strncasecmp(pre2.transport, "udp", 3)) {
08038       transport = SIP_TRANSPORT_UDP;
08039    } else {
08040       transport = SIP_TRANSPORT_UDP;
08041       ast_log(LOG_NOTICE, "'%.3s' is not a valid transport type on line %d of sip.conf. defaulting to udp.\n", pre2.transport, lineno);
08042    }
08043 
08044    /* if no portnum specified, set default for transport */
08045    if (!portnum) {
08046       if (transport == SIP_TRANSPORT_TLS) {
08047          portnum = STANDARD_TLS_PORT;
08048       } else {
08049          portnum = STANDARD_SIP_PORT;
08050       }
08051    }
08052 
08053    if (!(reg = ast_calloc(1, sizeof(*reg)))) {
08054       ast_log(LOG_ERROR, "Out of memory. Can't allocate SIP registry entry\n");
08055       return -1;
08056    }
08057 
08058    if (ast_string_field_init(reg, 256)) {
08059       ast_log(LOG_ERROR, "Out of memory. Can't allocate SIP registry strings\n");
08060       ast_free(reg);
08061       return -1;
08062    }
08063 
08064    ast_atomic_fetchadd_int(&regobjs, 1);
08065    ASTOBJ_INIT(reg);
08066    ast_string_field_set(reg, callback, ast_strip_quoted(S_OR(host2.extension, "s"), "\"", "\""));
08067    ast_string_field_set(reg, username, ast_strip_quoted(S_OR(user1.userpart, ""), "\"", "\""));
08068    ast_string_field_set(reg, hostname, ast_strip_quoted(S_OR(host3.host, ""), "\"", "\""));
08069    ast_string_field_set(reg, authuser, ast_strip_quoted(S_OR(user1.authuser, ""), "\"", "\""));
08070    ast_string_field_set(reg, secret, ast_strip_quoted(S_OR(user1.secret, ""), "\"", "\""));
08071    ast_string_field_set(reg, peername, ast_strip_quoted(S_OR(pre1.peer, ""), "\"", "\""));
08072 
08073    reg->transport = transport;
08074    reg->timeout = reg->expire = -1;
08075    reg->refresh = reg->expiry = reg->configured_expiry = (host1.expiry ? atoi(ast_strip_quoted(host1.expiry, "\"", "\"")) : default_expiry);
08076    reg->portno = portnum;
08077    reg->callid_valid = FALSE;
08078    reg->ocseq = INITIAL_CSEQ;
08079    ASTOBJ_CONTAINER_LINK(&regl, reg); /* Add the new registry entry to the list */
08080    registry_unref(reg, "unref the reg pointer");   /* release the reference given by ASTOBJ_INIT. The container has another reference */
08081    return 0;
08082 }
08083 
08084 /*! \brief Parse mwi=> line in sip.conf and add to list */
08085 static int sip_subscribe_mwi(const char *value, int lineno)
08086 {
08087    struct sip_subscription_mwi *mwi;
08088    int portnum = 0;
08089    enum sip_transport transport = SIP_TRANSPORT_UDP;
08090    char buf[256] = "";
08091    char *username = NULL, *hostname = NULL, *secret = NULL, *authuser = NULL, *porta = NULL, *mailbox = NULL;
08092    
08093    if (!value) {
08094       return -1;
08095    }
08096    
08097    ast_copy_string(buf, value, sizeof(buf));
08098 
08099    sip_parse_host(buf, lineno, &username, &portnum, &transport);
08100    
08101    if ((hostname = strrchr(username, '@'))) {
08102       *hostname++ = '\0';
08103    }
08104    
08105    if ((secret = strchr(username, ':'))) {
08106       *secret++ = '\0';
08107       if ((authuser = strchr(secret, ':'))) {
08108          *authuser++ = '\0';
08109       }
08110    }
08111    
08112    if ((mailbox = strchr(hostname, '/'))) {
08113       *mailbox++ = '\0';
08114    }
08115 
08116    if (ast_strlen_zero(username) || ast_strlen_zero(hostname) || ast_strlen_zero(mailbox)) {
08117       ast_log(LOG_WARNING, "Format for MWI subscription is user[:secret[:authuser]]@host[:port][/mailbox] at line %d\n", lineno);
08118       return -1;
08119    }
08120    
08121    if ((porta = strchr(hostname, ':'))) {
08122       *porta++ = '\0';
08123       if (!(portnum = atoi(porta))) {
08124          ast_log(LOG_WARNING, "%s is not a valid port number at line %d\n", porta, lineno);
08125          return -1;
08126       }
08127    }
08128    
08129    if (!(mwi = ast_calloc(1, sizeof(*mwi)))) {
08130       return -1;
08131    }
08132    
08133    if (ast_string_field_init(mwi, 256)) {
08134       ast_free(mwi);
08135       return -1;
08136    }
08137    
08138    ASTOBJ_INIT(mwi);
08139    ast_string_field_set(mwi, username, username);
08140    if (secret) {
08141       ast_string_field_set(mwi, secret, secret);
08142    }
08143    if (authuser) {
08144       ast_string_field_set(mwi, authuser, authuser);
08145    }
08146    ast_string_field_set(mwi, hostname, hostname);
08147    ast_string_field_set(mwi, mailbox, mailbox);
08148    mwi->resub = -1;
08149    mwi->portno = portnum;
08150    mwi->transport = transport;
08151    
08152    ASTOBJ_CONTAINER_LINK(&submwil, mwi);
08153    ASTOBJ_UNREF(mwi, sip_subscribe_mwi_destroy);
08154    
08155    return 0;
08156 }
08157 
08158 /*! \brief  Parse multiline SIP headers into one header
08159    This is enabled if pedanticsipchecking is enabled */
08160 static int lws2sws(char *msgbuf, int len) 
08161 {
08162    int h = 0, t = 0; 
08163    int lws = 0; 
08164 
08165    for (; h < len;) { 
08166       /* Eliminate all CRs */ 
08167       if (msgbuf[h] == '\r') { 
08168          h++; 
08169          continue; 
08170       } 
08171       /* Check for end-of-line */ 
08172       if (msgbuf[h] == '\n') { 
08173          /* Check for end-of-message */ 
08174          if (h + 1 == len) 
08175             break; 
08176          /* Check for a continuation line */ 
08177          if (msgbuf[h + 1] == ' ' || msgbuf[h + 1] == '\t') { 
08178             /* Merge continuation line */ 
08179             h++; 
08180             continue; 
08181          } 
08182          /* Propagate LF and start new line */ 
08183          msgbuf[t++] = msgbuf[h++]; 
08184          lws = 0;
08185          continue; 
08186       } 
08187       if (msgbuf[h] == ' ' || msgbuf[h] == '\t') { 
08188          if (lws) { 
08189             h++; 
08190             continue; 
08191          } 
08192          msgbuf[t++] = msgbuf[h++]; 
08193          lws = 1; 
08194          continue; 
08195       } 
08196       msgbuf[t++] = msgbuf[h++]; 
08197       if (lws) 
08198          lws = 0; 
08199    } 
08200    msgbuf[t] = '\0'; 
08201    return t; 
08202 }
08203 
08204 /*! \brief Parse a SIP message 
08205    \note this function is used both on incoming and outgoing packets
08206 */
08207 static int parse_request(struct sip_request *req)
08208 {
08209    char *c = req->data->str;
08210    ptrdiff_t *dst = req->header;
08211    int i = 0, lim = SIP_MAX_HEADERS - 1;
08212    unsigned int skipping_headers = 0;
08213    ptrdiff_t current_header_offset = 0;
08214    char *previous_header = "";
08215 
08216    req->header[0] = 0;
08217    req->headers = -1;   /* mark that we are working on the header */
08218    for (; *c; c++) {
08219       if (*c == '\r') {    /* remove \r */
08220          *c = '\0';
08221       } else if (*c == '\n') {   /* end of this line */
08222          *c = '\0';
08223          current_header_offset = (c + 1) - req->data->str;
08224          previous_header = req->data->str + dst[i];
08225          if (skipping_headers) {
08226             /* check to see if this line is blank; if so, turn off
08227                the skipping flag, so the next line will be processed
08228                as a body line */
08229             if (ast_strlen_zero(previous_header)) {
08230                skipping_headers = 0;
08231             }
08232             dst[i] = current_header_offset; /* record start of next line */
08233             continue;
08234          }
08235          if (sipdebug) {
08236             ast_debug(4, "%7s %2d [%3d]: %s\n",
08237                  req->headers < 0 ? "Header" : "Body",
08238                  i, (int) strlen(previous_header), previous_header);
08239          }
08240          if (ast_strlen_zero(previous_header) && req->headers < 0) {
08241             req->headers = i; /* record number of header lines */
08242             dst = req->line;  /* start working on the body */
08243             i = 0;
08244             lim = SIP_MAX_LINES - 1;
08245          } else { /* move to next line, check for overflows */
08246             if (i++ == lim) {
08247                /* if we're processing headers, then skip any remaining
08248                   headers and move on to processing the body, otherwise
08249                   we're done */
08250                if (req->headers != -1) {
08251                   break;
08252                } else {
08253                   req->headers = i;
08254                   dst = req->line;
08255                   i = 0;
08256                   lim = SIP_MAX_LINES - 1;
08257                   skipping_headers = 1;
08258                }
08259             }
08260          }
08261          dst[i] = current_header_offset; /* record start of next line */
08262       }
08263    }
08264 
08265    /* Check for last header or body line without CRLF. The RFC for SDP requires CRLF,
08266       but since some devices send without, we'll be generous in what we accept. However,
08267       if we've already reached the maximum number of lines for portion of the message
08268       we were parsing, we can't accept any more, so just ignore it.
08269    */
08270    previous_header = req->data->str + dst[i];
08271    if ((i < lim) && !ast_strlen_zero(previous_header)) {
08272       if (sipdebug) {
08273          ast_debug(4, "%7s %2d [%3d]: %s\n",
08274               req->headers < 0 ? "Header" : "Body",
08275               i, (int) strlen(previous_header), previous_header );
08276       }
08277       i++;
08278    }
08279 
08280    /* update count of header or body lines */
08281    if (req->headers >= 0) {   /* we are in the body */
08282       req->lines = i;
08283    } else {       /* no body */
08284       req->headers = i;
08285       req->lines = 0;
08286       /* req->data->used will be a NULL byte */
08287       req->line[0] = ast_str_strlen(req->data);
08288    }
08289 
08290    if (*c) {
08291       ast_log(LOG_WARNING, "Too many lines, skipping <%s>\n", c);
08292    }
08293 
08294    /* Split up the first line parts */
08295    return determine_firstline_parts(req);
08296 }
08297 
08298 /*!
08299   \brief Determine whether a SIP message contains an SDP in its body
08300   \param req the SIP request to process
08301   \return 1 if SDP found, 0 if not found
08302 
08303   Also updates req->sdp_start and req->sdp_count to indicate where the SDP
08304   lives in the message body.
08305 */
08306 static int find_sdp(struct sip_request *req)
08307 {
08308    const char *content_type;
08309    const char *content_length;
08310    const char *search;
08311    char *boundary;
08312    unsigned int x;
08313    int boundaryisquoted = FALSE;
08314    int found_application_sdp = FALSE;
08315    int found_end_of_headers = FALSE;
08316 
08317    content_length = get_header(req, "Content-Length");
08318 
08319    if (!ast_strlen_zero(content_length)) {
08320       if (sscanf(content_length, "%30u", &x) != 1) {
08321          ast_log(LOG_WARNING, "Invalid Content-Length: %s\n", content_length);
08322          return 0;
08323       }
08324 
08325       /* Content-Length of zero means there can't possibly be an
08326          SDP here, even if the Content-Type says there is */
08327       if (x == 0)
08328          return 0;
08329    }
08330 
08331    content_type = get_header(req, "Content-Type");
08332 
08333    /* if the body contains only SDP, this is easy */
08334    if (!strncasecmp(content_type, "application/sdp", 15)) {
08335       req->sdp_start = 0;
08336       req->sdp_count = req->lines;
08337       return req->lines ? 1 : 0;
08338    }
08339 
08340    /* if it's not multipart/mixed, there cannot be an SDP */
08341    if (strncasecmp(content_type, "multipart/mixed", 15))
08342       return 0;
08343 
08344    /* if there is no boundary marker, it's invalid */
08345    if ((search = strcasestr(content_type, ";boundary=")))
08346       search += 10;
08347    else if ((search = strcasestr(content_type, "; boundary=")))
08348       search += 11;
08349    else
08350       return 0;
08351 
08352    if (ast_strlen_zero(search))
08353       return 0;
08354 
08355    /* If the boundary is quoted with ", remove quote */
08356    if (*search == '\"')  {
08357       search++;
08358       boundaryisquoted = TRUE;
08359    }
08360 
08361    /* make a duplicate of the string, with two extra characters
08362       at the beginning */
08363    boundary = ast_strdupa(search - 2);
08364    boundary[0] = boundary[1] = '-';
08365    /* Remove final quote */
08366    if (boundaryisquoted)
08367       boundary[strlen(boundary) - 1] = '\0';
08368 
08369    /* search for the boundary marker, the empty line delimiting headers from
08370       sdp part and the end boundry if it exists */
08371 
08372    for (x = 0; x < (req->lines); x++) {
08373       char *line = REQ_OFFSET_TO_STR(req, line[x]);
08374       if (!strncasecmp(line, boundary, strlen(boundary))){
08375          if (found_application_sdp && found_end_of_headers) {
08376             req->sdp_count = (x - 1) - req->sdp_start;
08377             return 1;
08378          }
08379          found_application_sdp = FALSE;
08380       }
08381       if (!strcasecmp(line, "Content-Type: application/sdp"))
08382          found_application_sdp = TRUE;
08383       
08384       if (ast_strlen_zero(line)) {
08385          if (found_application_sdp && !found_end_of_headers){
08386             req->sdp_start = x;
08387             found_end_of_headers = TRUE;
08388          }
08389       }
08390    }
08391    if (found_application_sdp && found_end_of_headers) {
08392       req->sdp_count = x - req->sdp_start;
08393       return TRUE;
08394    }
08395    return FALSE;
08396 }
08397 
08398 /*! \brief Change hold state for a call */
08399 static void change_hold_state(struct sip_pvt *dialog, struct sip_request *req, int holdstate, int sendonly)
08400 {
08401    if (sip_cfg.notifyhold && (!holdstate || !ast_test_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD)))
08402       sip_peer_hold(dialog, holdstate);
08403    if (sip_cfg.callevents)
08404       manager_event(EVENT_FLAG_CALL, "Hold",
08405                "Status: %s\r\n"
08406                "Channel: %s\r\n"
08407                "Uniqueid: %s\r\n",
08408                holdstate ? "On" : "Off",
08409                dialog->owner->name,
08410                dialog->owner->uniqueid);
08411    append_history(dialog, holdstate ? "Hold" : "Unhold", "%s", req->data->str);
08412    if (!holdstate) { /* Put off remote hold */
08413       ast_clear_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD);   /* Clear both flags */
08414       return;
08415    }
08416    /* No address for RTP, we're on hold */
08417 
08418    if (sendonly == 1)   /* One directional hold (sendonly/recvonly) */
08419       ast_set_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD_ONEDIR);
08420    else if (sendonly == 2) /* Inactive stream */
08421       ast_set_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD_INACTIVE);
08422    else
08423       ast_set_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD_ACTIVE);
08424    return;
08425 }
08426 
08427 enum media_type {
08428    SDP_AUDIO,
08429    SDP_VIDEO,
08430    SDP_IMAGE,
08431    SDP_TEXT,
08432 };
08433 
08434 static int get_ip_and_port_from_sdp(struct sip_request *req, const enum media_type media, struct sockaddr_in *sin)
08435 {
08436    const char *m;
08437    const char *c;
08438    int miterator = req->sdp_start;
08439    int citerator = req->sdp_start;
08440    int x = 0;
08441    int numberofports;
08442    int len;
08443    char host[258] = ""; /*Initialize to empty so we will know if we have any input */
08444    struct ast_hostent audiohp;
08445    struct hostent *hp;
08446 
08447    c = get_sdp_iterate(&citerator, req, "c");
08448    if (sscanf(c, "IN IP4 %256s", host) != 1) {
08449       ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
08450       /* Continue since there may be a valid host in a c= line specific to the audio stream */
08451    }
08452    /* We only want the m and c lines for audio */
08453    for (m = get_sdp_iterate(&miterator, req, "m"); !ast_strlen_zero(m); m = get_sdp_iterate(&miterator, req, "m")) {
08454       if ((media == SDP_AUDIO && ((sscanf(m, "audio %30u/%30u RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
08455           (sscanf(m, "audio %30u RTP/AVP %n", &x, &len) == 1 && len > 0))) ||
08456          (media == SDP_VIDEO && ((sscanf(m, "video %30u/%30u RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
08457           (sscanf(m, "video %30u RTP/AVP %n", &x, &len) == 1 && len > 0)))) {
08458          /* See if there's a c= line for this media stream.
08459           * XXX There is no guarantee that we'll be grabbing the c= line for this
08460           * particular media stream here. However, this is the same logic used in process_sdp.
08461           */
08462          c = get_sdp_iterate(&citerator, req, "c");
08463          if (!ast_strlen_zero(c)) {
08464             sscanf(c, "IN IP4 %256s", host);
08465          }
08466          break;
08467       }
08468    }
08469 
08470    if (ast_strlen_zero(host) || x == 0) {
08471       ast_log(LOG_WARNING, "Failed to read an alternate host or port in SDP. Expect %s problems\n", media == SDP_AUDIO ? "audio" : "video");
08472       return -1;
08473    }
08474 
08475    hp = ast_gethostbyname(host, &audiohp);
08476    if (!hp) {
08477       ast_log(LOG_WARNING, "Could not look up IP address of alternate hostname. Expect %s problems\n", media == SDP_AUDIO? "audio" : "video");
08478       return -1;
08479    }
08480 
08481    memcpy(&sin->sin_addr, hp->h_addr, sizeof(sin->sin_addr));
08482    sin->sin_port = htons(x);
08483    return 0;
08484 }
08485 
08486 /*! \brief Process SIP SDP offer, select formats and activate RTP channels
08487    If offer is rejected, we will not change any properties of the call
08488    Return 0 on success, a negative value on errors.
08489    Must be called after find_sdp().
08490 */
08491 static int process_sdp(struct sip_pvt *p, struct sip_request *req, int t38action)
08492 {
08493    /* Iterators for SDP parsing */
08494    int start = req->sdp_start;
08495    int next = start;
08496    int iterator = start;
08497 
08498    /* Temporary vars for SDP parsing */
08499    char type = '\0';
08500    const char *value = NULL;
08501    const char *m = NULL;           /* SDP media offer */
08502    const char *nextm = NULL;
08503    int len = -1;
08504 
08505    /* Host information */
08506    struct ast_hostent sessionhp;
08507    struct ast_hostent audiohp;
08508    struct ast_hostent videohp;
08509    struct ast_hostent texthp;
08510    struct ast_hostent imagehp;
08511    struct hostent *hp = NULL; /*!< RTP Audio host IP */
08512    struct hostent *vhp = NULL;   /*!< RTP video host IP */
08513    struct hostent *thp = NULL;   /*!< RTP text host IP */
08514    struct hostent *ihp = NULL;     /*!< UDPTL host ip */
08515    int portno = -1;     /*!< RTP Audio port number */
08516    int vportno = -1;    /*!< RTP Video port number */
08517    int tportno = -1;    /*!< RTP Text port number */
08518    int udptlportno = -1;      /*!< UDPTL Image port number */
08519    struct sockaddr_in sin = { 0, }; /*!< media socket address */
08520    struct sockaddr_in vsin = { 0, };   /*!< video socket address */
08521    struct sockaddr_in isin = { 0, };   /*!< image socket address */
08522    struct sockaddr_in tsin = { 0, };   /*!< text socket address */
08523 
08524    /* Peer capability is the capability in the SDP, non codec is RFC2833 DTMF (101) */ 
08525    int peercapability = 0, peernoncodeccapability = 0;
08526    int vpeercapability = 0, vpeernoncodeccapability = 0;
08527    int tpeercapability = 0, tpeernoncodeccapability = 0;
08528 
08529    struct ast_rtp *newaudiortp, *newvideortp, *newtextrtp;
08530    int newjointcapability;          /* Negotiated capability */
08531    int newpeercapability;
08532    int newnoncodeccapability;
08533 
08534    const char *codecs;
08535    int codec;
08536 
08537    /* Others */
08538    int sendonly = -1;
08539    int vsendonly = -1;
08540    int numberofports;
08541    int numberofmediastreams = 0;
08542    int last_rtpmap_codec = 0;
08543    int red_data_pt[10];    /* For T.140 red */
08544    int red_num_gen = 0;    /* For T.140 red */
08545    char red_fmtp[100] = "empty"; /* For T.140 red */
08546    int debug = sip_debug_test_pvt(p);
08547 
08548    /* START UNKNOWN */
08549    char buf[SIPBUFSIZE];
08550    /* END UNKNOWN */
08551 
08552    /* Initial check */
08553    if (!p->rtp) {
08554       ast_log(LOG_ERROR, "Got SDP but have no RTP session allocated.\n");
08555       return -1;
08556    }
08557 
08558    /* Initialize the temporary RTP structures we use to evaluate the offer from the peer */
08559 #ifdef LOW_MEMORY
08560    newaudiortp = ast_threadstorage_get(&ts_audio_rtp, ast_rtp_alloc_size());
08561 #else
08562    newaudiortp = alloca(ast_rtp_alloc_size());
08563 #endif
08564    memset(newaudiortp, 0, ast_rtp_alloc_size());
08565    ast_rtp_new_init(newaudiortp);
08566    ast_rtp_pt_clear(newaudiortp);
08567 
08568 #ifdef LOW_MEMORY
08569    newvideortp = ast_threadstorage_get(&ts_video_rtp, ast_rtp_alloc_size());
08570 #else
08571    newvideortp = alloca(ast_rtp_alloc_size());
08572 #endif
08573    memset(newvideortp, 0, ast_rtp_alloc_size());
08574    ast_rtp_new_init(newvideortp);
08575    ast_rtp_pt_clear(newvideortp);
08576 
08577 #ifdef LOW_MEMORY
08578    newtextrtp = ast_threadstorage_get(&ts_text_rtp, ast_rtp_alloc_size());
08579 #else
08580    newtextrtp = alloca(ast_rtp_alloc_size());
08581 #endif
08582    memset(newtextrtp, 0, ast_rtp_alloc_size());
08583    ast_rtp_new_init(newtextrtp);
08584    ast_rtp_pt_clear(newtextrtp);
08585 
08586    /* Update our last rtprx when we receive an SDP, too */
08587    p->lastrtprx = p->lastrtptx = time(NULL); /* XXX why both ? */
08588 
08589    memset(p->offered_media, 0, sizeof(p->offered_media));
08590 
08591 
08592    /* default: novideo and notext set */
08593    p->novideo = TRUE;
08594    p->notext = TRUE;
08595 
08596    if (p->vrtp)
08597       ast_rtp_pt_clear(newvideortp);  /* Must be cleared in case no m=video line exists */
08598  
08599    if (p->trtp)
08600       ast_rtp_pt_clear(newtextrtp);  /* Must be cleared in case no m=text line exists */
08601    
08602    /* Scan for the first media stream (m=) line to limit scanning of globals */
08603    nextm = get_sdp_iterate(&next, req, "m");
08604    if (ast_strlen_zero(nextm)) {
08605       ast_log(LOG_WARNING, "Insufficient information for SDP (m= not found)\n");
08606       return -1;
08607    }
08608 
08609    /* Scan session level SDP parameters (lines before first media stream) */
08610    while ((type = get_sdp_line(&iterator, next - 1, req, &value)) != '\0') {
08611       int processed = FALSE;
08612       switch (type) {
08613       case 'o':
08614          /* If we end up receiving SDP that doesn't actually modify the session we don't want to treat this as a fatal
08615           * error. We just want to ignore the SDP and let the rest of the packet be handled as normal.
08616           */
08617          if (!process_sdp_o(value, p))
08618             return (p->session_modify == FALSE) ? 0 : -1;
08619          break;
08620       case 'c':
08621          if (process_sdp_c(value, &sessionhp)) {
08622             processed = TRUE;
08623             hp = &sessionhp.hp;
08624             vhp = hp;
08625             thp = hp;
08626             ihp = hp;
08627          }
08628          break;
08629       case 'a':
08630          if (process_sdp_a_sendonly(value, &sendonly)) {
08631             processed = TRUE;
08632             vsendonly = sendonly;
08633          }
08634          else if (process_sdp_a_audio(value, p, newaudiortp, &last_rtpmap_codec))
08635             processed = TRUE;
08636          else if (process_sdp_a_video(value, p, newvideortp, &last_rtpmap_codec))
08637             processed = TRUE;
08638          else if (process_sdp_a_text(value, p, newtextrtp, red_fmtp, &red_num_gen, red_data_pt, &last_rtpmap_codec))
08639             processed = TRUE;
08640          else if (process_sdp_a_image(value, p))
08641             processed = TRUE;
08642          break;
08643       }
08644 
08645       if (option_debug > 2)
08646          ast_log(LOG_DEBUG, "Processing session-level SDP %c=%s... %s\n", type, value, (processed == TRUE)? "OK." : "UNSUPPORTED.");
08647    }
08648 
08649 
08650 
08651    /* Scan media stream (m=) specific parameters loop */
08652    while (!ast_strlen_zero(nextm)) {
08653       int audio = FALSE;
08654       int video = FALSE;
08655       int image = FALSE;
08656       int text = FALSE;
08657       int x;
08658 
08659       numberofports = 1;
08660       len = -1;
08661       start = next;
08662       m = nextm;
08663       iterator = next;
08664       nextm = get_sdp_iterate(&next, req, "m");
08665 
08666       /* Search for audio media definition */
08667       if ((sscanf(m, "audio %30u/%30u RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
08668           (sscanf(m, "audio %30u RTP/AVP %n", &x, &len) == 1 && len > 0)) {
08669          audio = TRUE;
08670          p->offered_media[SDP_AUDIO].offered = TRUE;
08671          numberofmediastreams++;
08672          portno = x;
08673 
08674          /* Scan through the RTP payload types specified in a "m=" line: */
08675          codecs = m + len;
08676          ast_copy_string(p->offered_media[SDP_AUDIO].text, codecs, sizeof(p->offered_media[SDP_AUDIO].text));
08677          for (; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
08678             if (sscanf(codecs, "%30u%n", &codec, &len) != 1) {
08679                ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
08680                return -1;
08681             }
08682             if (debug)
08683                ast_verbose("Found RTP audio format %d\n", codec);
08684 
08685             ast_rtp_set_m_type(newaudiortp, codec);
08686          }
08687       /* Search for video media definition */
08688       } else if ((sscanf(m, "video %30u/%30u RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
08689             (sscanf(m, "video %30u RTP/AVP %n", &x, &len) == 1 && len >= 0)) {
08690          video = TRUE;
08691          p->novideo = FALSE;
08692          p->offered_media[SDP_VIDEO].offered = TRUE;
08693          numberofmediastreams++;
08694          vportno = x;
08695 
08696          /* Scan through the RTP payload types specified in a "m=" line: */
08697          codecs = m + len;
08698          ast_copy_string(p->offered_media[SDP_VIDEO].text, codecs, sizeof(p->offered_media[SDP_VIDEO].text));
08699          for (; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
08700             if (sscanf(codecs, "%30u%n", &codec, &len) != 1) {
08701                ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
08702                return -1;
08703             }
08704             if (debug)
08705                ast_verbose("Found RTP video format %d\n", codec);
08706             ast_rtp_set_m_type(newvideortp, codec);
08707          }
08708       /* Search for text media definition */
08709       } else if ((sscanf(m, "text %30u/%30u RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
08710             (sscanf(m, "text %30u RTP/AVP %n", &x, &len) == 1 && len > 0)) {
08711          text = TRUE;
08712          p->notext = FALSE;
08713          p->offered_media[SDP_TEXT].offered = TRUE;
08714          numberofmediastreams++;
08715          tportno = x;
08716 
08717          /* Scan through the RTP payload types specified in a "m=" line: */
08718          codecs = m + len;
08719          ast_copy_string(p->offered_media[SDP_TEXT].text, codecs, sizeof(p->offered_media[SDP_TEXT].text));
08720          for (; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
08721             if (sscanf(codecs, "%30u%n", &codec, &len) != 1) {
08722                ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
08723                return -1;
08724             }
08725             if (debug)
08726                ast_verbose("Found RTP text format %d\n", codec);
08727             ast_rtp_set_m_type(newtextrtp, codec);
08728          }
08729       /* Search for image media definition */
08730       } else if (p->udptl && ((sscanf(m, "image %30u udptl t38%n", &x, &len) == 1 && len > 0) ||
08731                (sscanf(m, "image %30u UDPTL t38%n", &x, &len) == 1 && len > 0) )) {
08732          image = TRUE;
08733          if (debug)
08734             ast_verbose("Got T.38 offer in SDP in dialog %s\n", p->callid);
08735          p->offered_media[SDP_IMAGE].offered = TRUE;
08736          udptlportno = x;
08737          numberofmediastreams++;
08738 
08739          if (p->t38.state != T38_ENABLED) {
08740             memset(&p->t38.their_parms, 0, sizeof(p->t38.their_parms));
08741 
08742             /* default EC to none, the remote end should
08743              * respond with the EC they want to use */
08744             ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_NONE);
08745          }
08746       } else {
08747          ast_log(LOG_WARNING, "Unsupported SDP media type in offer: %s\n", m);
08748          continue;
08749       }
08750 
08751       /* Check for number of ports */
08752       if (numberofports > 1)
08753          ast_log(LOG_WARNING, "SDP offered %d ports for media, not supported by Asterisk. Will try anyway...\n", numberofports);
08754       
08755 
08756 
08757       /* Media stream specific parameters */
08758       while ((type = get_sdp_line(&iterator, next - 1, req, &value)) != '\0') {
08759          int processed = FALSE;
08760 
08761          switch (type) {
08762          case 'c':
08763             if (audio) {
08764                if (process_sdp_c(value, &audiohp)) {
08765                   processed = TRUE;
08766                   hp = &audiohp.hp;
08767                }
08768             } else if (video) {
08769                if (process_sdp_c(value, &videohp)) {
08770                   processed = TRUE;
08771                   vhp = &videohp.hp;
08772                }
08773             } else if (text) {
08774                if (process_sdp_c(value, &texthp)) {
08775                   processed = TRUE;
08776                   thp = &texthp.hp;
08777                }
08778             } else if (image) {
08779                if (process_sdp_c(value, &imagehp)) {
08780                   processed = TRUE;
08781                   ihp = &imagehp.hp;
08782                }
08783             }
08784             break;
08785          case 'a':
08786             /* Audio specific scanning */
08787             if (audio) {
08788                if (process_sdp_a_sendonly(value, &sendonly))
08789                   processed = TRUE;
08790                else if (process_sdp_a_audio(value, p, newaudiortp, &last_rtpmap_codec))
08791                   processed = TRUE;
08792             }
08793             /* Video specific scanning */
08794             else if (video) {
08795                if (process_sdp_a_sendonly(value, &vsendonly))
08796                   processed = TRUE;
08797                else if (process_sdp_a_video(value, p, newvideortp, &last_rtpmap_codec))
08798                   processed = TRUE;
08799             }
08800             /* Text (T.140) specific scanning */
08801             else if (text) {
08802                if (process_sdp_a_text(value, p, newtextrtp, red_fmtp, &red_num_gen, red_data_pt, &last_rtpmap_codec))
08803                   processed = TRUE;
08804             }
08805             /* Image (T.38 FAX) specific scanning */
08806             else if (image) {
08807                if (process_sdp_a_image(value, p))
08808                   processed = TRUE;
08809             }
08810             break;
08811          }
08812 
08813          if (option_debug > 2)
08814             ast_log(LOG_DEBUG, "Processing media-level (%s) SDP %c=%s... %s\n",
08815                   (audio == TRUE)? "audio" : (video == TRUE)? "video" : "image",
08816                   type, value,
08817                   (processed == TRUE)? "OK." : "UNSUPPORTED.");
08818       }
08819    }
08820 
08821 
08822    /* Sanity checks */
08823    if (!hp && !vhp && !thp && !ihp) {
08824       ast_log(LOG_WARNING, "Insufficient information in SDP (c=)...\n");
08825       return -1;
08826    }
08827 
08828    if (portno == -1 && vportno == -1 && udptlportno == -1  && tportno == -1)
08829       /* No acceptable offer found in SDP  - we have no ports */
08830       /* Do not change RTP or VRTP if this is a re-invite */
08831       return -2;
08832 
08833    if (numberofmediastreams > 3)
08834       /* We have too many fax, audio and/or video and/or text media streams, fail this offer */
08835       return -3;
08836 
08837    if (udptlportno == -1) {
08838       change_t38_state(p, T38_DISABLED);
08839    }
08840 
08841 
08842    /* Now gather all of the codecs that we are asked for: */
08843    ast_rtp_get_current_formats(newaudiortp, &peercapability, &peernoncodeccapability);
08844    ast_rtp_get_current_formats(newvideortp, &vpeercapability, &vpeernoncodeccapability);
08845    ast_rtp_get_current_formats(newtextrtp, &tpeercapability, &tpeernoncodeccapability);
08846 
08847    newjointcapability = p->capability & (peercapability | vpeercapability | tpeercapability);
08848    newpeercapability = (peercapability | vpeercapability | tpeercapability);
08849    newnoncodeccapability = p->noncodeccapability & peernoncodeccapability;
08850 
08851    if (debug) {
08852       /* shame on whoever coded this.... */
08853       char s1[SIPBUFSIZE], s2[SIPBUFSIZE], s3[SIPBUFSIZE], s4[SIPBUFSIZE], s5[SIPBUFSIZE];
08854 
08855       ast_verbose("Capabilities: us - %s, peer - audio=%s/video=%s/text=%s, combined - %s\n",
08856              ast_getformatname_multiple(s1, SIPBUFSIZE, p->capability),
08857              ast_getformatname_multiple(s2, SIPBUFSIZE, peercapability),
08858              ast_getformatname_multiple(s3, SIPBUFSIZE, vpeercapability),
08859              ast_getformatname_multiple(s4, SIPBUFSIZE, tpeercapability),
08860              ast_getformatname_multiple(s5, SIPBUFSIZE, newjointcapability));
08861 
08862       ast_verbose("Non-codec capabilities (dtmf): us - %s, peer - %s, combined - %s\n",
08863              ast_rtp_lookup_mime_multiple(s1, SIPBUFSIZE, p->noncodeccapability, 0, 0),
08864              ast_rtp_lookup_mime_multiple(s2, SIPBUFSIZE, peernoncodeccapability, 0, 0),
08865              ast_rtp_lookup_mime_multiple(s3, SIPBUFSIZE, newnoncodeccapability, 0, 0));
08866    }
08867    if (!newjointcapability && (portno != -1)) {
08868       ast_log(LOG_NOTICE, "No compatible codecs, not accepting this offer!\n");
08869       /* Do NOT Change current setting */
08870       return -1;
08871    }
08872 
08873    /* Setup audio address and port */
08874    if (p->rtp) {
08875       if (portno > 0) {
08876          sin.sin_family = AF_INET;
08877          sin.sin_port = htons(portno);
08878          memcpy(&sin.sin_addr, hp->h_addr, sizeof(sin.sin_addr));
08879          ast_rtp_set_peer(p->rtp, &sin);
08880          if (debug)
08881             ast_verbose("Peer audio RTP is at port %s:%d\n", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
08882          /* We are now ready to change the sip session and p->rtp and p->vrtp with the offered codecs, since                                                                                                    
08883             they are acceptable */
08884          p->jointcapability = newjointcapability;                /* Our joint codec profile for this call */
08885          p->peercapability = newpeercapability;                  /* The other sides capability in latest offer */
08886          p->jointnoncodeccapability = newnoncodeccapability;     /* DTMF capabilities */
08887 
08888          ast_rtp_pt_copy(p->rtp, newaudiortp);
08889 
08890          if (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO) {
08891             ast_clear_flag(&p->flags[0], SIP_DTMF);
08892             if (newnoncodeccapability & AST_RTP_DTMF) {
08893                /* XXX Would it be reasonable to drop the DSP at this point? XXX */
08894                ast_set_flag(&p->flags[0], SIP_DTMF_RFC2833);
08895                /* Since RFC2833 is now negotiated we need to change some properties of the RTP stream */
08896                ast_rtp_setdtmf(p->rtp, 1);
08897                ast_rtp_setdtmfcompensate(p->rtp, ast_test_flag(&p->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
08898             } else {
08899                ast_set_flag(&p->flags[0], SIP_DTMF_INBAND);
08900             }
08901          }
08902       } else if (udptlportno > 0) {
08903          if (debug)
08904             ast_verbose("Got T.38 Re-invite without audio. Keeping RTP active during T.38 session.\n");
08905       } else {
08906          ast_rtp_stop(p->rtp);
08907          if (debug)
08908             ast_verbose("Peer doesn't provide audio\n");
08909       }
08910    }
08911 
08912    /* Setup video address and port */
08913    if (p->vrtp) {
08914       if (vportno > 0) {
08915          vsin.sin_family = AF_INET;
08916          vsin.sin_port = htons(vportno);
08917          memcpy(&vsin.sin_addr, vhp->h_addr, sizeof(vsin.sin_addr));
08918          ast_rtp_set_peer(p->vrtp, &vsin);
08919          if (debug) 
08920             ast_verbose("Peer video RTP is at port %s:%d\n", ast_inet_ntoa(vsin.sin_addr), ntohs(vsin.sin_port));
08921          ast_rtp_pt_copy(p->vrtp, newvideortp);
08922       } else {
08923          ast_rtp_stop(p->vrtp);
08924          if (debug)
08925             ast_verbose("Peer doesn't provide video\n");
08926       }
08927    }
08928 
08929    /* Setup text address and port */
08930    if (p->trtp) {
08931       if (tportno > 0) {
08932          tsin.sin_family = AF_INET;
08933          tsin.sin_port = htons(tportno);
08934          memcpy(&tsin.sin_addr, thp->h_addr, sizeof(tsin.sin_addr));
08935          ast_rtp_set_peer(p->trtp, &tsin);
08936          if (debug) 
08937             ast_verbose("Peer T.140 RTP is at port %s:%d\n", ast_inet_ntoa(tsin.sin_addr), ntohs(tsin.sin_port));
08938          if ((p->jointcapability & AST_FORMAT_T140RED)) {
08939             p->red = 1;
08940             rtp_red_init(p->trtp, 300, red_data_pt, 2);
08941          } else {
08942             p->red = 0;
08943          }
08944          ast_rtp_pt_copy(p->trtp, newtextrtp);
08945       } else {
08946          ast_rtp_stop(p->trtp);
08947          if (debug)
08948             ast_verbose("Peer doesn't provide T.140\n");
08949       }
08950    }
08951    /* Setup image address and port */
08952    if (p->udptl) {
08953       if (udptlportno > 0) {
08954          isin.sin_family = AF_INET;
08955          isin.sin_port = htons(udptlportno);
08956          if (ast_test_flag(&p->flags[0], SIP_NAT) && ast_test_flag(&p->flags[1], SIP_PAGE2_UDPTL_DESTINATION)) {
08957             struct sockaddr_in remote_address = { 0, };
08958             ast_rtp_get_peer(p->rtp, &remote_address);
08959             if (remote_address.sin_addr.s_addr) {
08960                memcpy(&isin, &remote_address, sizeof(isin));
08961                if (debug) {
08962                   ast_log(LOG_DEBUG, "Peer T.38 UDPTL is set behind NAT and with destination, destination address now %s\n", ast_inet_ntoa(isin.sin_addr));
08963                }
08964             }
08965          } else {
08966             memcpy(&isin.sin_addr, ihp->h_addr, sizeof(isin.sin_addr));
08967          }
08968          ast_udptl_set_peer(p->udptl, &isin);
08969          if (debug)
08970             ast_debug(1,"Peer T.38 UDPTL is at port %s:%d\n", ast_inet_ntoa(isin.sin_addr), ntohs(isin.sin_port));
08971 
08972          /* verify the far max ifp can be calculated. this requires far max datagram to be set. */
08973          if (!ast_udptl_get_far_max_datagram(p->udptl)) {
08974             /* setting to zero will force a default if none was provided by the SDP */
08975             ast_udptl_set_far_max_datagram(p->udptl, 0);
08976          }
08977 
08978          /* Remote party offers T38, we need to update state */
08979          if ((t38action == SDP_T38_ACCEPT) &&
08980              (p->t38.state == T38_LOCAL_REINVITE)) {
08981             change_t38_state(p, T38_ENABLED);
08982          } else if ((t38action == SDP_T38_INITIATE) &&
08983                p->owner && p->lastinvite) {
08984             change_t38_state(p, T38_PEER_REINVITE); /* T38 Offered in re-invite from remote party */
08985             /* If fax detection is enabled then send us off to the fax extension */
08986             if (ast_test_flag(&p->flags[1], SIP_PAGE2_FAX_DETECT_T38)) {
08987                ast_channel_lock(p->owner);
08988                if (strcmp(p->owner->exten, "fax")) {
08989                   const char *target_context = S_OR(p->owner->macrocontext, p->owner->context);
08990                   ast_channel_unlock(p->owner);
08991                   if (ast_exists_extension(p->owner, target_context, "fax", 1, p->owner->cid.cid_num)) {
08992                      ast_verbose(VERBOSE_PREFIX_2 "Redirecting '%s' to fax extension due to peer T.38 re-INVITE\n", p->owner->name);
08993                      pbx_builtin_setvar_helper(p->owner, "FAXEXTEN", p->owner->exten);
08994                      if (ast_async_goto(p->owner, target_context, "fax", 1)) {
08995                         ast_log(LOG_NOTICE, "Failed to async goto '%s' into fax of '%s'\n", p->owner->name, target_context);
08996                      }
08997                   } else {
08998                      ast_log(LOG_NOTICE, "T.38 re-INVITE detected but no fax extension\n");
08999                   }
09000                } else {
09001                   ast_channel_unlock(p->owner);
09002                }
09003             }
09004          }
09005       } else {
09006          ast_udptl_stop(p->udptl);
09007          if (debug)
09008             ast_debug(1, "Peer doesn't provide T.38 UDPTL\n");
09009       }
09010    }
09011 
09012    if ((portno == -1) && (p->t38.state != T38_DISABLED)) {
09013       ast_debug(3, "Have T.38 but no audio, accepting offer anyway\n");
09014                 return 0;
09015         }
09016 
09017    /* Ok, we're going with this offer */
09018    ast_debug(2, "We're settling with these formats: %s\n", ast_getformatname_multiple(buf, SIPBUFSIZE, p->jointcapability));
09019 
09020    if (!p->owner)    /* There's no open channel owning us so we can return here. For a re-invite or so, we proceed */
09021       return 0;
09022 
09023    ast_debug(4, "We have an owner, now see if we need to change this call\n");
09024 
09025    if (!(p->owner->nativeformats & p->jointcapability) && (p->jointcapability & AST_FORMAT_AUDIO_MASK)) {
09026       if (debug) {
09027          char s1[SIPBUFSIZE], s2[SIPBUFSIZE];
09028          ast_debug(1, "Oooh, we need to change our audio formats since our peer supports only %s and not %s\n", 
09029             ast_getformatname_multiple(s1, SIPBUFSIZE, p->jointcapability),
09030             ast_getformatname_multiple(s2, SIPBUFSIZE, p->owner->nativeformats));
09031       }
09032       p->owner->nativeformats = ast_codec_choose(&p->prefs, p->jointcapability, 1) | (p->capability & vpeercapability) | (p->capability & tpeercapability);
09033       ast_set_read_format(p->owner, p->owner->readformat);
09034       ast_set_write_format(p->owner, p->owner->writeformat);
09035    }
09036    
09037    if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)
09038          && (sin.sin_addr.s_addr || vsin.sin_addr.s_addr ||
09039          isin.sin_addr.s_addr || tsin.sin_addr.s_addr)
09040          && (!sendonly || sendonly == -1)) {
09041       ast_queue_control(p->owner, AST_CONTROL_UNHOLD);
09042       /* Activate a re-invite */
09043       ast_queue_frame(p->owner, &ast_null_frame);
09044       change_hold_state(p, req, FALSE, sendonly);
09045    } else if (!(sin.sin_addr.s_addr || vsin.sin_addr.s_addr ||
09046          isin.sin_addr.s_addr || tsin.sin_addr.s_addr)
09047          || (sendonly && sendonly != -1)) {
09048       ast_queue_control_data(p->owner, AST_CONTROL_HOLD, 
09049                    S_OR(p->mohsuggest, NULL),
09050                    !ast_strlen_zero(p->mohsuggest) ? strlen(p->mohsuggest) + 1 : 0);
09051       if (sendonly)
09052          ast_rtp_stop(p->rtp);
09053       /* RTCP needs to go ahead, even if we're on hold!!! */
09054       /* Activate a re-invite */
09055       ast_queue_frame(p->owner, &ast_null_frame);
09056       change_hold_state(p, req, TRUE, sendonly);
09057    }
09058    
09059    return 0;
09060 }
09061 
09062 static int process_sdp_o(const char *o, struct sip_pvt *p)
09063 {
09064    char *o_copy;
09065    char *token;
09066    int64_t rua_version;
09067 
09068    /* Store the SDP version number of remote UA. This will allow us to
09069    distinguish between session modifications and session refreshes. If
09070    the remote UA does not send an incremented SDP version number in a
09071    subsequent RE-INVITE then that means its not changing media session.
09072    The RE-INVITE may have been sent to update connected party, remote
09073    target or to refresh the session (Session-Timers).  Asterisk must not
09074    change media session and increment its own version number in answer
09075    SDP in this case. */
09076 
09077    p->session_modify = TRUE;
09078 
09079    if (ast_strlen_zero(o)) {
09080       ast_log(LOG_WARNING, "SDP syntax error. SDP without an o= line\n");
09081       return FALSE;
09082    }
09083 
09084    o_copy = ast_strdupa(o);
09085    token = strsep(&o_copy, " ");  /* Skip username   */
09086    if (!o_copy) {
09087       ast_log(LOG_WARNING, "SDP syntax error in o= line username\n");
09088       return FALSE;
09089    }
09090    token = strsep(&o_copy, " ");  /* Skip session-id */
09091    if (!o_copy) {
09092       ast_log(LOG_WARNING, "SDP syntax error in o= line session-id\n");
09093       return FALSE;
09094    }
09095    token = strsep(&o_copy, " ");  /* Version         */
09096    if (!o_copy) {
09097       ast_log(LOG_WARNING, "SDP syntax error in o= line\n");
09098       return FALSE;
09099    }
09100    if (!sscanf(token, "%30" SCNd64, &rua_version)) {
09101       ast_log(LOG_WARNING, "SDP syntax error in o= line version\n");
09102       return FALSE;
09103    }
09104 
09105    /* we need to check the SDP version number the other end sent us;
09106     * our rules for deciding what to accept are a bit complex.
09107     *
09108     * 1) if 'ignoresdpversion' has been set for this dialog, then
09109     *    we will just accept whatever they sent and assume it is
09110     *    a modification of the session, even if it is not
09111     * 2) otherwise, if this is the first SDP we've seen from them
09112     *    we accept it
09113     * 3) otherwise, if the new SDP version number is higher than the
09114     *    old one, we accept it
09115     * 4) otherwise, if this SDP is in response to us requesting a switch
09116     *    to T.38, we accept the SDP, but also generate a warning message
09117     *    that this peer should have the 'ignoresdpversion' option set,
09118     *    because it is not following the SDP offer/answer RFC; if we did
09119     *    not request a switch to T.38, then we stop parsing the SDP, as it
09120     *    has not changed from the previous version
09121     */
09122 
09123    if (ast_test_flag(&p->flags[1], SIP_PAGE2_IGNORESDPVERSION) ||
09124        (p->sessionversion_remote < 0) ||
09125        (p->sessionversion_remote < rua_version)) {
09126       p->sessionversion_remote = rua_version;
09127    } else {
09128       if (p->t38.state == T38_LOCAL_REINVITE) {
09129          p->sessionversion_remote = rua_version;
09130          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);
09131       } else {
09132          p->session_modify = FALSE;
09133          ast_debug(2, "Call %s responded to our reinvite without changing SDP version; ignoring SDP.\n", p->callid);
09134          return FALSE;
09135       }
09136    }
09137 
09138    return TRUE;
09139 }
09140 
09141 static int process_sdp_c(const char *c, struct ast_hostent *ast_hp)
09142 {
09143    char host[258];
09144    struct hostent *hp;
09145 
09146    /* Check for Media-description-level-address */
09147    if (sscanf(c, "IN IP4 %255s", host) != 1) {
09148       ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
09149       return FALSE;
09150    } else {
09151       if (!(hp = ast_gethostbyname(host, ast_hp))) {
09152          ast_log(LOG_WARNING, "Unable to lookup RTP Audio host in c= line, '%s'\n", c);
09153          return FALSE;
09154       }
09155       return TRUE;
09156    }
09157    return FALSE;
09158 }
09159 
09160 static int process_sdp_a_sendonly(const char *a, int *sendonly)
09161 {
09162    int found = FALSE;
09163 
09164    if (!strcasecmp(a, "sendonly")) {
09165       if (*sendonly == -1)
09166          *sendonly = 1;
09167       found = TRUE;
09168    } else if (!strcasecmp(a, "inactive")) {
09169       if (*sendonly == -1)
09170          *sendonly = 2;
09171       found = TRUE;
09172    }  else if (!strcasecmp(a, "sendrecv")) {
09173       if (*sendonly == -1)
09174          *sendonly = 0;
09175       found = TRUE;
09176    }
09177    return found;
09178 }
09179 
09180 static int process_sdp_a_audio(const char *a, struct sip_pvt *p, struct ast_rtp *newaudiortp, int *last_rtpmap_codec)
09181 {
09182    int found = FALSE;
09183    int codec;
09184    char mimeSubtype[128];
09185    char fmtp_string[64];
09186    unsigned int sample_rate;
09187    int debug = sip_debug_test_pvt(p);
09188 
09189    if (!strncasecmp(a, "ptime", 5)) {
09190       char *tmp = strrchr(a, ':');
09191       long int framing = 0;
09192       if (tmp) {
09193          tmp++;
09194          framing = strtol(tmp, NULL, 10);
09195          if (framing == LONG_MIN || framing == LONG_MAX) {
09196             framing = 0;
09197             ast_debug(1, "Can't read framing from SDP: %s\n", a);
09198          }
09199       }
09200       if (framing && p->autoframing) {
09201          struct ast_codec_pref *pref = ast_rtp_codec_getpref(p->rtp);
09202          int codec_n;
09203          int format = 0;
09204          for (codec_n = 0; codec_n < MAX_RTP_PT; codec_n++) {
09205             format = ast_rtp_codec_getformat(codec_n);
09206             if (!format)   /* non-codec or not found */
09207                continue;
09208             if (option_debug)
09209                ast_log(LOG_DEBUG, "Setting framing for %d to %ld\n", format, framing);
09210             ast_codec_pref_setsize(pref, format, framing);
09211          }
09212          ast_rtp_codec_setpref(p->rtp, pref);
09213       }
09214       found = TRUE;
09215    } else if (sscanf(a, "rtpmap: %30u %127[^/]/%30u", &codec, mimeSubtype, &sample_rate) == 3) {
09216       /* We have a rtpmap to handle */
09217       if (*last_rtpmap_codec < SDP_MAX_RTPMAP_CODECS) {
09218          if (ast_rtp_set_rtpmap_type_rate(newaudiortp, codec, "audio", mimeSubtype,
09219              ast_test_flag(&p->flags[0], SIP_G726_NONSTANDARD) ? AST_RTP_OPT_G726_NONSTANDARD : 0, sample_rate) != -1) {
09220             if (debug)
09221                ast_verbose("Found audio description format %s for ID %d\n", mimeSubtype, codec);
09222             //found_rtpmap_codecs[last_rtpmap_codec] = codec;
09223             (*last_rtpmap_codec)++;
09224             found = TRUE;
09225          } else {
09226             ast_rtp_unset_m_type(newaudiortp, codec);
09227             if (debug)
09228                ast_verbose("Found unknown media description format %s for ID %d\n", mimeSubtype, codec);
09229          }
09230       } else {
09231          if (debug)
09232             ast_verbose("Discarded description format %s for ID %d\n", mimeSubtype, codec);
09233       }
09234    } else if (sscanf(a, "fmtp: %30u %63s", &codec, fmtp_string) == 2) {
09235       struct rtpPayloadType payload;
09236 
09237       payload = ast_rtp_lookup_pt(newaudiortp, codec);
09238       if (payload.code && payload.isAstFormat) {
09239          unsigned int bit_rate;
09240 
09241          switch (payload.code) {
09242          case AST_FORMAT_SIREN7:
09243             if (sscanf(fmtp_string, "bitrate=%30u", &bit_rate) == 1) {
09244                if (bit_rate != 32000) {
09245                   ast_log(LOG_WARNING, "Got Siren7 offer at %d bps, but only 32000 bps supported; ignoring.\n", bit_rate);
09246                   ast_rtp_unset_m_type(newaudiortp, codec);
09247                } else {
09248                   found = TRUE;
09249                }
09250             }
09251             break;
09252          case AST_FORMAT_SIREN14:
09253             if (sscanf(fmtp_string, "bitrate=%30u", &bit_rate) == 1) {
09254                if (bit_rate != 48000) {
09255                   ast_log(LOG_WARNING, "Got Siren14 offer at %d bps, but only 48000 bps supported; ignoring.\n", bit_rate);
09256                   ast_rtp_unset_m_type(newaudiortp, codec);
09257                } else {
09258                   found = TRUE;
09259                }
09260             }
09261             break;
09262          }
09263       }
09264    }
09265 
09266    return found;
09267 }
09268 
09269 static int process_sdp_a_video(const char *a, struct sip_pvt *p, struct ast_rtp *newvideortp, int *last_rtpmap_codec)
09270 {
09271    int found = FALSE;
09272    int codec;
09273    char mimeSubtype[128];
09274    unsigned int sample_rate;
09275    int debug = sip_debug_test_pvt(p);
09276 
09277    if (sscanf(a, "rtpmap: %30u %127[^/]/%30u", &codec, mimeSubtype, &sample_rate) == 3) {
09278       /* We have a rtpmap to handle */
09279       if (*last_rtpmap_codec < SDP_MAX_RTPMAP_CODECS) {
09280          /* Note: should really look at the '#chans' params too */
09281          if (!strncasecmp(mimeSubtype, "H26", 3) || !strncasecmp(mimeSubtype, "MP4", 3)) {
09282             if (ast_rtp_set_rtpmap_type_rate(newvideortp, codec, "video", mimeSubtype, 0, sample_rate) != -1) {
09283                if (debug)
09284                   ast_verbose("Found video description format %s for ID %d\n", mimeSubtype, codec);
09285                //found_rtpmap_codecs[last_rtpmap_codec] = codec;
09286                (*last_rtpmap_codec)++;
09287                found = TRUE;
09288             } else {
09289                ast_rtp_unset_m_type(newvideortp, codec);
09290                if (debug) 
09291                   ast_verbose("Found unknown media description format %s for ID %d\n", mimeSubtype, codec);
09292             }
09293          }
09294       } else {
09295          if (debug)
09296             ast_verbose("Discarded description format %s for ID %d\n", mimeSubtype, codec);
09297       }
09298    }
09299 
09300    return found;
09301 }
09302 
09303 static int process_sdp_a_text(const char *a, struct sip_pvt *p, struct ast_rtp *newtextrtp, char *red_fmtp, int *red_num_gen, int *red_data_pt, int *last_rtpmap_codec)
09304 {
09305    int found = FALSE;
09306    int codec;
09307    char mimeSubtype[128];
09308    unsigned int sample_rate;
09309    char *red_cp;
09310    int debug = sip_debug_test_pvt(p);
09311 
09312    if (sscanf(a, "rtpmap: %30u %127[^/]/%30u", &codec, mimeSubtype, &sample_rate) == 3) {
09313       /* We have a rtpmap to handle */
09314       if (*last_rtpmap_codec < SDP_MAX_RTPMAP_CODECS) {
09315          if (!strncasecmp(mimeSubtype, "T140", 4)) { /* Text */
09316             if (p->trtp) {
09317                /* ast_verbose("Adding t140 mimeSubtype to textrtp struct\n"); */
09318                ast_rtp_set_rtpmap_type(newtextrtp, codec, "text", mimeSubtype, 0);
09319                found = TRUE;
09320             }
09321          } else if (!strncasecmp(mimeSubtype, "RED", 3)) { /* Text with Redudancy */
09322             if (p->trtp) {
09323                ast_rtp_set_rtpmap_type(newtextrtp, codec, "text", mimeSubtype, 0);
09324                sprintf(red_fmtp, "fmtp:%d ", codec); 
09325                if (debug)
09326                   ast_verbose("RED submimetype has payload type: %d\n", codec);
09327                found = TRUE;
09328             }
09329          }
09330       } else {
09331          if (debug)
09332             ast_verbose("Discarded description format %s for ID %d\n", mimeSubtype, codec);
09333       }
09334    } else if (!strncmp(a, red_fmtp, strlen(red_fmtp))) {
09335       /* count numbers of generations in fmtp */
09336       red_cp = &red_fmtp[strlen(red_fmtp)];
09337       strncpy(red_fmtp, a, 100);
09338 
09339       sscanf(red_cp, "%30u", &red_data_pt[*red_num_gen]);
09340       red_cp = strtok(red_cp, "/");
09341       while (red_cp && (*red_num_gen)++ < RED_MAX_GENERATION) {
09342          sscanf(red_cp, "%30u", &red_data_pt[*red_num_gen]);
09343          red_cp = strtok(NULL, "/");
09344       }
09345       red_cp = red_fmtp;
09346       found = TRUE;
09347    }
09348 
09349    return found;
09350 }
09351 
09352 static int process_sdp_a_image(const char *a, struct sip_pvt *p)
09353 {
09354    int found = FALSE;
09355    char s[256];
09356    unsigned int x;
09357 
09358    if ((sscanf(a, "T38FaxMaxBuffer:%30u", &x) == 1)) {
09359       ast_debug(3, "MaxBufferSize:%d\n", x);
09360       found = TRUE;
09361    } else if ((sscanf(a, "T38MaxBitRate:%30u", &x) == 1) || (sscanf(a, "T38FaxMaxRate:%30u", &x) == 1)) {
09362       ast_debug(3, "T38MaxBitRate: %d\n", x);
09363       switch (x) {
09364       case 14400:
09365          p->t38.their_parms.rate = AST_T38_RATE_14400;
09366          break;
09367       case 12000:
09368          p->t38.their_parms.rate = AST_T38_RATE_12000;
09369          break;
09370       case 9600:
09371          p->t38.their_parms.rate = AST_T38_RATE_9600;
09372          break;
09373       case 7200:
09374          p->t38.their_parms.rate = AST_T38_RATE_7200;
09375          break;
09376       case 4800:
09377          p->t38.their_parms.rate = AST_T38_RATE_4800;
09378          break;
09379       case 2400:
09380          p->t38.their_parms.rate = AST_T38_RATE_2400;
09381          break;
09382       }
09383       found = TRUE;
09384    } else if ((sscanf(a, "T38FaxVersion:%30u", &x) == 1)) {
09385       ast_debug(3, "FaxVersion: %u\n", x);
09386       p->t38.their_parms.version = x;
09387       found = TRUE;
09388    } else if ((sscanf(a, "T38FaxMaxDatagram:%30u", &x) == 1) || (sscanf(a, "T38MaxDatagram:%30u", &x) == 1)) {
09389       /* override the supplied value if the configuration requests it */
09390       if (((signed int) p->t38_maxdatagram >= 0) && ((unsigned int) p->t38_maxdatagram > x)) {
09391          ast_debug(1, "Overriding T38FaxMaxDatagram '%d' with '%d'\n", x, p->t38_maxdatagram);
09392          x = p->t38_maxdatagram;
09393       }
09394       ast_debug(3, "FaxMaxDatagram: %u\n", x);
09395       ast_udptl_set_far_max_datagram(p->udptl, x);
09396       found = TRUE;
09397    } else if ((strncmp(a, "T38FaxFillBitRemoval", 20) == 0)) {
09398       if (sscanf(a, "T38FaxFillBitRemoval:%30u", &x) == 1) {
09399          ast_debug(3, "FillBitRemoval: %d\n", x);
09400          if (x == 1) {
09401             p->t38.their_parms.fill_bit_removal = TRUE;
09402          }
09403       } else {
09404          ast_debug(3, "FillBitRemoval\n");
09405          p->t38.their_parms.fill_bit_removal = TRUE;
09406       }
09407       found = TRUE;
09408    } else if ((strncmp(a, "T38FaxTranscodingMMR", 20) == 0)) {
09409       if (sscanf(a, "T38FaxTranscodingMMR:%30u", &x) == 1) {
09410          ast_debug(3, "Transcoding MMR: %d\n", x);
09411          if (x == 1) {
09412             p->t38.their_parms.transcoding_mmr = TRUE;
09413          }
09414       } else {
09415          ast_debug(3, "Transcoding MMR\n");
09416          p->t38.their_parms.transcoding_mmr = TRUE;
09417       }
09418       found = TRUE;
09419    } else if ((strncmp(a, "T38FaxTranscodingJBIG", 21) == 0)) {
09420       if (sscanf(a, "T38FaxTranscodingJBIG:%30u", &x) == 1) {
09421          ast_debug(3, "Transcoding JBIG: %d\n", x);
09422          if (x == 1) {
09423             p->t38.their_parms.transcoding_jbig = TRUE;
09424          }
09425       } else {
09426          ast_debug(3, "Transcoding JBIG\n");
09427          p->t38.their_parms.transcoding_jbig = TRUE;
09428       }
09429       found = TRUE;
09430    } else if ((sscanf(a, "T38FaxRateManagement:%255s", s) == 1)) {
09431       ast_debug(3, "RateManagement: %s\n", s);
09432       if (!strcasecmp(s, "localTCF"))
09433          p->t38.their_parms.rate_management = AST_T38_RATE_MANAGEMENT_LOCAL_TCF;
09434       else if (!strcasecmp(s, "transferredTCF"))
09435          p->t38.their_parms.rate_management = AST_T38_RATE_MANAGEMENT_TRANSFERRED_TCF;
09436       found = TRUE;
09437    } else if ((sscanf(a, "T38FaxUdpEC:%255s", s) == 1)) {
09438       ast_debug(3, "UDP EC: %s\n", s);
09439       if (!strcasecmp(s, "t38UDPRedundancy")) {
09440          ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_REDUNDANCY);
09441       } else if (!strcasecmp(s, "t38UDPFEC")) {
09442          ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_FEC);
09443       } else {
09444          ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_NONE);
09445       }
09446       found = TRUE;
09447    }
09448 
09449    return found;
09450 }
09451 
09452 
09453 #ifdef LOW_MEMORY
09454 static void ts_ast_rtp_destroy(void *data)
09455 {
09456     struct ast_rtp *tmp = data;
09457     ast_rtp_destroy(tmp);
09458 }
09459 #endif
09460 
09461 /*! \brief Add "Supported" header to sip message.  Since some options may
09462  *  be disabled in the config, the sip_pvt must be inspected to determine what
09463  *  is supported for this dialog. */
09464 static int add_supported_header(struct sip_pvt *pvt, struct sip_request *req)
09465 {
09466    int res;
09467    if (st_get_mode(pvt) != SESSION_TIMER_MODE_REFUSE) {
09468       res = add_header(req, "Supported", "replaces, timer");
09469    } else {
09470       res = add_header(req, "Supported", "replaces");
09471    }
09472    return res;
09473 }
09474 
09475 /*! \brief Add header to SIP message */
09476 static int add_header(struct sip_request *req, const char *var, const char *value)
09477 {
09478    if (req->headers == SIP_MAX_HEADERS) {
09479       ast_log(LOG_WARNING, "Out of SIP header space\n");
09480       return -1;
09481    }
09482 
09483    if (req->lines) {
09484       ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
09485       return -1;
09486    }
09487 
09488    if (sip_cfg.compactheaders) {
09489       var = find_alias(var, var);
09490    }
09491 
09492    ast_str_append(&req->data, 0, "%s: %s\r\n", var, value);
09493    req->header[req->headers] = req->len;
09494 
09495    req->len = ast_str_strlen(req->data);
09496    req->headers++;
09497 
09498    return 0;   
09499 }
09500 
09501 /*! \brief Add 'Content-Length' header and content to SIP message */
09502 static int finalize_content(struct sip_request *req)
09503 {
09504    char clen[10];
09505 
09506    if (req->lines) {
09507       ast_log(LOG_WARNING, "finalize_content() called on a message that has already been finalized\n");
09508       return -1;
09509    }
09510 
09511    snprintf(clen, sizeof(clen), "%zd", ast_str_strlen(req->content));
09512    add_header(req, "Content-Length", clen);
09513 
09514    if (ast_str_strlen(req->content)) {
09515       ast_str_append(&req->data, 0, "\r\n%s", ast_str_buffer(req->content));
09516       req->len = ast_str_strlen(req->data);
09517    }
09518    req->lines = ast_str_strlen(req->content) ? 1 : 0;
09519    return 0;
09520 }
09521 
09522 /*! \brief Add content (not header) to SIP message */
09523 static int add_content(struct sip_request *req, const char *line)
09524 {
09525    if (req->lines) {
09526       ast_log(LOG_WARNING, "Can't add more content when the content has been finalized\n");
09527       return -1;
09528    }
09529 
09530    ast_str_append(&req->content, 0, "%s", line);
09531    return 0;
09532 }
09533 
09534 /*! \brief Copy one header field from one request to another */
09535 static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field)
09536 {
09537    const char *tmp = get_header(orig, field);
09538 
09539    if (!ast_strlen_zero(tmp)) /* Add what we're responding to */
09540       return add_header(req, field, tmp);
09541    ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
09542    return -1;
09543 }
09544 
09545 /*! \brief Copy all headers from one request to another */
09546 static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field)
09547 {
09548    int start = 0;
09549    int copied = 0;
09550    for (;;) {
09551       const char *tmp = __get_header(orig, field, &start);
09552 
09553       if (ast_strlen_zero(tmp))
09554          break;
09555       /* Add what we're responding to */
09556       add_header(req, field, tmp);
09557       copied++;
09558    }
09559    return copied ? 0 : -1;
09560 }
09561 
09562 /*! \brief Copy SIP VIA Headers from the request to the response
09563 \note If the client indicates that it wishes to know the port we received from,
09564    it adds ;rport without an argument to the topmost via header. We need to
09565    add the port number (from our point of view) to that parameter.
09566 \verbatim
09567    We always add ;received=<ip address> to the topmost via header.
09568 \endverbatim
09569    Received: RFC 3261, rport RFC 3581 */
09570 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field)
09571 {
09572    int copied = 0;
09573    int start = 0;
09574 
09575    for (;;) {
09576       char new[512];
09577       const char *oh = __get_header(orig, field, &start);
09578 
09579       if (ast_strlen_zero(oh))
09580          break;
09581 
09582       if (!copied) { /* Only check for empty rport in topmost via header */
09583          char leftmost[512], *others, *rport;
09584 
09585          /* Only work on leftmost value */
09586          ast_copy_string(leftmost, oh, sizeof(leftmost));
09587          others = strchr(leftmost, ',');
09588          if (others)
09589              *others++ = '\0';
09590 
09591          /* Find ;rport;  (empty request) */
09592          rport = strstr(leftmost, ";rport");
09593          if (rport && *(rport+6) == '=') 
09594             rport = NULL;     /* We already have a parameter to rport */
09595 
09596          /* Check rport if NAT=yes or NAT=rfc3581 (which is the default setting)  */
09597          if (rport && ((ast_test_flag(&p->flags[0], SIP_NAT) == SIP_NAT_ALWAYS) || (ast_test_flag(&p->flags[0], SIP_NAT) == SIP_NAT_RFC3581))) {
09598             /* We need to add received port - rport */
09599             char *end;
09600 
09601             rport = strstr(leftmost, ";rport");
09602 
09603             if (rport) {
09604                end = strchr(rport + 1, ';');
09605                if (end)
09606                   memmove(rport, end, strlen(end) + 1);
09607                else
09608                   *rport = '\0';
09609             }
09610 
09611             /* Add rport to first VIA header if requested */
09612             snprintf(new, sizeof(new), "%s;received=%s;rport=%d%s%s",
09613                leftmost, ast_inet_ntoa(p->recv.sin_addr),
09614                ntohs(p->recv.sin_port),
09615                others ? "," : "", others ? others : "");
09616          } else {
09617             /* We should *always* add a received to the topmost via */
09618             snprintf(new, sizeof(new), "%s;received=%s%s%s",
09619                leftmost, ast_inet_ntoa(p->recv.sin_addr),
09620                others ? "," : "", others ? others : "");
09621          }
09622          oh = new;   /* the header to copy */
09623       }  /* else add the following via headers untouched */
09624       add_header(req, field, oh);
09625       copied++;
09626    }
09627    if (!copied) {
09628       ast_log(LOG_NOTICE, "No header field '%s' present to copy\n", field);
09629       return -1;
09630    }
09631    return 0;
09632 }
09633 
09634 /*! \brief Add route header into request per learned route */
09635 static void add_route(struct sip_request *req, struct sip_route *route)
09636 {
09637    char r[SIPBUFSIZE*2], *p;
09638    int n, rem = sizeof(r);
09639 
09640    if (!route)
09641       return;
09642 
09643    p = r;
09644    for (;route ; route = route->next) {
09645       n = strlen(route->hop);
09646       if (rem < n+3) /* we need room for ",<route>" */
09647          break;
09648       if (p != r) {  /* add a separator after fist route */
09649          *p++ = ',';
09650          --rem;
09651       }
09652       *p++ = '<';
09653       ast_copy_string(p, route->hop, rem); /* cannot fail */
09654       p += n;
09655       *p++ = '>';
09656       rem -= (n+2);
09657    }
09658    *p = '\0';
09659    add_header(req, "Route", r);
09660 }
09661 
09662 /*! \brief Set destination from SIP URI 
09663  *
09664  * Parse uri to h (host) and port - uri is already just the part inside the <> 
09665  * general form we are expecting is sip[s]:username[:password][;parameter]@host[:port][;...] 
09666  * If there's a port given, turn NAPTR/SRV off. NAPTR might indicate SIPS preference even
09667  * for SIP: uri's
09668  *
09669  * If there's a sips: uri scheme, TLS will be required. 
09670  */
09671 static void set_destination(struct sip_pvt *p, char *uri)
09672 {
09673    char *h, *maddr, hostname[256];
09674    int port, hn;
09675    struct hostent *hp;
09676    struct ast_hostent ahp;
09677    int debug=sip_debug_test_pvt(p);
09678    int tls_on = FALSE;
09679    int use_dns = sip_cfg.srvlookup;
09680 
09681    if (debug)
09682       ast_verbose("set_destination: Parsing <%s> for address/port to send to\n", uri);
09683 
09684    /* Find and parse hostname */
09685    h = strchr(uri, '@');
09686    if (h)
09687       ++h;
09688    else {
09689       h = uri;
09690       if (!strncasecmp(h, "sip:", 4)) {
09691          h += 4;
09692       } else if (!strncasecmp(h, "sips:", 5)) {
09693          h += 5;
09694          tls_on = TRUE;
09695       }
09696    }
09697    hn = strcspn(h, ":;>") + 1;
09698    if (hn > sizeof(hostname)) 
09699       hn = sizeof(hostname);
09700    ast_copy_string(hostname, h, hn);
09701    /* XXX bug here if string has been trimmed to sizeof(hostname) */
09702    h += hn - 1;
09703 
09704    /* Is "port" present? if not default to STANDARD_SIP_PORT */
09705    if (*h == ':') {
09706       /* Parse port */
09707       ++h;
09708       port = strtol(h, &h, 10);
09709       use_dns = FALSE;
09710    } else
09711       port = tls_on ? STANDARD_TLS_PORT : STANDARD_SIP_PORT;
09712 
09713    /* Got the hostname:port - but maybe there's a "maddr=" to override address? */
09714    maddr = strstr(h, "maddr=");
09715    if (maddr) {
09716       maddr += 6;
09717       hn = strspn(maddr, "0123456789.") + 1;
09718       if (hn > sizeof(hostname))
09719          hn = sizeof(hostname);
09720       ast_copy_string(hostname, maddr, hn);
09721    }
09722 
09723    /*! \todo XXX If we have use_dns on, then look for NAPTR/SRV, otherwise, just look for A records */
09724    
09725    hp = ast_gethostbyname(hostname, &ahp);
09726    if (hp == NULL)  {
09727       ast_log(LOG_WARNING, "Can't find address for host '%s'\n", hostname);
09728       return;
09729    }
09730    p->sa.sin_family = AF_INET;
09731    memcpy(&p->sa.sin_addr, hp->h_addr, sizeof(p->sa.sin_addr));
09732    p->sa.sin_port = htons(port);
09733    if (debug)
09734       ast_verbose("set_destination: set destination to %s, port %d\n", ast_inet_ntoa(p->sa.sin_addr), port);
09735 }
09736 
09737 /*! \brief Initialize SIP response, based on SIP request */
09738 static int init_resp(struct sip_request *resp, const char *msg)
09739 {
09740    /* Initialize a response */
09741    memset(resp, 0, sizeof(*resp));
09742    resp->method = SIP_RESPONSE;
09743    if (!(resp->data = ast_str_create(SIP_MIN_PACKET)))
09744       goto e_return;
09745    if (!(resp->content = ast_str_create(SIP_MIN_PACKET)))
09746       goto e_free_data;
09747    resp->header[0] = 0;
09748    ast_str_set(&resp->data, 0, "SIP/2.0 %s\r\n", msg);
09749    resp->len = resp->data->used;
09750    resp->headers++;
09751    return 0;
09752 
09753 e_free_data:
09754    ast_free(resp->data);
09755    resp->data = NULL;
09756 e_return:
09757    return -1;
09758 }
09759 
09760 /*! \brief Initialize SIP request */
09761 static int init_req(struct sip_request *req, int sipmethod, const char *recip)
09762 {
09763    /* Initialize a request */
09764    memset(req, 0, sizeof(*req));
09765    if (!(req->data = ast_str_create(SIP_MIN_PACKET)))
09766       goto e_return;
09767    if (!(req->content = ast_str_create(SIP_MIN_PACKET)))
09768       goto e_free_data;
09769    req->method = sipmethod;
09770    req->header[0] = 0;
09771    ast_str_set(&req->data, 0, "%s %s SIP/2.0\r\n", sip_methods[sipmethod].text, recip);
09772    req->len = ast_str_strlen(req->data);
09773    req->headers++;
09774    return 0;
09775 
09776 e_free_data:
09777    ast_free(req->data);
09778    req->data = NULL;
09779 e_return:
09780    return -1;
09781 }
09782 
09783 /*! \brief Deinitialize SIP response/request */
09784 static void deinit_req(struct sip_request *req)
09785 {
09786    if (req->data) {
09787       ast_free(req->data);
09788       req->data = NULL;
09789    }
09790    if (req->content) {
09791       ast_free(req->content);
09792       req->content = NULL;
09793    }
09794 }
09795 
09796 
09797 /*! \brief Test if this response needs a contact header */
09798 static inline int resp_needs_contact(const char *msg, enum sipmethod method) {
09799    /* Requirements for Contact header inclusion in responses generated
09800     * from the header tables found in the following RFCs.  Where the
09801     * Contact header was marked mandatory (m) or optional (o) this
09802     * function returns 1.
09803     *
09804     * - RFC 3261 (ACK, BYE, CANCEL, INVITE, OPTIONS, REGISTER)
09805     * - RFC 2976 (INFO)
09806     * - RFC 3262 (PRACK)
09807     * - RFC 3265 (SUBSCRIBE, NOTIFY)
09808     * - RFC 3311 (UPDATE)
09809     * - RFC 3428 (MESSAGE)
09810     * - RFC 3515 (REFER)
09811     * - RFC 3903 (PUBLISH)
09812     */
09813 
09814    switch (method) {
09815       /* 1xx, 2xx, 3xx, 485 */
09816       case SIP_INVITE:
09817       case SIP_UPDATE:
09818       case SIP_SUBSCRIBE:
09819       case SIP_NOTIFY:
09820          if ((msg[0] >= '1' && msg[0] <= '3') || !strncmp(msg, "485", 3))
09821             return 1;
09822          break;
09823 
09824       /* 2xx, 3xx, 485 */
09825       case SIP_REGISTER:
09826       case SIP_OPTIONS:
09827          if (msg[0] == '2' || msg[0] == '3' || !strncmp(msg, "485", 3))
09828             return 1;
09829          break;
09830 
09831       /* 3xx, 485 */
09832       case SIP_BYE:
09833       case SIP_PRACK:
09834       case SIP_MESSAGE:
09835       case SIP_PUBLISH:
09836          if (msg[0] == '3' || !strncmp(msg, "485", 3))
09837             return 1;
09838          break;
09839 
09840       /* 2xx, 3xx, 4xx, 5xx, 6xx */
09841       case SIP_REFER:
09842          if (msg[0] >= '2' && msg[0] <= '6')
09843             return 1;
09844          break;
09845 
09846       /* contact will not be included for everything else */
09847       case SIP_ACK:
09848       case SIP_CANCEL:
09849       case SIP_INFO:
09850       case SIP_PING:
09851       default:
09852          return 0;
09853    }
09854    return 0;
09855 }
09856 
09857 /*! \brief Prepare SIP response packet */
09858 static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req)
09859 {
09860    char newto[256];
09861    const char *ot;
09862 
09863    init_resp(resp, msg);
09864    copy_via_headers(p, resp, req, "Via");
09865    if (msg[0] == '1' || msg[0] == '2')
09866       copy_all_header(resp, req, "Record-Route");
09867    copy_header(resp, req, "From");
09868    ot = get_header(req, "To");
09869    if (!strcasestr(ot, "tag=") && strncmp(msg, "100", 3)) {
09870       /* Add the proper tag if we don't have it already.  If they have specified
09871          their tag, use it.  Otherwise, use our own tag */
09872       if (!ast_strlen_zero(p->theirtag) && ast_test_flag(&p->flags[0], SIP_OUTGOING))
09873          snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
09874       else if (p->tag && !ast_test_flag(&p->flags[0], SIP_OUTGOING))
09875          snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->tag);
09876       else
09877          ast_copy_string(newto, ot, sizeof(newto));
09878       ot = newto;
09879    }
09880    add_header(resp, "To", ot);
09881    copy_header(resp, req, "Call-ID");
09882    copy_header(resp, req, "CSeq");
09883    if (!ast_strlen_zero(global_useragent))
09884       add_header(resp, "Server", global_useragent);
09885    add_header(resp, "Allow", ALLOWED_METHODS);
09886    add_supported_header(p, resp);
09887 
09888    /* If this is an invite, add Session-Timers related headers if the feature is active for this session */
09889    if (p->method == SIP_INVITE && p->stimer && p->stimer->st_active == TRUE && p->stimer->st_active_peer_ua == TRUE) {
09890       char se_hdr[256];
09891       snprintf(se_hdr, sizeof(se_hdr), "%d;refresher=%s", p->stimer->st_interval, 
09892          strefresher2str(p->stimer->st_ref));
09893       add_header(resp, "Session-Expires", se_hdr);
09894    }
09895 
09896    if (msg[0] == '2' && (p->method == SIP_SUBSCRIBE || p->method == SIP_REGISTER)) {
09897       /* For registration responses, we also need expiry and
09898          contact info */
09899       char tmp[256];
09900 
09901       snprintf(tmp, sizeof(tmp), "%d", p->expiry);
09902       add_header(resp, "Expires", tmp);
09903       if (p->expiry) {  /* Only add contact if we have an expiry time */
09904          char contact[SIPBUFSIZE];
09905          const char *contact_uri = p->method == SIP_SUBSCRIBE ? p->our_contact : p->fullcontact;
09906          char *brackets = strchr(contact_uri, '<');
09907          snprintf(contact, sizeof(contact), "%s%s%s;expires=%d", brackets ? "" : "<", contact_uri, brackets ? "" : ">", p->expiry);
09908          add_header(resp, "Contact", contact);  /* Not when we unregister */
09909       }
09910    } else if (!ast_strlen_zero(p->our_contact) && resp_needs_contact(msg, p->method)) {
09911       add_header(resp, "Contact", p->our_contact);
09912    }
09913 
09914    if (!ast_strlen_zero(p->url)) {
09915       add_header(resp, "Access-URL", p->url);
09916       ast_string_field_set(p, url, NULL);
09917    }
09918 
09919    /* default to routing the response to the address where the request
09920     * came from.  Since we don't have a transport layer, we do this here.
09921     */
09922    p->sa = p->recv;
09923 
09924    if (process_via(p, req)) {
09925       ast_log(LOG_WARNING, "error processing via header, will send response to originating address\n");
09926    }
09927 
09928    return 0;
09929 }
09930 
09931 /*! \brief Initialize a SIP request message (not the initial one in a dialog) */
09932 static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, int seqno, int newbranch)
09933 {
09934    struct sip_request *orig = &p->initreq;
09935    char stripped[80];
09936    char tmp[80];
09937    char newto[256];
09938    const char *c;
09939    const char *ot, *of;
09940    int is_strict = FALSE;     /*!< Strict routing flag */
09941    int is_outbound = ast_test_flag(&p->flags[0], SIP_OUTGOING);   /* Session direction */
09942 
09943    memset(req, 0, sizeof(struct sip_request));
09944    
09945    snprintf(p->lastmsg, sizeof(p->lastmsg), "Tx: %s", sip_methods[sipmethod].text);
09946    
09947    if (!seqno) {
09948       p->ocseq++;
09949       seqno = p->ocseq;
09950    }
09951    
09952    /* A CANCEL must have the same branch as the INVITE that it is canceling. */
09953    if (sipmethod == SIP_CANCEL) {
09954       p->branch = p->invite_branch;
09955       build_via(p);
09956    } else if (newbranch && (sipmethod == SIP_INVITE)) {
09957       p->branch ^= ast_random();
09958       p->invite_branch = p->branch;
09959       build_via(p);
09960    } else if (newbranch) {
09961       p->branch ^= ast_random();
09962       build_via(p);
09963    }
09964 
09965    /* Check for strict or loose router */
09966    if (p->route && !ast_strlen_zero(p->route->hop) && strstr(p->route->hop, ";lr") == NULL) {
09967       is_strict = TRUE;
09968       if (sipdebug)
09969          ast_debug(1, "Strict routing enforced for session %s\n", p->callid);
09970    }
09971    
09972    if (sipmethod == SIP_CANCEL)
09973       c = REQ_OFFSET_TO_STR(&p->initreq, rlPart2); /* Use original URI */
09974    else if (sipmethod == SIP_ACK) {
09975       /* Use URI from Contact: in 200 OK (if INVITE) 
09976       (we only have the contacturi on INVITEs) */
09977       if (!ast_strlen_zero(p->okcontacturi))
09978          c = is_strict ? p->route->hop : p->okcontacturi;
09979       else
09980          c = REQ_OFFSET_TO_STR(&p->initreq, rlPart2);
09981    } else if (!ast_strlen_zero(p->okcontacturi)) 
09982       c = is_strict ? p->route->hop : p->okcontacturi; /* Use for BYE or REINVITE */
09983    else if (!ast_strlen_zero(p->uri)) 
09984       c = p->uri;
09985    else {
09986       char *n;
09987       /* We have no URI, use To: or From:  header as URI (depending on direction) */
09988       ast_copy_string(stripped, get_header(orig, is_outbound ? "To" : "From"),
09989             sizeof(stripped));
09990       n = get_in_brackets(stripped);
09991       c = remove_uri_parameters(n);
09992    }  
09993    init_req(req, sipmethod, c);
09994 
09995    snprintf(tmp, sizeof(tmp), "%d %s", seqno, sip_methods[sipmethod].text);
09996 
09997    add_header(req, "Via", p->via);
09998    if (p->route) {
09999       set_destination(p, p->route->hop);
10000       add_route(req, is_strict ? p->route->next : p->route);
10001    }
10002    add_header(req, "Max-Forwards", DEFAULT_MAX_FORWARDS);
10003 
10004    ot = get_header(orig, "To");
10005    of = get_header(orig, "From");
10006 
10007    /* Add tag *unless* this is a CANCEL, in which case we need to send it exactly
10008       as our original request, including tag (or presumably lack thereof) */
10009    if (!strcasestr(ot, "tag=") && sipmethod != SIP_CANCEL) {
10010       /* Add the proper tag if we don't have it already.  If they have specified
10011          their tag, use it.  Otherwise, use our own tag */
10012       if (is_outbound && !ast_strlen_zero(p->theirtag))
10013          snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
10014       else if (!is_outbound)
10015          snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->tag);
10016       else
10017          snprintf(newto, sizeof(newto), "%s", ot);
10018       ot = newto;
10019    }
10020 
10021    if (is_outbound) {
10022       add_header(req, "From", of);
10023       add_header(req, "To", ot);
10024    } else {
10025       add_header(req, "From", ot);
10026       add_header(req, "To", of);
10027    }
10028    /* Do not add Contact for MESSAGE, BYE and Cancel requests */
10029    if (sipmethod != SIP_BYE && sipmethod != SIP_CANCEL && sipmethod != SIP_MESSAGE)
10030       add_header(req, "Contact", p->our_contact);
10031 
10032    copy_header(req, orig, "Call-ID");
10033    add_header(req, "CSeq", tmp);
10034 
10035    if (!ast_strlen_zero(global_useragent))
10036       add_header(req, "User-Agent", global_useragent);
10037 
10038    if (!ast_strlen_zero(p->rpid))
10039       add_header(req, "Remote-Party-ID", p->rpid);
10040 
10041    if (!ast_strlen_zero(p->url)) {
10042       add_header(req, "Access-URL", p->url);
10043       ast_string_field_set(p, url, NULL);
10044    }
10045 
10046    /* Add Session-Timers related headers if the feature is active for this session.
10047       An exception to this behavior is the ACK request. Since Asterisk never requires 
10048       session-timers support from a remote end-point (UAS) in an INVITE, it must 
10049       not send 'Require: timer' header in the ACK request. 
10050       This should only be added in the INVITE transactions, not MESSAGE or REFER or other
10051       in-dialog messages.
10052    */
10053    if (p->stimer && p->stimer->st_active == TRUE && p->stimer->st_active_peer_ua == TRUE 
10054        && sipmethod == SIP_INVITE) {
10055       char se_hdr[256];
10056       snprintf(se_hdr, sizeof(se_hdr), "%d;refresher=%s", p->stimer->st_interval, 
10057          strefresher2str(p->stimer->st_ref));
10058       add_header(req, "Require", "timer");
10059       add_header(req, "Session-Expires", se_hdr);
10060       snprintf(se_hdr, sizeof(se_hdr), "%d", st_get_se(p, FALSE));
10061       add_header(req, "Min-SE", se_hdr);
10062    }
10063 
10064    return 0;
10065 }
10066 
10067 /*! \brief Base transmit response function */
10068 static int __transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable)
10069 {
10070    struct sip_request resp;
10071    int seqno = 0;
10072 
10073    if (reliable && (sscanf(get_header(req, "CSeq"), "%30d ", &seqno) != 1)) {
10074       ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
10075       return -1;
10076    }
10077    respprep(&resp, p, msg, req);
10078    /* If we are cancelling an incoming invite for some reason, add information
10079       about the reason why we are doing this in clear text */
10080    if (p->method == SIP_INVITE && msg[0] != '1' && p->owner && p->owner->hangupcause) {
10081       char buf[10];
10082 
10083       add_header(&resp, "X-Asterisk-HangupCause", ast_cause2str(p->owner->hangupcause));
10084       snprintf(buf, sizeof(buf), "%d", p->owner->hangupcause);
10085       add_header(&resp, "X-Asterisk-HangupCauseCode", buf);
10086    }
10087    return send_response(p, &resp, reliable, seqno);
10088 }
10089 
10090 static int temp_pvt_init(void *data)
10091 {
10092    struct sip_pvt *p = data;
10093 
10094    p->do_history = 0;   /* XXX do we need it ? isn't already all 0 ? */
10095    return ast_string_field_init(p, 512);
10096 }
10097 
10098 static void temp_pvt_cleanup(void *data)
10099 {
10100    struct sip_pvt *p = data;
10101 
10102    ast_string_field_free_memory(p);
10103 
10104    ast_free(data);
10105 }
10106 
10107 /*! \brief Transmit response, no retransmits, using a temporary pvt structure */
10108 static int transmit_response_using_temp(ast_string_field callid, struct sockaddr_in *sin, int useglobal_nat, const int intended_method, const struct sip_request *req, const char *msg)
10109 {
10110    struct sip_pvt *p = NULL;
10111 
10112    if (!(p = ast_threadstorage_get(&ts_temp_pvt, sizeof(*p)))) {
10113       ast_log(LOG_ERROR, "Failed to get temporary pvt\n");
10114       return -1;
10115    }
10116 
10117    /* XXX the structure may be dirty from previous usage.
10118     * Here we should state clearly how we should reinitialize it
10119     * before using it.
10120     * E.g. certainly the threadstorage should be left alone,
10121     * but other thihngs such as flags etc. maybe need cleanup ?
10122     */
10123     
10124    /* Initialize the bare minimum */
10125    p->method = intended_method;
10126 
10127    if (!sin)
10128       p->ourip = internip;
10129    else {
10130       p->sa = *sin;
10131       ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
10132    }
10133 
10134    p->branch = ast_random();
10135    make_our_tag(p->tag, sizeof(p->tag));
10136    p->ocseq = INITIAL_CSEQ;
10137 
10138    if (useglobal_nat && sin) {
10139       ast_copy_flags(&p->flags[0], &global_flags[0], SIP_NAT);
10140       p->recv = *sin;
10141       do_setnat(p, ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE);
10142    }
10143 
10144    ast_string_field_set(p, fromdomain, default_fromdomain);
10145    build_via(p);
10146    ast_string_field_set(p, callid, callid);
10147 
10148    copy_socket_data(&p->socket, &req->socket);
10149 
10150    /* Use this temporary pvt structure to send the message */
10151    __transmit_response(p, msg, req, XMIT_UNRELIABLE);
10152 
10153    /* Free the string fields, but not the pool space */
10154    ast_string_field_init(p, 0);
10155 
10156    return 0;
10157 }
10158 
10159 /*! \brief Transmit response, no retransmits */
10160 static int transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req) 
10161 {
10162    return __transmit_response(p, msg, req, XMIT_UNRELIABLE);
10163 }
10164 
10165 /*! \brief Transmit response, no retransmits */
10166 static int transmit_response_with_unsupported(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *unsupported) 
10167 {
10168    struct sip_request resp;
10169    respprep(&resp, p, msg, req);
10170    append_date(&resp);
10171    add_header(&resp, "Unsupported", unsupported);
10172    return send_response(p, &resp, XMIT_UNRELIABLE, 0);
10173 }
10174 
10175 /*! \brief Transmit 422 response with Min-SE header (Session-Timers)  */
10176 static int transmit_response_with_minse(struct sip_pvt *p, const char *msg, const struct sip_request *req, int minse_int)
10177 {
10178    struct sip_request resp;
10179    char minse_str[20];
10180 
10181    respprep(&resp, p, msg, req);
10182    append_date(&resp);
10183 
10184    snprintf(minse_str, sizeof(minse_str), "%d", minse_int);
10185    add_header(&resp, "Min-SE", minse_str);
10186    return send_response(p, &resp, XMIT_UNRELIABLE, 0);
10187 }
10188 
10189 
10190 /*! \brief Transmit response, Make sure you get an ACK
10191    This is only used for responses to INVITEs, where we need to make sure we get an ACK
10192 */
10193 static int transmit_response_reliable(struct sip_pvt *p, const char *msg, const struct sip_request *req)
10194 {
10195    return __transmit_response(p, msg, req, req->ignore ? XMIT_UNRELIABLE : XMIT_CRITICAL);
10196 }
10197 
10198 /*! \brief Append date to SIP message */
10199 static void append_date(struct sip_request *req)
10200 {
10201    char tmpdat[256];
10202    struct tm tm;
10203    time_t t = time(NULL);
10204 
10205    gmtime_r(&t, &tm);
10206    strftime(tmpdat, sizeof(tmpdat), "%a, %d %b %Y %T GMT", &tm);
10207    add_header(req, "Date", tmpdat);
10208 }
10209 
10210 /*! \brief Append date and content length before transmitting response */
10211 static int transmit_response_with_date(struct sip_pvt *p, const char *msg, const struct sip_request *req)
10212 {
10213    struct sip_request resp;
10214    respprep(&resp, p, msg, req);
10215    append_date(&resp);
10216    return send_response(p, &resp, XMIT_UNRELIABLE, 0);
10217 }
10218 
10219 /*! \brief Append Accept header, content length before transmitting response */
10220 static int transmit_response_with_allow(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable)
10221 {
10222    struct sip_request resp;
10223    respprep(&resp, p, msg, req);
10224    add_header(&resp, "Accept", "application/sdp");
10225    return send_response(p, &resp, reliable, 0);
10226 }
10227 
10228 /*! \brief Respond with authorization request */
10229 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)
10230 {
10231    struct sip_request resp;
10232    char tmp[512];
10233    int seqno = 0;
10234 
10235    if (reliable && (sscanf(get_header(req, "CSeq"), "%30d ", &seqno) != 1)) {
10236       ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
10237       return -1;
10238    }
10239    /* Stale means that they sent us correct authentication, but 
10240       based it on an old challenge (nonce) */
10241    snprintf(tmp, sizeof(tmp), "Digest algorithm=MD5, realm=\"%s\", nonce=\"%s\"%s", sip_cfg.realm, randdata, stale ? ", stale=true" : "");
10242    respprep(&resp, p, msg, req);
10243    add_header(&resp, header, tmp);
10244    append_history(p, "AuthChal", "Auth challenge sent for %s - nc %d", p->username, p->noncecount);
10245    return send_response(p, &resp, reliable, seqno);
10246 }
10247 
10248 /* Only use a static string for the msg, here! */
10249 static int transmit_provisional_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, int with_sdp)
10250 {
10251    int res;
10252 
10253    if (!(res = with_sdp ? transmit_response_with_sdp(p, msg, req, XMIT_UNRELIABLE, FALSE) : transmit_response(p, msg, req))) {
10254       p->last_provisional = msg;
10255       update_provisional_keepalive(p, with_sdp);
10256    }
10257 
10258    return res;
10259 }
10260 
10261 /*! \brief Add text body to SIP message */
10262 static int add_text(struct sip_request *req, const char *text)
10263 {
10264    /* XXX Convert \n's to \r\n's XXX */
10265    add_header(req, "Content-Type", "text/plain;charset=UTF-8");
10266    add_content(req, text);
10267    return 0;
10268 }
10269 
10270 /*! \brief Add DTMF INFO tone to sip message 
10271    Mode =   0 for application/dtmf-relay (Cisco)
10272       1 for application/dtmf
10273 */
10274 static int add_digit(struct sip_request *req, char digit, unsigned int duration, int mode)
10275 {
10276    char tmp[256];
10277    int event;
10278    if (mode) {
10279       /* Application/dtmf short version used by some implementations */
10280       if (digit == '*')
10281          event = 10;
10282       else if (digit == '#')
10283          event = 11;
10284       else if ((digit >= 'A') && (digit <= 'D'))
10285          event = 12 + digit - 'A';
10286       else
10287          event = atoi(&digit);
10288       snprintf(tmp, sizeof(tmp), "%d\r\n", event);
10289       add_header(req, "Content-Type", "application/dtmf");
10290       add_content(req, tmp);
10291    } else {
10292       /* Application/dtmf-relay as documented by Cisco */
10293       snprintf(tmp, sizeof(tmp), "Signal=%c\r\nDuration=%u\r\n", digit, duration);
10294       add_header(req, "Content-Type", "application/dtmf-relay");
10295       add_content(req, tmp);
10296    }
10297    return 0;
10298 }
10299 
10300 /*! \brief add XML encoded media control with update 
10301    \note XML: The only way to turn 0 bits of information into a few hundred. (markster) */
10302 static int add_vidupdate(struct sip_request *req)
10303 {
10304    const char *xml_is_a_huge_waste_of_space =
10305       "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\r\n"
10306       " <media_control>\r\n"
10307       "  <vc_primitive>\r\n"
10308       "   <to_encoder>\r\n"
10309       "    <picture_fast_update>\r\n"
10310       "    </picture_fast_update>\r\n"
10311       "   </to_encoder>\r\n"
10312       "  </vc_primitive>\r\n"
10313       " </media_control>\r\n";
10314    add_header(req, "Content-Type", "application/media_control+xml");
10315    add_content(req, xml_is_a_huge_waste_of_space);
10316    return 0;
10317 }
10318 
10319 /*! \brief Add codec offer to SDP offer/answer body in INVITE or 200 OK */
10320 static void add_codec_to_sdp(const struct sip_pvt *p, int codec,
10321               struct ast_str **m_buf, struct ast_str **a_buf,
10322               int debug, int *min_packet_size)
10323 {
10324    int rtp_code;
10325    struct ast_format_list fmt;
10326 
10327 
10328    if (debug)
10329       ast_verbose("Adding codec 0x%x (%s) to SDP\n", codec, ast_getformatname(codec));
10330    if ((rtp_code = ast_rtp_lookup_code(p->rtp, 1, codec)) == -1)
10331       return;
10332 
10333    if (p->rtp) {
10334       struct ast_codec_pref *pref = ast_rtp_codec_getpref(p->rtp);
10335       fmt = ast_codec_pref_getsize(pref, codec);
10336    } else /* I dont see how you couldn't have p->rtp, but good to check for and error out if not there like earlier code */
10337       return;
10338    ast_str_append(m_buf, 0, " %d", rtp_code);
10339    ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%d\r\n", rtp_code,
10340              ast_rtp_lookup_mime_subtype(1, codec,
10341                      ast_test_flag(&p->flags[0], SIP_G726_NONSTANDARD) ? AST_RTP_OPT_G726_NONSTANDARD : 0),
10342              ast_rtp_lookup_sample_rate(1, codec));
10343 
10344    switch (codec) {
10345    case AST_FORMAT_G729A:
10346       /* Indicate that we don't support VAD (G.729 annex B) */
10347       ast_str_append(a_buf, 0, "a=fmtp:%d annexb=no\r\n", rtp_code);
10348       break;
10349    case AST_FORMAT_G723_1:
10350       /* Indicate that we don't support VAD (G.723.1 annex A) */
10351       ast_str_append(a_buf, 0, "a=fmtp:%d annexa=no\r\n", rtp_code);
10352       break;
10353    case AST_FORMAT_ILBC:
10354       /* Add information about us using only 20/30 ms packetization */
10355       ast_str_append(a_buf, 0, "a=fmtp:%d mode=%d\r\n", rtp_code, fmt.cur_ms);
10356       break;
10357    case AST_FORMAT_SIREN7:
10358       /* Indicate that we only expect 32Kbps */
10359       ast_str_append(a_buf, 0, "a=fmtp:%d bitrate=32000\r\n", rtp_code);
10360       break;
10361    case AST_FORMAT_SIREN14:
10362       /* Indicate that we only expect 48Kbps */
10363       ast_str_append(a_buf, 0, "a=fmtp:%d bitrate=48000\r\n", rtp_code);
10364       break;
10365    }
10366 
10367    if (fmt.cur_ms && (fmt.cur_ms < *min_packet_size))
10368       *min_packet_size = fmt.cur_ms;
10369 
10370    /* Our first codec packetization processed cannot be zero */
10371    if ((*min_packet_size)==0 && fmt.cur_ms)
10372       *min_packet_size = fmt.cur_ms;
10373 }
10374 
10375 /*! \brief Add video codec offer to SDP offer/answer body in INVITE or 200 OK */
10376 /* This is different to the audio one now so we can add more caps later */
10377 static void add_vcodec_to_sdp(const struct sip_pvt *p, int codec,
10378               struct ast_str **m_buf, struct ast_str **a_buf,
10379               int debug, int *min_packet_size)
10380 {
10381    int rtp_code;
10382 
10383    if (!p->vrtp)
10384       return;
10385 
10386    if (debug)
10387       ast_verbose("Adding video codec 0x%x (%s) to SDP\n", codec, ast_getformatname(codec));
10388 
10389    if ((rtp_code = ast_rtp_lookup_code(p->vrtp, 1, codec)) == -1)
10390       return;
10391 
10392    ast_str_append(m_buf, 0, " %d", rtp_code);
10393    ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%d\r\n", rtp_code,
10394              ast_rtp_lookup_mime_subtype(1, codec, 0),
10395              ast_rtp_lookup_sample_rate(1, codec));
10396    /* Add fmtp code here */
10397 }
10398 
10399 /*! \brief Add text codec offer to SDP offer/answer body in INVITE or 200 OK */
10400 static void add_tcodec_to_sdp(const struct sip_pvt *p, int codec,
10401               struct ast_str **m_buf, struct ast_str **a_buf,
10402               int debug, int *min_packet_size)
10403 {
10404    int rtp_code;
10405 
10406    if (!p->trtp)
10407       return;
10408 
10409    if (debug)
10410       ast_verbose("Adding text codec 0x%x (%s) to SDP\n", codec, ast_getformatname(codec));
10411 
10412    if ((rtp_code = ast_rtp_lookup_code(p->trtp, 1, codec)) == -1)
10413       return;
10414 
10415    ast_str_append(m_buf, 0, " %d", rtp_code);
10416    ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%d\r\n", rtp_code,
10417              ast_rtp_lookup_mime_subtype(1, codec, 0),
10418              ast_rtp_lookup_sample_rate(1, codec));
10419    /* Add fmtp code here */
10420 
10421    if (codec == AST_FORMAT_T140RED) {
10422       ast_str_append(a_buf, 0, "a=fmtp:%d %d/%d/%d\r\n", rtp_code,
10423           ast_rtp_lookup_code(p->trtp, 1, AST_FORMAT_T140),
10424           ast_rtp_lookup_code(p->trtp, 1, AST_FORMAT_T140),
10425           ast_rtp_lookup_code(p->trtp, 1, AST_FORMAT_T140));
10426 
10427    }
10428 }
10429 
10430 
10431 /*! \brief Get Max T.38 Transmission rate from T38 capabilities */
10432 static unsigned int t38_get_rate(enum ast_control_t38_rate rate)
10433 {
10434    switch (rate) {
10435    case AST_T38_RATE_2400:
10436       return 2400;
10437    case AST_T38_RATE_4800:
10438       return 4800;
10439    case AST_T38_RATE_7200:
10440       return 7200;
10441    case AST_T38_RATE_9600:
10442       return 9600;
10443    case AST_T38_RATE_12000:
10444       return 12000;
10445    case AST_T38_RATE_14400:
10446       return 14400;
10447    default:
10448       return 0;
10449    }
10450 }
10451 
10452 /*! \brief Add RFC 2833 DTMF offer to SDP */
10453 static void add_noncodec_to_sdp(const struct sip_pvt *p, int format,
10454             struct ast_str **m_buf, struct ast_str **a_buf,
10455             int debug)
10456 {
10457    int rtp_code;
10458 
10459    if (debug)
10460       ast_verbose("Adding non-codec 0x%x (%s) to SDP\n", format, ast_rtp_lookup_mime_subtype(0, format, 0));
10461    if ((rtp_code = ast_rtp_lookup_code(p->rtp, 0, format)) == -1)
10462       return;
10463 
10464    ast_str_append(m_buf, 0, " %d", rtp_code);
10465    ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%d\r\n", rtp_code,
10466              ast_rtp_lookup_mime_subtype(0, format, 0),
10467              ast_rtp_lookup_sample_rate(0, format));
10468    if (format == AST_RTP_DTMF)   /* Indicate we support DTMF and FLASH... */
10469       ast_str_append(a_buf, 0, "a=fmtp:%d 0-16\r\n", rtp_code);
10470 }
10471 
10472 /*! \brief Set all IP media addresses for this call 
10473    \note called from add_sdp()
10474 */
10475 static void get_our_media_address(struct sip_pvt *p, int needvideo,
10476    struct sockaddr_in *sin, struct sockaddr_in *vsin, struct sockaddr_in *tsin,
10477    struct sockaddr_in *dest, struct sockaddr_in *vdest)
10478 {
10479    /* First, get our address */
10480    ast_rtp_get_us(p->rtp, sin);
10481    if (p->vrtp)
10482       ast_rtp_get_us(p->vrtp, vsin);
10483    if (p->trtp)
10484       ast_rtp_get_us(p->trtp, tsin);
10485 
10486    /* Now, try to figure out where we want them to send data */
10487    /* Is this a re-invite to move the media out, then use the original offer from caller  */
10488    if (p->redirip.sin_addr.s_addr) {   /* If we have a redirection IP, use it */
10489       dest->sin_port = p->redirip.sin_port;
10490       dest->sin_addr = p->redirip.sin_addr;
10491    } else {
10492       dest->sin_addr = p->ourip.sin_addr;
10493       dest->sin_port = sin->sin_port;
10494    }
10495    if (needvideo) {
10496       /* Determine video destination */
10497       if (p->vredirip.sin_addr.s_addr) {
10498          vdest->sin_addr = p->vredirip.sin_addr;
10499          vdest->sin_port = p->vredirip.sin_port;
10500       } else {
10501          vdest->sin_addr = p->ourip.sin_addr;
10502          vdest->sin_port = vsin->sin_port;
10503       }
10504    }
10505 
10506 }
10507 
10508 /*! \brief Add Session Description Protocol message 
10509 
10510     If oldsdp is TRUE, then the SDP version number is not incremented. This mechanism
10511     is used in Session-Timers where RE-INVITEs are used for refreshing SIP sessions 
10512     without modifying the media session in any way. 
10513 */
10514 static enum sip_result add_sdp(struct sip_request *resp, struct sip_pvt *p, int oldsdp, int add_audio, int add_t38)
10515 {
10516    int alreadysent = 0;
10517    int doing_directmedia = FALSE;
10518 
10519    struct sockaddr_in sin;
10520    struct sockaddr_in vsin;
10521    struct sockaddr_in tsin;
10522    struct sockaddr_in dest;
10523    struct sockaddr_in udptlsin;
10524    struct sockaddr_in vdest = { 0, };
10525    struct sockaddr_in tdest = { 0, };
10526    struct sockaddr_in udptldest = { 0, };
10527 
10528    /* SDP fields */
10529    char *version =   "v=0\r\n";     /* Protocol version */
10530    char subject[256];            /* Subject of the session */
10531    char owner[256];           /* Session owner/creator */
10532    char connection[256];            /* Connection data */
10533    char *session_time = "t=0 0\r\n";         /* Time the session is active */
10534    char bandwidth[256] = "";        /* Max bitrate */
10535    char *hold = "";
10536    struct ast_str *m_audio = ast_str_alloca(256);  /* Media declaration line for audio */
10537    struct ast_str *m_video = ast_str_alloca(256);  /* Media declaration line for video */
10538    struct ast_str *m_text = ast_str_alloca(256);   /* Media declaration line for text */
10539    struct ast_str *m_modem = ast_str_alloca(256);  /* Media declaration line for modem */
10540    struct ast_str *a_audio = ast_str_alloca(1024); /* Attributes for audio */
10541    struct ast_str *a_video = ast_str_alloca(1024); /* Attributes for video */
10542    struct ast_str *a_text = ast_str_alloca(1024);  /* Attributes for text */
10543    struct ast_str *a_modem = ast_str_alloca(1024); /* Attributes for modem */
10544 
10545    int x;
10546    int capability = 0;
10547    int needaudio = FALSE;
10548    int needvideo = FALSE;
10549    int needtext = FALSE;
10550    int debug = sip_debug_test_pvt(p);
10551    int min_audio_packet_size = 0;
10552    int min_video_packet_size = 0;
10553    int min_text_packet_size = 0;
10554 
10555    char codecbuf[SIPBUFSIZE];
10556    char buf[SIPBUFSIZE];
10557    char dummy_answer[256];
10558 
10559    /* Set the SDP session name */
10560    snprintf(subject, sizeof(subject), "s=%s\r\n", ast_strlen_zero(global_sdpsession) ? "-" : global_sdpsession);
10561 
10562    if (!p->rtp) {
10563       ast_log(LOG_WARNING, "No way to add SDP without an RTP structure\n");
10564       return AST_FAILURE;
10565    }
10566    /* XXX We should not change properties in the SIP dialog until 
10567       we have acceptance of the offer if this is a re-invite */
10568 
10569    /* Set RTP Session ID and version */
10570    if (!p->sessionid) {
10571       p->sessionid = (int)ast_random();
10572       p->sessionversion = p->sessionid;
10573    } else {
10574       if (oldsdp == FALSE)
10575          p->sessionversion++;
10576    }
10577 
10578    if (add_audio) {
10579       doing_directmedia = (p->redirip.sin_addr.s_addr && p->redircodecs) ? TRUE : FALSE;
10580       /* Check if we need video in this call */
10581       if ((p->jointcapability & AST_FORMAT_VIDEO_MASK) && !p->novideo) {
10582          if (p->vrtp) {
10583             needvideo = TRUE;
10584             ast_debug(2, "This call needs video offers!\n");
10585          } else
10586             ast_debug(2, "This call needs video offers, but there's no video support enabled!\n");
10587       }
10588       /* Check if we need text in this call */
10589       if ((p->jointcapability & AST_FORMAT_TEXT_MASK) && !p->notext) {
10590          if (sipdebug_text)
10591             ast_verbose("We think we can do text\n");
10592          if (p->trtp) {
10593             if (sipdebug_text) {
10594                ast_verbose("And we have a text rtp object\n");
10595             }
10596             needtext = TRUE;
10597             ast_debug(2, "This call needs text offers! \n");
10598          } else {
10599             ast_debug(2, "This call needs text offers, but there's no text support enabled ! \n");
10600          }
10601       }
10602    }
10603 
10604    get_our_media_address(p, needvideo, &sin, &vsin, &tsin, &dest, &vdest);
10605 
10606    snprintf(owner, sizeof(owner), "o=%s %d %d IN IP4 %s\r\n", ast_strlen_zero(global_sdpowner) ? "-" : global_sdpowner, p->sessionid, p->sessionversion, ast_inet_ntoa(dest.sin_addr));
10607    snprintf(connection, sizeof(connection), "c=IN IP4 %s\r\n", ast_inet_ntoa(dest.sin_addr));
10608 
10609    if (add_audio) {
10610       if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD) == SIP_PAGE2_CALL_ONHOLD_ONEDIR) {
10611          hold = "a=recvonly\r\n";
10612          doing_directmedia = FALSE;
10613       } else if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD) == SIP_PAGE2_CALL_ONHOLD_INACTIVE) {
10614          hold = "a=inactive\r\n";
10615          doing_directmedia = FALSE;
10616       } else {
10617          hold = "a=sendrecv\r\n";
10618       }
10619 
10620       capability = p->jointcapability;
10621 
10622       /* XXX note, Video and Text are negated - 'true' means 'no' */
10623       ast_debug(1, "** Our capability: %s Video flag: %s Text flag: %s\n", ast_getformatname_multiple(codecbuf, sizeof(codecbuf), capability), 
10624            p->novideo ? "True" : "False", p->notext ? "True" : "False");
10625       ast_debug(1, "** Our prefcodec: %s \n", ast_getformatname_multiple(codecbuf, sizeof(codecbuf), p->prefcodec));
10626 
10627       if (doing_directmedia) {
10628          capability &= p->redircodecs;
10629          ast_debug(1, "** Our native-bridge filtered capablity: %s\n", ast_getformatname_multiple(codecbuf, sizeof(codecbuf), capability));
10630       }
10631 
10632       /* Check if we need audio */
10633       if (capability & AST_FORMAT_AUDIO_MASK)
10634          needaudio = TRUE;
10635 
10636       if (debug) 
10637          ast_verbose("Audio is at %s port %d\n", ast_inet_ntoa(p->ourip.sin_addr), ntohs(sin.sin_port)); 
10638 
10639       /* Ok, we need video. Let's add what we need for video and set codecs.
10640          Video is handled differently than audio since we can not transcode. */
10641       if (needvideo) {
10642          ast_str_append(&m_video, 0, "m=video %d RTP/AVP", ntohs(vdest.sin_port));
10643 
10644          /* Build max bitrate string */
10645          if (p->maxcallbitrate)
10646             snprintf(bandwidth, sizeof(bandwidth), "b=CT:%d\r\n", p->maxcallbitrate);
10647          if (debug) 
10648             ast_verbose("Video is at %s port %d\n", ast_inet_ntoa(p->ourip.sin_addr), ntohs(vdest.sin_port));  
10649       }
10650 
10651       /* Ok, we need text. Let's add what we need for text and set codecs.
10652          Text is handled differently than audio since we can not transcode. */
10653       if (needtext) {
10654          if (sipdebug_text)
10655             ast_verbose("Lets set up the text sdp\n");
10656          /* Determine text destination */
10657          if (p->tredirip.sin_addr.s_addr) {
10658             tdest.sin_addr = p->tredirip.sin_addr;
10659             tdest.sin_port = p->tredirip.sin_port;
10660          } else {
10661             tdest.sin_addr = p->ourip.sin_addr;
10662             tdest.sin_port = tsin.sin_port;
10663          }
10664          ast_str_append(&m_text, 0, "m=text %d RTP/AVP", ntohs(tdest.sin_port));
10665          if (debug) /* XXX should I use tdest below ? */
10666             ast_verbose("Text is at %s port %d\n", ast_inet_ntoa(p->ourip.sin_addr), ntohs(tsin.sin_port)); 
10667 
10668       }
10669 
10670       /* Start building generic SDP headers */
10671 
10672       /* We break with the "recommendation" and send our IP, in order that our
10673          peer doesn't have to ast_gethostbyname() us */
10674 
10675       ast_str_append(&m_audio, 0, "m=audio %d RTP/AVP", ntohs(dest.sin_port));
10676 
10677       /* Now, start adding audio codecs. These are added in this order:
10678          - First what was requested by the calling channel
10679          - Then preferences in order from sip.conf device config for this peer/user
10680          - Then other codecs in capabilities, including video
10681       */
10682 
10683       /* Prefer the audio codec we were requested to use, first, no matter what 
10684          Note that p->prefcodec can include video codecs, so mask them out
10685       */
10686       if (capability & p->prefcodec) {
10687          int codec = p->prefcodec & AST_FORMAT_AUDIO_MASK;
10688 
10689          add_codec_to_sdp(p, codec, &m_audio, &a_audio, debug, &min_audio_packet_size);
10690          alreadysent |= codec;
10691       }
10692 
10693       /* Start by sending our preferred audio/video codecs */
10694       for (x = 0; x < 32; x++) {
10695          int codec;
10696 
10697          if (!(codec = ast_codec_pref_index(&p->prefs, x)))
10698             break; 
10699 
10700          if (!(capability & codec))
10701             continue;
10702 
10703          if (alreadysent & codec)
10704             continue;
10705 
10706          add_codec_to_sdp(p, codec, &m_audio, &a_audio, debug, &min_audio_packet_size);
10707          alreadysent |= codec;
10708       }
10709 
10710       /* Now send any other common audio and video codecs, and non-codec formats: */
10711       for (x = 1; x <= (needtext ? AST_FORMAT_TEXT_MASK : (needvideo ? AST_FORMAT_VIDEO_MASK : AST_FORMAT_AUDIO_MASK)); x <<= 1) {
10712          if (!(capability & x))  /* Codec not requested */
10713             continue;
10714 
10715          if (alreadysent & x) /* Already added to SDP */
10716             continue;
10717 
10718          if (x & AST_FORMAT_AUDIO_MASK)
10719             add_codec_to_sdp(p, x, &m_audio, &a_audio, debug, &min_audio_packet_size);
10720          else if (x & AST_FORMAT_VIDEO_MASK)
10721             add_vcodec_to_sdp(p, x, &m_video, &a_video, debug, &min_video_packet_size);
10722          else if (x & AST_FORMAT_TEXT_MASK)
10723             add_tcodec_to_sdp(p, x, &m_text, &a_text, debug, &min_text_packet_size);
10724       }
10725 
10726       /* Now add DTMF RFC2833 telephony-event as a codec */
10727       for (x = 1; x <= AST_RTP_MAX; x <<= 1) {
10728          if (!(p->jointnoncodeccapability & x))
10729             continue;
10730 
10731          add_noncodec_to_sdp(p, x, &m_audio, &a_audio, debug);
10732       }
10733 
10734       ast_debug(3, "-- Done with adding codecs to SDP\n");
10735 
10736       if (!p->owner || !ast_internal_timing_enabled(p->owner))
10737          ast_str_append(&a_audio, 0, "a=silenceSupp:off - - - -\r\n");
10738 
10739       if (min_audio_packet_size)
10740          ast_str_append(&a_audio, 0, "a=ptime:%d\r\n", min_audio_packet_size);
10741 
10742       /* XXX don't think you can have ptime for video */
10743       if (min_video_packet_size)
10744          ast_str_append(&a_video, 0, "a=ptime:%d\r\n", min_video_packet_size);
10745 
10746       /* XXX don't think you can have ptime for text */
10747       if (min_text_packet_size)
10748          ast_str_append(&a_text, 0, "a=ptime:%d\r\n", min_text_packet_size);
10749  
10750       if (m_audio->len - m_audio->used < 2 || m_video->len - m_video->used < 2 ||
10751           m_text->len - m_text->used < 2 || a_text->len - a_text->used < 2 ||
10752           a_audio->len - a_audio->used < 2 || a_video->len - a_video->used < 2)
10753          ast_log(LOG_WARNING, "SIP SDP may be truncated due to undersized buffer!!\n");
10754    }
10755 
10756    if (add_t38) {
10757       /* Our T.38 end is */
10758       ast_udptl_get_us(p->udptl, &udptlsin);
10759 
10760       /* Determine T.38 UDPTL destination */
10761       if (p->udptlredirip.sin_addr.s_addr) {
10762          udptldest.sin_port = p->udptlredirip.sin_port;
10763          udptldest.sin_addr = p->udptlredirip.sin_addr;
10764       } else {
10765          udptldest.sin_addr = p->ourip.sin_addr;
10766          udptldest.sin_port = udptlsin.sin_port;
10767       }
10768 
10769       if (debug)
10770          ast_debug(1, "T.38 UDPTL is at %s port %d\n", ast_inet_ntoa(p->ourip.sin_addr), ntohs(udptlsin.sin_port));
10771 
10772       /* We break with the "recommendation" and send our IP, in order that our
10773          peer doesn't have to ast_gethostbyname() us */
10774 
10775       ast_str_append(&m_modem, 0, "m=image %d udptl t38\r\n", ntohs(udptldest.sin_port));
10776 
10777       ast_str_append(&a_modem, 0, "a=T38FaxVersion:%d\r\n", p->t38.our_parms.version);
10778       ast_str_append(&a_modem, 0, "a=T38MaxBitRate:%d\r\n", t38_get_rate(p->t38.our_parms.rate));
10779       if (p->t38.our_parms.fill_bit_removal) {
10780          ast_str_append(&a_modem, 0, "a=T38FaxFillBitRemoval\r\n");
10781       }
10782       if (p->t38.our_parms.transcoding_mmr) {
10783          ast_str_append(&a_modem, 0, "a=T38FaxTranscodingMMR\r\n");
10784       }
10785       if (p->t38.our_parms.transcoding_jbig) {
10786          ast_str_append(&a_modem, 0, "a=T38FaxTranscodingJBIG\r\n");
10787       }
10788       switch (p->t38.our_parms.rate_management) {
10789       case AST_T38_RATE_MANAGEMENT_TRANSFERRED_TCF:
10790          ast_str_append(&a_modem, 0, "a=T38FaxRateManagement:transferredTCF\r\n");
10791          break;
10792       case AST_T38_RATE_MANAGEMENT_LOCAL_TCF:
10793          ast_str_append(&a_modem, 0, "a=T38FaxRateManagement:localTCF\r\n");
10794          break;
10795       }
10796       ast_str_append(&a_modem, 0, "a=T38FaxMaxDatagram:%u\r\n", ast_udptl_get_local_max_datagram(p->udptl));
10797       switch (ast_udptl_get_error_correction_scheme(p->udptl)) {
10798       case UDPTL_ERROR_CORRECTION_NONE:
10799          break;
10800       case UDPTL_ERROR_CORRECTION_FEC:
10801          ast_str_append(&a_modem, 0, "a=T38FaxUdpEC:t38UDPFEC\r\n");
10802          break;
10803       case UDPTL_ERROR_CORRECTION_REDUNDANCY:
10804          ast_str_append(&a_modem, 0, "a=T38FaxUdpEC:t38UDPRedundancy\r\n");
10805          break;
10806       }
10807    }
10808 
10809    if (needaudio)
10810       ast_str_append(&m_audio, 0, "\r\n");
10811    if (needvideo)
10812       ast_str_append(&m_video, 0, "\r\n");
10813    if (needtext)
10814       ast_str_append(&m_text, 0, "\r\n");
10815 
10816    add_header(resp, "Content-Type", "application/sdp");
10817    add_content(resp, version);
10818    add_content(resp, owner);
10819    add_content(resp, subject);
10820    add_content(resp, connection);
10821    if (needvideo)    /* only if video response is appropriate */
10822       add_content(resp, bandwidth);
10823    add_content(resp, session_time);
10824    if (needaudio) {
10825       add_content(resp, m_audio->str);
10826       add_content(resp, a_audio->str);
10827       add_content(resp, hold);
10828    } else if (p->offered_media[SDP_AUDIO].offered) {
10829       snprintf(dummy_answer, sizeof(dummy_answer), "m=audio 0 RTP/AVP %s\r\n", p->offered_media[SDP_AUDIO].text);
10830       add_content(resp, dummy_answer);
10831    }
10832    if (needvideo) { /* only if video response is appropriate */
10833       add_content(resp, m_video->str);
10834       add_content(resp, a_video->str);
10835       add_content(resp, hold);   /* Repeat hold for the video stream */
10836    } else if (p->offered_media[SDP_VIDEO].offered) {
10837       snprintf(dummy_answer, sizeof(dummy_answer), "m=video 0 RTP/AVP %s\r\n", p->offered_media[SDP_VIDEO].text);
10838       add_content(resp, dummy_answer);
10839    }
10840    if (needtext) { /* only if text response is appropriate */
10841       add_content(resp, m_text->str);
10842       add_content(resp, a_text->str);
10843       add_content(resp, hold);   /* Repeat hold for the text stream */
10844    } else if (p->offered_media[SDP_TEXT].offered) {
10845       snprintf(dummy_answer, sizeof(dummy_answer), "m=text 0 RTP/AVP %s\r\n", p->offered_media[SDP_TEXT].text);
10846       add_content(resp, dummy_answer);
10847    }
10848    if (add_t38) {
10849       add_content(resp, m_modem->str);
10850       add_content(resp, a_modem->str);
10851    } else if (p->offered_media[SDP_IMAGE].offered) {
10852       add_content(resp, "m=image 0 udptl t38\r\n");
10853    }
10854 
10855    /* Update lastrtprx when we send our SDP */
10856    p->lastrtprx = p->lastrtptx = time(NULL); /* XXX why both ? */
10857 
10858    ast_debug(3, "Done building SDP. Settling with this capability: %s\n", ast_getformatname_multiple(buf, SIPBUFSIZE, capability));
10859 
10860    return AST_SUCCESS;
10861 }
10862 
10863 /*! \brief Used for 200 OK and 183 early media */
10864 static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans)
10865 {
10866    struct sip_request resp;
10867    int seqno;
10868    
10869    if (sscanf(get_header(req, "CSeq"), "%30d ", &seqno) != 1) {
10870       ast_log(LOG_WARNING, "Unable to get seqno from '%s'\n", get_header(req, "CSeq"));
10871       return -1;
10872    }
10873    respprep(&resp, p, msg, req);
10874    if (p->udptl) {
10875       add_sdp(&resp, p, 0, 0, 1);
10876    } else 
10877       ast_log(LOG_ERROR, "Can't add SDP to response, since we have no UDPTL session allocated. Call-ID %s\n", p->callid);
10878    if (retrans && !p->pendinginvite)
10879       p->pendinginvite = seqno;     /* Buggy clients sends ACK on RINGING too */
10880    return send_response(p, &resp, retrans, seqno);
10881 }
10882 
10883 /*! \brief copy SIP request (mostly used to save request for responses) */
10884 static void copy_request(struct sip_request *dst, const struct sip_request *src)
10885 {
10886    /* XXX this function can encounter memory allocation errors, perhaps it
10887     * should return a value */
10888 
10889    struct ast_str *duplicate = dst->data;
10890    struct ast_str *duplicate_content = dst->content;
10891 
10892    /* copy the entire request then restore the original data and content
10893     * members from the dst request */
10894    memcpy(dst, src, sizeof(*dst));
10895    dst->data = duplicate;
10896    dst->content = duplicate_content;
10897 
10898    /* copy the data into the dst request */
10899    if (!dst->data && !(dst->data = ast_str_create(ast_str_strlen(src->data) + 1)))
10900       return;
10901    ast_str_copy_string(&dst->data, src->data);
10902 
10903    /* copy the content into the dst request (if it exists) */
10904    if (src->content) {
10905       if (!dst->content && !(dst->content = ast_str_create(ast_str_strlen(src->content) + 1)))
10906          return;
10907       ast_str_copy_string(&dst->content, src->content);
10908    }
10909 }
10910 
10911 /*! \brief Used for 200 OK and 183 early media 
10912    \return Will return XMIT_ERROR for network errors.
10913 */
10914 static int transmit_response_with_sdp(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable, int oldsdp)
10915 {
10916    struct sip_request resp;
10917    int seqno;
10918    if (sscanf(get_header(req, "CSeq"), "%30d ", &seqno) != 1) {
10919       ast_log(LOG_WARNING, "Unable to get seqno from '%s'\n", get_header(req, "CSeq"));
10920       return -1;
10921    }
10922    respprep(&resp, p, msg, req);
10923    if (p->rtp) {
10924       if (!p->autoframing && !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
10925          ast_debug(1, "Setting framing from config on incoming call\n");
10926          ast_rtp_codec_setpref(p->rtp, &p->prefs);
10927       }
10928       try_suggested_sip_codec(p);
10929       if (p->t38.state == T38_ENABLED) {
10930          add_sdp(&resp, p, oldsdp, TRUE, TRUE);
10931       } else {
10932          add_sdp(&resp, p, oldsdp, TRUE, FALSE);
10933       }
10934    } else 
10935       ast_log(LOG_ERROR, "Can't add SDP to response, since we have no RTP session allocated. Call-ID %s\n", p->callid);
10936    if (reliable && !p->pendinginvite)
10937       p->pendinginvite = seqno;     /* Buggy clients sends ACK on RINGING too */
10938    return send_response(p, &resp, reliable, seqno);
10939 }
10940 
10941 /*! \brief Parse first line of incoming SIP request */
10942 static int determine_firstline_parts(struct sip_request *req) 
10943 {
10944    char *e = ast_skip_blanks(req->data->str);   /* there shouldn't be any */
10945    char *local_rlPart1;
10946 
10947    if (!*e)
10948       return -1;
10949    req->rlPart1 = e - req->data->str;  /* method or protocol */
10950    local_rlPart1 = e;
10951    e = ast_skip_nonblanks(e);
10952    if (*e)
10953       *e++ = '\0';
10954    /* Get URI or status code */
10955    e = ast_skip_blanks(e);
10956    if ( !*e )
10957       return -1;
10958    ast_trim_blanks(e);
10959 
10960    if (!strcasecmp(local_rlPart1, "SIP/2.0") ) { /* We have a response */
10961       if (strlen(e) < 3)   /* status code is 3 digits */
10962          return -1;
10963       req->rlPart2 = e - req->data->str;
10964    } else { /* We have a request */
10965       if ( *e == '<' ) { /* XXX the spec says it must not be in <> ! */
10966          ast_debug(3, "Oops. Bogus uri in <> %s\n", e);
10967          e++;
10968          if (!*e)
10969             return -1; 
10970       }
10971       req->rlPart2 = e - req->data->str;  /* URI */
10972       e = ast_skip_nonblanks(e);
10973       if (*e)
10974          *e++ = '\0';
10975       e = ast_skip_blanks(e);
10976       if (strcasecmp(e, "SIP/2.0") ) {
10977          ast_debug(3, "Skipping packet - Bad request protocol %s\n", e);
10978          return -1;
10979       }
10980    }
10981    return 1;
10982 }
10983 
10984 /*! \brief Transmit reinvite with SDP
10985 \note    A re-invite is basically a new INVITE with the same CALL-ID and TAG as the
10986    INVITE that opened the SIP dialogue 
10987    We reinvite so that the audio stream (RTP) go directly between
10988    the SIP UAs. SIP Signalling stays with * in the path.
10989    
10990    If t38version is TRUE, we send T38 SDP for re-invite from audio/video to
10991    T38 UDPTL transmission on the channel
10992 
10993     If oldsdp is TRUE then the SDP version number is not incremented. This
10994     is needed for Session-Timers so we can send a re-invite to refresh the
10995     SIP session without modifying the media session. 
10996 */
10997 static int transmit_reinvite_with_sdp(struct sip_pvt *p, int t38version, int oldsdp)
10998 {
10999    struct sip_request req;
11000    
11001    reqprep(&req, p, ast_test_flag(&p->flags[0], SIP_REINVITE_UPDATE) ?  SIP_UPDATE : SIP_INVITE, 0, 1);
11002 
11003    add_header(&req, "Allow", ALLOWED_METHODS);
11004    add_supported_header(p, &req);
11005    if (sipdebug) {
11006       if (oldsdp == TRUE)
11007          add_header(&req, "X-asterisk-Info", "SIP re-invite (Session-Timers)");
11008       else
11009          add_header(&req, "X-asterisk-Info", "SIP re-invite (External RTP bridge)");
11010    }
11011 
11012    if (p->do_history)
11013       append_history(p, "ReInv", "Re-invite sent");
11014    memset(p->offered_media, 0, sizeof(p->offered_media));
11015 
11016    if (t38version)
11017       add_sdp(&req, p, oldsdp, FALSE, TRUE);
11018    else
11019       add_sdp(&req, p, oldsdp, TRUE, FALSE);
11020 
11021    /* Use this as the basis */
11022    initialize_initreq(p, &req);
11023    p->lastinvite = p->ocseq;
11024    ast_set_flag(&p->flags[0], SIP_OUTGOING);       /* Change direction of this dialog */
11025 
11026    return send_request(p, &req, XMIT_CRITICAL, p->ocseq);
11027 }
11028 
11029 /* \brief Remove URI parameters at end of URI, not in username part though */
11030 static char *remove_uri_parameters(char *uri)
11031 {
11032    char *atsign;
11033    atsign = strchr(uri, '@'); /* First, locate the at sign */
11034    if (!atsign)
11035       atsign = uri;  /* Ok hostname only, let's stick with the rest */
11036    atsign = strchr(atsign, ';'); /* Locate semi colon */
11037    if (atsign)
11038       *atsign = '\0';   /* Kill at the semi colon */
11039    return uri;
11040 }
11041 
11042 /*! \brief Check Contact: URI of SIP message */
11043 static void extract_uri(struct sip_pvt *p, struct sip_request *req)
11044 {
11045    char stripped[SIPBUFSIZE];
11046    char *c;
11047 
11048    ast_copy_string(stripped, get_header(req, "Contact"), sizeof(stripped));
11049    c = get_in_brackets(stripped);
11050    /* Cut the URI at the at sign after the @, not in the username part */
11051    c = remove_uri_parameters(c);
11052    if (!ast_strlen_zero(c))
11053       ast_string_field_set(p, uri, c);
11054 
11055 }
11056 
11057 /*! \brief Build contact header - the contact header we send out */
11058 static void build_contact(struct sip_pvt *p)
11059 {
11060    char tmp[SIPBUFSIZE];
11061    char *user = ast_uri_encode(p->exten, tmp, sizeof(tmp), 1);
11062    int ourport = ntohs(p->ourip.sin_port);
11063 
11064    /* only add port if it's non-standard for the transport type */
11065    if (!sip_standard_port(p->socket.type, ourport)) {
11066       if (p->socket.type == SIP_TRANSPORT_UDP)
11067          ast_string_field_build(p, our_contact, "<sip:%s%s%s:%d>", user, ast_strlen_zero(user) ? "" : "@", ast_inet_ntoa(p->ourip.sin_addr), ourport);
11068       else
11069          ast_string_field_build(p, our_contact, "<sip:%s%s%s:%d;transport=%s>", user, ast_strlen_zero(user) ? "" : "@", ast_inet_ntoa(p->ourip.sin_addr), ourport, get_transport(p->socket.type));
11070    } else {
11071       if (p->socket.type == SIP_TRANSPORT_UDP)
11072          ast_string_field_build(p, our_contact, "<sip:%s%s%s>", user, ast_strlen_zero(user) ? "" : "@", ast_inet_ntoa(p->ourip.sin_addr));
11073       else
11074          ast_string_field_build(p, our_contact, "<sip:%s%s%s;transport=%s>", user, ast_strlen_zero(user) ? "" : "@", ast_inet_ntoa(p->ourip.sin_addr), get_transport(p->socket.type));
11075    }
11076 }
11077 
11078 /*! \brief Build the Remote Party-ID & From using callingpres options */
11079 static void build_rpid(struct sip_pvt *p)
11080 {
11081    int send_pres_tags = TRUE;
11082    const char *privacy=NULL;
11083    const char *screen=NULL;
11084    char buf[256];
11085    const char *clid = default_callerid;
11086    const char *clin = NULL;
11087    const char *fromdomain;
11088 
11089    if (!ast_strlen_zero(p->rpid) || !ast_strlen_zero(p->rpid_from))  
11090       return;
11091 
11092    if (p->owner && !ast_strlen_zero(p->owner->cid.cid_num))
11093       clid = p->owner->cid.cid_num;
11094    if (p->owner && p->owner->cid.cid_name)
11095       clin = p->owner->cid.cid_name;
11096    if (ast_strlen_zero(clin))
11097       clin = clid;
11098 
11099    switch (p->callingpres) {
11100    case AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED:
11101       privacy = "off";
11102       screen = "no";
11103       break;
11104    case AST_PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN:
11105       privacy = "off";
11106       screen = "yes";
11107       break;
11108    case AST_PRES_ALLOWED_USER_NUMBER_FAILED_SCREEN:
11109       privacy = "off";
11110       screen = "no";
11111       break;
11112    case AST_PRES_ALLOWED_NETWORK_NUMBER:
11113       privacy = "off";
11114       screen = "yes";
11115       break;
11116    case AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED:
11117       privacy = "full";
11118       screen = "no";
11119       break;
11120    case AST_PRES_PROHIB_USER_NUMBER_PASSED_SCREEN:
11121       privacy = "full";
11122       screen = "yes";
11123       break;
11124    case AST_PRES_PROHIB_USER_NUMBER_FAILED_SCREEN:
11125       privacy = "full";
11126       screen = "no";
11127       break;
11128    case AST_PRES_PROHIB_NETWORK_NUMBER:
11129       privacy = "full";
11130       screen = "yes";
11131       break;
11132    case AST_PRES_NUMBER_NOT_AVAILABLE:
11133       send_pres_tags = FALSE;
11134       break;
11135    default:
11136       ast_log(LOG_WARNING, "Unsupported callingpres (%d)\n", p->callingpres);
11137       if ((p->callingpres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED)
11138          privacy = "full";
11139       else
11140          privacy = "off";
11141       screen = "no";
11142       break;
11143    }
11144    
11145    fromdomain = S_OR(p->fromdomain, ast_inet_ntoa(p->ourip.sin_addr));
11146 
11147    snprintf(buf, sizeof(buf), "\"%s\" <sip:%s@%s>", clin, clid, fromdomain);
11148    if (send_pres_tags)
11149       snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), ";privacy=%s;screen=%s", privacy, screen);
11150    ast_string_field_set(p, rpid, buf);
11151 
11152    ast_string_field_build(p, rpid_from, "\"%s\" <sip:%s@%s>;tag=%s", clin,
11153                 S_OR(p->fromuser, clid),
11154                 fromdomain, p->tag);
11155 }
11156 
11157 /*! \brief Initiate new SIP request to peer/user */
11158 static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod)
11159 {
11160    struct ast_str *invite = ast_str_alloca(256);
11161    char from[256];
11162    char to[256];
11163    char tmp_n[SIPBUFSIZE/2];  /* build a local copy of 'n' if needed */
11164    char tmp_l[SIPBUFSIZE/2];  /* build a local copy of 'l' if needed */
11165    const char *l = NULL;   /* XXX what is this, exactly ? */
11166    const char *n = NULL;   /* XXX what is this, exactly ? */
11167    const char *d = NULL;   /* domain in from header */
11168    const char *urioptions = "";
11169    int ourport;
11170 
11171    if (ast_test_flag(&p->flags[0], SIP_USEREQPHONE)) {
11172       const char *s = p->username;  /* being a string field, cannot be NULL */
11173 
11174       /* Test p->username against allowed characters in AST_DIGIT_ANY
11175          If it matches the allowed characters list, then sipuser = ";user=phone"
11176          If not, then sipuser = ""
11177       */
11178       /* + is allowed in first position in a tel: uri */
11179       if (*s == '+')
11180          s++;
11181       for (; *s; s++) {
11182          if (!strchr(AST_DIGIT_ANYNUM, *s) )
11183             break;
11184       }
11185       /* If we have only digits, add ;user=phone to the uri */
11186       if (!*s)
11187          urioptions = ";user=phone";
11188    }
11189 
11190 
11191    snprintf(p->lastmsg, sizeof(p->lastmsg), "Init: %s", sip_methods[sipmethod].text);
11192 
11193    d = S_OR(p->fromdomain, ast_inet_ntoa(p->ourip.sin_addr));
11194    if (p->owner) {
11195       l = p->owner->cid.cid_num;
11196       n = p->owner->cid.cid_name;
11197    }
11198    /* if we are not sending RPID and user wants his callerid restricted */
11199    if (!ast_test_flag(&p->flags[0], SIP_SENDRPID) &&
11200        ((p->callingpres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED)) {
11201       l = CALLERID_UNKNOWN;
11202       n = l;
11203       d = FROMDOMAIN_INVALID;
11204    }
11205    if (ast_strlen_zero(l))
11206       l = default_callerid;
11207    if (ast_strlen_zero(n))
11208       n = l;
11209    /* Allow user to be overridden */
11210    if (!ast_strlen_zero(p->fromuser))
11211       l = p->fromuser;
11212    else /* Save for any further attempts */
11213       ast_string_field_set(p, fromuser, l);
11214 
11215    /* Allow user to be overridden */
11216    if (!ast_strlen_zero(p->fromname))
11217       n = p->fromname;
11218    else /* Save for any further attempts */
11219       ast_string_field_set(p, fromname, n);
11220 
11221    if (sip_cfg.pedanticsipchecking) {
11222       ast_uri_encode(n, tmp_n, sizeof(tmp_n), 0);
11223       n = tmp_n;
11224       ast_uri_encode(l, tmp_l, sizeof(tmp_l), 0);
11225       l = tmp_l;
11226    }
11227 
11228    ourport = ntohs(p->ourip.sin_port);
11229    if (!sip_standard_port(p->socket.type, ourport) && ast_strlen_zero(p->fromdomain))
11230       snprintf(from, sizeof(from), "\"%s\" <sip:%s@%s:%d>;tag=%s", n, l, d, ourport, p->tag);
11231    else
11232       snprintf(from, sizeof(from), "\"%s\" <sip:%s@%s>;tag=%s", n, l, d, p->tag);
11233 
11234    /* If we're calling a registered SIP peer, use the fullcontact to dial to the peer */
11235    if (!ast_strlen_zero(p->fullcontact)) {
11236       /* If we have full contact, trust it */
11237       ast_str_append(&invite, 0, "%s", p->fullcontact);
11238    } else {
11239       /* Otherwise, use the username while waiting for registration */
11240       ast_str_append(&invite, 0, "sip:");
11241       if (!ast_strlen_zero(p->username)) {
11242          n = p->username;
11243          if (sip_cfg.pedanticsipchecking) {
11244             ast_uri_encode(n, tmp_n, sizeof(tmp_n), 0);
11245             n = tmp_n;
11246          }
11247          ast_str_append(&invite, 0, "%s@", n);
11248       }
11249       ast_str_append(&invite, 0, "%s", p->tohost);
11250       if (p->portinuri)
11251          ast_str_append(&invite, 0, ":%d", ntohs(p->sa.sin_port));
11252       ast_str_append(&invite, 0, "%s", urioptions);
11253    }
11254 
11255    /* If custom URI options have been provided, append them */
11256    if (p->options && !ast_strlen_zero(p->options->uri_options))
11257       ast_str_append(&invite, 0, ";%s", p->options->uri_options);
11258    
11259    /* This is the request URI, which is the next hop of the call
11260       which may or may not be the destination of the call
11261    */
11262    ast_string_field_set(p, uri, invite->str);
11263   
11264    if (!ast_strlen_zero(p->todnid)) {
11265       /*! \todo Need to add back the VXML URL here at some point, possibly use build_string for all this junk */
11266       if (!strchr(p->todnid, '@')) {
11267          /* We have no domain in the dnid */
11268          snprintf(to, sizeof(to), "<sip:%s@%s>%s%s", p->todnid, p->tohost, ast_strlen_zero(p->theirtag) ? "" : ";tag=", p->theirtag);
11269       } else {
11270          snprintf(to, sizeof(to), "<sip:%s>%s%s", p->todnid, ast_strlen_zero(p->theirtag) ? "" : ";tag=", p->theirtag);
11271       }
11272    } else {
11273       if (sipmethod == SIP_NOTIFY && !ast_strlen_zero(p->theirtag)) { 
11274          /* If this is a NOTIFY, use the From: tag in the subscribe (RFC 3265) */
11275          snprintf(to, sizeof(to), "<%s%s>;tag=%s", (strncasecmp(p->uri, "sip:", 4) ? "sip:" : ""), p->uri, p->theirtag);
11276       } else if (p->options && p->options->vxml_url) {
11277          /* If there is a VXML URL append it to the SIP URL */
11278          snprintf(to, sizeof(to), "<%s>;%s", p->uri, p->options->vxml_url);
11279       } else 
11280          snprintf(to, sizeof(to), "<%s>", p->uri);
11281    }
11282 
11283    init_req(req, sipmethod, p->uri);
11284    /* now tmp_n is available so reuse it to build the CSeq */
11285    snprintf(tmp_n, sizeof(tmp_n), "%d %s", ++p->ocseq, sip_methods[sipmethod].text);
11286 
11287    add_header(req, "Via", p->via);
11288    add_header(req, "Max-Forwards", DEFAULT_MAX_FORWARDS);
11289    /* This will be a no-op most of the time. However, under certain circumstances,
11290     * NOTIFY messages will use this function for preparing the request and should
11291     * have Route headers present.
11292     */
11293    add_route(req, p->route);
11294 
11295    /* Build Remote Party-ID and From */
11296    if (ast_test_flag(&p->flags[0], SIP_SENDRPID) && (sipmethod == SIP_INVITE)) {
11297       build_rpid(p);
11298       add_header(req, "From", p->rpid_from);
11299    } else 
11300       add_header(req, "From", from);
11301    add_header(req, "To", to);
11302    ast_string_field_set(p, exten, l);
11303    build_contact(p);
11304    add_header(req, "Contact", p->our_contact);
11305    add_header(req, "Call-ID", p->callid);
11306    add_header(req, "CSeq", tmp_n);
11307    if (!ast_strlen_zero(global_useragent))
11308       add_header(req, "User-Agent", global_useragent);
11309    if (!ast_strlen_zero(p->rpid))
11310       add_header(req, "Remote-Party-ID", p->rpid);
11311 }
11312 
11313 /*! \brief Build REFER/INVITE/OPTIONS/SUBSCRIBE message and transmit it 
11314    \param init 0 = Prepare request within dialog, 1= prepare request, new branch, 2= prepare new request and new dialog. do_proxy_auth calls this with init!=2
11315  \param p sip_pvt structure
11316  \param sdp unknown 
11317  \param sipmethod unknown 
11318  
11319 */
11320 static int transmit_invite(struct sip_pvt *p, int sipmethod, int sdp, int init)
11321 {
11322    struct sip_request req;
11323    struct ast_variable *var;
11324    
11325    req.method = sipmethod;
11326    if (init) {/* Bump branch even on initial requests */
11327       p->branch ^= ast_random();
11328       p->invite_branch = p->branch;
11329       build_via(p);
11330    }
11331    if (init > 1)
11332       initreqprep(&req, p, sipmethod);
11333    else
11334       /* If init=1, we should not generate a new branch. If it's 0, we need a new branch. */
11335       reqprep(&req, p, sipmethod, 0, init ? 0 : 1);
11336       
11337    if (p->options && p->options->auth)
11338       add_header(&req, p->options->authheader, p->options->auth);
11339    append_date(&req);
11340    if (sipmethod == SIP_REFER) { /* Call transfer */
11341       if (p->refer) {
11342          char buf[SIPBUFSIZE];
11343          if (!ast_strlen_zero(p->refer->refer_to))
11344             add_header(&req, "Refer-To", p->refer->refer_to);
11345          if (!ast_strlen_zero(p->refer->referred_by)) {
11346             snprintf(buf, sizeof(buf), "%s <%s>", p->refer->referred_by_name, p->refer->referred_by);
11347             add_header(&req, "Referred-By", buf);
11348          }
11349       }
11350    } else if (sipmethod == SIP_SUBSCRIBE) { /* We only support sending MWI subscriptions right now */
11351       char buf[SIPBUFSIZE];
11352 
11353       add_header(&req, "Event", "message-summary");
11354       add_header(&req, "Accept", "application/simple-message-summary");
11355       snprintf(buf, sizeof(buf), "%d", mwi_expiry);
11356       add_header(&req, "Expires", buf);
11357    }
11358 
11359    /* This new INVITE is part of an attended transfer. Make sure that the
11360    other end knows and replace the current call with this new call */
11361    if (p->options && !ast_strlen_zero(p->options->replaces)) {
11362       add_header(&req, "Replaces", p->options->replaces);
11363       add_header(&req, "Require", "replaces");
11364    }
11365 
11366    /* Add Session-Timers related headers */
11367    if (st_get_mode(p) == SESSION_TIMER_MODE_ORIGINATE) {
11368       char i2astr[10];
11369 
11370       if (!p->stimer->st_interval)
11371          p->stimer->st_interval = st_get_se(p, TRUE);
11372 
11373       p->stimer->st_active = TRUE;
11374       
11375       snprintf(i2astr, sizeof(i2astr), "%d", p->stimer->st_interval);
11376       add_header(&req, "Session-Expires", i2astr);
11377       snprintf(i2astr, sizeof(i2astr), "%d", st_get_se(p, FALSE));
11378       add_header(&req, "Min-SE", i2astr);
11379    }
11380 
11381    add_header(&req, "Allow", ALLOWED_METHODS);
11382    add_supported_header(p, &req);
11383 
11384    if(p->notify_headers) {
11385       char buf[512];
11386       for (var = p->notify_headers; var; var = var->next) {
11387          ast_copy_string(buf, var->value, sizeof(buf));
11388          add_header(&req, var->name, ast_unescape_semicolon(buf));
11389       }
11390    }
11391    if (p->options && p->options->addsipheaders && p->owner) {
11392       struct ast_channel *chan = p->owner; /* The owner channel */
11393       struct varshead *headp;
11394    
11395       ast_channel_lock(chan);
11396 
11397       headp = &chan->varshead;
11398 
11399       if (!headp)
11400          ast_log(LOG_WARNING, "No Headp for the channel...ooops!\n");
11401       else {
11402          const struct ast_var_t *current;
11403          AST_LIST_TRAVERSE(headp, current, entries) {  
11404             /* SIPADDHEADER: Add SIP header to outgoing call */
11405             if (!strncasecmp(ast_var_name(current), "SIPADDHEADER", strlen("SIPADDHEADER"))) {
11406                char *content, *end;
11407                const char *header = ast_var_value(current);
11408                char *headdup = ast_strdupa(header);
11409 
11410                /* Strip of the starting " (if it's there) */
11411                if (*headdup == '"')
11412                   headdup++;
11413                if ((content = strchr(headdup, ':'))) {
11414                   *content++ = '\0';
11415                   content = ast_skip_blanks(content); /* Skip white space */
11416                   /* Strip the ending " (if it's there) */
11417                   end = content + strlen(content) -1; 
11418                   if (*end == '"')
11419                      *end = '\0';
11420                
11421                   add_header(&req, headdup, content);
11422                   if (sipdebug)
11423                      ast_debug(1, "Adding SIP Header \"%s\" with content :%s: \n", headdup, content);
11424                }
11425             }
11426          }
11427       }
11428 
11429       ast_channel_unlock(chan);
11430    }
11431    if (sdp) {
11432       memset(p->offered_media, 0, sizeof(p->offered_media));
11433       if (p->udptl && p->t38.state == T38_LOCAL_REINVITE) {
11434          ast_debug(1, "T38 is in state %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
11435          add_sdp(&req, p, FALSE, FALSE, TRUE);
11436       } else if (p->rtp) 
11437          add_sdp(&req, p, FALSE, TRUE, FALSE);
11438    }
11439 
11440    if (!p->initreq.headers || init > 2)
11441       initialize_initreq(p, &req);
11442    p->lastinvite = p->ocseq;
11443    return send_request(p, &req, init ? XMIT_CRITICAL : XMIT_RELIABLE, p->ocseq);
11444 }
11445 
11446 /*! \brief Send a subscription or resubscription for MWI */
11447 static int sip_subscribe_mwi_do(const void *data)
11448 {
11449    struct sip_subscription_mwi *mwi = (struct sip_subscription_mwi*)data;
11450    
11451    if (!mwi) {
11452       return -1;
11453    }
11454    
11455    mwi->resub = -1;
11456    __sip_subscribe_mwi_do(mwi);
11457    ASTOBJ_UNREF(mwi, sip_subscribe_mwi_destroy);
11458    
11459    return 0;
11460 }
11461 
11462 /*! \brief Actually setup an MWI subscription or resubscribe */
11463 static int __sip_subscribe_mwi_do(struct sip_subscription_mwi *mwi)
11464 {
11465    /* If we have no DNS manager let's do a lookup */
11466    if (!mwi->dnsmgr) {
11467       char transport[MAXHOSTNAMELEN];
11468       snprintf(transport, sizeof(transport), "_%s._%s", get_srv_service(mwi->transport), get_srv_protocol(mwi->transport));
11469       ast_dnsmgr_lookup(mwi->hostname, &mwi->us, &mwi->dnsmgr, sip_cfg.srvlookup ? transport : NULL);
11470    }
11471 
11472    /* If we already have a subscription up simply send a resubscription */
11473    if (mwi->call) {
11474       transmit_invite(mwi->call, SIP_SUBSCRIBE, 0, 0);
11475       return 0;
11476    }
11477    
11478    /* Create a dialog that we will use for the subscription */
11479    if (!(mwi->call = sip_alloc(NULL, NULL, 0, SIP_SUBSCRIBE, NULL))) {
11480       return -1;
11481    }
11482 
11483    ref_proxy(mwi->call, obproxy_get(mwi->call, NULL));
11484 
11485    if (!mwi->us.sin_port && mwi->portno) {
11486       mwi->us.sin_port = htons(mwi->portno);
11487    }
11488    
11489    /* Setup the destination of our subscription */
11490    if (create_addr(mwi->call, mwi->hostname, &mwi->us, 0)) {
11491       dialog_unlink_all(mwi->call, TRUE, TRUE);
11492       mwi->call = dialog_unref(mwi->call, "unref dialog after unlink_all");
11493       return 0;
11494    }
11495    
11496    if (!mwi->dnsmgr && mwi->portno) {
11497       mwi->call->sa.sin_port = htons(mwi->portno);
11498       mwi->call->recv.sin_port = htons(mwi->portno);
11499    } else {
11500       mwi->portno = ntohs(mwi->call->sa.sin_port);
11501    }
11502    
11503    /* Set various other information */
11504    if (!ast_strlen_zero(mwi->authuser)) {
11505       ast_string_field_set(mwi->call, peername, mwi->authuser);
11506       ast_string_field_set(mwi->call, authname, mwi->authuser);
11507       ast_string_field_set(mwi->call, fromuser, mwi->authuser);
11508    } else {
11509       ast_string_field_set(mwi->call, peername, mwi->username);
11510       ast_string_field_set(mwi->call, authname, mwi->username);
11511       ast_string_field_set(mwi->call, fromuser, mwi->username);
11512    }
11513    ast_string_field_set(mwi->call, username, mwi->username);
11514    if (!ast_strlen_zero(mwi->secret)) {
11515       ast_string_field_set(mwi->call, peersecret, mwi->secret);
11516    }
11517    set_socket_transport(&mwi->call->socket, mwi->transport);
11518    mwi->call->socket.port = htons(mwi->portno);
11519    ast_sip_ouraddrfor(&mwi->call->sa.sin_addr, &mwi->call->ourip, mwi->call);
11520    build_contact(mwi->call);
11521    build_via(mwi->call);
11522    build_callid_pvt(mwi->call);
11523    ast_set_flag(&mwi->call->flags[0], SIP_OUTGOING);
11524    
11525    /* Associate the call with us */
11526    mwi->call->mwi = ASTOBJ_REF(mwi);
11527    
11528    /* Actually send the packet */
11529    transmit_invite(mwi->call, SIP_SUBSCRIBE, 0, 2);
11530 
11531    return 0;
11532 }
11533 
11534 static int find_calling_channel(struct ast_channel *c, void *data) {
11535    struct sip_pvt *p = data;
11536 
11537    return (c->pbx &&
11538          (!strcasecmp(c->macroexten, p->exten) || !strcasecmp(c->exten, p->exten)) &&
11539          (sip_cfg.notifycid == IGNORE_CONTEXT || !strcasecmp(c->context, p->context)));
11540 }
11541 
11542 /*! \brief Used in the SUBSCRIBE notification subsystem (RFC3265) */
11543 static int transmit_state_notify(struct sip_pvt *p, int state, int full, int timeout)
11544 {
11545    struct ast_str *tmp = ast_str_alloca(4000);
11546    char from[256], to[256];
11547    char *c, *mfrom, *mto;
11548    struct sip_request req;
11549    char hint[AST_MAX_EXTENSION];
11550    char *statestring = "terminated";
11551    const struct cfsubscription_types *subscriptiontype;
11552    enum state { NOTIFY_OPEN, NOTIFY_INUSE, NOTIFY_CLOSED } local_state = NOTIFY_OPEN;
11553    char *pidfstate = "--";
11554    char *pidfnote= "Ready";
11555    
11556    memset(from, 0, sizeof(from));
11557    memset(to, 0, sizeof(to));
11558 
11559    switch (state) {
11560    case (AST_EXTENSION_RINGING | AST_EXTENSION_INUSE):
11561       statestring = (sip_cfg.notifyringing) ? "early" : "confirmed";
11562       local_state = NOTIFY_INUSE;
11563       pidfstate = "busy";
11564       pidfnote = "Ringing";
11565       break;
11566    case AST_EXTENSION_RINGING:
11567       statestring = "early";
11568       local_state = NOTIFY_INUSE;
11569       pidfstate = "busy";
11570       pidfnote = "Ringing";
11571       break;
11572    case AST_EXTENSION_INUSE:
11573       statestring = "confirmed";
11574       local_state = NOTIFY_INUSE;
11575       pidfstate = "busy";
11576       pidfnote = "On the phone";
11577       break;
11578    case AST_EXTENSION_BUSY:
11579       statestring = "confirmed";
11580       local_state = NOTIFY_CLOSED;
11581       pidfstate = "busy";
11582       pidfnote = "On the phone";
11583       break;
11584    case AST_EXTENSION_UNAVAILABLE:
11585       statestring = "terminated";
11586       local_state = NOTIFY_CLOSED;
11587       pidfstate = "away";
11588       pidfnote = "Unavailable";
11589       break;
11590    case AST_EXTENSION_ONHOLD:
11591       statestring = "confirmed";
11592       local_state = NOTIFY_CLOSED;
11593       pidfstate = "busy";
11594       pidfnote = "On hold";
11595       break;
11596    case AST_EXTENSION_NOT_INUSE:
11597    default:
11598       /* Default setting */
11599       break;
11600    }
11601 
11602    subscriptiontype = find_subscription_type(p->subscribed);
11603    
11604    /* Check which device/devices we are watching  and if they are registered */
11605    if (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, p->context, p->exten)) {
11606       char *hint2 = hint, *individual_hint = NULL;
11607       int hint_count = 0, unavailable_count = 0;
11608 
11609       while ((individual_hint = strsep(&hint2, "&"))) {
11610          hint_count++;
11611 
11612          if (ast_device_state(individual_hint) == AST_DEVICE_UNAVAILABLE)
11613             unavailable_count++;
11614       }
11615 
11616       /* If none of the hinted devices are registered, we will
11617        * override notification and show no availability.
11618        */
11619       if (hint_count > 0 && hint_count == unavailable_count) {
11620          local_state = NOTIFY_CLOSED;
11621          pidfstate = "away";
11622          pidfnote = "Not online";
11623       }
11624    }
11625 
11626    ast_copy_string(from, get_header(&p->initreq, "From"), sizeof(from));
11627    c = get_in_brackets(from);
11628    if (strncasecmp(c, "sip:", 4) && strncasecmp(c, "sips:", 5)) {
11629       ast_log(LOG_WARNING, "Huh?  Not a SIP header (%s)?\n", c);
11630       return -1;
11631    }
11632    
11633    mfrom = remove_uri_parameters(c);
11634 
11635    ast_copy_string(to, get_header(&p->initreq, "To"), sizeof(to));
11636    c = get_in_brackets(to);
11637    if (strncasecmp(c, "sip:", 4) && strncasecmp(c, "sips:", 5)) {
11638       ast_log(LOG_WARNING, "Huh?  Not a SIP header (%s)?\n", c);
11639       return -1;
11640    }
11641    mto = remove_uri_parameters(c);
11642 
11643    reqprep(&req, p, SIP_NOTIFY, 0, 1);
11644 
11645    
11646    add_header(&req, "Event", subscriptiontype->event);
11647    add_header(&req, "Content-Type", subscriptiontype->mediatype);
11648    switch(state) {
11649    case AST_EXTENSION_DEACTIVATED:
11650       if (timeout)
11651          add_header(&req, "Subscription-State", "terminated;reason=timeout");
11652       else {
11653          add_header(&req, "Subscription-State", "terminated;reason=probation");
11654          add_header(&req, "Retry-After", "60");
11655       }
11656       break;
11657    case AST_EXTENSION_REMOVED:
11658       add_header(&req, "Subscription-State", "terminated;reason=noresource");
11659       break;
11660    default:
11661       if (p->expiry)
11662          add_header(&req, "Subscription-State", "active");
11663       else  /* Expired */
11664          add_header(&req, "Subscription-State", "terminated;reason=timeout");
11665    }
11666    switch (p->subscribed) {
11667    case XPIDF_XML:
11668    case CPIM_PIDF_XML:
11669       ast_str_append(&tmp, 0,
11670          "<?xml version=\"1.0\"?>\n"
11671          "<!DOCTYPE presence PUBLIC \"-//IETF//DTD RFCxxxx XPIDF 1.0//EN\" \"xpidf.dtd\">\n"
11672          "<presence>\n");
11673       ast_str_append(&tmp, 0, "<presentity uri=\"%s;method=SUBSCRIBE\" />\n", mfrom);
11674       ast_str_append(&tmp, 0, "<atom id=\"%s\">\n", p->exten);
11675       ast_str_append(&tmp, 0, "<address uri=\"%s;user=ip\" priority=\"0.800000\">\n", mto);
11676       ast_str_append(&tmp, 0, "<status status=\"%s\" />\n", (local_state ==  NOTIFY_OPEN) ? "open" : (local_state == NOTIFY_INUSE) ? "inuse" : "closed");
11677       ast_str_append(&tmp, 0, "<msnsubstatus substatus=\"%s\" />\n", (local_state == NOTIFY_OPEN) ? "online" : (local_state == NOTIFY_INUSE) ? "onthephone" : "offline");
11678       ast_str_append(&tmp, 0, "</address>\n</atom>\n</presence>\n");
11679       break;
11680    case PIDF_XML: /* Eyebeam supports this format */
11681       ast_str_append(&tmp, 0,
11682          "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n"
11683          "<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);
11684       ast_str_append(&tmp, 0, "<pp:person><status>\n");
11685       if (pidfstate[0] != '-')
11686          ast_str_append(&tmp, 0, "<ep:activities><ep:%s/></ep:activities>\n", pidfstate);
11687       ast_str_append(&tmp, 0, "</status></pp:person>\n");
11688       ast_str_append(&tmp, 0, "<note>%s</note>\n", pidfnote); /* Note */
11689       ast_str_append(&tmp, 0, "<tuple id=\"%s\">\n", p->exten); /* Tuple start */
11690       ast_str_append(&tmp, 0, "<contact priority=\"1\">%s</contact>\n", mto);
11691       if (pidfstate[0] == 'b') /* Busy? Still open ... */
11692          ast_str_append(&tmp, 0, "<status><basic>open</basic></status>\n");
11693       else
11694          ast_str_append(&tmp, 0, "<status><basic>%s</basic></status>\n", (local_state != NOTIFY_CLOSED) ? "open" : "closed");
11695       ast_str_append(&tmp, 0, "</tuple>\n</presence>\n");
11696       break;
11697    case DIALOG_INFO_XML: /* SNOM subscribes in this format */
11698       ast_str_append(&tmp, 0, "<?xml version=\"1.0\"?>\n");
11699       ast_str_append(&tmp, 0, "<dialog-info xmlns=\"urn:ietf:params:xml:ns:dialog-info\" version=\"%d\" state=\"%s\" entity=\"%s\">\n", p->dialogver++, full ? "full" : "partial", mto);
11700       if ((state & AST_EXTENSION_RINGING) && sip_cfg.notifyringing) {
11701          const char *local_display = p->exten;
11702          char *local_target = mto;
11703 
11704          /* There are some limitations to how this works.  The primary one is that the
11705             callee must be dialing the same extension that is being monitored.  Simply dialing
11706             the hint'd device is not sufficient. */
11707          if (sip_cfg.notifycid) {
11708             struct ast_channel *caller = ast_channel_search_locked(find_calling_channel, p);
11709 
11710             if (caller) {
11711                int need = strlen(caller->cid.cid_num) + strlen(p->fromdomain) + sizeof("sip:@");
11712                local_target = alloca(need);
11713                snprintf(local_target, need, "sip:%s@%s", caller->cid.cid_num, p->fromdomain);
11714                if (!(ast_strlen_zero(caller->cid.cid_name))) {
11715                   local_display = ast_strdupa(caller->cid.cid_name);
11716                }
11717                ast_channel_unlock(caller);
11718                caller = NULL;
11719             }
11720             /* We create a fake call-id which the phone will send back in an INVITE
11721              * Replaces header which we can grab and do some magic with. */
11722             if (sip_cfg.pedanticsipchecking) {
11723                ast_str_append(&tmp, 0, "<dialog id=\"%s\" call-id=\"pickup-%s\" local-tag=\"%s\" remote-tag=\"%s\" direction=\"recipient\">\n",
11724                   p->exten, p->callid, p->theirtag, p->tag);
11725             } else {
11726                ast_str_append(&tmp, 0, "<dialog id=\"%s\" call-id=\"pickup-%s\" direction=\"recipient\">\n",
11727                   p->exten, p->callid);
11728             }
11729             ast_str_append(&tmp, 0, 
11730                   "<remote>\n"
11731                   /* See the limitations of this above.  Luckily the phone seems to still be
11732                      happy when these values are not correct. */
11733                   "<identity display=\"%s\">%s</identity>\n"
11734                   "<target uri=\"%s\"/>\n"
11735                   "</remote>\n"
11736                   "<local>\n"
11737                   "<identity>%s</identity>\n"
11738                   "<target uri=\"%s\"/>\n"
11739                   "</local>\n",
11740                   local_display, local_target, local_target, mto, mto);
11741          } else {
11742             ast_str_append(&tmp, 0, "<dialog id=\"%s\" direction=\"recipient\">\n", p->exten);
11743          }
11744       } else {
11745          ast_str_append(&tmp, 0, "<dialog id=\"%s\">\n", p->exten);
11746       }
11747       ast_str_append(&tmp, 0, "<state>%s</state>\n", statestring);
11748       if (state == AST_EXTENSION_ONHOLD) {
11749          ast_str_append(&tmp, 0, "<local>\n<target uri=\"%s\">\n"
11750                                          "<param pname=\"+sip.rendering\" pvalue=\"no\"/>\n"
11751                                          "</target>\n</local>\n", mto);
11752       }
11753       ast_str_append(&tmp, 0, "</dialog>\n</dialog-info>\n");
11754       break;
11755    case NONE:
11756    default:
11757       break;
11758    }
11759 
11760    add_content(&req, tmp->str);
11761 
11762    p->pendinginvite = p->ocseq;  /* Remember that we have a pending NOTIFY in order not to confuse the NOTIFY subsystem */
11763 
11764    return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
11765 }
11766 
11767 /*! \brief Notify user of messages waiting in voicemail (RFC3842)
11768 \note - Notification only works for registered peers with mailbox= definitions
11769    in sip.conf
11770    - We use the SIP Event package message-summary
11771     MIME type defaults to  "application/simple-message-summary";
11772  */
11773 static int transmit_notify_with_mwi(struct sip_pvt *p, int newmsgs, int oldmsgs, const char *vmexten)
11774 {
11775    struct sip_request req;
11776    struct ast_str *out = ast_str_alloca(500);
11777    int ourport = ntohs(p->ourip.sin_port);
11778    const char *exten = S_OR(vmexten, default_vmexten);
11779 
11780    initreqprep(&req, p, SIP_NOTIFY);
11781    add_header(&req, "Event", "message-summary");
11782    add_header(&req, "Content-Type", default_notifymime);
11783    ast_str_append(&out, 0, "Messages-Waiting: %s\r\n", newmsgs ? "yes" : "no");
11784 
11785    if (!ast_strlen_zero(p->fromdomain)) {
11786       ast_str_append(&out, 0, "Message-Account: sip:%s@%s\r\n", exten, p->fromdomain);
11787    } else if (!sip_standard_port(p->socket.type, ourport)) {
11788       if (p->socket.type == SIP_TRANSPORT_UDP) {
11789          ast_str_append(&out, 0, "Message-Account: sip:%s@%s:%d\r\n", exten, ast_inet_ntoa(p->ourip.sin_addr), ourport);
11790       } else {
11791          ast_str_append(&out, 0, "Message-Account: sip:%s@%s:%d;transport=%s\r\n", exten, ast_inet_ntoa(p->ourip.sin_addr), ourport, get_transport(p->socket.type));
11792       }
11793    } else {
11794       if (p->socket.type == SIP_TRANSPORT_UDP) {
11795          ast_str_append(&out, 0, "Message-Account: sip:%s@%s\r\n", exten, ast_inet_ntoa(p->ourip.sin_addr));
11796       } else {
11797          ast_str_append(&out, 0, "Message-Account: sip:%s@%s;transport=%s\r\n", exten, ast_inet_ntoa(p->ourip.sin_addr), get_transport(p->socket.type));
11798       }
11799    }
11800    /* Cisco has a bug in the SIP stack where it can't accept the
11801       (0/0) notification. This can temporarily be disabled in
11802       sip.conf with the "buggymwi" option */
11803    ast_str_append(&out, 0, "Voice-Message: %d/%d%s\r\n",
11804       newmsgs, oldmsgs, (ast_test_flag(&p->flags[1], SIP_PAGE2_BUGGY_MWI) ? "" : " (0/0)"));
11805 
11806    if (p->subscribed) {
11807       if (p->expiry)
11808          add_header(&req, "Subscription-State", "active");
11809       else  /* Expired */
11810          add_header(&req, "Subscription-State", "terminated;reason=timeout");
11811    }
11812 
11813    add_content(&req, out->str);
11814 
11815    if (!p->initreq.headers) 
11816       initialize_initreq(p, &req);
11817    return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
11818 }
11819 
11820 /*! \brief Notify a transferring party of the status of transfer (RFC3515) */
11821 static int transmit_notify_with_sipfrag(struct sip_pvt *p, int cseq, char *message, int terminate)
11822 {
11823    struct sip_request req;
11824    char tmp[SIPBUFSIZE/2];
11825    
11826    reqprep(&req, p, SIP_NOTIFY, 0, 1);
11827    snprintf(tmp, sizeof(tmp), "refer;id=%d", cseq);
11828    add_header(&req, "Event", tmp);
11829    add_header(&req, "Subscription-state", terminate ? "terminated;reason=noresource" : "active");
11830    add_header(&req, "Content-Type", "message/sipfrag;version=2.0");
11831    add_header(&req, "Allow", ALLOWED_METHODS);
11832    add_supported_header(p, &req);
11833 
11834    snprintf(tmp, sizeof(tmp), "SIP/2.0 %s\r\n", message);
11835    add_content(&req, tmp);
11836 
11837    if (!p->initreq.headers)
11838       initialize_initreq(p, &req);
11839 
11840    return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
11841 }
11842 
11843 /*! \brief Notify device with custom headers from sip_notify.conf */
11844 static int transmit_notify_custom(struct sip_pvt *p, struct ast_variable *vars) {
11845    struct sip_request req;
11846    struct ast_variable *var, *newvar;
11847 
11848    initreqprep(&req, p, SIP_NOTIFY);
11849 
11850    /* Copy notify vars and add headers */
11851    p->notify_headers = newvar = ast_variable_new("Subscription-State", "terminated", "");
11852    add_header(&req, newvar->name, newvar->value);
11853    for (var = vars; var; var = var->next) {
11854       char buf[512];
11855 
11856       if (!strcasecmp(var->name, "Content-Length")) {
11857          ast_debug(2, "Ignoring pair %s=%s\n", var->name, var->value);
11858          continue; /* ignore content-length, it is calculated automatically */
11859       }
11860 
11861       ast_debug(2, "  Adding pair %s=%s\n", var->name, var->value);
11862       ast_copy_string(buf, var->value, sizeof(buf));
11863       add_header(&req, var->name, ast_unescape_semicolon(buf));
11864       newvar->next = ast_variable_new(var->name, var->value, "");
11865       newvar = newvar->next;
11866    }
11867 
11868    if (!p->initreq.headers) { /* Initialize first request before sending */
11869       initialize_initreq(p, &req);
11870    }
11871 
11872    return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
11873 }
11874 
11875 static int manager_sipnotify(struct mansession *s, const struct message *m)
11876 {
11877    const char *channame = astman_get_header(m, "Channel");
11878    struct ast_variable *vars = astman_get_variables(m);
11879    struct sip_pvt *p;
11880 
11881    if (ast_strlen_zero(channame)) {
11882       astman_send_error(s, m, "SIPNotify requires a channel name");
11883       return 0;
11884    }
11885 
11886    if (!strncasecmp(channame, "sip/", 4)) {
11887       channame += 4;
11888    }
11889 
11890    if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY, NULL))) {
11891       astman_send_error(s, m, "Unable to build sip pvt data for notify (memory/socket error)");
11892       return 0;
11893    }
11894 
11895    if (create_addr(p, channame, NULL, 0)) {
11896       /* Maybe they're not registered, etc. */
11897       dialog_unlink_all(p, TRUE, TRUE);
11898       dialog_unref(p, "unref dialog inside for loop" );
11899       /* sip_destroy(p); */
11900       astman_send_error(s, m, "Could not create address");
11901       return 0;
11902    }
11903 
11904    /* Notify is outgoing call */
11905    ast_set_flag(&p->flags[0], SIP_OUTGOING);
11906 
11907    /* Recalculate our side, and recalculate Call ID */
11908    ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
11909    build_via(p);
11910    ao2_t_unlink(dialogs, p, "About to change the callid -- remove the old name");
11911    build_callid_pvt(p);
11912    ao2_t_link(dialogs, p, "Linking in new name");
11913    dialog_ref(p, "bump the count of p, which transmit_sip_request will decrement.");
11914    sip_scheddestroy(p, SIP_TRANS_TIMEOUT);
11915 
11916    if (!transmit_notify_custom(p, vars)) {
11917       astman_send_ack(s, m, "Notify Sent");
11918    } else {
11919       astman_send_error(s, m, "Unable to send notify");
11920    }
11921    ast_variables_destroy(vars);
11922    return 0;
11923 }
11924 
11925 static char mandescr_sipnotify[] =
11926 "Description: Sends a SIP Notify event\n"
11927 "All parameters for this event must be specified in the body of this request\n"
11928 "via multiple Variable: name=value sequences.\n"
11929 "Variables: \n"
11930 "  *Channel: <peername>       Peer to receive the notify. Required.\n"
11931 "  *Variable: <name>=<value>  At least one variable pair must be specified.\n"
11932 "  ActionID: <id>             Action ID for this transaction. Will be returned.\n";
11933 
11934 static const struct _map_x_s regstatestrings[] = {
11935    { REG_STATE_FAILED,     "Failed" },
11936    { REG_STATE_UNREGISTERED, "Unregistered"},
11937    { REG_STATE_REGSENT, "Request Sent"},
11938    { REG_STATE_AUTHSENT, "Auth. Sent"},
11939    { REG_STATE_REGISTERED, "Registered"},
11940    { REG_STATE_REJECTED, "Rejected"},
11941    { REG_STATE_TIMEOUT, "Timeout"},
11942    { REG_STATE_NOAUTH, "No Authentication"},
11943    { -1, NULL } /* terminator */
11944 };
11945 
11946 /*! \brief Convert registration state status to string */
11947 static const char *regstate2str(enum sipregistrystate regstate)
11948 {
11949    return map_x_s(regstatestrings, regstate, "Unknown");
11950 }
11951 
11952 /*! \brief Update registration with SIP Proxy.
11953  * Called from the scheduler when the previous registration expires,
11954  * so we don't have to cancel the pending event.
11955  * We assume the reference so the sip_registry is valid, since it
11956  * is stored in the scheduled event anyways.
11957  */
11958 static int sip_reregister(const void *data) 
11959 {
11960    /* if we are here, we know that we need to reregister. */
11961    struct sip_registry *r= (struct sip_registry *) data;
11962 
11963    /* if we couldn't get a reference to the registry object, punt */
11964    if (!r)
11965       return 0;
11966 
11967    if (r->call && r->call->do_history)
11968       append_history(r->call, "RegistryRenew", "Account: %s@%s", r->username, r->hostname);
11969    /* Since registry's are only added/removed by the the monitor thread, this
11970       may be overkill to reference/dereference at all here */
11971    if (sipdebug)
11972       ast_log(LOG_NOTICE, "   -- Re-registration for  %s@%s\n", r->username, r->hostname);
11973 
11974    r->expire = -1;
11975    r->expiry = r->configured_expiry;
11976    __sip_do_register(r);
11977    registry_unref(r, "unref the re-register scheduled event");
11978    return 0;
11979 }
11980 
11981 /*! \brief Register with SIP proxy */
11982 static int __sip_do_register(struct sip_registry *r)
11983 {
11984    int res;
11985 
11986    res = transmit_register(r, SIP_REGISTER, NULL, NULL);
11987    return res;
11988 }
11989 
11990 /*! \brief Registration timeout, register again
11991  * Registered as a timeout handler during transmit_register(),
11992  * to retransmit the packet if a reply does not come back.
11993  * This is called by the scheduler so the event is not pending anymore when
11994  * we are called.
11995  */
11996 static int sip_reg_timeout(const void *data)
11997 {
11998 
11999    /* if we are here, our registration timed out, so we'll just do it over */
12000    struct sip_registry *r = (struct sip_registry *)data; /* the ref count should have been bumped when the sched item was added */
12001    struct sip_pvt *p;
12002    int res;
12003 
12004    /* if we couldn't get a reference to the registry object, punt */
12005    if (!r)
12006       return 0;
12007 
12008    if (r->dnsmgr) {
12009       /* If the registration has timed out, maybe the IP changed.  Force a refresh. */
12010       ast_dnsmgr_refresh(r->dnsmgr);
12011    }
12012 
12013    ast_log(LOG_NOTICE, "   -- Registration for '%s@%s' timed out, trying again (Attempt #%d)\n", r->username, r->hostname, r->regattempts); 
12014    /* If the initial tranmission failed, we may not have an existing dialog,
12015     * so it is possible that r->call == NULL.
12016     * Otherwise destroy it, as we have a timeout so we don't want it.
12017     */
12018    if (r->call) {
12019       /* Unlink us, destroy old call.  Locking is not relevant here because all this happens
12020          in the single SIP manager thread. */
12021       p = r->call;
12022       sip_pvt_lock(p);
12023       pvt_set_needdestroy(p, "registration timeout");
12024       /* Pretend to ACK anything just in case */
12025       __sip_pretend_ack(p);
12026       sip_pvt_unlock(p);
12027 
12028       /* decouple the two objects */
12029       /* p->registry == r, so r has 2 refs, and the unref won't take the object away */
12030       if (p->registry)
12031          p->registry = registry_unref(p->registry, "p->registry unreffed");
12032       r->call = dialog_unref(r->call, "unrefing r->call");
12033    }
12034    /* If we have a limit, stop registration and give up */
12035    r->timeout = -1;
12036    if (global_regattempts_max && r->regattempts > global_regattempts_max) {
12037       /* Ok, enough is enough. Don't try any more */
12038       /* We could add an external notification here... 
12039          steal it from app_voicemail :-) */
12040       ast_log(LOG_NOTICE, "   -- Giving up forever trying to register '%s@%s'\n", r->username, r->hostname);
12041       r->regstate = REG_STATE_FAILED;
12042    } else {
12043       r->regstate = REG_STATE_UNREGISTERED;
12044       res=transmit_register(r, SIP_REGISTER, NULL, NULL);
12045    }
12046    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));
12047    registry_unref(r, "unreffing registry_unref r");
12048    return 0;
12049 }
12050 
12051 /*! \brief Transmit register to SIP proxy or UA
12052  * auth = NULL on the initial registration (from sip_reregister())
12053  */
12054 static int transmit_register(struct sip_registry *r, int sipmethod, const char *auth, const char *authheader)
12055 {
12056    struct sip_request req;
12057    char from[256];
12058    char to[256];
12059    char tmp[80];
12060    char addr[80];
12061    struct sip_pvt *p;
12062    struct sip_peer *peer = NULL;
12063    int res;
12064    char *fromdomain;
12065    char *domainport = NULL;
12066 
12067    /* exit if we are already in process with this registrar ?*/
12068    if (r == NULL || ((auth == NULL) && (r->regstate == REG_STATE_REGSENT || r->regstate == REG_STATE_AUTHSENT))) {
12069       if (r) {
12070          ast_log(LOG_NOTICE, "Strange, trying to register %s@%s when registration already pending\n", r->username, r->hostname);
12071       }
12072       return 0;
12073    }
12074 
12075    if (r->dnsmgr == NULL) {
12076       char transport[MAXHOSTNAMELEN];
12077       peer = find_peer(r->hostname, NULL, TRUE, FINDPEERS, FALSE, 0);
12078       snprintf(transport, sizeof(transport), "_%s._%s",get_srv_service(r->transport), get_srv_protocol(r->transport)); /* have to use static get_transport function */
12079       ast_dnsmgr_lookup(peer ? peer->tohost : r->hostname, &r->us, &r->dnsmgr, sip_cfg.srvlookup ? transport : NULL);
12080       if (peer) {
12081          peer = unref_peer(peer, "removing peer ref for dnsmgr_lookup");
12082       }
12083    }
12084 
12085    if (r->call) { /* We have a registration */
12086       if (!auth) {
12087          ast_log(LOG_WARNING, "Already have a REGISTER going on to %s@%s?? \n", r->username, r->hostname);
12088          return 0;
12089       } else {
12090          p = dialog_ref(r->call, "getting a copy of the r->call dialog in transmit_register");
12091          make_our_tag(p->tag, sizeof(p->tag));  /* create a new local tag for every register attempt */
12092          ast_string_field_set(p, theirtag, NULL);  /* forget their old tag, so we don't match tags when getting response */
12093       }
12094    } else {
12095       /* Build callid for registration if we haven't registered before */
12096       if (!r->callid_valid) {
12097          build_callid_registry(r, internip.sin_addr, default_fromdomain);
12098          r->callid_valid = TRUE;
12099       }
12100       /* Allocate SIP dialog for registration */
12101       if (!(p = sip_alloc( r->callid, NULL, 0, SIP_REGISTER, NULL))) {
12102          ast_log(LOG_WARNING, "Unable to allocate registration transaction (memory or socket error)\n");
12103          return 0;
12104       }
12105       
12106       if (p->do_history)
12107          append_history(p, "RegistryInit", "Account: %s@%s", r->username, r->hostname);
12108 
12109       /* Use port number specified if no SRV record was found */
12110       if (!r->us.sin_port && r->portno)
12111          r->us.sin_port = htons(r->portno);
12112 
12113       /* Find address to hostname */
12114       if (create_addr(p, S_OR(r->peername, r->hostname), &r->us, 0)) {
12115          /* we have what we hope is a temporary network error,
12116           * probably DNS.  We need to reschedule a registration try */
12117          dialog_unlink_all(p, TRUE, TRUE);
12118          p = dialog_unref(p, "unref dialog after unlink_all");
12119          if (r->timeout > -1) {
12120             AST_SCHED_REPLACE_UNREF(r->timeout, sched, global_reg_timeout * 1000, sip_reg_timeout, r,
12121                               registry_unref(_data, "del for REPLACE of registry ptr"), 
12122                               registry_unref(r, "object ptr dec when SCHED_REPLACE add failed"),
12123                               registry_addref(r,"add for REPLACE registry ptr"));
12124             ast_log(LOG_WARNING, "Still have a registration timeout for %s@%s (create_addr() error), %d\n", r->username, r->hostname, r->timeout);
12125          } else {
12126             r->timeout = ast_sched_add(sched, global_reg_timeout * 1000, sip_reg_timeout, registry_addref(r, "add for REPLACE registry ptr"));
12127             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);
12128          }
12129          r->regattempts++;
12130          return 0;
12131       }
12132 
12133       /* Copy back Call-ID in case create_addr changed it */
12134       ast_string_field_set(r, callid, p->callid);
12135       if (!r->dnsmgr && r->portno) {
12136          p->sa.sin_port = htons(r->portno);
12137          p->recv.sin_port = htons(r->portno);
12138       } else { /* Set registry port to the port set from the peer definition/srv or default */
12139          r->portno = ntohs(p->sa.sin_port);
12140       }
12141       ast_set_flag(&p->flags[0], SIP_OUTGOING); /* Registration is outgoing call */
12142       r->call = dialog_ref(p, "copying dialog into registry r->call");     /* Save pointer to SIP dialog */
12143       p->registry = registry_addref(r, "transmit_register: addref to p->registry in transmit_register"); /* Add pointer to registry in packet */
12144       if (!ast_strlen_zero(r->secret)) {  /* Secret (password) */
12145          ast_string_field_set(p, peersecret, r->secret);
12146       }
12147       if (!ast_strlen_zero(r->md5secret))
12148          ast_string_field_set(p, peermd5secret, r->md5secret);
12149       /* User name in this realm  
12150       - if authuser is set, use that, otherwise use username */
12151       if (!ast_strlen_zero(r->authuser)) {   
12152          ast_string_field_set(p, peername, r->authuser);
12153          ast_string_field_set(p, authname, r->authuser);
12154       } else if (!ast_strlen_zero(r->username)) {
12155          ast_string_field_set(p, peername, r->username);
12156          ast_string_field_set(p, authname, r->username);
12157          ast_string_field_set(p, fromuser, r->username);
12158       }
12159       if (!ast_strlen_zero(r->username))
12160          ast_string_field_set(p, username, r->username);
12161       /* Save extension in packet */
12162       if (!ast_strlen_zero(r->callback))
12163          ast_string_field_set(p, exten, r->callback);
12164 
12165       /* Set transport and port so the correct contact is built */
12166       set_socket_transport(&p->socket, r->transport);
12167       if (r->transport == SIP_TRANSPORT_TLS || r->transport == SIP_TRANSPORT_TCP) {
12168          p->socket.port = sip_tcp_desc.local_address.sin_port;
12169       }
12170 
12171       /*
12172         check which address we should use in our contact header 
12173         based on whether the remote host is on the external or
12174         internal network so we can register through nat
12175        */
12176       ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
12177       build_contact(p);
12178    }
12179 
12180    /* set up a timeout */
12181    if (auth == NULL)  {
12182       if (r->timeout > -1)
12183          ast_log(LOG_WARNING, "Still have a registration timeout, #%d - deleting it\n", r->timeout);
12184       AST_SCHED_REPLACE_UNREF(r->timeout, sched, global_reg_timeout * 1000, sip_reg_timeout, r,
12185                         registry_unref(_data,"reg ptr unrefed from del in SCHED_REPLACE"),
12186                         registry_unref(r,"reg ptr unrefed from add failure in SCHED_REPLACE"),
12187                         registry_addref(r,"reg ptr reffed from add in SCHED_REPLACE"));
12188       ast_debug(1, "Scheduled a registration timeout for %s id  #%d \n", r->hostname, r->timeout);
12189    }
12190 
12191    if ((fromdomain = strchr(r->username, '@'))) {
12192       /* the domain name is just behind '@' */
12193       fromdomain++ ;
12194       /* We have a domain in the username for registration */
12195       snprintf(from, sizeof(from), "<sip:%s>;tag=%s", r->username, p->tag);
12196       if (!ast_strlen_zero(p->theirtag))
12197          snprintf(to, sizeof(to), "<sip:%s>;tag=%s", r->username, p->theirtag);
12198       else
12199          snprintf(to, sizeof(to), "<sip:%s>", r->username);
12200 
12201       /* If the registration username contains '@', then the domain should be used as
12202          the equivalent of "fromdomain" for the registration */
12203       if (ast_strlen_zero(p->fromdomain)) {
12204          ast_string_field_set(p, fromdomain, fromdomain);
12205       }
12206    } else {
12207       snprintf(from, sizeof(from), "<sip:%s@%s>;tag=%s", r->username, p->tohost, p->tag);
12208       if (!ast_strlen_zero(p->theirtag))
12209          snprintf(to, sizeof(to), "<sip:%s@%s>;tag=%s", r->username, p->tohost, p->theirtag);
12210       else
12211          snprintf(to, sizeof(to), "<sip:%s@%s>", r->username, p->tohost);
12212    }
12213    
12214    /* Fromdomain is what we are registering to, regardless of actual
12215       host name from SRV */
12216    if (!ast_strlen_zero(p->fromdomain)) {
12217       domainport = strrchr(p->fromdomain, ':');
12218       if (domainport) {
12219          *domainport++ = '\0'; /* trim off domainport from p->fromdomain */
12220          if (ast_strlen_zero(domainport))
12221             domainport = NULL;
12222       }     
12223       if (domainport) {       
12224          if (atoi(domainport) != STANDARD_SIP_PORT)
12225             snprintf(addr, sizeof(addr), "sip:%s:%s", p->fromdomain, domainport);
12226          else
12227             snprintf(addr, sizeof(addr), "sip:%s", p->fromdomain);
12228       } else {
12229          if (r->portno && r->portno != STANDARD_SIP_PORT)
12230             snprintf(addr, sizeof(addr), "sip:%s:%d", p->fromdomain, r->portno);
12231          else
12232             snprintf(addr, sizeof(addr), "sip:%s", p->fromdomain);
12233       }
12234    } else {
12235       if (r->portno && r->portno != STANDARD_SIP_PORT)
12236          snprintf(addr, sizeof(addr), "sip:%s:%d", r->hostname, r->portno);
12237       else
12238          snprintf(addr, sizeof(addr), "sip:%s", r->hostname);
12239    }
12240    ast_string_field_set(p, uri, addr);
12241 
12242    p->branch ^= ast_random();
12243 
12244    init_req(&req, sipmethod, addr);
12245 
12246    /* Add to CSEQ */
12247    snprintf(tmp, sizeof(tmp), "%u %s", ++r->ocseq, sip_methods[sipmethod].text);
12248    p->ocseq = r->ocseq;
12249 
12250    build_via(p);
12251    add_header(&req, "Via", p->via);
12252    add_header(&req, "Max-Forwards", DEFAULT_MAX_FORWARDS);
12253    add_header(&req, "From", from);
12254    add_header(&req, "To", to);
12255    add_header(&req, "Call-ID", p->callid);
12256    add_header(&req, "CSeq", tmp);
12257    if (!ast_strlen_zero(global_useragent))
12258       add_header(&req, "User-Agent", global_useragent);
12259 
12260    
12261    if (auth)   /* Add auth header */
12262       add_header(&req, authheader, auth);
12263    else if (!ast_strlen_zero(r->nonce)) {
12264       char digest[1024];
12265 
12266       /* We have auth data to reuse, build a digest header.
12267        * Note, this is not always useful because some parties do not
12268        * like nonces to be reused (for good reasons!) so they will
12269        * challenge us anyways.
12270        */
12271       if (sipdebug)
12272          ast_debug(1, "   >>> Re-using Auth data for %s@%s\n", r->username, r->hostname);
12273       ast_string_field_set(p, realm, r->realm);
12274       ast_string_field_set(p, nonce, r->nonce);
12275       ast_string_field_set(p, domain, r->domain);
12276       ast_string_field_set(p, opaque, r->opaque);
12277       ast_string_field_set(p, qop, r->qop);
12278       p->noncecount = ++r->noncecount;
12279 
12280       memset(digest, 0, sizeof(digest));
12281       if(!build_reply_digest(p, sipmethod, digest, sizeof(digest)))
12282          add_header(&req, "Authorization", digest);
12283       else
12284          ast_log(LOG_NOTICE, "No authorization available for authentication of registration to %s@%s\n", r->username, r->hostname);
12285    
12286    }
12287 
12288    snprintf(tmp, sizeof(tmp), "%d", r->expiry);
12289    add_header(&req, "Expires", tmp);
12290    add_header(&req, "Contact", p->our_contact);
12291 
12292    initialize_initreq(p, &req);
12293    if (sip_debug_test_pvt(p)) {
12294       ast_verbose("REGISTER %d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
12295    }
12296    r->regstate = auth ? REG_STATE_AUTHSENT : REG_STATE_REGSENT;
12297    r->regattempts++; /* Another attempt */
12298    ast_debug(4, "REGISTER attempt %d to %s@%s\n", r->regattempts, r->username, r->hostname);
12299    res = send_request(p, &req, XMIT_CRITICAL, p->ocseq);
12300    dialog_unref(p, "p is finished here at the end of transmit_register");
12301    return res;
12302 }
12303 
12304 /*! \brief Transmit text with SIP MESSAGE method */
12305 static int transmit_message_with_text(struct sip_pvt *p, const char *text)
12306 {
12307    struct sip_request req;
12308    
12309    reqprep(&req, p, SIP_MESSAGE, 0, 1);
12310    add_text(&req, text);
12311    return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
12312 }
12313 
12314 /*! \brief Allocate SIP refer structure */
12315 static int sip_refer_allocate(struct sip_pvt *p)
12316 {
12317    p->refer = ast_calloc(1, sizeof(struct sip_refer)); 
12318    return p->refer ? 1 : 0;
12319 }
12320 
12321 /*! \brief Transmit SIP REFER message (initiated by the transfer() dialplan application
12322    \note this is currently broken as we have no way of telling the dialplan
12323    engine whether a transfer succeeds or fails.
12324    \todo Fix the transfer() dialplan function so that a transfer may fail
12325 */
12326 static int transmit_refer(struct sip_pvt *p, const char *dest)
12327 {
12328    struct sip_request req = { 
12329       .headers = 0,  
12330    };
12331    char from[256];
12332    const char *of;
12333    char *c;
12334    char referto[256];
12335    char *ttag, *ftag;
12336    char *theirtag = ast_strdupa(p->theirtag);
12337    int   use_tls=FALSE;
12338 
12339    if (sipdebug)
12340       ast_debug(1, "SIP transfer of %s to %s\n", p->callid, dest);
12341 
12342    /* Are we transfering an inbound or outbound call ? */
12343    if (ast_test_flag(&p->flags[0], SIP_OUTGOING))  {
12344       of = get_header(&p->initreq, "To");
12345       ttag = theirtag;
12346       ftag = p->tag;
12347    } else {
12348       of = get_header(&p->initreq, "From");
12349       ftag = theirtag;
12350       ttag = p->tag;
12351    }
12352 
12353    ast_copy_string(from, of, sizeof(from));
12354    of = get_in_brackets(from);
12355    ast_string_field_set(p, from, of);
12356    if (!strncasecmp(of, "sip:", 4)) {
12357       of += 4;
12358    }else if (!strncasecmp(of, "sips:", 5)) {
12359       of += 5;
12360       use_tls = TRUE;
12361    } else {
12362       ast_log(LOG_NOTICE, "From address missing 'sip(s):', assuming sip:\n");
12363    }
12364    /* Get just the username part */
12365    if ((c = strchr(dest, '@')))
12366       c = NULL;
12367    else if ((c = strchr(of, '@')))
12368       *c++ = '\0';
12369    if (c) 
12370       snprintf(referto, sizeof(referto), "<sip%s:%s@%s>", use_tls ? "s" : "", dest, c);
12371    else
12372       snprintf(referto, sizeof(referto), "<sip%s:%s>", use_tls ? "s" : "", dest);
12373 
12374    /* save in case we get 407 challenge */
12375    sip_refer_allocate(p);
12376    ast_copy_string(p->refer->refer_to, referto, sizeof(p->refer->refer_to));
12377    ast_copy_string(p->refer->referred_by, p->our_contact, sizeof(p->refer->referred_by));
12378    p->refer->status = REFER_SENT;   /* Set refer status */
12379 
12380    reqprep(&req, p, SIP_REFER, 0, 1);
12381 
12382    add_header(&req, "Refer-To", referto);
12383    add_header(&req, "Allow", ALLOWED_METHODS);
12384    add_supported_header(p, &req);
12385    if (!ast_strlen_zero(p->our_contact))
12386       add_header(&req, "Referred-By", p->our_contact);
12387 
12388    return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
12389 
12390    /* We should propably wait for a NOTIFY here until we ack the transfer */
12391    /* Maybe fork a new thread and wait for a STATUS of REFER_200OK on the refer status before returning to app_transfer */
12392 
12393    /*! \todo In theory, we should hang around and wait for a reply, before
12394    returning to the dial plan here. Don't know really how that would
12395    affect the transfer() app or the pbx, but, well, to make this
12396    useful we should have a STATUS code on transfer().
12397    */
12398 }
12399 
12400 
12401 /*! \brief Send SIP INFO dtmf message, see Cisco documentation on cisco.com */
12402 static int transmit_info_with_digit(struct sip_pvt *p, const char digit, unsigned int duration)
12403 {
12404    struct sip_request req;
12405    
12406    reqprep(&req, p, SIP_INFO, 0, 1);
12407    add_digit(&req, digit, duration, (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_SHORTINFO));
12408    return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
12409 }
12410 
12411 /*! \brief Send SIP INFO with video update request */
12412 static int transmit_info_with_vidupdate(struct sip_pvt *p)
12413 {
12414    struct sip_request req;
12415    
12416    reqprep(&req, p, SIP_INFO, 0, 1);
12417    add_vidupdate(&req);
12418    return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
12419 }
12420 
12421 /*! \brief Transmit generic SIP request 
12422    returns XMIT_ERROR if transmit failed with a critical error (don't retry)
12423 */
12424 static int transmit_request(struct sip_pvt *p, int sipmethod, int seqno, enum xmittype reliable, int newbranch)
12425 {
12426    struct sip_request resp;
12427    
12428    if (sipmethod == SIP_ACK)
12429       p->invitestate = INV_CONFIRMED;
12430 
12431    reqprep(&resp, p, sipmethod, seqno, newbranch);
12432    if (sipmethod == SIP_CANCEL && p->answered_elsewhere) 
12433       add_header(&resp, "Reason", "SIP;cause=200;text=\"Call completed elsewhere\"");
12434 
12435    return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);
12436 }
12437 
12438 /*! \brief return the request and response heade for a 401 or 407 code */
12439 static void auth_headers(enum sip_auth_type code, char **header, char **respheader)
12440 {
12441    if (code == WWW_AUTH) {       /* 401 */
12442       *header = "WWW-Authenticate";
12443       *respheader = "Authorization";
12444    } else if (code == PROXY_AUTH) { /* 407 */
12445       *header = "Proxy-Authenticate";
12446       *respheader = "Proxy-Authorization";
12447    } else {
12448       ast_verbose("-- wrong response code %d\n", code);
12449       *header = *respheader = "Invalid";
12450    }
12451 }
12452 
12453 /*! \brief Transmit SIP request, auth added */
12454 static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, int seqno, enum xmittype reliable, int newbranch)
12455 {
12456    struct sip_request resp;
12457    
12458    reqprep(&resp, p, sipmethod, seqno, newbranch);
12459    if (!ast_strlen_zero(p->realm)) {
12460       char digest[1024];
12461 
12462       memset(digest, 0, sizeof(digest));
12463       if(!build_reply_digest(p, sipmethod, digest, sizeof(digest))) {
12464          char *dummy, *response;
12465          enum sip_auth_type code = p->options ? p->options->auth_type : PROXY_AUTH; /* XXX force 407 if unknown */
12466          auth_headers(code, &dummy, &response);
12467          add_header(&resp, response, digest);
12468       } else
12469          ast_log(LOG_WARNING, "No authentication available for call %s\n", p->callid);
12470    }
12471    /* If we are hanging up and know a cause for that, send it in clear text to make
12472       debugging easier. */
12473    if (sipmethod == SIP_BYE)  {
12474       char buf[10];
12475 
12476       add_header(&resp, "X-Asterisk-HangupCause", ast_cause2str(p->hangupcause));
12477       snprintf(buf, sizeof(buf), "%d", p->hangupcause);
12478       add_header(&resp, "X-Asterisk-HangupCauseCode", buf);
12479    }
12480 
12481    return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);   
12482 }
12483 
12484 /*! \brief Remove registration data from realtime database or AST/DB when registration expires */
12485 static void destroy_association(struct sip_peer *peer)
12486 {
12487    int realtimeregs = ast_check_realtime("sipregs");
12488    char *tablename = (realtimeregs) ? "sipregs" : "sippeers";
12489 
12490    if (!sip_cfg.ignore_regexpire) {
12491       if (peer->rt_fromcontact && sip_cfg.peer_rtupdate) {
12492          ast_update_realtime(tablename, "name", peer->name, "fullcontact", "", "ipaddr", "", "port", "", "regseconds", "0", "regserver", "", "useragent", "", "lastms", "", SENTINEL);
12493       } else {
12494          ast_db_del("SIP/Registry", peer->name);
12495       }
12496    }
12497 }
12498 
12499 static void set_socket_transport(struct sip_socket *socket, int transport)
12500 {
12501    /* if the transport type changes, clear all socket data */
12502    if (socket->type != transport) {
12503       socket->fd = -1;
12504       socket->type = transport;
12505       if (socket->tcptls_session) {
12506          ao2_ref(socket->tcptls_session, -1);
12507          socket->tcptls_session = NULL;
12508       }
12509    }
12510 }
12511 
12512 /*! \brief Expire registration of SIP peer */
12513 static int expire_register(const void *data)
12514 {
12515    struct sip_peer *peer = (struct sip_peer *)data;
12516 
12517    if (!peer)     /* Hmmm. We have no peer. Weird. */
12518       return 0;
12519 
12520    peer->expire = -1;
12521    peer->portinuri = 0;
12522 
12523    destroy_association(peer); /* remove registration data from storage */
12524    set_socket_transport(&peer->socket, peer->default_outbound_transport);
12525 
12526    if (peer->socket.tcptls_session) {
12527       ao2_ref(peer->socket.tcptls_session, -1);
12528       peer->socket.tcptls_session = NULL;
12529    }
12530 
12531    manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: Unregistered\r\nCause: Expired\r\n", peer->name);
12532    register_peer_exten(peer, FALSE);   /* Remove regexten */
12533    ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", peer->name);
12534 
12535    /* Do we need to release this peer from memory? 
12536       Only for realtime peers and autocreated peers
12537    */
12538    if (peer->is_realtime)
12539       ast_debug(3, "-REALTIME- peer expired registration. Name: %s. Realtime peer objects now %d\n", peer->name, rpeerobjs);
12540 
12541    if (peer->selfdestruct ||
12542        ast_test_flag(&peer->flags[1], SIP_PAGE2_RTAUTOCLEAR)) {
12543       unlink_peer_from_tables(peer);
12544    }
12545 
12546    /* Only clear the addr after we check for destruction.  The addr must remain
12547     * in order to unlink from the peers_by_ip container correctly */
12548    memset(&peer->addr, 0, sizeof(peer->addr));
12549 
12550    unref_peer(peer, "removing peer ref for expire_register");
12551 
12552    return 0;
12553 }
12554 
12555 /*! \brief Poke peer (send qualify to check if peer is alive and well) */
12556 static int sip_poke_peer_s(const void *data)
12557 {
12558    struct sip_peer *peer = (struct sip_peer *)data;
12559    struct sip_peer *foundpeer;
12560 
12561    peer->pokeexpire = -1;
12562 
12563    foundpeer = ao2_find(peers, peer, OBJ_POINTER);
12564    if (!foundpeer) {
12565       unref_peer(peer, "removing poke peer ref");
12566       return 0;
12567    } else if (foundpeer->name != peer->name) {
12568       unref_peer(foundpeer, "removing above peer ref");
12569       unref_peer(peer, "removing poke peer ref");
12570       return 0;
12571    }
12572 
12573    unref_peer(foundpeer, "removing above peer ref");
12574    sip_poke_peer(peer, 0);
12575    unref_peer(peer, "removing poke peer ref");
12576 
12577    return 0;
12578 }
12579 
12580 /*! \brief Get registration details from Asterisk DB */
12581 static void reg_source_db(struct sip_peer *peer)
12582 {
12583    char data[256];
12584    struct in_addr in;
12585    int expire;
12586    int port;
12587    char *scan, *addr, *port_str, *expiry_str, *username, *contact;
12588 
12589    if (peer->rt_fromcontact) 
12590       return;
12591    if (ast_db_get("SIP/Registry", peer->name, data, sizeof(data)))
12592       return;
12593 
12594    scan = data;
12595    addr = strsep(&scan, ":");
12596    port_str = strsep(&scan, ":");
12597    expiry_str = strsep(&scan, ":");
12598    username = strsep(&scan, ":");
12599    contact = scan;   /* Contact include sip: and has to be the last part of the database entry as long as we use : as a separator */
12600 
12601    if (!inet_aton(addr, &in))
12602       return;
12603 
12604    if (port_str)
12605       port = atoi(port_str);
12606    else
12607       return;
12608 
12609    if (expiry_str)
12610       expire = atoi(expiry_str);
12611    else
12612       return;
12613 
12614    if (username)
12615       ast_string_field_set(peer, username, username);
12616    if (contact)
12617       ast_string_field_set(peer, fullcontact, contact);
12618 
12619    ast_debug(2, "SIP Seeding peer from astdb: '%s' at %s@%s:%d for %d\n",
12620        peer->name, peer->username, ast_inet_ntoa(in), port, expire);
12621 
12622    memset(&peer->addr, 0, sizeof(peer->addr));
12623    peer->addr.sin_family = AF_INET;
12624    peer->addr.sin_addr = in;
12625    peer->addr.sin_port = htons(port);
12626    if (sipsock < 0) {
12627       /* SIP isn't up yet, so schedule a poke only, pretty soon */
12628       AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched, ast_random() % 5000 + 1, sip_poke_peer_s, peer,
12629             unref_peer(_data, "removing poke peer ref"),
12630             unref_peer(peer, "removing poke peer ref"),
12631             ref_peer(peer, "adding poke peer ref"));
12632    } else {
12633       sip_poke_peer(peer, 0);
12634    }
12635    AST_SCHED_REPLACE_UNREF(peer->expire, sched, (expire + 10) * 1000, expire_register, peer,
12636          unref_peer(_data, "remove registration ref"),
12637          unref_peer(peer, "remove registration ref"),
12638          ref_peer(peer, "add registration ref"));
12639    register_peer_exten(peer, TRUE);
12640 }
12641 
12642 /*! \brief Save contact header for 200 OK on INVITE */
12643 static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req)
12644 {
12645    char contact[SIPBUFSIZE]; 
12646    char *c;
12647 
12648    /* Look for brackets */
12649    ast_copy_string(contact, get_header(req, "Contact"), sizeof(contact));
12650    c = get_in_brackets(contact);
12651 
12652    /* Save full contact to call pvt for later bye or re-invite */
12653    ast_string_field_set(pvt, fullcontact, c);
12654 
12655    /* Save URI for later ACKs, BYE or RE-invites */
12656    ast_string_field_set(pvt, okcontacturi, c);
12657 
12658    /* We should return false for URI:s we can't handle,
12659       like tel:, mailto:,ldap: etc */
12660    return TRUE;      
12661 }
12662 
12663 static int __set_address_from_contact(const char *fullcontact, struct sockaddr_in *sin, int tcp)
12664 {
12665    struct hostent *hp;
12666    struct ast_hostent ahp;
12667    int port = STANDARD_SIP_PORT;
12668    char *host, *pt, *transport;
12669    char contact_buf[256];
12670    char *contact;
12671 
12672    /* Work on a copy */
12673    ast_copy_string(contact_buf, fullcontact, sizeof(contact_buf));
12674    contact = contact_buf;
12675 
12676    /* 
12677     * We have only the part in <brackets> here so we just need to parse a SIP URI.
12678     *
12679     * Note: The outbound proxy could be using UDP between the proxy and Asterisk.
12680     * We still need to be able to send to the remote agent through the proxy.
12681     */
12682 
12683    if (parse_uri(contact, "sip:,sips:", &contact, NULL, &host, &pt, NULL, &transport)) {
12684       ast_log(LOG_WARNING, "Invalid contact uri %s (missing sip: or sips:), attempting to use anyway\n", fullcontact);
12685    }
12686 
12687    /* set port */
12688    if (((get_transport_str2enum(transport) == SIP_TRANSPORT_TLS)) || !(strncasecmp(fullcontact, "sips", 4))) {
12689       port = port_str2int(pt, STANDARD_TLS_PORT);
12690    } else {
12691       port = port_str2int(pt, STANDARD_SIP_PORT);
12692    }
12693 
12694 
12695    /* XXX This could block for a long time XXX */
12696    /* We should only do this if it's a name, not an IP */
12697    /* \todo - if there's no PORT number in contact - we are required to check NAPTR/SRV records
12698       to find transport, port address and hostname. If there's a port number, we have to
12699       assume that the domain part is a host name and only look for an A/AAAA record in DNS.
12700    */
12701    hp = ast_gethostbyname(host, &ahp);
12702    if (!hp)  {
12703       ast_log(LOG_WARNING, "Invalid host name in Contact: (can't resolve in DNS) : '%s'\n", host);
12704       return -1;
12705    }
12706    sin->sin_family = AF_INET;
12707    memcpy(&sin->sin_addr, hp->h_addr, sizeof(sin->sin_addr));
12708    sin->sin_port = htons(port);
12709 
12710    return 0;
12711 }
12712 
12713 /*! \brief Change the other partys IP address based on given contact */
12714 static int set_address_from_contact(struct sip_pvt *pvt)
12715 {
12716    if (ast_test_flag(&pvt->flags[0], SIP_NAT_ROUTE)) {
12717       /* NAT: Don't trust the contact field.  Just use what they came to us
12718          with. */
12719       /*! \todo We need to save the TRANSPORT here too */
12720       pvt->sa = pvt->recv;
12721       return 0;
12722    }
12723 
12724    return __set_address_from_contact(pvt->fullcontact, &pvt->sa, pvt->socket.type == SIP_TRANSPORT_TLS ? 1 : 0);
12725 }
12726 
12727 /*! \brief Parse contact header and save registration (peer registration) */
12728 static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *peer, struct sip_request *req)
12729 {
12730    char contact[SIPBUFSIZE];
12731    char data[SIPBUFSIZE];
12732    const char *expires = get_header(req, "Expires");
12733    int expire = atoi(expires);
12734    char *curi, *host, *pt, *transport;
12735    int port;
12736    int transport_type;
12737    const char *useragent;
12738    struct hostent *hp;
12739    struct ast_hostent ahp;
12740    struct sockaddr_in oldsin, testsin;
12741    char *firstcuri = NULL;
12742    int start = 0;
12743    int wildcard_found = 0;
12744    int single_binding_found;
12745 
12746    ast_copy_string(contact, __get_header(req, "Contact", &start), sizeof(contact));
12747 
12748    if (ast_strlen_zero(expires)) {  /* No expires header, try look in Contact: */
12749       char *s = strcasestr(contact, ";expires=");
12750       if (s) {
12751          expires = strsep(&s, ";"); /* trim ; and beyond */
12752          if (sscanf(expires + 9, "%30d", &expire) != 1)
12753             expire = default_expiry;
12754       } else {
12755          /* Nothing has been specified */
12756          expire = default_expiry;
12757       }
12758    }
12759 
12760    copy_socket_data(&pvt->socket, &req->socket);
12761 
12762    do {
12763       /* Look for brackets */
12764       curi = contact;
12765       if (strchr(contact, '<') == NULL)   /* No <, check for ; and strip it */
12766          strsep(&curi, ";");  /* This is Header options, not URI options */
12767       curi = get_in_brackets(contact);
12768       if (!firstcuri) {
12769          firstcuri = ast_strdupa(curi);
12770       }
12771 
12772       if (!strcasecmp(curi, "*")) {
12773          wildcard_found = 1;
12774       } else {
12775          single_binding_found = 1;
12776       }
12777 
12778       if (wildcard_found && (ast_strlen_zero(expires) || expire != 0 || single_binding_found)) {
12779          /* Contact header parameter "*" detected, so punt if: Expires header is missing,
12780           * Expires value is not zero, or another Contact header is present. */
12781          return PARSE_REGISTER_FAILED;
12782       }
12783 
12784       ast_copy_string(contact, __get_header(req, "Contact", &start), sizeof(contact));
12785    } while (!ast_strlen_zero(contact));
12786    curi = firstcuri;
12787 
12788    /* if they did not specify Contact: or Expires:, they are querying
12789       what we currently have stored as their contact address, so return
12790       it
12791    */
12792    if (ast_strlen_zero(curi) && ast_strlen_zero(expires)) {
12793       /* If we have an active registration, tell them when the registration is going to expire */
12794       if (peer->expire > -1 && !ast_strlen_zero(peer->fullcontact))
12795          pvt->expiry = ast_sched_when(sched, peer->expire);
12796       return PARSE_REGISTER_QUERY;
12797    } else if (!strcasecmp(curi, "*") || !expire) { /* Unregister this peer */
12798       /* This means remove all registrations and return OK */
12799       memset(&peer->addr, 0, sizeof(peer->addr));
12800       set_socket_transport(&peer->socket, peer->default_outbound_transport);
12801 
12802       AST_SCHED_DEL_UNREF(sched, peer->expire,
12803             unref_peer(peer, "remove register expire ref"));
12804 
12805       destroy_association(peer);
12806 
12807       register_peer_exten(peer, FALSE);   /* Remove extension from regexten= setting in sip.conf */
12808       ast_string_field_set(peer, fullcontact, "");
12809       ast_string_field_set(peer, useragent, "");
12810       peer->sipoptions = 0;
12811       peer->lastms = 0;
12812       peer->portinuri = 0;
12813       pvt->expiry = 0;
12814 
12815       ast_verb(3, "Unregistered SIP '%s'\n", peer->name);
12816 
12817       manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: Unregistered\r\n", peer->name);
12818       return PARSE_REGISTER_UPDATE;
12819    }
12820 
12821    /* Store whatever we got as a contact from the client */
12822    ast_string_field_set(peer, fullcontact, curi);
12823 
12824    /* For the 200 OK, we should use the received contact */
12825    ast_string_field_build(pvt, our_contact, "<%s>", curi);
12826 
12827    /* Make sure it's a SIP URL */
12828    if (parse_uri(curi, "sip:,sips:", &curi, NULL, &host, &pt, NULL, &transport)) {
12829       ast_log(LOG_NOTICE, "Not a valid SIP contact (missing sip:) trying to use anyway\n");
12830    }
12831 
12832    /* If we have a port number in the given URI, make sure we do remember to not check for NAPTR/SRV records. 
12833       The domain part is actually a host. */
12834    peer->portinuri = !ast_strlen_zero(pt) ? TRUE : FALSE;
12835 
12836    /* handle the transport type specified in Contact header. */
12837    if ((transport_type = get_transport_str2enum(transport))) {
12838       /* if the port is not specified but the transport is, make sure to set the
12839        * default port to match the specified transport.  This may or may not be the
12840        * same transport used by the pvt struct for the Register dialog. */
12841       
12842       port = port_str2int(pt, (transport_type == SIP_TRANSPORT_TLS) ? STANDARD_TLS_PORT : STANDARD_SIP_PORT);
12843    } else {
12844       port = port_str2int(pt, STANDARD_SIP_PORT);
12845       transport_type = pvt->socket.type;
12846    }
12847 
12848    /* if the peer's socket type is different than the Registration
12849     * transport type, change it.  If it got this far, it is a
12850     * supported type, but check just in case */
12851    if ((peer->socket.type != transport_type) && (peer->transports & transport_type)) {
12852       set_socket_transport(&peer->socket, transport_type);
12853    }
12854 
12855    oldsin = peer->addr;
12856 
12857    /* If we were already linked into the peers_by_ip container unlink ourselves so nobody can find us */
12858    if (peer->addr.sin_addr.s_addr) {
12859       ao2_t_unlink(peers_by_ip, peer, "ao2_unlink of peer from peers_by_ip table");
12860    }
12861 
12862    if (!ast_test_flag(&peer->flags[0], SIP_NAT_ROUTE)) {
12863       /* use the data provided in the Contact header for call routing */
12864       ast_debug(1, "Store REGISTER's Contact header for call routing.\n");
12865       /* XXX This could block for a long time XXX */
12866       /*! \todo Check NAPTR/SRV if we have not got a port in the URI */
12867       hp = ast_gethostbyname(host, &ahp);
12868       if (!hp)  {
12869          ast_log(LOG_WARNING, "Invalid host '%s'\n", host);
12870          ast_string_field_set(peer, fullcontact, "");
12871          ast_string_field_set(pvt, our_contact, "");
12872          return PARSE_REGISTER_FAILED;
12873       }
12874       peer->addr.sin_family = AF_INET;
12875       memcpy(&peer->addr.sin_addr, hp->h_addr, sizeof(peer->addr.sin_addr));
12876       peer->addr.sin_port = htons(port);
12877    } else {
12878       /* Don't trust the contact field.  Just use what they came to us
12879          with */
12880       ast_debug(1, "Store REGISTER's src-IP:port for call routing.\n");
12881       peer->addr = pvt->recv;
12882    }
12883 
12884    /* Check that they're allowed to register at this IP */
12885    memcpy(&testsin.sin_addr, &peer->addr.sin_addr, sizeof(testsin.sin_addr));
12886    if (ast_apply_ha(global_contact_ha, &testsin) != AST_SENSE_ALLOW ||
12887          ast_apply_ha(peer->contactha, &testsin) != AST_SENSE_ALLOW) {
12888       ast_log(LOG_WARNING, "Host '%s' disallowed by contact ACL (violating IP %s)\n", host, ast_inet_ntoa(testsin.sin_addr));
12889       ast_string_field_set(peer, fullcontact, "");
12890       ast_string_field_set(pvt, our_contact, "");
12891       return PARSE_REGISTER_DENIED;
12892    }
12893 
12894    /* if the Contact header information copied into peer->addr matches the
12895     * received address, and the transport types are the same, then copy socket
12896     * data into the peer struct */
12897    if ((peer->socket.type == pvt->socket.type) &&
12898       (peer->addr.sin_addr.s_addr == pvt->recv.sin_addr.s_addr) &&
12899       (peer->addr.sin_port == pvt->recv.sin_port)){
12900 
12901       copy_socket_data(&peer->socket, &pvt->socket);
12902    }
12903 
12904    /* Now that our address has been updated put ourselves back into the container for lookups */
12905    ao2_t_link(peers_by_ip, peer, "ao2_link into peers_by_ip table");
12906 
12907    /* Save SIP options profile */
12908    peer->sipoptions = pvt->sipoptions;
12909 
12910    if (!ast_strlen_zero(curi) && ast_strlen_zero(peer->username))
12911       ast_string_field_set(peer, username, curi);
12912 
12913    AST_SCHED_DEL_UNREF(sched, peer->expire,
12914          unref_peer(peer, "remove register expire ref"));
12915 
12916    if (expire > max_expiry)
12917       expire = max_expiry;
12918    if (expire < min_expiry)
12919       expire = min_expiry;
12920    if (peer->is_realtime && !ast_test_flag(&peer->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
12921       peer->expire = -1;
12922    } else {
12923       peer->expire = ast_sched_add(sched, (expire + 10) * 1000, expire_register,
12924             ref_peer(peer, "add registration ref"));
12925       if (peer->expire == -1) {
12926          unref_peer(peer, "remote registration ref");
12927       }
12928    }
12929    pvt->expiry = expire;
12930    snprintf(data, sizeof(data), "%s:%d:%d:%s:%s", ast_inet_ntoa(peer->addr.sin_addr), ntohs(peer->addr.sin_port), expire, peer->username, peer->fullcontact);
12931    /* Saving TCP connections is useless, we won't be able to reconnect 
12932       XXX WHY???? XXX
12933       \todo Fix this immediately.
12934    */
12935    if (!peer->rt_fromcontact && (peer->socket.type & SIP_TRANSPORT_UDP))
12936       ast_db_put("SIP/Registry", peer->name, data);
12937    manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: Registered\r\nAddress: %s\r\nPort: %d\r\n", peer->name,  ast_inet_ntoa(peer->addr.sin_addr), ntohs(peer->addr.sin_port));
12938 
12939    /* Is this a new IP address for us? */
12940    if (VERBOSITY_ATLEAST(2) && inaddrcmp(&peer->addr, &oldsin)) {
12941       ast_verbose(VERBOSE_PREFIX_3 "Registered SIP '%s' at %s port %d\n", peer->name, ast_inet_ntoa(peer->addr.sin_addr), ntohs(peer->addr.sin_port));
12942    }
12943    sip_poke_peer(peer, 0);
12944    register_peer_exten(peer, 1);
12945    
12946    /* Save User agent */
12947    useragent = get_header(req, "User-Agent");
12948    if (strcasecmp(useragent, peer->useragent)) {
12949       ast_string_field_set(peer, useragent, useragent);
12950       ast_verb(4, "Saved useragent \"%s\" for peer %s\n", peer->useragent, peer->name);
12951    }
12952    return PARSE_REGISTER_UPDATE;
12953 }
12954 
12955 /*! \brief Remove route from route list */
12956 static void free_old_route(struct sip_route *route)
12957 {
12958    struct sip_route *next;
12959 
12960    while (route) {
12961       next = route->next;
12962       ast_free(route);
12963       route = next;
12964    }
12965 }
12966 
12967 /*! \brief List all routes - mostly for debugging */
12968 static void list_route(struct sip_route *route)
12969 {
12970    if (!route)
12971       ast_verbose("list_route: no route\n");
12972    else {
12973       for (;route; route = route->next)
12974          ast_verbose("list_route: hop: <%s>\n", route->hop);
12975    }
12976 }
12977 
12978 /*! \brief Build route list from Record-Route header */
12979 static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards)
12980 {
12981    struct sip_route *thishop, *head, *tail;
12982    int start = 0;
12983    int len;
12984    const char *rr, *contact, *c;
12985 
12986    /* Once a persistant route is set, don't fool with it */
12987    if (p->route && p->route_persistant) {
12988       ast_debug(1, "build_route: Retaining previous route: <%s>\n", p->route->hop);
12989       return;
12990    }
12991 
12992    if (p->route) {
12993       free_old_route(p->route);
12994       p->route = NULL;
12995    }
12996 
12997    /* We only want to create the route set the first time this is called */
12998    p->route_persistant = 1;
12999    
13000    /* Build a tailq, then assign it to p->route when done.
13001     * If backwards, we add entries from the head so they end up
13002     * in reverse order. However, we do need to maintain a correct
13003     * tail pointer because the contact is always at the end.
13004     */
13005    head = NULL;
13006    tail = head;
13007    /* 1st we pass through all the hops in any Record-Route headers */
13008    for (;;) {
13009       /* Each Record-Route header */
13010       rr = __get_header(req, "Record-Route", &start);
13011       if (*rr == '\0')
13012          break;
13013       for (; (rr = strchr(rr, '<')) ; rr += len) { /* Each route entry */
13014          ++rr;
13015          len = strcspn(rr, ">") + 1;
13016          /* Make a struct route */
13017          if ((thishop = ast_malloc(sizeof(*thishop) + len))) {
13018             /* ast_calloc is not needed because all fields are initialized in this block */
13019             ast_copy_string(thishop->hop, rr, len);
13020             ast_debug(2, "build_route: Record-Route hop: <%s>\n", thishop->hop);
13021             /* Link in */
13022             if (backwards) {
13023                /* Link in at head so they end up in reverse order */
13024                thishop->next = head;
13025                head = thishop;
13026                /* If this was the first then it'll be the tail */
13027                if (!tail)
13028                   tail = thishop;
13029             } else {
13030                thishop->next = NULL;
13031                /* Link in at the end */
13032                if (tail)
13033                   tail->next = thishop;
13034                else
13035                   head = thishop;
13036                tail = thishop;
13037             }
13038          }
13039       }
13040    }
13041 
13042    /* Only append the contact if we are dealing with a strict router */
13043    if (!head || (!ast_strlen_zero(head->hop) && strstr(head->hop, ";lr") == NULL) ) {
13044       /* 2nd append the Contact: if there is one */
13045       /* Can be multiple Contact headers, comma separated values - we just take the first */
13046       contact = get_header(req, "Contact");
13047       if (!ast_strlen_zero(contact)) {
13048          ast_debug(2, "build_route: Contact hop: %s\n", contact);
13049          /* Look for <: delimited address */
13050          c = strchr(contact, '<');
13051          if (c) {
13052             /* Take to > */
13053             ++c;
13054             len = strcspn(c, ">") + 1;
13055          } else {
13056             /* No <> - just take the lot */
13057             c = contact;
13058             len = strlen(contact) + 1;
13059          }
13060          if ((thishop = ast_malloc(sizeof(*thishop) + len))) {
13061             /* ast_calloc is not needed because all fields are initialized in this block */
13062             ast_copy_string(thishop->hop, c, len);
13063             thishop->next = NULL;
13064             /* Goes at the end */
13065             if (tail)
13066                tail->next = thishop;
13067             else
13068                head = thishop;
13069          }
13070       }
13071    }
13072 
13073    /* Store as new route */
13074    p->route = head;
13075 
13076    /* For debugging dump what we ended up with */
13077    if (sip_debug_test_pvt(p))
13078       list_route(p->route);
13079 }
13080 
13081 /*! \brief builds the sip_pvt's randdata field which is used for the nonce
13082  *  challenge.  When forceupdate is not set, the nonce is only updated if
13083  *  the current one is stale.  In this case, a stalenonce is one which
13084  *  has already received a response, if a nonce has not received a response
13085  *  it is not always necessary or beneficial to create a new one. */
13086 
13087 static void set_nonce_randdata(struct sip_pvt *p, int forceupdate)
13088 {
13089    if (p->stalenonce || forceupdate || ast_strlen_zero(p->randdata)) {
13090       ast_string_field_build(p, randdata, "%08lx", ast_random()); /* Create nonce for challenge */
13091       p->stalenonce = 0;
13092    }
13093 }
13094 
13095 AST_THREADSTORAGE(check_auth_buf);
13096 #define CHECK_AUTH_BUF_INITLEN   256
13097 
13098 /*! \brief  Check user authorization from peer definition 
13099    Some actions, like REGISTER and INVITEs from peers require
13100    authentication (if peer have secret set) 
13101     \return 0 on success, non-zero on error
13102 */
13103 static enum check_auth_result check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
13104                 const char *secret, const char *md5secret, int sipmethod,
13105                 char *uri, enum xmittype reliable, int ignore)
13106 {
13107    const char *response;
13108    char *reqheader, *respheader;
13109    const char *authtoken;
13110    char a1_hash[256];
13111    char resp_hash[256]="";
13112    char *c;
13113    int  wrongnonce = FALSE;
13114    int  good_response;
13115    const char *usednonce = p->randdata;
13116    struct ast_str *buf;
13117    int res;
13118 
13119    /* table of recognised keywords, and their value in the digest */
13120    enum keys { K_RESP, K_URI, K_USER, K_NONCE, K_LAST };
13121    struct x {
13122       const char *key;
13123       const char *s;
13124    } *i, keys[] = {
13125       [K_RESP] = { "response=", "" },
13126       [K_URI] = { "uri=", "" },
13127       [K_USER] = { "username=", "" },
13128       [K_NONCE] = { "nonce=", "" },
13129       [K_LAST] = { NULL, NULL}
13130    };
13131 
13132    /* Always OK if no secret */
13133    if (ast_strlen_zero(secret) && ast_strlen_zero(md5secret))
13134       return AUTH_SUCCESSFUL;
13135 
13136    /* Always auth with WWW-auth since we're NOT a proxy */
13137    /* Using proxy-auth in a B2BUA may block proxy authorization in the same transaction */
13138    response = "401 Unauthorized";
13139 
13140    /*
13141     * Note the apparent swap of arguments below, compared to other
13142     * usages of auth_headers().
13143     */
13144    auth_headers(WWW_AUTH, &respheader, &reqheader);
13145 
13146    authtoken =  get_header(req, reqheader);  
13147    if (ignore && !ast_strlen_zero(p->randdata) && ast_strlen_zero(authtoken)) {
13148       /* This is a retransmitted invite/register/etc, don't reconstruct authentication
13149          information */
13150       if (!reliable) {
13151          /* Resend message if this was NOT a reliable delivery.   Otherwise the
13152             retransmission should get it */
13153          transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, 0);
13154          /* Schedule auto destroy in 32 seconds (according to RFC 3261) */
13155          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13156       }
13157       return AUTH_CHALLENGE_SENT;
13158    } else if (ast_strlen_zero(p->randdata) || ast_strlen_zero(authtoken)) {
13159       /* We have no auth, so issue challenge and request authentication */
13160       set_nonce_randdata(p, 1); /* Create nonce for challenge */
13161       transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, 0);
13162       /* Schedule auto destroy in 32 seconds */
13163       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13164       return AUTH_CHALLENGE_SENT;
13165    } 
13166 
13167    /* --- We have auth, so check it */
13168 
13169    /* Whoever came up with the authentication section of SIP can suck my %&#$&* for not putting
13170       an example in the spec of just what it is you're doing a hash on. */
13171 
13172    if (!(buf = ast_str_thread_get(&check_auth_buf, CHECK_AUTH_BUF_INITLEN)))
13173       return AUTH_SECRET_FAILED; /*! XXX \todo need a better return code here */
13174 
13175    /* Make a copy of the response and parse it */
13176    res = ast_str_set(&buf, 0, "%s", authtoken);
13177 
13178    if (res == AST_DYNSTR_BUILD_FAILED)
13179       return AUTH_SECRET_FAILED; /*! XXX \todo need a better return code here */
13180 
13181    c = buf->str;
13182 
13183    while(c && *(c = ast_skip_blanks(c)) ) { /* lookup for keys */
13184       for (i = keys; i->key != NULL; i++) {
13185          const char *separator = ",";  /* default */
13186 
13187          if (strncasecmp(c, i->key, strlen(i->key)) != 0)
13188             continue;
13189          /* Found. Skip keyword, take text in quotes or up to the separator. */
13190          c += strlen(i->key);
13191          if (*c == '"') { /* in quotes. Skip first and look for last */
13192             c++;
13193             separator = "\"";
13194          }
13195          i->s = c;
13196          strsep(&c, separator);
13197          break;
13198       }
13199       if (i->key == NULL) /* not found, jump after space or comma */
13200          strsep(&c, " ,");
13201    }
13202 
13203    /* Verify that digest username matches  the username we auth as */
13204    if (strcmp(username, keys[K_USER].s)) {
13205       ast_log(LOG_WARNING, "username mismatch, have <%s>, digest has <%s>\n",
13206          username, keys[K_USER].s);
13207       /* Oops, we're trying something here */
13208       return AUTH_USERNAME_MISMATCH;
13209    }
13210 
13211    /* Verify nonce from request matches our nonce, and the nonce has not already been responded to.
13212     * If this check fails, send 401 with new nonce */
13213    if (strcasecmp(p->randdata, keys[K_NONCE].s) || p->stalenonce) { /* XXX it was 'n'casecmp ? */
13214       wrongnonce = TRUE;
13215       usednonce = keys[K_NONCE].s;
13216    } else {
13217       p->stalenonce = 1; /* now, since the nonce has a response, mark it as stale so it can't be sent or responded to again */
13218    }
13219 
13220    if (!ast_strlen_zero(md5secret))
13221       ast_copy_string(a1_hash, md5secret, sizeof(a1_hash));
13222    else {
13223       char a1[256];
13224       snprintf(a1, sizeof(a1), "%s:%s:%s", username, sip_cfg.realm, secret);
13225       ast_md5_hash(a1_hash, a1);
13226    }
13227 
13228    /* compute the expected response to compare with what we received */
13229    {
13230       char a2[256];
13231       char a2_hash[256];
13232       char resp[256];
13233 
13234       snprintf(a2, sizeof(a2), "%s:%s", sip_methods[sipmethod].text,
13235             S_OR(keys[K_URI].s, uri));
13236       ast_md5_hash(a2_hash, a2);
13237       snprintf(resp, sizeof(resp), "%s:%s:%s", a1_hash, usednonce, a2_hash);
13238       ast_md5_hash(resp_hash, resp);
13239    }
13240 
13241    good_response = keys[K_RESP].s &&
13242          !strncasecmp(keys[K_RESP].s, resp_hash, strlen(resp_hash));
13243    if (wrongnonce) {
13244       if (good_response) {
13245          if (sipdebug)
13246             ast_log(LOG_NOTICE, "Correct auth, but based on stale nonce received from '%s'\n", get_header(req, "From"));
13247          /* We got working auth token, based on stale nonce . */
13248          set_nonce_randdata(p, 0);
13249          transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, TRUE);
13250       } else {
13251          /* Everything was wrong, so give the device one more try with a new challenge */
13252          if (!req->ignore) {
13253             if (sipdebug)
13254                ast_log(LOG_NOTICE, "Bad authentication received from '%s'\n", get_header(req, "To"));
13255             set_nonce_randdata(p, 1);
13256          } else {
13257             if (sipdebug)
13258                ast_log(LOG_NOTICE, "Duplicate authentication received from '%s'\n", get_header(req, "To"));
13259          }
13260          transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, FALSE);
13261       }
13262 
13263       /* Schedule auto destroy in 32 seconds */
13264       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13265       return AUTH_CHALLENGE_SENT;
13266    } 
13267    if (good_response) {
13268       append_history(p, "AuthOK", "Auth challenge successful for %s", username);
13269       return AUTH_SUCCESSFUL;
13270    }
13271 
13272    /* Ok, we have a bad username/secret pair */
13273    /* Tell the UAS not to re-send this authentication data, because
13274       it will continue to fail
13275    */
13276 
13277    return AUTH_SECRET_FAILED;
13278 }
13279 
13280 /*! \brief Change onhold state of a peer using a pvt structure */
13281 static void sip_peer_hold(struct sip_pvt *p, int hold)
13282 {
13283    struct sip_peer *peer = find_peer(p->peername, NULL, 1, FINDALLDEVICES, FALSE, 0);
13284 
13285    if (!peer)
13286       return;
13287 
13288    /* If they put someone on hold, increment the value... otherwise decrement it */
13289    ast_atomic_fetchadd_int(&peer->onHold, (hold ? +1 : -1));
13290 
13291    /* Request device state update */
13292    ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", peer->name);
13293    unref_peer(peer, "sip_peer_hold: from find_peer operation");
13294    
13295    return;
13296 }
13297 
13298 /*! \brief Receive MWI events that we have subscribed to */
13299 static void mwi_event_cb(const struct ast_event *event, void *userdata)
13300 {
13301    struct sip_peer *peer = userdata;
13302 
13303    ao2_lock(peer);
13304    sip_send_mwi_to_peer(peer, event, 0);
13305    ao2_unlock(peer);
13306 }
13307 
13308 /*! \brief Callback for the devicestate notification (SUBSCRIBE) support subsystem
13309 \note If you add an "hint" priority to the extension in the dial plan,
13310    you will get notifications on device state changes */
13311 static int cb_extensionstate(char *context, char* exten, int state, void *data)
13312 {
13313    struct sip_pvt *p = data;
13314 
13315    sip_pvt_lock(p);
13316 
13317    switch(state) {
13318    case AST_EXTENSION_DEACTIVATED:  /* Retry after a while */
13319    case AST_EXTENSION_REMOVED:   /* Extension is gone */
13320       if (p->autokillid > -1 && sip_cancel_destroy(p))   /* Remove subscription expiry for renewals */
13321          ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
13322       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);  /* Delete subscription in 32 secs */
13323       ast_verb(2, "Extension state: Watcher for hint %s %s. Notify User %s\n", exten, state == AST_EXTENSION_DEACTIVATED ? "deactivated" : "removed", p->username);
13324       p->stateid = -1;
13325       p->subscribed = NONE;
13326       append_history(p, "Subscribestatus", "%s", state == AST_EXTENSION_REMOVED ? "HintRemoved" : "Deactivated");
13327       break;
13328    default: /* Tell user */
13329       p->laststate = state;
13330       break;
13331    }
13332    if (p->subscribed != NONE) {  /* Only send state NOTIFY if we know the format */
13333       if (!p->pendinginvite) {
13334          transmit_state_notify(p, state, 1, FALSE);
13335       } else {
13336          /* We already have a NOTIFY sent that is not answered. Queue the state up.
13337             if many state changes happen meanwhile, we will only send a notification of the last one */
13338          ast_set_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE);
13339       }
13340    }
13341    ast_verb(2, "Extension Changed %s[%s] new state %s for Notify User %s %s\n", exten, context, ast_extension_state2str(state), p->username,
13342          ast_test_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE) ? "(queued)" : "");
13343 
13344    sip_pvt_unlock(p);
13345 
13346    return 0;
13347 }
13348 
13349 /*! \brief Send a fake 401 Unauthorized response when the administrator
13350   wants to hide the names of local devices  from fishers
13351  */
13352 static void transmit_fake_auth_response(struct sip_pvt *p, int sipmethod, struct sip_request *req, enum xmittype reliable)
13353 {
13354    /* We have to emulate EXACTLY what we'd get with a good peer
13355     * and a bad password, or else we leak information. */
13356    const char *response = "407 Proxy Authentication Required";
13357    const char *reqheader = "Proxy-Authorization";
13358    const char *respheader = "Proxy-Authenticate";
13359    const char *authtoken;
13360    struct ast_str *buf;
13361    char *c;
13362 
13363    /* table of recognised keywords, and their value in the digest */
13364    enum keys { K_NONCE, K_LAST };
13365    struct x {
13366       const char *key;
13367       const char *s;
13368    } *i, keys[] = {
13369       [K_NONCE] = { "nonce=", "" },
13370       [K_LAST] = { NULL, NULL}
13371    };
13372 
13373    if (sipmethod == SIP_REGISTER || sipmethod == SIP_SUBSCRIBE) {
13374       response = "401 Unauthorized";
13375       reqheader = "Authorization";
13376       respheader = "WWW-Authenticate";
13377    }
13378    authtoken = get_header(req, reqheader);
13379    if (req->ignore && !ast_strlen_zero(p->randdata) && ast_strlen_zero(authtoken)) {
13380       /* This is a retransmitted invite/register/etc, don't reconstruct authentication
13381        * information */
13382       transmit_response_with_auth(p, response, req, p->randdata, 0, respheader, 0);
13383       /* Schedule auto destroy in 32 seconds (according to RFC 3261) */
13384       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13385       return;
13386    } else if (ast_strlen_zero(p->randdata) || ast_strlen_zero(authtoken)) {
13387       /* We have no auth, so issue challenge and request authentication */
13388       set_nonce_randdata(p, 1);
13389       transmit_response_with_auth(p, response, req, p->randdata, 0, respheader, 0);
13390       /* Schedule auto destroy in 32 seconds */
13391       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13392       return;
13393    }
13394 
13395    if (!(buf = ast_str_thread_get(&check_auth_buf, CHECK_AUTH_BUF_INITLEN))) {
13396       transmit_response(p, "403 Forbidden (Bad auth)", &p->initreq);
13397       return;
13398    }
13399 
13400    /* Make a copy of the response and parse it */
13401    if (ast_str_set(&buf, 0, "%s", authtoken) == AST_DYNSTR_BUILD_FAILED) {
13402       transmit_response(p, "403 Forbidden (Bad auth)", &p->initreq);
13403       return;
13404    }
13405 
13406    c = buf->str;
13407 
13408    while (c && *(c = ast_skip_blanks(c))) { /* lookup for keys */
13409       for (i = keys; i->key != NULL; i++) {
13410          const char *separator = ",";  /* default */
13411 
13412          if (strncasecmp(c, i->key, strlen(i->key)) != 0) {
13413             continue;
13414          }
13415          /* Found. Skip keyword, take text in quotes or up to the separator. */
13416          c += strlen(i->key);
13417          if (*c == '"') { /* in quotes. Skip first and look for last */
13418             c++;
13419             separator = "\"";
13420          }
13421          i->s = c;
13422          strsep(&c, separator);
13423          break;
13424       }
13425       if (i->key == NULL) { /* not found, jump after space or comma */
13426          strsep(&c, " ,");
13427       }
13428    }
13429 
13430    /* Verify nonce from request matches our nonce.  If not, send 401 with new nonce */
13431    if (strcasecmp(p->randdata, keys[K_NONCE].s)) {
13432       if (!req->ignore) {
13433          set_nonce_randdata(p, 1);
13434       }
13435       transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, FALSE);
13436 
13437       /* Schedule auto destroy in 32 seconds */
13438       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13439    } else {
13440       transmit_response(p, "403 Forbidden (Bad auth)", &p->initreq);
13441    }
13442 }
13443 
13444 /*!
13445  * Terminate the uri at the first ';' or space.
13446  * Technically we should ignore escaped space per RFC3261 (19.1.1 etc)
13447  * but don't do it for the time being. Remember the uri format is:
13448  * (User-parameters was added after RFC 3261)
13449  *\verbatim
13450  *
13451  * sip:user:password;user-parameters@host:port;uri-parameters?headers
13452  * sips:user:password;user-parameters@host:port;uri-parameters?headers
13453  *
13454  *\endverbatim
13455  * \todo As this function does not support user-parameters, it's considered broken
13456  * and needs fixing.
13457  */
13458 static char *terminate_uri(char *uri)
13459 {
13460    char *t = uri;
13461    while (*t && *t > ' ' && *t != ';')
13462       t++;
13463    *t = '\0';
13464    return uri;
13465 }
13466 
13467 /*! \brief Verify registration of user 
13468    - Registration is done in several steps, first a REGISTER without auth
13469      to get a challenge (nonce) then a second one with auth
13470    - Registration requests are only matched with peers that are marked as "dynamic"
13471  */
13472 static enum check_auth_result register_verify(struct sip_pvt *p, struct sockaddr_in *sin,
13473                      struct sip_request *req, char *uri)
13474 {
13475    enum check_auth_result res = AUTH_NOT_FOUND;
13476    struct sip_peer *peer;
13477    char tmp[256];
13478    char *name, *c;
13479    char *domain;
13480 
13481    terminate_uri(uri);  /* warning, overwrite the string */
13482 
13483    ast_copy_string(tmp, get_header(req, "To"), sizeof(tmp));
13484    if (sip_cfg.pedanticsipchecking)
13485       ast_uri_decode(tmp);
13486 
13487    c = get_in_brackets(tmp);
13488    c = remove_uri_parameters(c);
13489 
13490    if (!strncasecmp(c, "sip:", 4)) {
13491       name = c + 4;
13492    } else if (!strncasecmp(c, "sips:", 5)) {
13493       name = c + 5;
13494    } else {
13495       name = c;
13496       ast_log(LOG_NOTICE, "Invalid to address: '%s' from %s (missing sip:) trying to use anyway...\n", c, ast_inet_ntoa(sin->sin_addr));
13497    }
13498 
13499    /*! \todo XXX here too we interpret a missing @domain as a name-only
13500     * URI, whereas the RFC says this is a domain-only uri.
13501     */
13502    /* Strip off the domain name */
13503    if ((c = strchr(name, '@'))) {
13504       *c++ = '\0';
13505       domain = c;
13506       if ((c = strchr(domain, ':')))   /* Remove :port */
13507          *c = '\0';
13508       if (!AST_LIST_EMPTY(&domain_list)) {
13509          if (!check_sip_domain(domain, NULL, 0)) {
13510             transmit_response(p, "404 Not found (unknown domain)", &p->initreq);
13511             return AUTH_UNKNOWN_DOMAIN;
13512          }
13513       }
13514    }
13515    c = strchr(name, ';');  /* Remove any Username parameters */
13516    if (c)
13517       *c = '\0';
13518 
13519    ast_string_field_set(p, exten, name);
13520    build_contact(p);
13521    if (req->ignore) {
13522       /* Expires is a special case, where we only want to load the peer if this isn't a deregistration attempt */
13523       const char *expires = get_header(req, "Expires");
13524       int expire = atoi(expires);
13525 
13526       if (ast_strlen_zero(expires)) { /* No expires header; look in Contact */
13527          if ((expires = strcasestr(get_header(req, "Contact"), ";expires="))) {
13528             expire = atoi(expires + 9);
13529          }
13530       }
13531       if (!ast_strlen_zero(expires) && expire == 0) {
13532          transmit_response_with_date(p, "200 OK", req);
13533          return 0;
13534       }
13535    }
13536    peer = find_peer(name, NULL, TRUE, FINDPEERS, FALSE, 0);
13537    if (!(peer && ast_apply_ha(peer->ha, sin))) {
13538       /* Peer fails ACL check */
13539       if (peer) {
13540          unref_peer(peer, "register_verify: unref_peer: from find_peer operation");
13541          peer = NULL;
13542          res = AUTH_ACL_FAILED;
13543       } else
13544          res = AUTH_NOT_FOUND;
13545    }
13546 
13547    if (peer) {
13548       /*! \todo OEJ Remove this - there's never RTP in a REGISTER dialog... */
13549       /* Set Frame packetization */
13550       if (p->rtp) {
13551          ast_rtp_codec_setpref(p->rtp, &peer->prefs);
13552          p->autoframing = peer->autoframing;
13553       }
13554       if (!peer->host_dynamic) {
13555          ast_log(LOG_ERROR, "Peer '%s' is trying to register, but not configured as host=dynamic\n", peer->name);
13556          res = AUTH_PEER_NOT_DYNAMIC;
13557       } else {
13558          ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_NAT);
13559          if (ast_test_flag(&p->flags[1], SIP_PAGE2_REGISTERTRYING))
13560             transmit_response(p, "100 Trying", req);
13561          if (!(res = check_auth(p, req, peer->name, peer->secret, peer->md5secret, SIP_REGISTER, uri, XMIT_UNRELIABLE, req->ignore))) {
13562             if (sip_cancel_destroy(p))
13563                ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
13564 
13565             if (check_request_transport(peer, req)) {
13566                ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
13567                transmit_response_with_date(p, "403 Forbidden", req);
13568                res = AUTH_BAD_TRANSPORT;
13569             } else {
13570 
13571                /* We have a successful registration attempt with proper authentication,
13572                   now, update the peer */
13573                switch (parse_register_contact(p, peer, req)) {
13574                case PARSE_REGISTER_DENIED:
13575                   ast_log(LOG_WARNING, "Registration denied because of contact ACL\n");
13576                   transmit_response_with_date(p, "603 Denied", req);
13577                   peer->lastmsgssent = -1;
13578                   res = 0;
13579                   break;
13580                case PARSE_REGISTER_FAILED:
13581                   ast_log(LOG_WARNING, "Failed to parse contact info\n");
13582                   transmit_response_with_date(p, "400 Bad Request", req);
13583                   peer->lastmsgssent = -1;
13584                   res = 0;
13585                   break;
13586                case PARSE_REGISTER_QUERY:
13587                   ast_string_field_set(p, fullcontact, peer->fullcontact);
13588                   transmit_response_with_date(p, "200 OK", req);
13589                   peer->lastmsgssent = -1;
13590                   res = 0;
13591                   break;
13592                case PARSE_REGISTER_UPDATE:
13593                   ast_string_field_set(p, fullcontact, peer->fullcontact);
13594                   update_peer(peer, p->expiry);
13595                   /* Say OK and ask subsystem to retransmit msg counter */
13596                   transmit_response_with_date(p, "200 OK", req);
13597                   if (!ast_test_flag((&peer->flags[1]), SIP_PAGE2_SUBSCRIBEMWIONLY))
13598                      peer->lastmsgssent = -1;
13599                   res = 0;
13600                   break;
13601                }
13602             }
13603 
13604          } 
13605       }
13606    }
13607    if (!peer && sip_cfg.autocreatepeer) {
13608       /* Create peer if we have autocreate mode enabled */
13609       peer = temp_peer(name);
13610       if (peer) {
13611          ao2_t_link(peers, peer, "link peer into peer table");
13612          if (peer->addr.sin_addr.s_addr) {
13613             ao2_t_link(peers_by_ip, peer, "link peer into peers-by-ip table");
13614          }
13615          
13616          if (sip_cancel_destroy(p))
13617             ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
13618          switch (parse_register_contact(p, peer, req)) {
13619          case PARSE_REGISTER_DENIED:
13620             ast_log(LOG_WARNING, "Registration denied because of contact ACL\n");
13621             transmit_response_with_date(p, "403 Forbidden (ACL)", req);
13622             peer->lastmsgssent = -1;
13623             res = 0;
13624             break;
13625          case PARSE_REGISTER_FAILED:
13626             ast_log(LOG_WARNING, "Failed to parse contact info\n");
13627             transmit_response_with_date(p, "400 Bad Request", req);
13628             peer->lastmsgssent = -1;
13629             res = 0;
13630             break;
13631          case PARSE_REGISTER_QUERY:
13632             ast_string_field_set(p, fullcontact, peer->fullcontact);
13633             transmit_response_with_date(p, "200 OK", req);
13634             peer->lastmsgssent = -1;
13635             res = 0;
13636             break;
13637          case PARSE_REGISTER_UPDATE:
13638             ast_string_field_set(p, fullcontact, peer->fullcontact);
13639             /* Say OK and ask subsystem to retransmit msg counter */
13640             transmit_response_with_date(p, "200 OK", req);
13641             manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: Registered\r\nAddress: %s\r\nPort: %d\r\n", peer->name, ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
13642             peer->lastmsgssent = -1;
13643             res = 0;
13644             break;
13645          }
13646       }
13647    }
13648    if (!peer && sip_cfg.alwaysauthreject) {
13649       /* If we found a peer, we transmit a 100 Trying.  Therefore, if we're
13650        * trying to avoid leaking information, we MUST also transmit the same
13651        * response when we DON'T find a peer. */
13652       transmit_response(p, "100 Trying", req);
13653       /* Insert a fake delay between the 100 and the subsequent failure. */
13654       sched_yield();
13655    }
13656    if (!res) {
13657       ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", peer->name);
13658    }
13659    if (res < 0) {
13660       switch (res) {
13661       case AUTH_SECRET_FAILED:
13662          /* Wrong password in authentication. Go away, don't try again until you fixed it */
13663          transmit_response(p, "403 Forbidden (Bad auth)", &p->initreq);
13664          if (global_authfailureevents)
13665             manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: Rejected\r\nCause: AUTH_SECRET_FAILED\r\nAddress: %s\r\nPort: %d\r\n", 
13666                name, ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
13667          break;
13668       case AUTH_USERNAME_MISMATCH:
13669          /* Username and digest username does not match.
13670             Asterisk uses the From: username for authentication. We need the
13671             devices to use the same authentication user name until we support
13672             proper authentication by digest auth name */
13673       case AUTH_NOT_FOUND:
13674       case AUTH_PEER_NOT_DYNAMIC:
13675       case AUTH_ACL_FAILED:
13676          if (sip_cfg.alwaysauthreject) {
13677             transmit_fake_auth_response(p, SIP_REGISTER, &p->initreq, XMIT_UNRELIABLE);
13678             if (global_authfailureevents) {
13679                manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: Rejected\r\nCause: %s\r\nAddress: %s\r\nPort: %d\r\n",
13680                   name, res == AUTH_PEER_NOT_DYNAMIC ? "AUTH_PEER_NOT_DYNAMIC" : "URI_NOT_FOUND",
13681                   ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
13682             }
13683          } else {
13684             /* URI not found */
13685             if (res == AUTH_PEER_NOT_DYNAMIC) {
13686                transmit_response(p, "403 Forbidden", &p->initreq);
13687                if (global_authfailureevents) {
13688                   manager_event(EVENT_FLAG_SYSTEM, "PeerStatus",
13689                      "ChannelType: SIP\r\n"
13690                      "Peer: SIP/%s\r\n"
13691                      "PeerStatus: Rejected\r\n"
13692                      "Cause: AUTH_PEER_NOT_DYNAMIC\r\n"
13693                      "Address: %s\r\n"
13694                      "Port: %d\r\n",
13695                      name, ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
13696                }
13697             } else {
13698                transmit_response(p, "404 Not found", &p->initreq);
13699                if (global_authfailureevents) {
13700                   manager_event(EVENT_FLAG_SYSTEM, "PeerStatus",
13701                      "ChannelType: SIP\r\n"
13702                      "Peer: SIP/%s\r\n"
13703                      "PeerStatus: Rejected\r\n"
13704                      "Cause: %s\r\n"
13705                      "Address: %s\r\n"
13706                      "Port: %d\r\n",
13707                      name,
13708                      (res == AUTH_USERNAME_MISMATCH) ? "AUTH_USERNAME_MISMATCH" : "URI_NOT_FOUND",
13709                      ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
13710                }
13711             }
13712          }
13713          break;
13714       case AUTH_BAD_TRANSPORT:
13715       default:
13716          break;
13717       }
13718    }
13719    if (peer)
13720       unref_peer(peer, "register_verify: unref_peer: tossing stack peer pointer at end of func");
13721 
13722    return res;
13723 }
13724 
13725 /*! \brief Translate referring cause */
13726 static void sip_set_redirstr(struct sip_pvt *p, char *reason) {
13727 
13728    if (!strcmp(reason, "unknown")) {
13729       ast_string_field_set(p, redircause, "UNKNOWN");
13730    } else if (!strcmp(reason, "user-busy")) {
13731       ast_string_field_set(p, redircause, "BUSY");
13732    } else if (!strcmp(reason, "no-answer")) {
13733       ast_string_field_set(p, redircause, "NOANSWER");
13734    } else if (!strcmp(reason, "unavailable")) {
13735       ast_string_field_set(p, redircause, "UNREACHABLE");
13736    } else if (!strcmp(reason, "unconditional")) {
13737       ast_string_field_set(p, redircause, "UNCONDITIONAL");
13738    } else if (!strcmp(reason, "time-of-day")) {
13739       ast_string_field_set(p, redircause, "UNKNOWN");
13740    } else if (!strcmp(reason, "do-not-disturb")) {
13741       ast_string_field_set(p, redircause, "UNKNOWN");
13742    } else if (!strcmp(reason, "deflection")) {
13743       ast_string_field_set(p, redircause, "UNKNOWN");
13744    } else if (!strcmp(reason, "follow-me")) {
13745       ast_string_field_set(p, redircause, "UNKNOWN");
13746    } else if (!strcmp(reason, "out-of-service")) {
13747       ast_string_field_set(p, redircause, "UNREACHABLE");
13748    } else if (!strcmp(reason, "away")) {
13749       ast_string_field_set(p, redircause, "UNREACHABLE");
13750    } else {
13751       ast_string_field_set(p, redircause, "UNKNOWN");
13752    }
13753 }
13754 
13755 /*! \brief Get referring dnis */
13756 static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq)
13757 {
13758    char tmp[256], *exten, *rexten, *rdomain;
13759    char *params, *reason = NULL;
13760    struct sip_request *req;
13761    
13762    req = oreq ? oreq : &p->initreq;
13763 
13764    ast_copy_string(tmp, get_header(req, "Diversion"), sizeof(tmp));
13765    if (ast_strlen_zero(tmp))
13766       return 0;
13767 
13768    /*! \todo This function does not take user-parameters into consideration.
13769       First look for @, then start looking for ; to find uri-parameters.
13770    */
13771    params = strchr(tmp, ';');
13772 
13773    exten = get_in_brackets(tmp);
13774    if (!strncasecmp(exten, "sip:", 4)) {
13775       exten += 4;
13776    } else if (!strncasecmp(exten, "sips:", 5)) {
13777       exten += 5;
13778    } else {
13779       ast_log(LOG_WARNING, "Huh?  Not an RDNIS SIP header (%s)?\n", exten);
13780       return -1;
13781    }
13782 
13783    /* Get diversion-reason param if present */
13784    if (params) {
13785       *params = '\0';   /* Cut off parameters  */
13786       params++;
13787       while (*params == ';' || *params == ' ')
13788          params++;
13789       /* Check if we have a reason parameter */
13790       if ((reason = strcasestr(params, "reason="))) {
13791          reason+=7;
13792          /* Remove enclosing double-quotes */
13793          if (*reason == '"') 
13794             ast_strip_quoted(reason, "\"", "\"");
13795          if (!ast_strlen_zero(reason)) {
13796             sip_set_redirstr(p, reason);
13797             if (p->owner) {
13798                pbx_builtin_setvar_helper(p->owner, "__PRIREDIRECTREASON", p->redircause);
13799                pbx_builtin_setvar_helper(p->owner, "__SIPREDIRECTREASON", reason);
13800             }
13801          }
13802       }
13803    }
13804 
13805    rdomain = exten;
13806    rexten = strsep(&rdomain, "@");  /* trim anything after @ */
13807    if (p->owner) 
13808       pbx_builtin_setvar_helper(p->owner, "__SIPRDNISDOMAIN", rdomain);
13809 
13810    if (sip_debug_test_pvt(p))
13811       ast_verbose("RDNIS for this call is is %s (reason %s)\n", exten, reason ? reason : "");
13812 
13813    ast_string_field_set(p, rdnis, rexten);
13814 
13815    return 0;
13816 }
13817 
13818 /*! \brief Find out who the call is for.
13819    We use the request uri as a destination. 
13820    This code assumes authentication has been done, so that the
13821    device (peer/user) context is already set.
13822    \return 0 on success (found a matching extension),
13823    1 for pickup extension or overlap dialling support (if we support it),
13824    -1 on error.
13825 
13826   \note If the incoming uri is a SIPS: uri, we are required to carry this across
13827    the dialplan, so that the outbound call also is a sips: call or encrypted
13828    IAX2 call. If that's not available, the call should FAIL.
13829 */
13830 static int get_destination(struct sip_pvt *p, struct sip_request *oreq)
13831 {
13832    char tmp[256] = "", *uri, *a;
13833    char tmpf[256] = "", *from = NULL;
13834    struct sip_request *req;
13835    char *colon;
13836    char *decoded_uri;
13837    
13838    req = oreq;
13839    if (!req)
13840       req = &p->initreq;
13841 
13842    /* Find the request URI */
13843    if (req->rlPart2)
13844       ast_copy_string(tmp, REQ_OFFSET_TO_STR(req, rlPart2), sizeof(tmp));
13845    
13846    if (sip_cfg.pedanticsipchecking)
13847       ast_uri_decode(tmp);
13848 
13849    uri = get_in_brackets(tmp);
13850    
13851    if (!strncasecmp(uri, "sip:", 4)) {
13852       uri += 4;
13853    } else if (!strncasecmp(uri, "sips:", 5)) {
13854       uri += 5;
13855    } else {
13856       ast_log(LOG_WARNING, "Huh?  Not a SIP header (%s)?\n", uri);
13857       return -1;
13858    }
13859 
13860    /* Now find the From: caller ID and name */
13861    /* XXX Why is this done in get_destination? Isn't it already done?
13862       Needs to be checked 
13863         */
13864    ast_copy_string(tmpf, get_header(req, "From"), sizeof(tmpf));
13865    if (!ast_strlen_zero(tmpf)) {
13866       if (sip_cfg.pedanticsipchecking)
13867          ast_uri_decode(tmpf);
13868       from = get_in_brackets(tmpf);
13869    } 
13870    
13871    if (!ast_strlen_zero(from)) {
13872       if (!strncasecmp(from, "sip:", 4)) {
13873          from += 4;
13874       } else if (!strncasecmp(from, "sips:", 5)) {
13875          from += 5;
13876       } else {
13877          ast_log(LOG_WARNING, "Huh?  Not a SIP header (%s)?\n", from);
13878          return -1;
13879       }
13880       if ((a = strchr(from, '@')))
13881          *a++ = '\0';
13882       else
13883          a = from;   /* just a domain */
13884       from = strsep(&from, ";"); /* Remove userinfo options */
13885       a = strsep(&a, ";");    /* Remove URI options */
13886       ast_string_field_set(p, fromdomain, a);
13887    }
13888 
13889    /* Skip any options and find the domain */
13890 
13891    /* Get the target domain */
13892    if ((a = strchr(uri, '@'))) {
13893       *a++ = '\0';
13894    } else { /* No username part */
13895       a = uri;
13896       uri = "s";  /* Set extension to "s" */
13897    }
13898    colon = strchr(a, ':'); /* Remove :port */
13899    if (colon)
13900       *colon = '\0';
13901 
13902    uri = strsep(&uri, ";");   /* Remove userinfo options */
13903    a = strsep(&a, ";");    /* Remove URI options */
13904 
13905    ast_string_field_set(p, domain, a);
13906 
13907    if (!AST_LIST_EMPTY(&domain_list)) {
13908       char domain_context[AST_MAX_EXTENSION];
13909 
13910       domain_context[0] = '\0';
13911       if (!check_sip_domain(p->domain, domain_context, sizeof(domain_context))) {
13912          if (!sip_cfg.allow_external_domains && (req->method == SIP_INVITE || req->method == SIP_REFER)) {
13913             ast_debug(1, "Got SIP %s to non-local domain '%s'; refusing request.\n", sip_methods[req->method].text, p->domain);
13914             return -2;
13915          }
13916       }
13917       /* If we don't have a peer (i.e. we're a guest call),
13918        * overwrite the original context */
13919       if (!ast_test_flag(&p->flags[1], SIP_PAGE2_HAVEPEERCONTEXT) && !ast_strlen_zero(domain_context))
13920          ast_string_field_set(p, context, domain_context);
13921    }
13922 
13923    /* If the request coming in is a subscription and subscribecontext has been specified use it */
13924    if (req->method == SIP_SUBSCRIBE && !ast_strlen_zero(p->subscribecontext))
13925       ast_string_field_set(p, context, p->subscribecontext);
13926 
13927    if (sip_debug_test_pvt(p))
13928       ast_verbose("Looking for %s in %s (domain %s)\n", uri, p->context, p->domain);
13929 
13930    /* Since extensions.conf can have unescaped characters, try matching a
13931     * decoded uri in addition to the non-decoded uri. */
13932    decoded_uri = ast_strdupa(uri);
13933    ast_uri_decode(decoded_uri);
13934 
13935    /* If this is a subscription we actually just need to see if a hint exists for the extension */
13936    if (req->method == SIP_SUBSCRIBE) {
13937       char hint[AST_MAX_EXTENSION];
13938       int which = 0;
13939       if (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, p->context, uri) ||
13940           (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, p->context, decoded_uri) && (which = 1))) {
13941          if (!oreq) {
13942             ast_string_field_set(p, exten, which ? decoded_uri : uri);
13943          }
13944          return 0;
13945       } else {
13946          return -1;
13947       }
13948    } else {
13949       int which = 0;
13950       /* Check the dialplan for the username part of the request URI,
13951          the domain will be stored in the SIPDOMAIN variable
13952          Return 0 if we have a matching extension */
13953       if (ast_exists_extension(NULL, p->context, uri, 1, S_OR(p->cid_num, from)) ||
13954           (ast_exists_extension(NULL, p->context, decoded_uri, 1, S_OR(p->cid_num, from)) && (which = 1)) ||
13955           !strcmp(decoded_uri, ast_pickup_ext())) {
13956          if (!oreq) {
13957             ast_string_field_set(p, exten, which ? decoded_uri : uri);
13958          }
13959          return 0;
13960       }
13961    }
13962 
13963    /* Return 1 for pickup extension or overlap dialling support (if we support it) */
13964    if((ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP) && 
13965        ast_canmatch_extension(NULL, p->context, decoded_uri, 1, S_OR(p->cid_num, from))) ||
13966        !strncmp(decoded_uri, ast_pickup_ext(), strlen(decoded_uri))) {
13967       return 1;
13968    }
13969    
13970    return -1;
13971 }
13972 
13973 /*! \brief Lock dialog lock and find matching pvt lock  
13974    \return a reference, remember to release it when done 
13975 */
13976 static struct sip_pvt *get_sip_pvt_byid_locked(const char *callid, const char *totag, const char *fromtag) 
13977 {
13978    struct sip_pvt *sip_pvt_ptr;
13979    struct sip_pvt tmp_dialog = {
13980       .callid = callid,
13981    };
13982 
13983    if (totag)
13984       ast_debug(4, "Looking for callid %s (fromtag %s totag %s)\n", callid, fromtag ? fromtag : "<no fromtag>", totag ? totag : "<no totag>");
13985 
13986    /* Search dialogs and find the match */
13987    
13988    sip_pvt_ptr = ao2_t_find(dialogs, &tmp_dialog, OBJ_POINTER, "ao2_find of dialog in dialogs table");
13989    if (sip_pvt_ptr) {
13990       /* Go ahead and lock it (and its owner) before returning */
13991       sip_pvt_lock(sip_pvt_ptr);
13992       if (sip_cfg.pedanticsipchecking) {
13993          unsigned char frommismatch = 0, tomismatch = 0;
13994 
13995          if (ast_strlen_zero(fromtag)) {
13996             sip_pvt_unlock(sip_pvt_ptr);
13997             ast_debug(4, "Matched %s call for callid=%s - no from tag specified, pedantic check fails\n",
13998                  sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid);
13999             return NULL;
14000          }
14001 
14002          if (ast_strlen_zero(totag)) {
14003             sip_pvt_unlock(sip_pvt_ptr);
14004             ast_debug(4, "Matched %s call for callid=%s - no to tag specified, pedantic check fails\n",
14005                  sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid);
14006             return NULL;
14007          }
14008          /* RFC 3891
14009           * > 3.  User Agent Server Behavior: Receiving a Replaces Header
14010           * > The Replaces header contains information used to match an existing
14011           * > SIP dialog (call-id, to-tag, and from-tag).  Upon receiving an INVITE
14012           * > with a Replaces header, the User Agent (UA) attempts to match this
14013           * > information with a confirmed or early dialog.  The User Agent Server
14014           * > (UAS) matches the to-tag and from-tag parameters as if they were tags
14015           * > present in an incoming request.  In other words, the to-tag parameter
14016           * > is compared to the local tag, and the from-tag parameter is compared
14017           * > to the remote tag.
14018           *
14019           * Thus, the totag is always compared to the local tag, regardless if
14020           * this our call is an incoming or outgoing call.
14021           */
14022          frommismatch = !!strcmp(fromtag, sip_pvt_ptr->theirtag);
14023          tomismatch = !!strcmp(totag, sip_pvt_ptr->tag);
14024 
14025          if (frommismatch || tomismatch) {
14026             sip_pvt_unlock(sip_pvt_ptr);
14027             if (frommismatch) {
14028                ast_debug(4, "Matched %s call for callid=%s - pedantic from tag check fails; their tag is %s our tag is %s\n",
14029                     sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid, 
14030                     fromtag, sip_pvt_ptr->theirtag);
14031             }
14032             if (tomismatch) {
14033                ast_debug(4, "Matched %s call for callid=%s - pedantic to tag check fails; their tag is %s our tag is %s\n",
14034                     sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid, 
14035                     totag, sip_pvt_ptr->tag);
14036             }
14037             return NULL;
14038          }
14039       }
14040       
14041       if (totag)
14042          ast_debug(4, "Matched %s call - their tag is %s Our tag is %s\n",
14043                  sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING",
14044                  sip_pvt_ptr->theirtag, sip_pvt_ptr->tag);
14045 
14046       /* deadlock avoidance... */
14047       while (sip_pvt_ptr->owner && ast_channel_trylock(sip_pvt_ptr->owner)) {
14048          sip_pvt_unlock(sip_pvt_ptr);
14049          usleep(1);
14050          sip_pvt_lock(sip_pvt_ptr);
14051       }
14052    }
14053    
14054    return sip_pvt_ptr;
14055 }
14056 
14057 /*! \brief Call transfer support (the REFER method) 
14058  *    Extracts Refer headers into pvt dialog structure 
14059  *
14060  * \note If we get a SIPS uri in the refer-to header, we're required to set up a secure signalling path
14061  * to that extension. As a minimum, this needs to be added to a channel variable, if not a channel
14062  * flag.
14063  */
14064 static int get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req)
14065 {
14066 
14067    const char *p_referred_by = NULL;
14068    char *h_refer_to = NULL; 
14069    char *h_referred_by = NULL;
14070    char *refer_to;
14071    const char *p_refer_to;
14072    char *referred_by_uri = NULL;
14073    char *ptr;
14074    struct sip_request *req = NULL;
14075    const char *transfer_context = NULL;
14076    struct sip_refer *referdata;
14077 
14078 
14079    req = outgoing_req;
14080    referdata = transferer->refer;
14081 
14082    if (!req)
14083       req = &transferer->initreq;
14084 
14085    p_refer_to = get_header(req, "Refer-To");
14086    if (ast_strlen_zero(p_refer_to)) {
14087       ast_log(LOG_WARNING, "Refer-To Header missing. Skipping transfer.\n");
14088       return -2;  /* Syntax error */
14089    }
14090    h_refer_to = ast_strdupa(p_refer_to);
14091    refer_to = get_in_brackets(h_refer_to);
14092    if (sip_cfg.pedanticsipchecking)
14093       ast_uri_decode(refer_to);
14094 
14095    if (!strncasecmp(refer_to, "sip:", 4)) {
14096       refer_to += 4;       /* Skip sip: */
14097    } else if (!strncasecmp(refer_to, "sips:", 5)) {
14098       refer_to += 5;
14099    } else {
14100       ast_log(LOG_WARNING, "Can't transfer to non-sip: URI.  (Refer-to: %s)?\n", refer_to);
14101       return -3;
14102    }
14103 
14104    /* Get referred by header if it exists */
14105    p_referred_by = get_header(req, "Referred-By");
14106 
14107    /* Give useful transfer information to the dialplan */
14108    if (transferer->owner) {
14109       struct ast_channel *peer = ast_bridged_channel(transferer->owner);
14110       if (peer) {
14111          pbx_builtin_setvar_helper(peer, "SIPREFERRINGCONTEXT", transferer->context);
14112          pbx_builtin_setvar_helper(peer, "SIPREFERREDBYHDR", p_referred_by);
14113       }
14114    }
14115 
14116    if (!ast_strlen_zero(p_referred_by)) {
14117       char *lessthan;
14118       h_referred_by = ast_strdupa(p_referred_by);
14119       if (sip_cfg.pedanticsipchecking)
14120          ast_uri_decode(h_referred_by);
14121 
14122       /* Store referrer's caller ID name */
14123       ast_copy_string(referdata->referred_by_name, h_referred_by, sizeof(referdata->referred_by_name));
14124       if ((lessthan = strchr(referdata->referred_by_name, '<'))) {
14125          *(lessthan - 1) = '\0'; /* Space */
14126       }
14127 
14128       referred_by_uri = get_in_brackets(h_referred_by);
14129       if (!strncasecmp(referred_by_uri, "sip:", 4)) {
14130          referred_by_uri += 4;      /* Skip sip: */
14131       } else if (!strncasecmp(referred_by_uri, "sips:", 5)) {
14132          referred_by_uri += 5;      /* Skip sips: */
14133       } else {
14134          ast_log(LOG_WARNING, "Huh?  Not a sip: header (Referred-by: %s). Skipping.\n", referred_by_uri);
14135          referred_by_uri = NULL;
14136       }
14137    }
14138 
14139    /* Check for arguments in the refer_to header */
14140    if ((ptr = strcasestr(refer_to, "replaces="))) {
14141       char *to = NULL, *from = NULL;
14142       
14143       /* This is an attended transfer */
14144       referdata->attendedtransfer = 1;
14145       ast_copy_string(referdata->replaces_callid, ptr+9, sizeof(referdata->replaces_callid));
14146       ast_uri_decode(referdata->replaces_callid);
14147       if ((ptr = strchr(referdata->replaces_callid, ';')))  /* Find options */ {
14148          *ptr++ = '\0';
14149       }
14150       
14151       if (ptr) {
14152          /* Find the different tags before we destroy the string */
14153          to = strcasestr(ptr, "to-tag=");
14154          from = strcasestr(ptr, "from-tag=");
14155       }
14156       
14157       /* Grab the to header */
14158       if (to) {
14159          ptr = to + 7;
14160          if ((to = strchr(ptr, '&')))
14161             *to = '\0';
14162          if ((to = strchr(ptr, ';')))
14163             *to = '\0';
14164          ast_copy_string(referdata->replaces_callid_totag, ptr, sizeof(referdata->replaces_callid_totag));
14165       }
14166       
14167       if (from) {
14168          ptr = from + 9;
14169          if ((to = strchr(ptr, '&')))
14170             *to = '\0';
14171          if ((to = strchr(ptr, ';')))
14172             *to = '\0';
14173          ast_copy_string(referdata->replaces_callid_fromtag, ptr, sizeof(referdata->replaces_callid_fromtag));
14174       }
14175 
14176       if (!strcmp(referdata->replaces_callid, transferer->callid) &&
14177          (!sip_cfg.pedanticsipchecking ||
14178          (!strcmp(referdata->replaces_callid_fromtag, transferer->theirtag) &&
14179          !strcmp(referdata->replaces_callid_totag, transferer->tag)))) {
14180             ast_log(LOG_WARNING, "Got an attempt to replace own Call-ID on %s\n", transferer->callid);
14181             return -4;
14182       }
14183 
14184       if (!sip_cfg.pedanticsipchecking)
14185          ast_debug(2, "Attended transfer: Will use Replace-Call-ID : %s (No check of from/to tags)\n", referdata->replaces_callid );
14186       else
14187          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>" );
14188    }
14189    
14190    if ((ptr = strchr(refer_to, '@'))) {   /* Separate domain */
14191       char *urioption = NULL, *domain;
14192       *ptr++ = '\0';
14193 
14194       if ((urioption = strchr(ptr, ';'))) /* Separate urioptions */
14195          *urioption++ = '\0';
14196       
14197       domain = ptr;
14198       if ((ptr = strchr(domain, ':'))) /* Remove :port */
14199          *ptr = '\0';
14200       
14201       /* Save the domain for the dial plan */
14202       ast_copy_string(referdata->refer_to_domain, domain, sizeof(referdata->refer_to_domain));
14203       if (urioption)
14204          ast_copy_string(referdata->refer_to_urioption, urioption, sizeof(referdata->refer_to_urioption));
14205    }
14206 
14207    if ((ptr = strchr(refer_to, ';')))  /* Remove options */
14208       *ptr = '\0';
14209    ast_copy_string(referdata->refer_to, refer_to, sizeof(referdata->refer_to));
14210    
14211    if (referred_by_uri) {
14212       if ((ptr = strchr(referred_by_uri, ';')))    /* Remove options */
14213          *ptr = '\0';
14214       ast_copy_string(referdata->referred_by, referred_by_uri, sizeof(referdata->referred_by));
14215    } else {
14216       referdata->referred_by[0] = '\0';
14217    }
14218 
14219    /* Determine transfer context */
14220    if (transferer->owner)  /* Mimic behaviour in res_features.c */
14221       transfer_context = pbx_builtin_getvar_helper(transferer->owner, "TRANSFER_CONTEXT");
14222 
14223    /* By default, use the context in the channel sending the REFER */
14224    if (ast_strlen_zero(transfer_context)) {
14225       transfer_context = S_OR(transferer->owner->macrocontext,
14226                S_OR(transferer->context, sip_cfg.default_context));
14227    }
14228 
14229    ast_copy_string(referdata->refer_to_context, transfer_context, sizeof(referdata->refer_to_context));
14230    
14231    /* Either an existing extension or the parking extension */
14232    if (referdata->attendedtransfer || ast_exists_extension(NULL, transfer_context, refer_to, 1, NULL) ) {
14233       if (sip_debug_test_pvt(transferer)) {
14234          ast_verbose("SIP transfer to extension %s@%s by %s\n", refer_to, transfer_context, referred_by_uri);
14235       }
14236       /* We are ready to transfer to the extension */
14237       return 0;
14238    } 
14239    if (sip_debug_test_pvt(transferer))
14240       ast_verbose("Failed SIP Transfer to non-existing extension %s in context %s\n n", refer_to, transfer_context);
14241 
14242    /* Failure, we can't find this extension */
14243    return -1;
14244 }
14245 
14246 
14247 /*! \brief Call transfer support (old way, deprecated by the IETF)
14248  * \note does not account for SIPS: uri requirements, nor check transport
14249  */
14250 static int get_also_info(struct sip_pvt *p, struct sip_request *oreq)
14251 {
14252    char tmp[256] = "", *c, *a;
14253    struct sip_request *req = oreq ? oreq : &p->initreq;
14254    struct sip_refer *referdata = NULL;
14255    const char *transfer_context = NULL;
14256    
14257    if (!p->refer && !sip_refer_allocate(p))
14258       return -1;
14259 
14260    referdata = p->refer;
14261 
14262    ast_copy_string(tmp, get_header(req, "Also"), sizeof(tmp));
14263    c = get_in_brackets(tmp);
14264 
14265    if (sip_cfg.pedanticsipchecking)
14266       ast_uri_decode(c);
14267 
14268    if (!strncasecmp(c, "sip:", 4)) {
14269       c += 4;
14270    } else if (!strncasecmp(c, "sips:", 5)) {
14271       c += 5;
14272    } else {
14273       ast_log(LOG_WARNING, "Huh?  Not a SIP header in Also: transfer (%s)?\n", c);
14274       return -1;
14275    }
14276 
14277    if ((a = strchr(c, ';')))  /* Remove arguments */
14278       *a = '\0';
14279    
14280    if ((a = strchr(c, '@'))) {   /* Separate Domain */
14281       *a++ = '\0';
14282       ast_copy_string(referdata->refer_to_domain, a, sizeof(referdata->refer_to_domain));
14283    }
14284    
14285    if (sip_debug_test_pvt(p))
14286       ast_verbose("Looking for %s in %s\n", c, p->context);
14287 
14288    if (p->owner)  /* Mimic behaviour in res_features.c */
14289       transfer_context = pbx_builtin_getvar_helper(p->owner, "TRANSFER_CONTEXT");
14290 
14291    /* By default, use the context in the channel sending the REFER */
14292    if (ast_strlen_zero(transfer_context)) {
14293       transfer_context = S_OR(p->owner->macrocontext,
14294                S_OR(p->context, sip_cfg.default_context));
14295    }
14296    if (ast_exists_extension(NULL, transfer_context, c, 1, NULL)) {
14297       /* This is a blind transfer */
14298       ast_debug(1, "SIP Bye-also transfer to Extension %s@%s \n", c, transfer_context);
14299       ast_copy_string(referdata->refer_to, c, sizeof(referdata->refer_to));
14300       ast_copy_string(referdata->referred_by, "", sizeof(referdata->referred_by));
14301       ast_copy_string(referdata->refer_contact, "", sizeof(referdata->refer_contact));
14302       referdata->refer_call = dialog_unref(referdata->refer_call, "unreffing referdata->refer_call");
14303       /* Set new context */
14304       ast_string_field_set(p, context, transfer_context);
14305       return 0;
14306    } else if (ast_canmatch_extension(NULL, p->context, c, 1, NULL)) {
14307       return 1;
14308    }
14309 
14310    return -1;
14311 }
14312 
14313 /*! \brief check received= and rport= in a SIP response.
14314  * If we get a response with received= and/or rport= in the Via:
14315  * line, use them as 'p->ourip' (see RFC 3581 for rport,
14316  * and RFC 3261 for received).
14317  * Using these two fields SIP can produce the correct
14318  * address and port in the SIP headers without the need for STUN.
14319  * The address part is also reused for the media sessions.
14320  * Note that ast_sip_ouraddrfor() still rewrites p->ourip
14321  * if you specify externip/seternaddr/stunaddr.
14322  */
14323 static attribute_unused void check_via_response(struct sip_pvt *p, struct sip_request *req)
14324 {
14325    char via[256];
14326    char *cur, *opts;
14327 
14328    ast_copy_string(via, get_header(req, "Via"), sizeof(via));
14329 
14330    /* Work on the leftmost value of the topmost Via header */
14331    opts = strchr(via, ',');
14332    if (opts)
14333       *opts = '\0';
14334 
14335    /* parse all relevant options */
14336    opts = strchr(via, ';');
14337    if (!opts)
14338       return;  /* no options to parse */
14339    *opts++ = '\0';
14340    while ( (cur = strsep(&opts, ";")) ) {
14341       if (!strncmp(cur, "rport=", 6)) {
14342          int port = strtol(cur+6, NULL, 10);
14343          /* XXX add error checking */
14344          p->ourip.sin_port = ntohs(port);
14345       } else if (!strncmp(cur, "received=", 9)) {
14346          if (ast_parse_arg(cur+9, PARSE_INADDR, &p->ourip))
14347             ;  /* XXX add error checking */
14348       }
14349    }
14350 }
14351 
14352 /*! \brief check Via: header for hostname, port and rport request/answer */
14353 static void check_via(struct sip_pvt *p, struct sip_request *req)
14354 {
14355    char via[512];
14356    char *c, *pt, *maddr;
14357    struct hostent *hp;
14358    struct ast_hostent ahp;
14359 
14360    ast_copy_string(via, get_header(req, "Via"), sizeof(via));
14361 
14362    /* Work on the leftmost value of the topmost Via header */
14363    c = strchr(via, ',');
14364    if (c)
14365       *c = '\0';
14366 
14367    /* Check for rport */
14368    c = strstr(via, ";rport");
14369    if (c && (c[6] != '=')) /* rport query, not answer */
14370       ast_set_flag(&p->flags[1], SIP_PAGE2_RPORT_PRESENT);
14371 
14372    /* Check for maddr */
14373    maddr = strstr(via, "maddr=");
14374    if (maddr) {
14375       maddr += 6;
14376       c = maddr + strspn(maddr, "0123456789.");
14377       *c = '\0';
14378    }
14379 
14380    c = strchr(via, ';');
14381    if (c)
14382       *c = '\0';
14383 
14384    c = strchr(via, ' ');
14385    if (c) {
14386       *c = '\0';
14387       c = ast_skip_blanks(c+1);
14388       if (strcasecmp(via, "SIP/2.0/UDP") && strcasecmp(via, "SIP/2.0/TCP") && strcasecmp(via, "SIP/2.0/TLS")) {
14389          ast_log(LOG_WARNING, "Don't know how to respond via '%s'\n", via);
14390          return;
14391       }
14392       pt = strchr(c, ':');
14393       if (pt)
14394          *pt++ = '\0';  /* remember port pointer */
14395       /* Use maddr if found */
14396       if (maddr)
14397          c = maddr;
14398       hp = ast_gethostbyname(c, &ahp);
14399       if (!hp) {
14400          ast_log(LOG_WARNING, "'%s' is not a valid host\n", c);
14401          return;
14402       }
14403       memset(&p->sa, 0, sizeof(p->sa));
14404       p->sa.sin_family = AF_INET;
14405       memcpy(&p->sa.sin_addr, hp->h_addr, sizeof(p->sa.sin_addr));
14406       p->sa.sin_port = htons(port_str2int(pt, STANDARD_SIP_PORT));
14407 
14408       if (sip_debug_test_pvt(p)) {
14409          const struct sockaddr_in *dst = sip_real_dst(p);
14410          ast_verbose("Sending to %s : %d (%s)\n", ast_inet_ntoa(dst->sin_addr), ntohs(dst->sin_port), sip_nat_mode(p));
14411       }
14412    }
14413 }
14414 
14415 /*! \brief  Get caller id name from SIP headers */
14416 static char *get_calleridname(const char *input, char *output, size_t outputsize)
14417 {
14418    const char *end = strchr(input, '<');  /* first_bracket */
14419    const char *tmp = strchr(input, '"');  /* first quote */
14420    int bytes = 0;
14421    int maxbytes = outputsize - 1;
14422 
14423    if (!end || end == input)  /* we require a part in brackets */
14424       return NULL;
14425 
14426    end--; /* move just before "<" */
14427 
14428    if (tmp && tmp <= end) {
14429       /* The quote (tmp) precedes the bracket (end+1).
14430        * Find the matching quote and return the content.
14431        */
14432       end = strchr(tmp+1, '"');
14433       if (!end)
14434          return NULL;
14435       bytes = (int) (end - tmp);
14436       /* protect the output buffer */
14437       if (bytes > maxbytes)
14438          bytes = maxbytes;
14439       ast_copy_string(output, tmp + 1, bytes);
14440    } else {
14441       /* No quoted string, or it is inside brackets. */
14442       /* clear the empty characters in the begining*/
14443       input = ast_skip_blanks(input);
14444       /* clear the empty characters in the end */
14445       while(*end && *end < 33 && end > input)
14446          end--;
14447       if (end >= input) {
14448          bytes = (int) (end - input) + 2;
14449          /* protect the output buffer */
14450          if (bytes > maxbytes)
14451             bytes = maxbytes;
14452          ast_copy_string(output, input, bytes);
14453       } else
14454          return NULL;
14455    }
14456    return output;
14457 }
14458 
14459 /*! \brief  Get caller id number from Remote-Party-ID header field 
14460  * Returns true if number should be restricted (privacy setting found)
14461  * output is set to NULL if no number found
14462  */
14463 static int get_rpid_num(const char *input, char *output, int maxlen)
14464 {
14465    char *start;
14466    char *end;
14467 
14468    start = strchr(input, ':');
14469    if (!start) {
14470       output[0] = '\0';
14471       return 0;
14472    }
14473    start++;
14474 
14475    /* we found "number" */
14476    ast_copy_string(output, start, maxlen);
14477    output[maxlen-1] = '\0';
14478 
14479    end = strchr(output, '@');
14480    if (end)
14481       *end = '\0';
14482    else
14483       output[0] = '\0';
14484    if (strstr(input, "privacy=full") || strstr(input, "privacy=uri"))
14485       return AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED;
14486 
14487    return 0;
14488 }
14489 
14490 
14491 /*! \brief helper function for check_{user|peer}_ok() */
14492 static void replace_cid(struct sip_pvt *p, const char *rpid_num, const char *calleridname)
14493 {
14494    /* replace callerid if rpid found, and not restricted */
14495    if (!ast_strlen_zero(rpid_num) && ast_test_flag(&p->flags[0], SIP_TRUSTRPID)) {
14496       char *tmp = ast_strdupa(rpid_num); /* XXX the copy can be done later */
14497       if (!ast_strlen_zero(calleridname))
14498          ast_string_field_set(p, cid_name, calleridname);
14499       if (global_shrinkcallerid && ast_is_shrinkable_phonenumber(tmp))
14500          ast_shrink_phone_number(tmp);
14501       ast_string_field_set(p, cid_num, tmp);
14502    }
14503 }
14504 
14505 /*! \brief Validate device authentication */
14506 static enum check_auth_result check_peer_ok(struct sip_pvt *p, char *of,
14507    struct sip_request *req, int sipmethod, struct sockaddr_in *sin,
14508    struct sip_peer **authpeer,
14509    enum xmittype reliable,
14510    char *rpid_num, char *calleridname, char *uri2)
14511 {
14512    enum check_auth_result res;
14513    int debug=sip_debug_test_addr(sin);
14514    struct sip_peer *peer;
14515 
14516    if (sipmethod == SIP_SUBSCRIBE) {
14517       /* For subscribes, match on device name only; for other methods,
14518       * match on IP address-port of the incoming request.
14519       */
14520       peer = find_peer(of, NULL, TRUE, FINDALLDEVICES, FALSE, 0);
14521    } else {
14522       /* First find devices based on username (avoid all type=peer's) */
14523       peer = find_peer(of, NULL, TRUE, FINDUSERS, FALSE, 0);
14524 
14525       /* Then find devices based on IP */
14526       if (!peer) {
14527          peer = find_peer(NULL, &p->recv, TRUE, FINDPEERS, FALSE, p->socket.type);
14528       }
14529    }
14530 
14531    if (!peer) {
14532       if (debug)
14533          ast_verbose("No matching peer for '%s' from '%s:%d'\n",
14534             of, ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
14535       return AUTH_DONT_KNOW;
14536    }
14537    if (!ast_apply_ha(peer->ha, sin)) {
14538       ast_debug(2, "Found peer '%s' for '%s', but fails host access\n", peer->name, of);
14539       unref_peer(peer, "unref_peer: check_peer_ok: from find_peer call, early return of AUTH_ACL_FAILED");
14540       return AUTH_ACL_FAILED;
14541    }
14542    if (debug)
14543       ast_verbose("Found peer '%s' for '%s' from %s:%d\n",
14544          peer->name, of, ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
14545 
14546    /* XXX what about p->prefs = peer->prefs; ? */
14547    /* Set Frame packetization */
14548    if (p->rtp) {
14549       ast_rtp_codec_setpref(p->rtp, &peer->prefs);
14550       p->autoframing = peer->autoframing;
14551    }
14552 
14553    /* Take the peer */
14554    ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
14555    ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
14556 
14557    if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) && p->udptl) {
14558       p->t38_maxdatagram = peer->t38_maxdatagram;
14559       set_t38_capabilities(p);
14560    }
14561 
14562    /* Copy SIP extensions profile to peer */
14563    /* XXX is this correct before a successful auth ? */
14564    if (p->sipoptions)
14565       peer->sipoptions = p->sipoptions;
14566 
14567    replace_cid(p, rpid_num, calleridname);
14568    do_setnat(p, ast_test_flag(&p->flags[0], SIP_NAT_ROUTE));
14569 
14570    ast_string_field_set(p, peersecret, peer->secret);
14571    ast_string_field_set(p, peermd5secret, peer->md5secret);
14572    ast_string_field_set(p, subscribecontext, peer->subscribecontext);
14573    ast_string_field_set(p, mohinterpret, peer->mohinterpret);
14574    ast_string_field_set(p, mohsuggest, peer->mohsuggest);
14575    ast_string_field_set(p, parkinglot, peer->parkinglot);
14576    if (peer->callingpres)  /* Peer calling pres setting will override RPID */
14577       p->callingpres = peer->callingpres;
14578    if (peer->maxms && peer->lastms)
14579       p->timer_t1 = peer->lastms < global_t1min ? global_t1min : peer->lastms;
14580    else
14581       p->timer_t1 = peer->timer_t1;
14582  
14583    /* Set timer B to control transaction timeouts */
14584    if (peer->timer_b)
14585       p->timer_b = peer->timer_b;
14586    else
14587       p->timer_b = 64 * p->timer_t1;
14588  
14589    if (ast_test_flag(&peer->flags[0], SIP_INSECURE_INVITE)) {
14590       /* Pretend there is no required authentication */
14591       ast_string_field_set(p, peersecret, NULL);
14592       ast_string_field_set(p, peermd5secret, NULL);
14593    }
14594    if (!(res = check_auth(p, req, peer->name, p->peersecret, p->peermd5secret, sipmethod, uri2, reliable, req->ignore))) {
14595       ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
14596       ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
14597       /* If we have a call limit, set flag */
14598       if (peer->call_limit)
14599          ast_set_flag(&p->flags[0], SIP_CALL_LIMIT);
14600       ast_string_field_set(p, peername, peer->name);
14601       ast_string_field_set(p, authname, peer->name);
14602 
14603       if (sipmethod == SIP_INVITE) {
14604          /* copy channel vars */
14605          p->chanvars = copy_vars(peer->chanvars);
14606       }
14607 
14608       if (authpeer) {
14609          ao2_t_ref(peer, 1, "copy pointer into (*authpeer)");
14610          (*authpeer) = peer;  /* Add a ref to the object here, to keep it in memory a bit longer if it is realtime */
14611       }
14612 
14613       if (!ast_strlen_zero(peer->username)) {
14614          ast_string_field_set(p, username, peer->username);
14615          /* Use the default username for authentication on outbound calls */
14616          /* XXX this takes the name from the caller... can we override ? */
14617          ast_string_field_set(p, authname, peer->username);
14618       }
14619       if (!ast_strlen_zero(peer->cid_num)) {
14620          char *tmp = ast_strdupa(peer->cid_num);
14621          if (global_shrinkcallerid && ast_is_shrinkable_phonenumber(tmp))
14622             ast_shrink_phone_number(tmp);
14623          ast_string_field_set(p, cid_num, tmp);
14624       }
14625       if (!ast_strlen_zero(peer->cid_name)) 
14626          ast_string_field_set(p, cid_name, peer->cid_name);
14627       ast_string_field_set(p, fullcontact, peer->fullcontact);
14628       if (!ast_strlen_zero(peer->context))
14629          ast_string_field_set(p, context, peer->context);
14630       ast_string_field_set(p, peersecret, peer->secret);
14631       ast_string_field_set(p, peermd5secret, peer->md5secret);
14632       ast_string_field_set(p, language, peer->language);
14633       ast_string_field_set(p, accountcode, peer->accountcode);
14634       p->amaflags = peer->amaflags;
14635       p->callgroup = peer->callgroup;
14636       p->pickupgroup = peer->pickupgroup;
14637       p->capability = peer->capability;
14638       p->prefs = peer->prefs;
14639       p->jointcapability = peer->capability;
14640       if (p->peercapability)
14641          p->jointcapability &= p->peercapability;
14642       p->maxcallbitrate = peer->maxcallbitrate;
14643       if (!ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS) &&
14644             (!ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT) ||
14645                !(p->capability & AST_FORMAT_VIDEO_MASK)) &&
14646             p->vrtp) {
14647          ast_rtp_destroy(p->vrtp);
14648          p->vrtp = NULL;
14649       }
14650       if ((!ast_test_flag(&p->flags[1], SIP_PAGE2_TEXTSUPPORT) || !(p->capability & AST_FORMAT_TEXT_MASK)) && p->trtp) {
14651          ast_rtp_destroy(p->trtp);
14652          p->trtp = NULL;
14653       }
14654       if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
14655           (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
14656          p->noncodeccapability |= AST_RTP_DTMF;
14657       else
14658          p->noncodeccapability &= ~AST_RTP_DTMF;
14659       p->jointnoncodeccapability = p->noncodeccapability;
14660    }
14661    unref_peer(peer, "check_peer_ok: unref_peer: tossing temp ptr to peer from find_peer");
14662    return res;
14663 }
14664 
14665 
14666 /*! \brief  Check if matching user or peer is defined 
14667    Match user on From: user name and peer on IP/port
14668    This is used on first invite (not re-invites) and subscribe requests 
14669     \return 0 on success, non-zero on failure
14670 */
14671 static enum check_auth_result check_user_full(struct sip_pvt *p, struct sip_request *req,
14672                      int sipmethod, char *uri, enum xmittype reliable,
14673                      struct sockaddr_in *sin, struct sip_peer **authpeer)
14674 {
14675    char from[256];
14676    char *dummy;   /* dummy return value for parse_uri */
14677    char *domain;  /* dummy return value for parse_uri */
14678    char *of;
14679    char rpid_num[50];
14680    const char *rpid;
14681    enum check_auth_result res;
14682    char calleridname[50];
14683    char *uri2 = ast_strdupa(uri);
14684 
14685    terminate_uri(uri2); /* trim extra stuff */
14686 
14687    ast_copy_string(from, get_header(req, "From"), sizeof(from));
14688    if (sip_cfg.pedanticsipchecking)
14689       ast_uri_decode(from);
14690    /* XXX here tries to map the username for invite things */
14691    memset(calleridname, 0, sizeof(calleridname));
14692    get_calleridname(from, calleridname, sizeof(calleridname));
14693    if (calleridname[0])
14694       ast_string_field_set(p, cid_name, calleridname);
14695 
14696    rpid = get_header(req, "Remote-Party-ID");
14697    memset(rpid_num, 0, sizeof(rpid_num));
14698    if (!ast_strlen_zero(rpid)) 
14699       p->callingpres = get_rpid_num(rpid, rpid_num, sizeof(rpid_num));
14700 
14701    of = get_in_brackets(from);
14702    if (ast_strlen_zero(p->exten)) {
14703       char *t = uri2;
14704       if (!strncasecmp(t, "sip:", 4))
14705          t+= 4;
14706       else if (!strncasecmp(t, "sips:", 5))
14707          t += 5;
14708       ast_string_field_set(p, exten, t);
14709       t = strchr(p->exten, '@');
14710       if (t)
14711          *t = '\0';
14712       if (ast_strlen_zero(p->our_contact))
14713          build_contact(p);
14714    }
14715    /* save the URI part of the From header */
14716    ast_string_field_set(p, from, of);
14717 
14718    /* ignore all fields but name */
14719    if (parse_uri(of, "sip:,sips:", &of, &dummy, &domain, &dummy, &dummy, NULL)) {
14720       ast_log(LOG_NOTICE, "From address missing 'sip:', using it anyway\n");
14721    }
14722 
14723    if (ast_strlen_zero(of)) {
14724       /* XXX note: the original code considered a missing @host
14725        * as a username-only URI. The SIP RFC (19.1.1) says that
14726        * this is wrong, and it should be considered as a domain-only URI.
14727        * For backward compatibility, we keep this block, but it is
14728        * really a mistake and should go away.
14729        */
14730       of = domain;
14731    } else {
14732       char *tmp = ast_strdupa(of);
14733       /* We need to be able to handle auth-headers looking like
14734          <sip:8164444422;phone-context=+1@1.2.3.4:5060;user=phone;tag=SDadkoa01-gK0c3bdb43>
14735       */
14736       tmp = strsep(&tmp, ";");
14737       if (global_shrinkcallerid && ast_is_shrinkable_phonenumber(tmp))
14738          ast_shrink_phone_number(tmp);
14739       ast_string_field_set(p, cid_num, tmp);
14740    }
14741 
14742    if (global_match_auth_username) {
14743       /*
14744        * XXX This is experimental code to grab the search key from the
14745        * Auth header's username instead of the 'From' name, if available.
14746        * Do not enable this block unless you understand the side effects (if any!)
14747        * Note, the search for "username" should be done in a more robust way.
14748        * Note2, at the moment we check both fields, though maybe we should
14749        * pick one or another depending on the request ? XXX
14750        */
14751       const char *hdr = get_header(req, "Authorization");
14752       if (ast_strlen_zero(hdr))
14753          hdr = get_header(req, "Proxy-Authorization");
14754 
14755       if ( !ast_strlen_zero(hdr) && (hdr = strstr(hdr, "username=\"")) ) {
14756          ast_copy_string(from, hdr + strlen("username=\""), sizeof(from));
14757          of = from;
14758          of = strsep(&of, "\"");
14759       }
14760    }
14761 
14762    res = check_peer_ok(p, of, req, sipmethod, sin,
14763          authpeer, reliable, rpid_num, calleridname, uri2);
14764    if (res != AUTH_DONT_KNOW)
14765       return res;
14766 
14767    /* Finally, apply the guest policy */
14768    if (sip_cfg.allowguest) {
14769       replace_cid(p, rpid_num, calleridname);
14770       res = AUTH_SUCCESSFUL;
14771    } else if (sip_cfg.alwaysauthreject)
14772       res = AUTH_FAKE_AUTH; /* reject with fake authorization request */
14773    else
14774       res = AUTH_SECRET_FAILED; /* we don't want any guests, authentication will fail */
14775 
14776 
14777    if (ast_test_flag(&p->flags[1], SIP_PAGE2_RPORT_PRESENT)) {
14778       ast_set_flag(&p->flags[0], SIP_NAT_ROUTE);
14779    }
14780 
14781    return res;
14782 }
14783 
14784 /*! \brief  Find user 
14785    If we get a match, this will add a reference pointer to the user object in ASTOBJ, that needs to be unreferenced
14786 */
14787 static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, char *uri, enum xmittype reliable, struct sockaddr_in *sin)
14788 {
14789    return check_user_full(p, req, sipmethod, uri, reliable, sin, NULL);
14790 }
14791 
14792 /*! \brief  Get text out of a SIP MESSAGE packet */
14793 static int get_msg_text(char *buf, int len, struct sip_request *req, int addnewline)
14794 {
14795    int x;
14796    int y;
14797 
14798    buf[0] = '\0';
14799    /*XXX isn't strlen(buf) going to always be 0? */
14800    y = len - strlen(buf) - 5;
14801    if (y < 0)
14802       y = 0;
14803    for (x = 0; x < req->lines; x++) {
14804       char *line = REQ_OFFSET_TO_STR(req, line[x]);
14805       strncat(buf, line, y); /* safe */
14806       y -= strlen(line) + 1;
14807       if (y < 0)
14808          y = 0;
14809       if (y != 0 && addnewline)
14810          strcat(buf, "\n"); /* safe */
14811    }
14812    return 0;
14813 }
14814 
14815 
14816 /*! \brief  Receive SIP MESSAGE method messages
14817 \note We only handle messages within current calls currently 
14818    Reference: RFC 3428 */
14819 static void receive_message(struct sip_pvt *p, struct sip_request *req)
14820 {
14821    char buf[1400];   
14822    struct ast_frame f;
14823    const char *content_type = get_header(req, "Content-Type");
14824 
14825    if (strncmp(content_type, "text/plain", strlen("text/plain"))) { /* No text/plain attachment */
14826       transmit_response(p, "415 Unsupported Media Type", req); /* Good enough, or? */
14827       if (!p->owner)
14828          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14829       return;
14830    }
14831 
14832    if (get_msg_text(buf, sizeof(buf), req, FALSE)) {
14833       ast_log(LOG_WARNING, "Unable to retrieve text from %s\n", p->callid);
14834       transmit_response(p, "202 Accepted", req);
14835       if (!p->owner)
14836          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14837       return;
14838    }
14839 
14840    if (p->owner) {
14841       if (sip_debug_test_pvt(p))
14842          ast_verbose("SIP Text message received: '%s'\n", buf);
14843       memset(&f, 0, sizeof(f));
14844       f.frametype = AST_FRAME_TEXT;
14845       f.subclass = 0;
14846       f.offset = 0;
14847       f.data.ptr = buf;
14848       f.datalen = strlen(buf) + 1;
14849       ast_queue_frame(p->owner, &f);
14850       transmit_response(p, "202 Accepted", req); /* We respond 202 accepted, since we relay the message */
14851       return;
14852    }
14853 
14854    /* Message outside of a call, we do not support that */
14855    ast_log(LOG_WARNING, "Received message to %s from %s, dropped it...\n  Content-Type:%s\n  Message: %s\n", get_header(req, "To"), get_header(req, "From"), content_type, buf);
14856    transmit_response(p, "405 Method Not Allowed", req);
14857    sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14858    return;
14859 }
14860 
14861 /*! \brief  CLI Command to show calls within limits set by call_limit */
14862 static char *sip_show_inuse(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14863 {
14864 #define FORMAT "%-25.25s %-15.15s %-15.15s \n"
14865 #define FORMAT2 "%-25.25s %-15.15s %-15.15s \n"
14866    char ilimits[40];
14867    char iused[40];
14868    int showall = FALSE;
14869    struct ao2_iterator i;
14870    struct sip_peer *peer;
14871    
14872    switch (cmd) {
14873    case CLI_INIT:
14874       e->command = "sip show inuse";
14875       e->usage =
14876          "Usage: sip show inuse [all]\n"
14877          "       List all SIP devices usage counters and limits.\n"
14878          "       Add option \"all\" to show all devices, not only those with a limit.\n";
14879       return NULL;
14880    case CLI_GENERATE:
14881       return NULL;
14882    }
14883 
14884    if (a->argc < 3) 
14885       return CLI_SHOWUSAGE;
14886 
14887    if (a->argc == 4 && !strcmp(a->argv[3], "all")) 
14888       showall = TRUE;
14889    
14890    ast_cli(a->fd, FORMAT, "* Peer name", "In use", "Limit");
14891 
14892    i = ao2_iterator_init(peers, 0);
14893    while ((peer = ao2_t_iterator_next(&i, "iterate thru peer table"))) {
14894       ao2_lock(peer);
14895       if (peer->call_limit)
14896          snprintf(ilimits, sizeof(ilimits), "%d", peer->call_limit);
14897       else 
14898          ast_copy_string(ilimits, "N/A", sizeof(ilimits));
14899       snprintf(iused, sizeof(iused), "%d/%d/%d", peer->inUse, peer->inRinging, peer->onHold);
14900       if (showall || peer->call_limit)
14901          ast_cli(a->fd, FORMAT2, peer->name, iused, ilimits);
14902       ao2_unlock(peer);
14903       unref_peer(peer, "toss iterator pointer");
14904    }
14905    ao2_iterator_destroy(&i);
14906 
14907    return CLI_SUCCESS;
14908 #undef FORMAT
14909 #undef FORMAT2
14910 }
14911 
14912 
14913 /*! \brief Convert transfer mode to text string */
14914 static char *transfermode2str(enum transfermodes mode)
14915 {
14916    if (mode == TRANSFER_OPENFORALL)
14917       return "open";
14918    else if (mode == TRANSFER_CLOSED)
14919       return "closed";
14920    return "strict";
14921 }
14922 
14923 static struct _map_x_s natmodes[] = {
14924    { SIP_NAT_NEVER,        "No"},
14925    { SIP_NAT_ROUTE,        "Route"},
14926    { SIP_NAT_ALWAYS,       "Always"},
14927    { SIP_NAT_RFC3581,      "RFC3581"},
14928    { -1,                   NULL}, /* terminator */
14929 };
14930 
14931 /*! \brief  Convert NAT setting to text string */
14932 static const char *nat2str(int nat)
14933 {
14934    return map_x_s(natmodes, nat, "Unknown");
14935 }
14936 
14937 #ifdef NOTUSED
14938 /* OEJ: This is not used, but may be useful in the future, so I don't want to 
14939    delete it. Keeping it enabled generates compiler warnings.
14940  */
14941 
14942 static struct _map_x_s natcfgmodes[] = {
14943    { SIP_NAT_NEVER,        "never"},
14944    { SIP_NAT_ROUTE,        "route"},
14945    { SIP_NAT_ALWAYS,       "yes"},
14946    { SIP_NAT_RFC3581,      "no"},
14947    { -1,                   NULL}, /* terminator */
14948 };
14949 
14950 /*! \brief  Convert NAT setting to text string appropriate for config files */
14951 static const char *nat2strconfig(int nat)
14952 {
14953    return map_x_s(natcfgmodes, nat, "Unknown");
14954 }
14955 #endif
14956 
14957 /*! \brief  Report Peer status in character string
14958  *  \return 0 if peer is unreachable, 1 if peer is online, -1 if unmonitored
14959  */
14960 
14961 
14962 /* Session-Timer Modes */
14963 static struct _map_x_s stmodes[] = {
14964         { SESSION_TIMER_MODE_ACCEPT,    "Accept"},
14965         { SESSION_TIMER_MODE_ORIGINATE, "Originate"},
14966         { SESSION_TIMER_MODE_REFUSE,    "Refuse"},
14967         { -1,                           NULL},
14968 };
14969 
14970 static const char *stmode2str(enum st_mode m)
14971 {
14972    return map_x_s(stmodes, m, "Unknown");
14973 }
14974 
14975 static enum st_mode str2stmode(const char *s)
14976 {
14977    return map_s_x(stmodes, s, -1);
14978 }
14979 
14980 /* Session-Timer Refreshers */
14981 static struct _map_x_s strefreshers[] = {
14982         { SESSION_TIMER_REFRESHER_AUTO,     "auto"},
14983         { SESSION_TIMER_REFRESHER_UAC,      "uac"},
14984         { SESSION_TIMER_REFRESHER_UAS,      "uas"},
14985         { -1,                               NULL},
14986 };
14987 
14988 static const char *strefresher2str(enum st_refresher r)
14989 {
14990    return map_x_s(strefreshers, r, "Unknown");
14991 }
14992 
14993 static enum st_refresher str2strefresher(const char *s)
14994 {
14995    return map_s_x(strefreshers, s, -1);
14996 }
14997 
14998 
14999 static int peer_status(struct sip_peer *peer, char *status, int statuslen)
15000 {
15001    int res = 0;
15002    if (peer->maxms) {
15003       if (peer->lastms < 0) {
15004          ast_copy_string(status, "UNREACHABLE", statuslen);
15005       } else if (peer->lastms > peer->maxms) {
15006          snprintf(status, statuslen, "LAGGED (%d ms)", peer->lastms);
15007          res = 1;
15008       } else if (peer->lastms) {
15009          snprintf(status, statuslen, "OK (%d ms)", peer->lastms);
15010          res = 1;
15011       } else {
15012          ast_copy_string(status, "UNKNOWN", statuslen);
15013       }
15014    } else { 
15015       ast_copy_string(status, "Unmonitored", statuslen);
15016       /* Checking if port is 0 */
15017       res = -1;
15018    }
15019    return res;
15020 }
15021 
15022 /*! \brief return Yes or No depending on the argument.
15023  * This is used in many places in CLI command, having a function to generate
15024  * this helps maintaining a consistent output (and possibly emitting the
15025  * output in other languages, at some point).
15026  */
15027 static const char *cli_yesno(int x)
15028 {
15029    return x ? "Yes" : "No";
15030 }
15031 
15032 /*! \brief  Show active TCP connections */
15033 static char *sip_show_tcp(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15034 {
15035    struct sip_threadinfo *th;
15036    struct ao2_iterator i;
15037 
15038 #define FORMAT2 "%-30.30s %3.6s %9.9s %6.6s\n"
15039 #define FORMAT  "%-30.30s %-6d %-9.9s %-6.6s\n"
15040 
15041    switch (cmd) {
15042    case CLI_INIT:
15043       e->command = "sip show tcp";
15044       e->usage =
15045          "Usage: sip show tcp\n"
15046          "       Lists all active TCP/TLS sessions.\n";
15047       return NULL;
15048    case CLI_GENERATE:
15049       return NULL;
15050    }
15051 
15052    if (a->argc != 3)
15053       return CLI_SHOWUSAGE;
15054 
15055    ast_cli(a->fd, FORMAT2, "Host", "Port", "Transport", "Type");
15056    i = ao2_iterator_init(threadt, 0);
15057    while ((th = ao2_t_iterator_next(&i, "iterate through tcp threads for 'sip show tcp'"))) {
15058       ast_cli(a->fd, FORMAT, ast_inet_ntoa(th->tcptls_session->remote_address.sin_addr), 
15059          ntohs(th->tcptls_session->remote_address.sin_port), 
15060          get_transport(th->type), 
15061          (th->tcptls_session->client ? "Client" : "Server"));
15062       ao2_t_ref(th, -1, "decrement ref from iterator");
15063    }
15064    ao2_iterator_destroy(&i);
15065    return CLI_SUCCESS;
15066 #undef FORMAT
15067 #undef FORMAT2
15068 }
15069 
15070 /*! \brief  CLI Command 'SIP Show Users' */
15071 static char *sip_show_users(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15072 {
15073    regex_t regexbuf;
15074    int havepattern = FALSE;
15075    struct ao2_iterator user_iter;
15076    struct sip_peer *user;
15077 
15078 #define FORMAT  "%-25.25s  %-15.15s  %-15.15s  %-15.15s  %-5.5s%-10.10s\n"
15079 
15080    switch (cmd) {
15081    case CLI_INIT:
15082       e->command = "sip show users";
15083       e->usage =
15084          "Usage: sip show users [like <pattern>]\n"
15085          "       Lists all known SIP users.\n"
15086          "       Optional regular expression pattern is used to filter the user list.\n";
15087       return NULL;
15088    case CLI_GENERATE:
15089       return NULL;
15090    }
15091 
15092    switch (a->argc) {
15093    case 5:
15094       if (!strcasecmp(a->argv[3], "like")) {
15095          if (regcomp(&regexbuf, a->argv[4], REG_EXTENDED | REG_NOSUB))
15096             return CLI_SHOWUSAGE;
15097          havepattern = TRUE;
15098       } else
15099          return CLI_SHOWUSAGE;
15100    case 3:
15101       break;
15102    default:
15103       return CLI_SHOWUSAGE;
15104    }
15105 
15106    ast_cli(a->fd, FORMAT, "Username", "Secret", "Accountcode", "Def.Context", "ACL", "NAT");
15107 
15108    user_iter = ao2_iterator_init(peers, 0);
15109    while ((user = ao2_iterator_next(&user_iter))) {
15110       ao2_lock(user);
15111       if (!(user->type & SIP_TYPE_USER)) {
15112          ao2_unlock(user);
15113          unref_peer(user, "sip show users");
15114          continue;
15115       }
15116 
15117       if (havepattern && regexec(&regexbuf, user->name, 0, NULL, 0)) {
15118          ao2_unlock(user);
15119          unref_peer(user, "sip show users");
15120          continue;
15121       }
15122 
15123       ast_cli(a->fd, FORMAT, user->name, 
15124          user->secret, 
15125          user->accountcode,
15126          user->context,
15127          cli_yesno(user->ha != NULL),
15128          nat2str(ast_test_flag(&user->flags[0], SIP_NAT)));
15129       ao2_unlock(user);
15130       unref_peer(user, "sip show users");
15131    }
15132    ao2_iterator_destroy(&user_iter);
15133 
15134    if (havepattern)
15135       regfree(&regexbuf);
15136 
15137    return CLI_SUCCESS;
15138 #undef FORMAT
15139 }
15140 
15141 /*! \brief Manager Action SIPShowRegistry description */
15142 static char mandescr_show_registry[] =
15143 "Description: Lists all registration requests and status\n"
15144 "Registrations will follow as separate events. followed by a final event called\n"
15145 "RegistrationsComplete.\n"
15146 "Variables: \n"
15147 "  ActionID: <id>       Action ID for this transaction. Will be returned.\n";
15148 
15149 /*! \brief Show SIP registrations in the manager API */
15150 static int manager_show_registry(struct mansession *s, const struct message *m)
15151 {
15152    const char *id = astman_get_header(m, "ActionID");
15153    char idtext[256] = "";
15154    int total = 0;
15155 
15156    if (!ast_strlen_zero(id))
15157       snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
15158 
15159    astman_send_listack(s, m, "Registrations will follow", "start");
15160 
15161    ASTOBJ_CONTAINER_TRAVERSE(&regl, 1, do {
15162       ASTOBJ_RDLOCK(iterator);
15163       astman_append(s,
15164          "Event: RegistryEntry\r\n"
15165          "%s"
15166          "Host: %s\r\n"
15167          "Port: %d\r\n"
15168          "Username: %s\r\n"
15169          "Refresh: %d\r\n"
15170          "State: %s\r\n"
15171          "RegistrationTime: %ld\r\n"
15172          "\r\n", idtext, iterator->hostname, iterator->portno ? iterator->portno : STANDARD_SIP_PORT,
15173                  iterator->username, iterator->refresh, regstate2str(iterator->regstate), (long) iterator->regtime.tv_sec);
15174       ASTOBJ_UNLOCK(iterator);
15175       total++;
15176    } while(0));
15177 
15178    astman_append(s,
15179       "Event: RegistrationsComplete\r\n"
15180       "EventList: Complete\r\n"
15181       "ListItems: %d\r\n"
15182       "%s"
15183       "\r\n", total, idtext);
15184    
15185    return 0;
15186 }
15187 
15188 static char mandescr_show_peers[] = 
15189 "Description: Lists SIP peers in text format with details on current status.\n"
15190 "Peerlist will follow as separate events, followed by a final event called\n"
15191 "PeerlistComplete.\n"
15192 "Variables: \n"
15193 "  ActionID: <id> Action ID for this transaction. Will be returned.\n";
15194 
15195 /*! \brief  Show SIP peers in the manager API */
15196 /*    Inspired from chan_iax2 */
15197 static int manager_sip_show_peers(struct mansession *s, const struct message *m)
15198 {
15199    const char *id = astman_get_header(m, "ActionID");
15200    const char *a[] = {"sip", "show", "peers"};
15201    char idtext[256] = "";
15202    int total = 0;
15203 
15204    if (!ast_strlen_zero(id))
15205       snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
15206 
15207    astman_send_listack(s, m, "Peer status list will follow", "start");
15208    /* List the peers in separate manager events */
15209    _sip_show_peers(-1, &total, s, m, 3, a);
15210    /* Send final confirmation */
15211    astman_append(s,
15212    "Event: PeerlistComplete\r\n"
15213    "EventList: Complete\r\n"
15214    "ListItems: %d\r\n"
15215    "%s"
15216    "\r\n", total, idtext);
15217    return 0;
15218 }
15219 
15220 /*! \brief  CLI Show Peers command */
15221 static char *sip_show_peers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15222 {
15223    switch (cmd) {
15224    case CLI_INIT:
15225       e->command = "sip show peers";
15226       e->usage =
15227          "Usage: sip show peers [like <pattern>]\n"
15228          "       Lists all known SIP peers.\n"
15229          "       Optional regular expression pattern is used to filter the peer list.\n";
15230       return NULL;
15231    case CLI_GENERATE:
15232       return NULL;
15233    }
15234 
15235    return _sip_show_peers(a->fd, NULL, NULL, NULL, a->argc, (const char **) a->argv);
15236 }
15237 
15238 int peercomparefunc(const void *a, const void *b);
15239 
15240 int peercomparefunc(const void *a, const void *b)
15241 {
15242    struct sip_peer **ap = (struct sip_peer **)a;
15243    struct sip_peer **bp = (struct sip_peer **)b;
15244    return strcmp((*ap)->name, (*bp)->name);
15245 }
15246 
15247 
15248 /*! \brief Execute sip show peers command */
15249 static char *_sip_show_peers(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char *argv[])
15250 {
15251    regex_t regexbuf;
15252    int havepattern = FALSE;
15253    struct sip_peer *peer;
15254    struct ao2_iterator i;
15255    
15256 /* the last argument is left-aligned, so we don't need a size anyways */
15257 #define FORMAT2 "%-25.25s  %-15.15s %-3.3s %-3.3s %-3.3s %-8s %-10s %s\n"
15258 #define FORMAT  "%-25.25s  %-15.15s %-3.3s %-3.3s %-3.3s %-8d %-10s %s\n"
15259 
15260    char name[256];
15261    int total_peers = 0;
15262    int peers_mon_online = 0;
15263    int peers_mon_offline = 0;
15264    int peers_unmon_offline = 0;
15265    int peers_unmon_online = 0;
15266    const char *id;
15267    char idtext[256] = "";
15268    int realtimepeers;
15269    int objcount = ao2_container_count(peers);
15270    struct sip_peer **peerarray;
15271    int k;
15272    
15273    
15274    realtimepeers = ast_check_realtime("sippeers");
15275    peerarray = ast_calloc(sizeof(struct sip_peer *), objcount);
15276 
15277    if (s) { /* Manager - get ActionID */
15278       id = astman_get_header(m, "ActionID");
15279       if (!ast_strlen_zero(id))
15280          snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
15281    }
15282 
15283    switch (argc) {
15284    case 5:
15285       if (!strcasecmp(argv[3], "like")) {
15286          if (regcomp(&regexbuf, argv[4], REG_EXTENDED | REG_NOSUB))
15287             return CLI_SHOWUSAGE;
15288          havepattern = TRUE;
15289       } else
15290          return CLI_SHOWUSAGE;
15291    case 3:
15292       break;
15293    default:
15294       return CLI_SHOWUSAGE;
15295    }
15296 
15297    if (!s) /* Normal list */
15298       ast_cli(fd, FORMAT2, "Name/username", "Host", "Dyn", "Nat", "ACL", "Port", "Status", (realtimepeers ? "Realtime" : ""));
15299    
15300 
15301    i = ao2_iterator_init(peers, 0);
15302    while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {  
15303       ao2_lock(peer);
15304 
15305       if (!(peer->type & SIP_TYPE_PEER)) {
15306          ao2_unlock(peer);
15307          unref_peer(peer, "unref peer because it's actually a user");
15308          continue;
15309       }
15310 
15311       if (havepattern && regexec(&regexbuf, peer->name, 0, NULL, 0)) {
15312          objcount--;
15313          ao2_unlock(peer);
15314          unref_peer(peer, "toss iterator peer ptr before continue");
15315          continue;
15316       }
15317 
15318       peerarray[total_peers++] = peer;
15319       ao2_unlock(peer);
15320    }
15321    ao2_iterator_destroy(&i);
15322    
15323    qsort(peerarray, total_peers, sizeof(struct sip_peer *), peercomparefunc);
15324 
15325    for(k=0; k < total_peers; k++) {
15326       char status[20] = "";
15327       char srch[2000];
15328       char pstatus;
15329       peer = peerarray[k];
15330       
15331       ao2_lock(peer);
15332       if (havepattern && regexec(&regexbuf, peer->name, 0, NULL, 0)) {
15333          ao2_unlock(peer);
15334          unref_peer(peer, "toss iterator peer ptr before continue");
15335          continue;
15336       }
15337 
15338       if (!ast_strlen_zero(peer->username) && !s)
15339          snprintf(name, sizeof(name), "%s/%s", peer->name, peer->username);
15340       else
15341          ast_copy_string(name, peer->name, sizeof(name));
15342       
15343       pstatus = peer_status(peer, status, sizeof(status));
15344       if (pstatus == 1)
15345          peers_mon_online++;
15346       else if (pstatus == 0)
15347          peers_mon_offline++;
15348       else {
15349          if (peer->addr.sin_port == 0)
15350             peers_unmon_offline++;
15351          else
15352             peers_unmon_online++;
15353       }
15354 
15355       snprintf(srch, sizeof(srch), FORMAT, name,
15356          peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "(Unspecified)",
15357          peer->host_dynamic ? " D " : "   ",    /* Dynamic or not? */
15358          ast_test_flag(&peer->flags[0], SIP_NAT_ROUTE) ? " N " : "   ", /* NAT=yes? */
15359          peer->ha ? " A " : "   ",  /* permit/deny */
15360          ntohs(peer->addr.sin_port), status,
15361          realtimepeers ? (peer->is_realtime ? "Cached RT":"") : "");
15362 
15363       if (!s)  {/* Normal CLI list */
15364          ast_cli(fd, FORMAT, name, 
15365          peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "(Unspecified)",
15366          peer->host_dynamic ? " D " : "   ",    /* Dynamic or not? */
15367          ast_test_flag(&peer->flags[0], SIP_NAT_ROUTE) ? " N " : "   ", /* NAT=yes? */
15368          peer->ha ? " A " : "   ",       /* permit/deny */
15369          
15370          ntohs(peer->addr.sin_port), status,
15371          realtimepeers ? (peer->is_realtime ? "Cached RT":"") : "");
15372       } else { /* Manager format */
15373          /* The names here need to be the same as other channels */
15374          astman_append(s, 
15375          "Event: PeerEntry\r\n%s"
15376          "Channeltype: SIP\r\n"
15377          "ObjectName: %s\r\n"
15378          "ChanObjectType: peer\r\n" /* "peer" or "user" */
15379          "IPaddress: %s\r\n"
15380          "IPport: %d\r\n"
15381          "Dynamic: %s\r\n"
15382          "Natsupport: %s\r\n"
15383          "VideoSupport: %s\r\n"
15384          "TextSupport: %s\r\n"
15385          "ACL: %s\r\n"
15386          "Status: %s\r\n"
15387          "RealtimeDevice: %s\r\n\r\n", 
15388          idtext,
15389          peer->name, 
15390          peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "-none-",
15391          ntohs(peer->addr.sin_port), 
15392          peer->host_dynamic ? "yes" : "no",  /* Dynamic or not? */
15393          ast_test_flag(&peer->flags[0], SIP_NAT_ROUTE) ? "yes" : "no",  /* NAT=yes? */
15394          ast_test_flag(&peer->flags[1], SIP_PAGE2_VIDEOSUPPORT) ? "yes" : "no",  /* VIDEOSUPPORT=yes? */
15395          ast_test_flag(&peer->flags[1], SIP_PAGE2_TEXTSUPPORT) ? "yes" : "no",   /* TEXTSUPPORT=yes? */
15396          peer->ha ? "yes" : "no",       /* permit/deny */
15397          status,
15398          realtimepeers ? (peer->is_realtime ? "yes":"no") : "no");
15399       }
15400       ao2_unlock(peer);
15401       unref_peer(peer, "toss iterator peer ptr");
15402    }
15403    
15404    if (!s)
15405       ast_cli(fd, "%d sip peers [Monitored: %d online, %d offline Unmonitored: %d online, %d offline]\n",
15406               total_peers, peers_mon_online, peers_mon_offline, peers_unmon_online, peers_unmon_offline);
15407 
15408    if (havepattern)
15409       regfree(&regexbuf);
15410 
15411    if (total)
15412       *total = total_peers;
15413    
15414    ast_free(peerarray);
15415    
15416    return CLI_SUCCESS;
15417 #undef FORMAT
15418 #undef FORMAT2
15419 }
15420 
15421 static int peer_dump_func(void *userobj, void *arg, int flags)
15422 {
15423    struct sip_peer *peer = userobj;
15424    int refc = ao2_t_ref(userobj, 0, "");
15425    int *fd = arg;
15426    
15427    ast_cli(*fd, "name: %s\ntype: peer\nobjflags: %d\nrefcount: %d\n\n", 
15428           peer->name, 0, refc);
15429    return 0;
15430 }
15431 
15432 static int dialog_dump_func(void *userobj, void *arg, int flags)
15433 {
15434    struct sip_pvt *pvt = userobj;
15435    int refc = ao2_t_ref(userobj, 0, "");
15436    int *fd = arg;
15437    
15438    ast_cli(*fd, "name: %s\ntype: dialog\nobjflags: %d\nrefcount: %d\n\n", 
15439           pvt->callid, 0, refc);
15440    return 0;
15441 }
15442 
15443 
15444 /*! \brief List all allocated SIP Objects (realtime or static) */
15445 static char *sip_show_objects(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15446 {
15447    char tmp[256];
15448    
15449    switch (cmd) {
15450    case CLI_INIT:
15451       e->command = "sip show objects";
15452       e->usage =
15453          "Usage: sip show objects\n"
15454          "       Lists status of known SIP objects\n";
15455       return NULL;
15456    case CLI_GENERATE:
15457       return NULL;
15458    }  
15459 
15460    if (a->argc != 3)
15461       return CLI_SHOWUSAGE;
15462    ast_cli(a->fd, "-= Peer objects: %d static, %d realtime, %d autocreate =-\n\n", speerobjs, rpeerobjs, apeerobjs);
15463    ao2_t_callback(peers, OBJ_NODATA, peer_dump_func, &a->fd, "initiate ao2_callback to dump peers");
15464    ast_cli(a->fd, "-= Registry objects: %d =-\n\n", regobjs);
15465    ASTOBJ_CONTAINER_DUMP(a->fd, tmp, sizeof(tmp), &regl);
15466    ast_cli(a->fd, "-= Dialog objects:\n\n");
15467    ao2_t_callback(dialogs, OBJ_NODATA, dialog_dump_func, &a->fd, "initiate ao2_callback to dump dialogs");
15468    return CLI_SUCCESS;
15469 }
15470 /*! \brief Print call group and pickup group */
15471 static void  print_group(int fd, ast_group_t group, int crlf)
15472 {
15473    char buf[256];
15474    ast_cli(fd, crlf ? "%s\r\n" : "%s\n", ast_print_group(buf, sizeof(buf), group) );
15475 }
15476 
15477 /*! \brief mapping between dtmf flags and strings */
15478 static struct _map_x_s dtmfstr[] = {
15479    { SIP_DTMF_RFC2833,     "rfc2833" },
15480    { SIP_DTMF_INFO,        "info" },
15481    { SIP_DTMF_SHORTINFO,   "shortinfo" },
15482    { SIP_DTMF_INBAND,      "inband" },
15483    { SIP_DTMF_AUTO,        "auto" },
15484    { -1,                   NULL }, /* terminator */
15485 };
15486 
15487 /*! \brief Convert DTMF mode to printable string */
15488 static const char *dtmfmode2str(int mode)
15489 {
15490    return map_x_s(dtmfstr, mode, "<error>");
15491 }
15492 
15493 /*! \brief maps a string to dtmfmode, returns -1 on error */
15494 static int str2dtmfmode(const char *str)
15495 {
15496    return map_s_x(dtmfstr, str, -1);
15497 }
15498 
15499 static struct _map_x_s insecurestr[] = {
15500    { SIP_INSECURE_PORT,    "port" },
15501    { SIP_INSECURE_INVITE,  "invite" },
15502    { SIP_INSECURE_PORT | SIP_INSECURE_INVITE, "port,invite" },
15503    { 0,                    "no" },
15504    { -1,                   NULL }, /* terminator */
15505 };
15506 
15507 /*! \brief Convert Insecure setting to printable string */
15508 static const char *insecure2str(int mode)
15509 {
15510    return map_x_s(insecurestr, mode, "<error>");
15511 }
15512 
15513 /*! \brief Destroy disused contexts between reloads
15514    Only used in reload_config so the code for regcontext doesn't get ugly
15515 */
15516 static void cleanup_stale_contexts(char *new, char *old)
15517 {
15518    char *oldcontext, *newcontext, *stalecontext, *stringp, newlist[AST_MAX_CONTEXT];
15519 
15520    while ((oldcontext = strsep(&old, "&"))) {
15521       stalecontext = '\0';
15522       ast_copy_string(newlist, new, sizeof(newlist));
15523       stringp = newlist;
15524       while ((newcontext = strsep(&stringp, "&"))) {
15525          if (!strcmp(newcontext, oldcontext)) {
15526             /* This is not the context you're looking for */
15527             stalecontext = '\0';
15528             break;
15529          } else if (strcmp(newcontext, oldcontext)) {
15530             stalecontext = oldcontext;
15531          }
15532          
15533       }
15534       if (stalecontext)
15535          ast_context_destroy(ast_context_find(stalecontext), "SIP");
15536    }
15537 }
15538 
15539 /*! 
15540  * \brief Match dialogs that need to be destroyed
15541  *
15542  * \details This is used with ao2_callback to unlink/delete all dialogs that
15543  * are marked needdestroy. It will return CMP_MATCH for candidates, and they
15544  * will be unlinked.
15545  *
15546  * \todo Re-work this to improve efficiency.  Currently, this function is called
15547  * on _every_ dialog after processing _every_ incoming SIP/UDP packet, or
15548  * potentially even more often when the scheduler has entries to run.
15549  */
15550 
15551 static int dialog_needdestroy(void *dialogobj, void *arg, int flags) 
15552 {
15553    struct sip_pvt *dialog = dialogobj;
15554    time_t *t = arg;
15555 
15556    if (sip_pvt_trylock(dialog)) {
15557       /* Don't block the monitor thread.  This function is called often enough
15558        * that we can wait for the next time around. */
15559       return 0;
15560    }
15561    
15562    /* Check RTP timeouts and kill calls if we have a timeout set and do not get RTP */
15563    check_rtp_timeout(dialog, *t);
15564 
15565    /* If we have sessions that needs to be destroyed, do it now */
15566    /* Check if we have outstanding requests not responsed to or an active call
15567       - if that's the case, wait with destruction */
15568    if (dialog->needdestroy && !dialog->packets && !dialog->owner) {
15569       /* We absolutely cannot destroy the rtp struct while a bridge is active or we WILL crash */
15570       if (dialog->rtp && ast_rtp_get_bridged(dialog->rtp)) {
15571          ast_debug(2, "Bridge still active.  Delaying destruction of SIP dialog '%s' Method: %s\n", dialog->callid, sip_methods[dialog->method].text);
15572          sip_pvt_unlock(dialog);
15573          return 0;
15574       }
15575       
15576       if (dialog->vrtp && ast_rtp_get_bridged(dialog->vrtp)) {
15577          ast_debug(2, "Bridge still active.  Delaying destroy of SIP dialog '%s' Method: %s\n", dialog->callid, sip_methods[dialog->method].text);
15578          sip_pvt_unlock(dialog);
15579          return 0;
15580       }
15581 
15582       sip_pvt_unlock(dialog);
15583       /* no, the unlink should handle this: dialog_unref(dialog, "needdestroy: one more refcount decrement to allow dialog to be destroyed"); */
15584       /* the CMP_MATCH will unlink this dialog from the dialog hash table */
15585       dialog_unlink_all(dialog, TRUE, FALSE);
15586       return 0; /* the unlink_all should unlink this from the table, so.... no need to return a match */
15587    }
15588 
15589    sip_pvt_unlock(dialog);
15590 
15591    return 0;
15592 }
15593 
15594 /*! \brief Remove temporary realtime objects from memory (CLI) */
15595 /*! \todo XXXX Propably needs an overhaul after removal of the devices */
15596 static char *sip_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15597 {
15598    struct sip_peer *peer, *pi;
15599    int prunepeer = FALSE;
15600    int multi = FALSE;
15601    char *name = NULL;
15602    regex_t regexbuf;
15603    struct ao2_iterator i;
15604    static char *choices[] = { "all", "like", NULL };
15605    char *cmplt;
15606    
15607    if (cmd == CLI_INIT) {
15608       e->command = "sip prune realtime [peer|all]";
15609       e->usage =
15610          "Usage: sip prune realtime [peer [<name>|all|like <pattern>]|all]\n"
15611          "       Prunes object(s) from the cache.\n"
15612          "       Optional regular expression pattern is used to filter the objects.\n";
15613       return NULL;
15614    } else if (cmd == CLI_GENERATE) {
15615       if (a->pos == 4 && !strcasecmp(a->argv[3], "peer")) {
15616          cmplt = ast_cli_complete(a->word, choices, a->n);
15617          if (!cmplt)
15618             cmplt = complete_sip_peer(a->word, a->n - sizeof(choices), SIP_PAGE2_RTCACHEFRIENDS);
15619          return cmplt;
15620       }
15621       if (a->pos == 5 && !strcasecmp(a->argv[4], "like"))
15622          return complete_sip_peer(a->word, a->n, SIP_PAGE2_RTCACHEFRIENDS);
15623       return NULL;
15624    }
15625    switch (a->argc) {
15626    case 4:
15627       name = a->argv[3];
15628       /* we accept a name in position 3, but keywords are not good. */
15629       if (!strcasecmp(name, "peer") || !strcasecmp(name, "like"))
15630          return CLI_SHOWUSAGE;
15631       prunepeer = TRUE;
15632       if (!strcasecmp(name, "all")) {
15633          multi = TRUE;
15634          name = NULL;
15635       }
15636       /* else a single name, already set */
15637       break;
15638    case 5:
15639       /* sip prune realtime {peer|like} name */
15640       name = a->argv[4];
15641       if (!strcasecmp(a->argv[3], "peer"))
15642          prunepeer = TRUE;
15643       else if (!strcasecmp(a->argv[3], "like")) {
15644          prunepeer = TRUE;
15645          multi = TRUE;
15646       } else
15647          return CLI_SHOWUSAGE;
15648       if (!strcasecmp(name, "like"))
15649          return CLI_SHOWUSAGE;
15650       if (!multi && !strcasecmp(name, "all")) {
15651          multi = TRUE;
15652          name = NULL;
15653       }
15654       break;
15655    case 6:
15656       name = a->argv[5];
15657       multi = TRUE;
15658       /* sip prune realtime {peer} like name */
15659       if (strcasecmp(a->argv[4], "like"))
15660          return CLI_SHOWUSAGE;
15661       if (!strcasecmp(a->argv[3], "peer")) {
15662          prunepeer = TRUE;
15663       } else
15664          return CLI_SHOWUSAGE;
15665       break;
15666    default:
15667       return CLI_SHOWUSAGE;
15668    }
15669 
15670    if (multi && name) {
15671       if (regcomp(&regexbuf, name, REG_EXTENDED | REG_NOSUB))
15672          return CLI_SHOWUSAGE;
15673    }
15674 
15675    if (multi) {
15676       if (prunepeer) {
15677          int pruned = 0;
15678          
15679          i = ao2_iterator_init(peers, 0);
15680          while ((pi = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
15681             ao2_lock(pi);
15682             if (name && regexec(&regexbuf, pi->name, 0, NULL, 0)) {
15683                unref_peer(pi, "toss iterator peer ptr before continue");
15684                ao2_unlock(pi);
15685                continue;
15686             };
15687             if (ast_test_flag(&pi->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
15688                pi->the_mark = 1;
15689                pruned++;
15690             }
15691             ao2_unlock(pi);
15692             unref_peer(pi, "toss iterator peer ptr");
15693          }
15694          ao2_iterator_destroy(&i);
15695          if (pruned) {
15696             unlink_marked_peers_from_tables();
15697             ast_cli(a->fd, "%d peers pruned.\n", pruned);
15698          } else
15699             ast_cli(a->fd, "No peers found to prune.\n");
15700       }
15701    } else {
15702       if (prunepeer) {
15703          struct sip_peer tmp;
15704          ast_copy_string(tmp.name, name, sizeof(tmp.name));
15705          if ((peer = ao2_t_find(peers, &tmp, OBJ_POINTER | OBJ_UNLINK, "finding to unlink from peers"))) {
15706             if (peer->addr.sin_addr.s_addr) {
15707                ao2_t_unlink(peers_by_ip, peer, "unlinking peer from peers_by_ip also");
15708             }
15709             if (!ast_test_flag(&peer->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
15710                ast_cli(a->fd, "Peer '%s' is not a Realtime peer, cannot be pruned.\n", name);
15711                /* put it back! */
15712                ao2_t_link(peers, peer, "link peer into peer table");
15713                if (peer->addr.sin_addr.s_addr) {
15714                   ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
15715                }
15716                
15717             } else
15718                ast_cli(a->fd, "Peer '%s' pruned.\n", name);
15719             unref_peer(peer, "sip_prune_realtime: unref_peer: tossing temp peer ptr");
15720          } else
15721             ast_cli(a->fd, "Peer '%s' not found.\n", name);
15722       }
15723    }
15724 
15725    return CLI_SUCCESS;
15726 }
15727 
15728 /*! \brief Print codec list from preference to CLI/manager */
15729 static void print_codec_to_cli(int fd, struct ast_codec_pref *pref)
15730 {
15731    int x, codec;
15732 
15733    for(x = 0; x < 32 ; x++) {
15734       codec = ast_codec_pref_index(pref, x);
15735       if (!codec)
15736          break;
15737       ast_cli(fd, "%s", ast_getformatname(codec));
15738       ast_cli(fd, ":%d", pref->framing[x]);
15739       if (x < 31 && ast_codec_pref_index(pref, x + 1))
15740          ast_cli(fd, ",");
15741    }
15742    if (!x)
15743       ast_cli(fd, "none");
15744 }
15745 
15746 /*! \brief Print domain mode to cli */
15747 static const char *domain_mode_to_text(const enum domain_mode mode)
15748 {
15749    switch (mode) {
15750    case SIP_DOMAIN_AUTO:
15751       return "[Automatic]";
15752    case SIP_DOMAIN_CONFIG:
15753       return "[Configured]";
15754    }
15755 
15756    return "";
15757 }
15758 
15759 /*! \brief CLI command to list local domains */
15760 static char *sip_show_domains(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15761 {
15762    struct domain *d;
15763 #define FORMAT "%-40.40s %-20.20s %-16.16s\n"
15764 
15765    switch (cmd) {
15766    case CLI_INIT:
15767       e->command = "sip show domains";
15768       e->usage =
15769          "Usage: sip show domains\n"
15770          "       Lists all configured SIP local domains.\n"
15771          "       Asterisk only responds to SIP messages to local domains.\n";
15772       return NULL;
15773    case CLI_GENERATE:
15774       return NULL;
15775    }
15776 
15777    if (AST_LIST_EMPTY(&domain_list)) {
15778       ast_cli(a->fd, "SIP Domain support not enabled.\n\n");
15779       return CLI_SUCCESS;
15780    } else {
15781       ast_cli(a->fd, FORMAT, "Our local SIP domains:", "Context", "Set by");
15782       AST_LIST_LOCK(&domain_list);
15783       AST_LIST_TRAVERSE(&domain_list, d, list)
15784          ast_cli(a->fd, FORMAT, d->domain, S_OR(d->context, "(default)"),
15785             domain_mode_to_text(d->mode));
15786       AST_LIST_UNLOCK(&domain_list);
15787       ast_cli(a->fd, "\n");
15788       return CLI_SUCCESS;
15789    }
15790 }
15791 #undef FORMAT
15792 
15793 static char mandescr_show_peer[] = 
15794 "Description: Show one SIP peer with details on current status.\n"
15795 "Variables: \n"
15796 "  Peer: <name>           The peer name you want to check.\n"
15797 "  ActionID: <id>   Optional action ID for this AMI transaction.\n";
15798 
15799 /*! \brief Show SIP peers in the manager API  */
15800 static int manager_sip_show_peer(struct mansession *s, const struct message *m)
15801 {
15802    const char *a[4];
15803    const char *peer;
15804 
15805    peer = astman_get_header(m, "Peer");
15806    if (ast_strlen_zero(peer)) {
15807       astman_send_error(s, m, "Peer: <name> missing.");
15808       return 0;
15809    }
15810    a[0] = "sip";
15811    a[1] = "show";
15812    a[2] = "peer";
15813    a[3] = peer;
15814 
15815    _sip_show_peer(1, -1, s, m, 4, a);
15816    astman_append(s, "\r\n\r\n" );
15817    return 0;
15818 }
15819 
15820 /*! \brief Show one peer in detail */
15821 static char *sip_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15822 {
15823    switch (cmd) {
15824    case CLI_INIT:
15825       e->command = "sip show peer";
15826       e->usage =
15827          "Usage: sip show peer <name> [load]\n"
15828          "       Shows all details on one SIP peer and the current status.\n"
15829          "       Option \"load\" forces lookup of peer in realtime storage.\n";
15830       return NULL;
15831    case CLI_GENERATE:
15832       return complete_sip_show_peer(a->line, a->word, a->pos, a->n);
15833    }
15834    return _sip_show_peer(0, a->fd, NULL, NULL, a->argc, (const char **) a->argv);
15835 }
15836 
15837 /*! \brief Send qualify message to peer from cli or manager. Mostly for debugging. */
15838 static char *_sip_qualify_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[])
15839 {
15840    struct sip_peer *peer;
15841    int load_realtime;
15842 
15843    if (argc < 4)
15844       return CLI_SHOWUSAGE;
15845 
15846    load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? TRUE : FALSE;
15847    if ((peer = find_peer(argv[3], NULL, load_realtime, FINDPEERS, FALSE, 0))) {
15848       sip_poke_peer(peer, 1);
15849       unref_peer(peer, "qualify: done with peer");
15850    } else if (type == 0) {
15851       ast_cli(fd, "Peer '%s' not found\n", argv[3]);
15852    } else {
15853       astman_send_error(s, m, "Peer not found");
15854    }
15855    return CLI_SUCCESS;
15856 }
15857 
15858 /*! \brief Qualify SIP peers in the manager API  */
15859 static int manager_sip_qualify_peer(struct mansession *s, const struct message *m)
15860 {
15861    const char *a[4];
15862    const char *peer;
15863 
15864    peer = astman_get_header(m, "Peer");
15865    if (ast_strlen_zero(peer)) {
15866       astman_send_error(s, m, "Peer: <name> missing.");
15867       return 0;
15868    }
15869    a[0] = "sip";
15870    a[1] = "qualify";
15871    a[2] = "peer";
15872    a[3] = peer;
15873 
15874    _sip_qualify_peer(1, -1, s, m, 4, a);
15875    astman_append(s, "\r\n\r\n" );
15876    return 0;
15877 }
15878 
15879 /*! \brief Send an OPTIONS packet to a SIP peer */
15880 static char *sip_qualify_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15881 {
15882    switch (cmd) {
15883    case CLI_INIT:
15884       e->command = "sip qualify peer";
15885       e->usage =
15886          "Usage: sip qualify peer <name> [load]\n"
15887          "       Requests a response from one SIP peer and the current status.\n"
15888          "       Option \"load\" forces lookup of peer in realtime storage.\n";
15889       return NULL;
15890    case CLI_GENERATE:
15891       return complete_sip_show_peer(a->line, a->word, a->pos, a->n);
15892    }
15893    return _sip_qualify_peer(0, a->fd, NULL, NULL, a->argc, (const char **) a->argv);
15894 }
15895 
15896 /*! \brief list peer mailboxes to CLI */
15897 static void peer_mailboxes_to_str(struct ast_str **mailbox_str, struct sip_peer *peer)
15898 {
15899    struct sip_mailbox *mailbox;
15900 
15901    AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
15902       ast_str_append(mailbox_str, 0, "%s%s%s%s",
15903          mailbox->mailbox,
15904          ast_strlen_zero(mailbox->context) ? "" : "@",
15905          S_OR(mailbox->context, ""),
15906          AST_LIST_NEXT(mailbox, entry) ? "," : "");
15907    }
15908 }
15909 
15910 static struct _map_x_s faxecmodes[] = {
15911    { SIP_PAGE2_T38SUPPORT_UDPTL,       "None"},
15912    { SIP_PAGE2_T38SUPPORT_UDPTL_FEC,      "FEC"},
15913    { SIP_PAGE2_T38SUPPORT_UDPTL_REDUNDANCY,  "Redundancy"},
15914    { -1,                NULL},
15915 };
15916 
15917 static const char *faxec2str(int faxec)
15918 {
15919    return map_x_s(faxecmodes, faxec, "Unknown");
15920 }
15921 
15922 /*! \brief Show one peer in detail (main function) */
15923 static char *_sip_show_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[])
15924 {
15925    char status[30] = "";
15926    char cbuf[256];
15927    struct sip_peer *peer;
15928    char codec_buf[512];
15929    struct ast_codec_pref *pref;
15930    struct ast_variable *v;
15931    struct sip_auth *auth;
15932    int x = 0, codec = 0, load_realtime;
15933    int realtimepeers;
15934 
15935    realtimepeers = ast_check_realtime("sippeers");
15936 
15937    if (argc < 4)
15938       return CLI_SHOWUSAGE;
15939 
15940    load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? TRUE : FALSE;
15941    peer = find_peer(argv[3], NULL, load_realtime, FINDPEERS, FALSE, 0);
15942 
15943    if (s) {    /* Manager */
15944       if (peer) {
15945          const char *id = astman_get_header(m, "ActionID");
15946 
15947          astman_append(s, "Response: Success\r\n");
15948          if (!ast_strlen_zero(id))
15949             astman_append(s, "ActionID: %s\r\n", id);
15950       } else {
15951          snprintf (cbuf, sizeof(cbuf), "Peer %s not found.", argv[3]);
15952          astman_send_error(s, m, cbuf);
15953          return CLI_SUCCESS;
15954       }
15955    }
15956    if (peer && type==0 ) { /* Normal listing */
15957       struct ast_str *mailbox_str = ast_str_alloca(512);
15958       ast_cli(fd, "\n\n");
15959       ast_cli(fd, "  * Name       : %s\n", peer->name);
15960       if (realtimepeers) { /* Realtime is enabled */
15961          ast_cli(fd, "  Realtime peer: %s\n", peer->is_realtime ? "Yes, cached" : "No");
15962       }
15963       ast_cli(fd, "  Secret       : %s\n", ast_strlen_zero(peer->secret)?"<Not set>":"<Set>");
15964       ast_cli(fd, "  MD5Secret    : %s\n", ast_strlen_zero(peer->md5secret)?"<Not set>":"<Set>");
15965       ast_cli(fd, "  Remote Secret: %s\n", ast_strlen_zero(peer->remotesecret)?"<Not set>":"<Set>");
15966       for (auth = peer->auth; auth; auth = auth->next) {
15967          ast_cli(fd, "  Realm-auth   : Realm %-15.15s User %-10.20s ", auth->realm, auth->username);
15968          ast_cli(fd, "%s\n", !ast_strlen_zero(auth->secret)?"<Secret set>":(!ast_strlen_zero(auth->md5secret)?"<MD5secret set>" : "<Not set>"));
15969       }
15970       ast_cli(fd, "  Context      : %s\n", peer->context);
15971       ast_cli(fd, "  Subscr.Cont. : %s\n", S_OR(peer->subscribecontext, "<Not set>") );
15972       ast_cli(fd, "  Language     : %s\n", peer->language);
15973       if (!ast_strlen_zero(peer->accountcode))
15974          ast_cli(fd, "  Accountcode  : %s\n", peer->accountcode);
15975       ast_cli(fd, "  AMA flags    : %s\n", ast_cdr_flags2str(peer->amaflags));
15976       ast_cli(fd, "  Transfer mode: %s\n", transfermode2str(peer->allowtransfer));
15977       ast_cli(fd, "  CallingPres  : %s\n", ast_describe_caller_presentation(peer->callingpres));
15978       if (!ast_strlen_zero(peer->fromuser))
15979          ast_cli(fd, "  FromUser     : %s\n", peer->fromuser);
15980       if (!ast_strlen_zero(peer->fromdomain))
15981          ast_cli(fd, "  FromDomain   : %s\n", peer->fromdomain);
15982       ast_cli(fd, "  Callgroup    : ");
15983       print_group(fd, peer->callgroup, 0);
15984       ast_cli(fd, "  Pickupgroup  : ");
15985       print_group(fd, peer->pickupgroup, 0);
15986       peer_mailboxes_to_str(&mailbox_str, peer);
15987       ast_cli(fd, "  Mailbox      : %s\n", mailbox_str->str);
15988       ast_cli(fd, "  VM Extension : %s\n", peer->vmexten);
15989       ast_cli(fd, "  LastMsgsSent : %d/%d\n", (peer->lastmsgssent & 0x7fff0000) >> 16, peer->lastmsgssent & 0xffff);
15990       ast_cli(fd, "  Call limit   : %d\n", peer->call_limit);
15991       if (peer->busy_level)
15992          ast_cli(fd, "  Busy level   : %d\n", peer->busy_level);
15993       ast_cli(fd, "  Dynamic      : %s\n", cli_yesno(peer->host_dynamic));
15994       ast_cli(fd, "  Callerid     : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, "<unspecified>"));
15995       ast_cli(fd, "  MaxCallBR    : %d kbps\n", peer->maxcallbitrate);
15996       ast_cli(fd, "  Expire       : %ld\n", ast_sched_when(sched, peer->expire));
15997       ast_cli(fd, "  Insecure     : %s\n", insecure2str(ast_test_flag(&peer->flags[0], SIP_INSECURE)));
15998       ast_cli(fd, "  Nat          : %s\n", nat2str(ast_test_flag(&peer->flags[0], SIP_NAT)));
15999       ast_cli(fd, "  ACL          : %s\n", cli_yesno(peer->ha != NULL));
16000       ast_cli(fd, "  T.38 support : %s\n", cli_yesno(ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)));
16001       ast_cli(fd, "  T.38 EC mode : %s\n", faxec2str(ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)));
16002       ast_cli(fd, "  T.38 MaxDtgrm: %d\n", peer->t38_maxdatagram);
16003       ast_cli(fd, "  DirectMedia  : %s\n", cli_yesno(ast_test_flag(&peer->flags[0], SIP_DIRECT_MEDIA)));
16004       ast_cli(fd, "  PromiscRedir : %s\n", cli_yesno(ast_test_flag(&peer->flags[0], SIP_PROMISCREDIR)));
16005       ast_cli(fd, "  User=Phone   : %s\n", cli_yesno(ast_test_flag(&peer->flags[0], SIP_USEREQPHONE)));
16006       ast_cli(fd, "  Video Support: %s\n", cli_yesno(ast_test_flag(&peer->flags[1], SIP_PAGE2_VIDEOSUPPORT) || ast_test_flag(&peer->flags[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS)));
16007       ast_cli(fd, "  Text Support : %s\n", cli_yesno(ast_test_flag(&peer->flags[1], SIP_PAGE2_TEXTSUPPORT)));
16008       ast_cli(fd, "  Ign SDP ver  : %s\n", cli_yesno(ast_test_flag(&peer->flags[1], SIP_PAGE2_IGNORESDPVERSION)));
16009       ast_cli(fd, "  Trust RPID   : %s\n", cli_yesno(ast_test_flag(&peer->flags[0], SIP_TRUSTRPID)));
16010       ast_cli(fd, "  Send RPID    : %s\n", cli_yesno(ast_test_flag(&peer->flags[0], SIP_SENDRPID)));
16011       ast_cli(fd, "  Subscriptions: %s\n", cli_yesno(ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)));
16012       ast_cli(fd, "  Overlap dial : %s\n", cli_yesno(ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWOVERLAP)));
16013       ast_cli(fd, "  Forward Loop : %s\n", cli_yesno(ast_test_flag(&peer->flags[1], SIP_PAGE2_FORWARD_LOOP_DETECTED)));
16014       if (peer->outboundproxy)
16015          ast_cli(fd, "  Outb. proxy  : %s %s\n", ast_strlen_zero(peer->outboundproxy->name) ? "<not set>" : peer->outboundproxy->name,
16016                      peer->outboundproxy->force ? "(forced)" : "");
16017 
16018       /* - is enumerated */
16019       ast_cli(fd, "  DTMFmode     : %s\n", dtmfmode2str(ast_test_flag(&peer->flags[0], SIP_DTMF)));
16020       ast_cli(fd, "  Timer T1     : %d\n", peer->timer_t1);
16021       ast_cli(fd, "  Timer B      : %d\n", peer->timer_b);
16022       ast_cli(fd, "  ToHost       : %s\n", peer->tohost);
16023       ast_cli(fd, "  Addr->IP     : %s Port %d\n",  peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "(Unspecified)", ntohs(peer->addr.sin_port));
16024       ast_cli(fd, "  Defaddr->IP  : %s Port %d\n", ast_inet_ntoa(peer->defaddr.sin_addr), ntohs(peer->defaddr.sin_port));
16025       ast_cli(fd, "  Prim.Transp. : %s\n", get_transport(peer->socket.type));
16026       ast_cli(fd, "  Allowed.Trsp : %s\n", get_transport_list(peer->transports)); 
16027       if (!ast_strlen_zero(global_regcontext))
16028          ast_cli(fd, "  Reg. exten   : %s\n", peer->regexten);
16029       ast_cli(fd, "  Def. Username: %s\n", peer->username);
16030       ast_cli(fd, "  SIP Options  : ");
16031       if (peer->sipoptions) {
16032          int lastoption = -1;
16033          for (x = 0 ; x < ARRAY_LEN(sip_options); x++) {
16034             if (sip_options[x].id != lastoption) {
16035                if (peer->sipoptions & sip_options[x].id)
16036                   ast_cli(fd, "%s ", sip_options[x].text);
16037                lastoption = x;
16038             }
16039          }
16040       } else
16041          ast_cli(fd, "(none)");
16042 
16043       ast_cli(fd, "\n");
16044       ast_cli(fd, "  Codecs       : ");
16045       ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
16046       ast_cli(fd, "%s\n", codec_buf);
16047       ast_cli(fd, "  Codec Order  : (");
16048       print_codec_to_cli(fd, &peer->prefs);
16049       ast_cli(fd, ")\n");
16050 
16051       ast_cli(fd, "  Auto-Framing :  %s \n", cli_yesno(peer->autoframing));
16052       ast_cli(fd, "  100 on REG   : %s\n", ast_test_flag(&peer->flags[1], SIP_PAGE2_REGISTERTRYING) ? "Yes" : "No");
16053       ast_cli(fd, "  Status       : ");
16054       peer_status(peer, status, sizeof(status));
16055       ast_cli(fd, "%s\n", status);
16056       ast_cli(fd, "  Useragent    : %s\n", peer->useragent);
16057       ast_cli(fd, "  Reg. Contact : %s\n", peer->fullcontact);
16058       ast_cli(fd, "  Qualify Freq : %d ms\n", peer->qualifyfreq);
16059       if (peer->chanvars) {
16060          ast_cli(fd, "  Variables    :\n");
16061          for (v = peer->chanvars ; v ; v = v->next)
16062             ast_cli(fd, "                 %s = %s\n", v->name, v->value);
16063       }
16064 
16065       ast_cli(fd, "  Sess-Timers  : %s\n", stmode2str(peer->stimer.st_mode_oper));
16066       ast_cli(fd, "  Sess-Refresh : %s\n", strefresher2str(peer->stimer.st_ref));
16067       ast_cli(fd, "  Sess-Expires : %d secs\n", peer->stimer.st_max_se);
16068       ast_cli(fd, "  Min-Sess     : %d secs\n", peer->stimer.st_min_se);
16069       ast_cli(fd, "  Parkinglot   : %s\n", peer->parkinglot);
16070       ast_cli(fd, "\n");
16071       peer = unref_peer(peer, "sip_show_peer: unref_peer: done with peer ptr");
16072    } else  if (peer && type == 1) { /* manager listing */
16073       char buffer[256];
16074       struct ast_str *mailbox_str = ast_str_alloca(512);
16075       astman_append(s, "Channeltype: SIP\r\n");
16076       astman_append(s, "ObjectName: %s\r\n", peer->name);
16077       astman_append(s, "ChanObjectType: peer\r\n");
16078       astman_append(s, "SecretExist: %s\r\n", ast_strlen_zero(peer->secret)?"N":"Y");
16079       astman_append(s, "RemoteSecretExist: %s\r\n", ast_strlen_zero(peer->remotesecret)?"N":"Y");
16080       astman_append(s, "MD5SecretExist: %s\r\n", ast_strlen_zero(peer->md5secret)?"N":"Y");
16081       astman_append(s, "Context: %s\r\n", peer->context);
16082       astman_append(s, "Language: %s\r\n", peer->language);
16083       if (!ast_strlen_zero(peer->accountcode))
16084          astman_append(s, "Accountcode: %s\r\n", peer->accountcode);
16085       astman_append(s, "AMAflags: %s\r\n", ast_cdr_flags2str(peer->amaflags));
16086       astman_append(s, "CID-CallingPres: %s\r\n", ast_describe_caller_presentation(peer->callingpres));
16087       if (!ast_strlen_zero(peer->fromuser))
16088          astman_append(s, "SIP-FromUser: %s\r\n", peer->fromuser);
16089       if (!ast_strlen_zero(peer->fromdomain))
16090          astman_append(s, "SIP-FromDomain: %s\r\n", peer->fromdomain);
16091       astman_append(s, "Callgroup: ");
16092       astman_append(s, "%s\r\n", ast_print_group(buffer, sizeof(buffer), peer->callgroup));
16093       astman_append(s, "Pickupgroup: ");
16094       astman_append(s, "%s\r\n", ast_print_group(buffer, sizeof(buffer), peer->pickupgroup));
16095       peer_mailboxes_to_str(&mailbox_str, peer);
16096       astman_append(s, "VoiceMailbox: %s\r\n", mailbox_str->str);
16097       astman_append(s, "TransferMode: %s\r\n", transfermode2str(peer->allowtransfer));
16098       astman_append(s, "LastMsgsSent: %d\r\n", peer->lastmsgssent);
16099       astman_append(s, "Call-limit: %d\r\n", peer->call_limit);
16100       astman_append(s, "Busy-level: %d\r\n", peer->busy_level);
16101       astman_append(s, "MaxCallBR: %d kbps\r\n", peer->maxcallbitrate);
16102       astman_append(s, "Dynamic: %s\r\n", peer->host_dynamic?"Y":"N");
16103       astman_append(s, "Callerid: %s\r\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, ""));
16104       astman_append(s, "RegExpire: %ld seconds\r\n", ast_sched_when(sched, peer->expire));
16105       astman_append(s, "SIP-AuthInsecure: %s\r\n", insecure2str(ast_test_flag(&peer->flags[0], SIP_INSECURE)));
16106       astman_append(s, "SIP-NatSupport: %s\r\n", nat2str(ast_test_flag(&peer->flags[0], SIP_NAT)));
16107       astman_append(s, "ACL: %s\r\n", (peer->ha?"Y":"N"));
16108       astman_append(s, "SIP-CanReinvite: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_DIRECT_MEDIA)?"Y":"N"));
16109       astman_append(s, "SIP-DirectMedia: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_DIRECT_MEDIA)?"Y":"N"));
16110       astman_append(s, "SIP-PromiscRedir: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_PROMISCREDIR)?"Y":"N"));
16111       astman_append(s, "SIP-UserPhone: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_USEREQPHONE)?"Y":"N"));
16112       astman_append(s, "SIP-VideoSupport: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_VIDEOSUPPORT)?"Y":"N"));
16113       astman_append(s, "SIP-TextSupport: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_TEXTSUPPORT)?"Y":"N"));
16114       astman_append(s, "SIP-T.38Support: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)?"Y":"N"));
16115       astman_append(s, "SIP-T.38EC: %s\r\n", faxec2str(ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)));
16116       astman_append(s, "SIP-T.38MaxDtgrm: %d\r\n", peer->t38_maxdatagram);
16117       astman_append(s, "SIP-Sess-Timers: %s\r\n", stmode2str(peer->stimer.st_mode_oper));
16118       astman_append(s, "SIP-Sess-Refresh: %s\r\n", strefresher2str(peer->stimer.st_ref));
16119       astman_append(s, "SIP-Sess-Expires: %d\r\n", peer->stimer.st_max_se);
16120       astman_append(s, "SIP-Sess-Min: %d\r\n", peer->stimer.st_min_se);
16121 
16122       /* - is enumerated */
16123       astman_append(s, "SIP-DTMFmode: %s\r\n", dtmfmode2str(ast_test_flag(&peer->flags[0], SIP_DTMF)));
16124       astman_append(s, "ToHost: %s\r\n", peer->tohost);
16125       astman_append(s, "Address-IP: %s\r\nAddress-Port: %d\r\n",  peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "", ntohs(peer->addr.sin_port));
16126       astman_append(s, "Default-addr-IP: %s\r\nDefault-addr-port: %d\r\n", ast_inet_ntoa(peer->defaddr.sin_addr), ntohs(peer->defaddr.sin_port));
16127       astman_append(s, "Default-Username: %s\r\n", peer->username);
16128       if (!ast_strlen_zero(global_regcontext))
16129          astman_append(s, "RegExtension: %s\r\n", peer->regexten);
16130       astman_append(s, "Codecs: ");
16131       ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
16132       astman_append(s, "%s\r\n", codec_buf);
16133       astman_append(s, "CodecOrder: ");
16134       pref = &peer->prefs;
16135       for(x = 0; x < 32 ; x++) {
16136          codec = ast_codec_pref_index(pref, x);
16137          if (!codec)
16138             break;
16139          astman_append(s, "%s", ast_getformatname(codec));
16140          if (x < 31 && ast_codec_pref_index(pref, x+1))
16141             astman_append(s, ",");
16142       }
16143 
16144       astman_append(s, "\r\n");
16145       astman_append(s, "Status: ");
16146       peer_status(peer, status, sizeof(status));
16147       astman_append(s, "%s\r\n", status);
16148       astman_append(s, "SIP-Useragent: %s\r\n", peer->useragent);
16149       astman_append(s, "Reg-Contact: %s\r\n", peer->fullcontact);
16150       astman_append(s, "QualifyFreq: %d ms\r\n", peer->qualifyfreq);
16151       astman_append(s, "Parkinglot: %s\r\n", peer->parkinglot);
16152       if (peer->chanvars) {
16153          for (v = peer->chanvars ; v ; v = v->next) {
16154             astman_append(s, "ChanVariable: %s=%s\r\n", v->name, v->value);
16155          }
16156       }
16157 
16158       peer = unref_peer(peer, "sip_show_peer: unref_peer: done with peer");
16159 
16160    } else {
16161       ast_cli(fd, "Peer %s not found.\n", argv[3]);
16162       ast_cli(fd, "\n");
16163    }
16164 
16165    return CLI_SUCCESS;
16166 }
16167 
16168 /*! \brief Do completion on user name */
16169 static char *complete_sip_user(const char *word, int state)
16170 {
16171    char *result = NULL;
16172    int wordlen = strlen(word);
16173    int which = 0;
16174    struct ao2_iterator user_iter;
16175    struct sip_peer *user;
16176 
16177    user_iter = ao2_iterator_init(peers, 0);
16178    while ((user = ao2_iterator_next(&user_iter))) {
16179       ao2_lock(user);
16180       if (!(user->type & SIP_TYPE_USER)) {
16181          ao2_unlock(user);
16182          unref_peer(user, "complete sip user");
16183          continue;
16184       }
16185       /* locking of the object is not required because only the name and flags are being compared */
16186       if (!strncasecmp(word, user->name, wordlen) && ++which > state) {
16187          result = ast_strdup(user->name);
16188       }
16189       ao2_unlock(user);
16190       unref_peer(user, "complete sip user");
16191       if (result) {
16192          break;
16193       }
16194    }
16195    ao2_iterator_destroy(&user_iter);
16196    return result;
16197 }
16198 /*! \brief Support routine for 'sip show user' CLI */
16199 static char *complete_sip_show_user(const char *line, const char *word, int pos, int state)
16200 {
16201    if (pos == 3)
16202       return complete_sip_user(word, state);
16203 
16204    return NULL;
16205 }
16206 
16207 /*! \brief Show one user in detail */
16208 static char *sip_show_user(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16209 {
16210    char cbuf[256];
16211    struct sip_peer *user;
16212    struct ast_variable *v;
16213    int load_realtime;
16214 
16215    switch (cmd) {
16216    case CLI_INIT:
16217       e->command = "sip show user";
16218       e->usage =
16219          "Usage: sip show user <name> [load]\n"
16220          "       Shows all details on one SIP user and the current status.\n"
16221          "       Option \"load\" forces lookup of peer in realtime storage.\n";
16222       return NULL;
16223    case CLI_GENERATE:
16224       return complete_sip_show_user(a->line, a->word, a->pos, a->n);
16225    }
16226 
16227    if (a->argc < 4)
16228       return CLI_SHOWUSAGE;
16229 
16230    /* Load from realtime storage? */
16231    load_realtime = (a->argc == 5 && !strcmp(a->argv[4], "load")) ? TRUE : FALSE;
16232 
16233    if ((user = find_peer(a->argv[3], NULL, load_realtime, FINDUSERS, FALSE, 0))) {
16234       ao2_lock(user);
16235       ast_cli(a->fd, "\n\n");
16236       ast_cli(a->fd, "  * Name       : %s\n", user->name);
16237       ast_cli(a->fd, "  Secret       : %s\n", ast_strlen_zero(user->secret)?"<Not set>":"<Set>");
16238       ast_cli(a->fd, "  MD5Secret    : %s\n", ast_strlen_zero(user->md5secret)?"<Not set>":"<Set>");
16239       ast_cli(a->fd, "  Context      : %s\n", user->context);
16240       ast_cli(a->fd, "  Language     : %s\n", user->language);
16241       if (!ast_strlen_zero(user->accountcode))
16242          ast_cli(a->fd, "  Accountcode  : %s\n", user->accountcode);
16243       ast_cli(a->fd, "  AMA flags    : %s\n", ast_cdr_flags2str(user->amaflags));
16244       ast_cli(a->fd, "  Transfer mode: %s\n", transfermode2str(user->allowtransfer));
16245       ast_cli(a->fd, "  MaxCallBR    : %d kbps\n", user->maxcallbitrate);
16246       ast_cli(a->fd, "  CallingPres  : %s\n", ast_describe_caller_presentation(user->callingpres));
16247       ast_cli(a->fd, "  Call limit   : %d\n", user->call_limit);
16248       ast_cli(a->fd, "  Callgroup    : ");
16249       print_group(a->fd, user->callgroup, 0);
16250       ast_cli(a->fd, "  Pickupgroup  : ");
16251       print_group(a->fd, user->pickupgroup, 0);
16252       ast_cli(a->fd, "  Callerid     : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), user->cid_name, user->cid_num, "<unspecified>"));
16253       ast_cli(a->fd, "  ACL          : %s\n", cli_yesno(user->ha != NULL));
16254       ast_cli(a->fd, "  Sess-Timers  : %s\n", stmode2str(user->stimer.st_mode_oper));
16255       ast_cli(a->fd, "  Sess-Refresh : %s\n", strefresher2str(user->stimer.st_ref));
16256       ast_cli(a->fd, "  Sess-Expires : %d secs\n", user->stimer.st_max_se);
16257       ast_cli(a->fd, "  Sess-Min-SE  : %d secs\n", user->stimer.st_min_se);
16258 
16259       ast_cli(a->fd, "  Codec Order  : (");
16260       print_codec_to_cli(a->fd, &user->prefs);
16261       ast_cli(a->fd, ")\n");
16262 
16263       ast_cli(a->fd, "  Auto-Framing:  %s \n", cli_yesno(user->autoframing));
16264       if (user->chanvars) {
16265          ast_cli(a->fd, "  Variables    :\n");
16266          for (v = user->chanvars ; v ; v = v->next)
16267             ast_cli(a->fd, "                 %s = %s\n", v->name, v->value);
16268       }
16269 
16270       ast_cli(a->fd, "\n");
16271 
16272       ao2_unlock(user);
16273       unref_peer(user, "sip show user");
16274    } else {
16275       ast_cli(a->fd, "User %s not found.\n", a->argv[3]);
16276       ast_cli(a->fd, "\n");
16277    }
16278 
16279    return CLI_SUCCESS;
16280 }
16281 
16282 
16283 static char *sip_show_sched(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16284 {
16285    struct ast_str *cbuf;
16286    struct ast_cb_names cbnames = {9, { "retrans_pkt",
16287                                         "__sip_autodestruct",
16288                                         "expire_register",
16289                                         "auto_congest",
16290                                         "sip_reg_timeout",
16291                                         "sip_poke_peer_s",
16292                                         "sip_poke_noanswer",
16293                                         "sip_reregister",
16294                                         "sip_reinvite_retry"},
16295                            { retrans_pkt,
16296                                      __sip_autodestruct,
16297                                      expire_register,
16298                                      auto_congest,
16299                                      sip_reg_timeout,
16300                                      sip_poke_peer_s,
16301                                      sip_poke_noanswer,
16302                                      sip_reregister,
16303                                      sip_reinvite_retry}};
16304    
16305    switch (cmd) {
16306    case CLI_INIT:
16307       e->command = "sip show sched";
16308       e->usage =
16309          "Usage: sip show sched\n"
16310          "       Shows stats on what's in the sched queue at the moment\n";
16311       return NULL;
16312    case CLI_GENERATE:
16313       return NULL;
16314    }
16315 
16316    cbuf = ast_str_alloca(2048);
16317 
16318    ast_cli(a->fd, "\n");
16319    ast_sched_report(sched, &cbuf, &cbnames);
16320    ast_cli(a->fd, "%s", cbuf->str);
16321 
16322    return CLI_SUCCESS;
16323 }
16324 
16325 /*! \brief  Show SIP Registry (registrations with other SIP proxies */
16326 static char *sip_show_registry(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16327 {
16328 #define FORMAT2 "%-30.30s %-6.6s %-12.12s  %8.8s %-20.20s %-25.25s\n"
16329 #define FORMAT  "%-30.30s %-6.6s %-12.12s  %8d %-20.20s %-25.25s\n"
16330    char host[80];
16331    char tmpdat[256];
16332    struct ast_tm tm;
16333    int counter = 0;
16334 
16335    switch (cmd) {
16336    case CLI_INIT:
16337       e->command = "sip show registry";
16338       e->usage =
16339          "Usage: sip show registry\n"
16340          "       Lists all registration requests and status.\n";
16341       return NULL;
16342    case CLI_GENERATE:
16343       return NULL;
16344    }
16345 
16346    if (a->argc != 3)
16347       return CLI_SHOWUSAGE;
16348    ast_cli(a->fd, FORMAT2, "Host", "dnsmgr", "Username", "Refresh", "State", "Reg.Time");
16349    
16350    ASTOBJ_CONTAINER_TRAVERSE(&regl, 1, do {
16351       ASTOBJ_RDLOCK(iterator);
16352       snprintf(host, sizeof(host), "%s:%d", iterator->hostname, iterator->portno ? iterator->portno : STANDARD_SIP_PORT);
16353       if (iterator->regtime.tv_sec) {
16354          ast_localtime(&iterator->regtime, &tm, NULL);
16355          ast_strftime(tmpdat, sizeof(tmpdat), "%a, %d %b %Y %T", &tm);
16356       } else 
16357          tmpdat[0] = '\0';
16358       ast_cli(a->fd, FORMAT, host, (iterator->dnsmgr) ? "Y" : "N", iterator->username, iterator->refresh, regstate2str(iterator->regstate), tmpdat);
16359       ASTOBJ_UNLOCK(iterator);
16360       counter++;
16361    } while(0));
16362    ast_cli(a->fd, "%d SIP registrations.\n", counter);
16363    return CLI_SUCCESS;
16364 #undef FORMAT
16365 #undef FORMAT2
16366 }
16367 
16368 /*! \brief Unregister (force expiration) a SIP peer in the registry via CLI 
16369    \note This function does not tell the SIP device what's going on,
16370    so use it with great care.
16371 */
16372 static char *sip_unregister(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16373 {
16374    struct sip_peer *peer;
16375    int load_realtime = 0;
16376 
16377    switch (cmd) {
16378    case CLI_INIT:
16379       e->command = "sip unregister";
16380       e->usage =
16381          "Usage: sip unregister <peer>\n"
16382          "       Unregister (force expiration) a SIP peer from the registry\n";
16383       return NULL;
16384    case CLI_GENERATE:
16385       return complete_sip_unregister(a->line, a->word, a->pos, a->n);
16386    }
16387    
16388    if (a->argc != 3)
16389       return CLI_SHOWUSAGE;
16390    
16391    if ((peer = find_peer(a->argv[2], NULL, load_realtime, FINDPEERS, TRUE, 0))) {
16392       if (peer->expire > 0) {
16393          AST_SCHED_DEL_UNREF(sched, peer->expire,
16394             unref_peer(peer, "remove register expire ref"));
16395          expire_register(ref_peer(peer, "ref for expire_register"));
16396          ast_cli(a->fd, "Unregistered peer \'%s\'\n\n", a->argv[2]);
16397       } else {
16398          ast_cli(a->fd, "Peer %s not registered\n", a->argv[2]);
16399       }
16400       unref_peer(peer, "sip_unregister: unref_peer via sip_unregister: done with peer from find_peer call");
16401    } else {
16402       ast_cli(a->fd, "Peer unknown: \'%s\'. Not unregistered.\n", a->argv[2]);
16403    }
16404    
16405    return CLI_SUCCESS;
16406 }
16407 
16408 /*! \brief Callback for show_chanstats */
16409 static int show_chanstats_cb(void *__cur, void *__arg, int flags)
16410 {
16411 #define FORMAT2 "%-15.15s  %-11.11s  %-8.8s %-10.10s  %-10.10s (     %%) %-6.6s %-10.10s  %-10.10s (     %%) %-6.6s\n"
16412 #define FORMAT  "%-15.15s  %-11.11s  %-8.8s %-10.10u%-1.1s %-10.10u (%5.2f%%) %-6.6u %-10.10u%-1.1s %-10.10u (%5.2f%%) %-6.6u\n"
16413    struct sip_pvt *cur = __cur;
16414    unsigned int rxcount, txcount, rxploss, txploss;
16415    char durbuf[10];
16416         int duration;
16417         int durh, durm, durs;
16418    struct ast_channel *c = cur->owner;
16419    struct __show_chan_arg *arg = __arg;
16420    int fd = arg->fd;
16421 
16422 
16423    if (cur->subscribed != NONE) /* Subscriptions */
16424       return 0;   /* don't care, we scan all channels */
16425 
16426    if (!cur->rtp) {
16427       if (sipdebug)
16428          ast_cli(fd, "%-15.15s  %-11.11s (inv state: %s) -- %s\n", ast_inet_ntoa(cur->sa.sin_addr), cur->callid, invitestate2string[cur->invitestate].desc, "-- No RTP active");
16429       return 0;   /* don't care, we scan all channels */
16430    }
16431    rxcount = ast_rtp_get_qosvalue(cur->rtp, AST_RTP_RXCOUNT);
16432    txcount = ast_rtp_get_qosvalue(cur->rtp, AST_RTP_TXCOUNT);
16433    rxploss = ast_rtp_get_qosvalue(cur->rtp, AST_RTP_RXPLOSS);
16434    txploss = ast_rtp_get_qosvalue(cur->rtp, AST_RTP_TXPLOSS);
16435 
16436    /* Find the duration of this channel */
16437    if (c && c->cdr && !ast_tvzero(c->cdr->start)) {
16438       duration = (int)(ast_tvdiff_ms(ast_tvnow(), c->cdr->start) / 1000);
16439       durh = duration / 3600;
16440       durm = (duration % 3600) / 60;
16441       durs = duration % 60;
16442       snprintf(durbuf, sizeof(durbuf), "%02d:%02d:%02d", durh, durm, durs);
16443    } else {
16444       durbuf[0] = '\0';
16445    }
16446    /* Print stats for every call with RTP */
16447    ast_cli(fd, FORMAT, 
16448       ast_inet_ntoa(cur->sa.sin_addr), 
16449       cur->callid, 
16450       durbuf,
16451       rxcount > (unsigned int) 100000 ? (unsigned int) (rxcount)/(unsigned int) 1000 : rxcount,
16452       rxcount > (unsigned int) 100000 ? "K":" ",
16453       rxploss,
16454       (rxcount + rxploss) > 0 ? (double) rxploss / (rxcount + rxploss) * 100 : 0,
16455       ast_rtp_get_qosvalue(cur->rtp, AST_RTP_RXJITTER),
16456       txcount > (unsigned int) 100000 ? (unsigned int) (txcount)/(unsigned int) 1000 : txcount,
16457       txcount > (unsigned int) 100000 ? "K":" ",
16458       txploss,
16459       txcount > 0 ? (double) txploss / txcount * 100 : 0,
16460       ast_rtp_get_qosvalue(cur->rtp, AST_RTP_TXJITTER)
16461    );
16462    arg->numchans++;
16463 
16464    return 0;   /* don't care, we scan all channels */
16465 }
16466 
16467 /*! \brief SIP show channelstats CLI (main function) */
16468 static char *sip_show_channelstats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16469 {
16470    struct __show_chan_arg arg = { .fd = a->fd, .numchans = 0 };
16471 
16472    switch (cmd) {
16473    case CLI_INIT:
16474       e->command = "sip show channelstats";
16475       e->usage =
16476          "Usage: sip show channelstats\n"
16477          "       Lists all currently active SIP channel's RTCP statistics.\n"
16478          "       Note that calls in the much optimized RTP P2P bridge mode will not show any packets here.";
16479       return NULL;
16480    case CLI_GENERATE:
16481       return NULL;
16482    }
16483 
16484    if (a->argc != 3)
16485       return CLI_SHOWUSAGE;
16486 
16487    ast_cli(a->fd, FORMAT2, "Peer", "Call ID", "Duration", "Recv: Pack", "Lost", "Jitter", "Send: Pack", "Lost", "Jitter");
16488    /* iterate on the container and invoke the callback on each item */
16489    ao2_t_callback(dialogs, OBJ_NODATA, show_chanstats_cb, &arg, "callback to sip show chanstats");
16490    ast_cli(a->fd, "%d active SIP channel%s\n", arg.numchans, (arg.numchans != 1) ? "s" : ""); 
16491    return CLI_SUCCESS;
16492 }
16493 #undef FORMAT
16494 #undef FORMAT2
16495 
16496 /*! \brief List global settings for the SIP channel */
16497 static char *sip_show_settings(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16498 {
16499    int realtimepeers;
16500    int realtimeregs;
16501    char codec_buf[SIPBUFSIZE];
16502    const char *msg;  /* temporary msg pointer */
16503 
16504    switch (cmd) {
16505    case CLI_INIT:
16506       e->command = "sip show settings";
16507       e->usage =
16508          "Usage: sip show settings\n"
16509          "       Provides detailed list of the configuration of the SIP channel.\n";
16510       return NULL;
16511    case CLI_GENERATE:
16512       return NULL;
16513    }
16514 
16515 
16516    realtimepeers = ast_check_realtime("sippeers");
16517    realtimeregs = ast_check_realtime("sipregs");
16518 
16519    if (a->argc != 3)
16520       return CLI_SHOWUSAGE;
16521    ast_cli(a->fd, "\n\nGlobal Settings:\n");
16522    ast_cli(a->fd, "----------------\n");
16523    ast_cli(a->fd, "  UDP SIP Port:           %d\n", ntohs(bindaddr.sin_port));
16524    ast_cli(a->fd, "  UDP Bindaddress:        %s\n", ast_inet_ntoa(bindaddr.sin_addr));
16525    ast_cli(a->fd, "  TCP SIP Port:           ");
16526    if (sip_tcp_desc.local_address.sin_family == AF_INET) {
16527       ast_cli(a->fd, "%d\n", ntohs(sip_tcp_desc.local_address.sin_port));
16528       ast_cli(a->fd, "  TCP Bindaddress:        %s\n", ast_inet_ntoa(sip_tcp_desc.local_address.sin_addr));
16529    } else {
16530       ast_cli(a->fd, "Disabled\n");
16531    }
16532    ast_cli(a->fd, "  TLS SIP Port:           ");
16533    if (default_tls_cfg.enabled != FALSE) {
16534       ast_cli(a->fd, "%d\n", ntohs(sip_tls_desc.local_address.sin_port));
16535       ast_cli(a->fd, "  TLS Bindaddress:        %s\n", ast_inet_ntoa(sip_tls_desc.local_address.sin_addr));
16536    } else {
16537       ast_cli(a->fd, "Disabled\n");
16538    }
16539    ast_cli(a->fd, "  Videosupport:           %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_VIDEOSUPPORT)));
16540    ast_cli(a->fd, "  Textsupport:            %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_TEXTSUPPORT)));
16541    ast_cli(a->fd, "  Ignore SDP sess. ver.:  %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_IGNORESDPVERSION)));
16542    ast_cli(a->fd, "  AutoCreate Peer:        %s\n", cli_yesno(sip_cfg.autocreatepeer));
16543    ast_cli(a->fd, "  Match Auth Username:    %s\n", cli_yesno(global_match_auth_username));
16544    ast_cli(a->fd, "  Allow unknown access:   %s\n", cli_yesno(sip_cfg.allowguest));
16545    ast_cli(a->fd, "  Allow subscriptions:    %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)));
16546    ast_cli(a->fd, "  Allow overlap dialing:  %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP)));
16547    ast_cli(a->fd, "  Allow promsic. redir:   %s\n", cli_yesno(ast_test_flag(&global_flags[0], SIP_PROMISCREDIR)));
16548    ast_cli(a->fd, "  Enable call counters:   %s\n", cli_yesno(global_callcounter));
16549    ast_cli(a->fd, "  SIP domain support:     %s\n", cli_yesno(!AST_LIST_EMPTY(&domain_list)));
16550    ast_cli(a->fd, "  Realm. auth:            %s\n", cli_yesno(authl != NULL));
16551    ast_cli(a->fd, "  Our auth realm          %s\n", sip_cfg.realm);
16552    ast_cli(a->fd, "  Call to non-local dom.: %s\n", cli_yesno(sip_cfg.allow_external_domains));
16553    ast_cli(a->fd, "  URI user is phone no:   %s\n", cli_yesno(ast_test_flag(&global_flags[0], SIP_USEREQPHONE)));
16554    ast_cli(a->fd, "  Always auth rejects:    %s\n", cli_yesno(sip_cfg.alwaysauthreject));
16555    ast_cli(a->fd, "  Direct RTP setup:       %s\n", cli_yesno(sip_cfg.directrtpsetup));
16556    ast_cli(a->fd, "  User Agent:             %s\n", global_useragent);
16557    ast_cli(a->fd, "  SDP Session Name:       %s\n", ast_strlen_zero(global_sdpsession) ? "-" : global_sdpsession);
16558    ast_cli(a->fd, "  SDP Owner Name:         %s\n", ast_strlen_zero(global_sdpowner) ? "-" : global_sdpowner);
16559    ast_cli(a->fd, "  Reg. context:           %s\n", S_OR(global_regcontext, "(not set)"));
16560    ast_cli(a->fd, "  Regexten on Qualify:    %s\n", cli_yesno(sip_cfg.regextenonqualify));
16561    ast_cli(a->fd, "  Caller ID:              %s\n", default_callerid);
16562    ast_cli(a->fd, "  From: Domain:           %s\n", default_fromdomain);
16563    ast_cli(a->fd, "  Record SIP history:     %s\n", recordhistory ? "On" : "Off");
16564    ast_cli(a->fd, "  Call Events:            %s\n", sip_cfg.callevents ? "On" : "Off");
16565    ast_cli(a->fd, "  Auth. Failure Events:   %s\n", global_authfailureevents ? "On" : "Off");
16566 
16567    ast_cli(a->fd, "  T.38 support:           %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_T38SUPPORT)));
16568    ast_cli(a->fd, "  T.38 EC mode:           %s\n", faxec2str(ast_test_flag(&global_flags[1], SIP_PAGE2_T38SUPPORT)));
16569    ast_cli(a->fd, "  T.38 MaxDtgrm:          %d\n", global_t38_maxdatagram);
16570 
16571    if (!realtimepeers && !realtimeregs)
16572       ast_cli(a->fd, "  SIP realtime:           Disabled\n" );
16573    else
16574       ast_cli(a->fd, "  SIP realtime:           Enabled\n" );
16575    ast_cli(a->fd, "  Qualify Freq :          %d ms\n", global_qualifyfreq);
16576    ast_cli(a->fd, "\nNetwork QoS Settings:\n");
16577    ast_cli(a->fd, "---------------------------\n");
16578    ast_cli(a->fd, "  IP ToS SIP:             %s\n", ast_tos2str(global_tos_sip));
16579    ast_cli(a->fd, "  IP ToS RTP audio:       %s\n", ast_tos2str(global_tos_audio));
16580    ast_cli(a->fd, "  IP ToS RTP video:       %s\n", ast_tos2str(global_tos_video));
16581    ast_cli(a->fd, "  IP ToS RTP text:        %s\n", ast_tos2str(global_tos_text));
16582    ast_cli(a->fd, "  802.1p CoS SIP:         %d\n", global_cos_sip);
16583    ast_cli(a->fd, "  802.1p CoS RTP audio:   %d\n", global_cos_audio);
16584    ast_cli(a->fd, "  802.1p CoS RTP video:   %d\n", global_cos_video);
16585    ast_cli(a->fd, "  802.1p CoS RTP text:    %d\n", global_cos_text);
16586    ast_cli(a->fd, "  Jitterbuffer enabled:   %s\n", cli_yesno(ast_test_flag(&global_jbconf, AST_JB_ENABLED)));
16587    ast_cli(a->fd, "  Jitterbuffer forced:    %s\n", cli_yesno(ast_test_flag(&global_jbconf, AST_JB_FORCED)));
16588    ast_cli(a->fd, "  Jitterbuffer max size:  %ld\n", global_jbconf.max_size);
16589    ast_cli(a->fd, "  Jitterbuffer resync:    %ld\n", global_jbconf.resync_threshold);
16590    ast_cli(a->fd, "  Jitterbuffer impl:      %s\n", global_jbconf.impl);
16591    ast_cli(a->fd, "  Jitterbuffer log:       %s\n", cli_yesno(ast_test_flag(&global_jbconf, AST_JB_LOG)));
16592 
16593    ast_cli(a->fd, "\nNetwork Settings:\n");
16594    ast_cli(a->fd, "---------------------------\n");
16595    /* determine if/how SIP address can be remapped */
16596    if (localaddr == NULL)
16597       msg = "Disabled, no localnet list";
16598    else if (externip.sin_addr.s_addr == 0)
16599       msg = "Disabled, externip is 0.0.0.0";
16600    else if (stunaddr.sin_addr.s_addr != 0)
16601       msg = "Enabled using STUN";
16602    else if (!ast_strlen_zero(externhost))
16603       msg = "Enabled using externhost";
16604    else
16605       msg = "Enabled using externip";
16606    ast_cli(a->fd, "  SIP address remapping:  %s\n", msg);
16607    ast_cli(a->fd, "  Externhost:             %s\n", S_OR(externhost, "<none>"));
16608    ast_cli(a->fd, "  Externip:               %s:%d\n", ast_inet_ntoa(externip.sin_addr), ntohs(externip.sin_port));
16609    ast_cli(a->fd, "  Externrefresh:          %d\n", externrefresh);
16610    {
16611       struct ast_ha *d;
16612       const char *prefix = "Localnet:";
16613       char buf[INET_ADDRSTRLEN]; /* need to print two addresses */
16614 
16615       for (d = localaddr; d ; prefix = "", d = d->next) {
16616          ast_cli(a->fd, "  %-24s%s/%s\n",
16617              prefix, ast_inet_ntoa(d->netaddr),
16618              inet_ntop(AF_INET, &d->netmask, buf, sizeof(buf)) );
16619       }
16620    }
16621    ast_cli(a->fd, "  STUN server:            %s:%d\n", ast_inet_ntoa(stunaddr.sin_addr), ntohs(stunaddr.sin_port));
16622  
16623    ast_cli(a->fd, "\nGlobal Signalling Settings:\n");
16624    ast_cli(a->fd, "---------------------------\n");
16625    ast_cli(a->fd, "  Codecs:                 ");
16626    ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, global_capability);
16627    ast_cli(a->fd, "%s\n", codec_buf);
16628    ast_cli(a->fd, "  Codec Order:            ");
16629    print_codec_to_cli(a->fd, &default_prefs);
16630    ast_cli(a->fd, "\n");
16631    ast_cli(a->fd, "  Relax DTMF:             %s\n", cli_yesno(global_relaxdtmf));
16632    ast_cli(a->fd, "  RFC2833 Compensation:   %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_RFC2833_COMPENSATE)));
16633    ast_cli(a->fd, "  Compact SIP headers:    %s\n", cli_yesno(sip_cfg.compactheaders));
16634    ast_cli(a->fd, "  RTP Keepalive:          %d %s\n", global_rtpkeepalive, global_rtpkeepalive ? "" : "(Disabled)" );
16635    ast_cli(a->fd, "  RTP Timeout:            %d %s\n", global_rtptimeout, global_rtptimeout ? "" : "(Disabled)" );
16636    ast_cli(a->fd, "  RTP Hold Timeout:       %d %s\n", global_rtpholdtimeout, global_rtpholdtimeout ? "" : "(Disabled)");
16637    ast_cli(a->fd, "  MWI NOTIFY mime type:   %s\n", default_notifymime);
16638    ast_cli(a->fd, "  DNS SRV lookup:         %s\n", cli_yesno(sip_cfg.srvlookup));
16639    ast_cli(a->fd, "  Pedantic SIP support:   %s\n", cli_yesno(sip_cfg.pedanticsipchecking));
16640    ast_cli(a->fd, "  Reg. min duration       %d secs\n", min_expiry);
16641    ast_cli(a->fd, "  Reg. max duration:      %d secs\n", max_expiry);
16642    ast_cli(a->fd, "  Reg. default duration:  %d secs\n", default_expiry);
16643    ast_cli(a->fd, "  Outbound reg. timeout:  %d secs\n", global_reg_timeout);
16644    ast_cli(a->fd, "  Outbound reg. attempts: %d\n", global_regattempts_max);
16645    ast_cli(a->fd, "  Notify ringing state:   %s\n", cli_yesno(sip_cfg.notifyringing));
16646    if (sip_cfg.notifyringing) {
16647       ast_cli(a->fd, "    Include CID:          %s%s\n",
16648             cli_yesno(sip_cfg.notifycid),
16649             sip_cfg.notifycid == IGNORE_CONTEXT ? " (Ignoring context)" : "");
16650    }
16651    ast_cli(a->fd, "  Notify hold state:      %s\n", cli_yesno(sip_cfg.notifyhold));
16652    ast_cli(a->fd, "  SIP Transfer mode:      %s\n", transfermode2str(sip_cfg.allowtransfer));
16653    ast_cli(a->fd, "  Max Call Bitrate:       %d kbps\n", default_maxcallbitrate);
16654    ast_cli(a->fd, "  Auto-Framing:           %s\n", cli_yesno(global_autoframing));
16655    ast_cli(a->fd, "  Outb. proxy:            %s %s\n", ast_strlen_zero(sip_cfg.outboundproxy.name) ? "<not set>" : sip_cfg.outboundproxy.name,
16656                      sip_cfg.outboundproxy.force ? "(forced)" : "");
16657    ast_cli(a->fd, "  Session Timers:         %s\n", stmode2str(global_st_mode));
16658    ast_cli(a->fd, "  Session Refresher:      %s\n", strefresher2str (global_st_refresher));
16659    ast_cli(a->fd, "  Session Expires:        %d secs\n", global_max_se);
16660    ast_cli(a->fd, "  Session Min-SE:         %d secs\n", global_min_se);
16661    ast_cli(a->fd, "  Timer T1:               %d\n", global_t1);
16662    ast_cli(a->fd, "  Timer T1 minimum:       %d\n", global_t1min);
16663    ast_cli(a->fd, "  Timer B:                %d\n", global_timer_b);
16664    ast_cli(a->fd, "  No premature media:     %s\n", global_prematuremediafilter ? "Yes" : "No");
16665 
16666    ast_cli(a->fd, "\nDefault Settings:\n");
16667    ast_cli(a->fd, "-----------------\n");
16668    ast_cli(a->fd, "  Allowed transports:     %s\n", get_transport_list(default_transports)); 
16669    ast_cli(a->fd, "  Outbound transport:    %s\n", get_transport(default_primary_transport));
16670    ast_cli(a->fd, "  Context:                %s\n", sip_cfg.default_context);
16671    ast_cli(a->fd, "  Nat:                    %s\n", nat2str(ast_test_flag(&global_flags[0], SIP_NAT)));
16672    ast_cli(a->fd, "  DTMF:                   %s\n", dtmfmode2str(ast_test_flag(&global_flags[0], SIP_DTMF)));
16673    ast_cli(a->fd, "  Qualify:                %d\n", default_qualify);
16674    ast_cli(a->fd, "  Use ClientCode:         %s\n", cli_yesno(ast_test_flag(&global_flags[0], SIP_USECLIENTCODE)));
16675    ast_cli(a->fd, "  Progress inband:        %s\n", (ast_test_flag(&global_flags[0], SIP_PROG_INBAND) == SIP_PROG_INBAND_NEVER) ? "Never" : (ast_test_flag(&global_flags[0], SIP_PROG_INBAND) == SIP_PROG_INBAND_NO) ? "No" : "Yes" );
16676    ast_cli(a->fd, "  Language:               %s\n", default_language);
16677    ast_cli(a->fd, "  MOH Interpret:          %s\n", default_mohinterpret);
16678    ast_cli(a->fd, "  MOH Suggest:            %s\n", default_mohsuggest);
16679    ast_cli(a->fd, "  Voice Mail Extension:   %s\n", default_vmexten);
16680    ast_cli(a->fd, "  Forward Detected Loops: %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_FORWARD_LOOP_DETECTED)));
16681    
16682    if (realtimepeers || realtimeregs) {
16683       ast_cli(a->fd, "\nRealtime SIP Settings:\n");
16684       ast_cli(a->fd, "----------------------\n");
16685       ast_cli(a->fd, "  Realtime Peers:         %s\n", cli_yesno(realtimepeers));
16686       ast_cli(a->fd, "  Realtime Regs:          %s\n", cli_yesno(realtimeregs));
16687       ast_cli(a->fd, "  Cache Friends:          %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)));
16688       ast_cli(a->fd, "  Update:                 %s\n", cli_yesno(sip_cfg.peer_rtupdate));
16689       ast_cli(a->fd, "  Ignore Reg. Expire:     %s\n", cli_yesno(sip_cfg.ignore_regexpire));
16690       ast_cli(a->fd, "  Save sys. name:         %s\n", cli_yesno(sip_cfg.rtsave_sysname));
16691       ast_cli(a->fd, "  Auto Clear:             %d (%s)\n", sip_cfg.rtautoclear, ast_test_flag(&global_flags[1], SIP_PAGE2_RTAUTOCLEAR) ? "Enabled" : "Disabled");
16692    }
16693    ast_cli(a->fd, "\n----\n");
16694    return CLI_SUCCESS;
16695 }
16696 
16697 static char *sip_show_mwi(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16698 {
16699 #define FORMAT  "%-30.30s  %-12.12s  %-10.10s  %-10.10s\n"
16700    char host[80];
16701    
16702    switch (cmd) {
16703    case CLI_INIT:
16704       e->command = "sip show mwi";
16705       e->usage =
16706          "Usage: sip show mwi\n"
16707          "       Provides a list of MWI subscriptions and status.\n";
16708       return NULL;
16709    case CLI_GENERATE:
16710       return NULL;
16711    }
16712    
16713    ast_cli(a->fd, FORMAT, "Host", "Username", "Mailbox", "Subscribed");
16714    
16715    ASTOBJ_CONTAINER_TRAVERSE(&submwil, 1, do {
16716       ASTOBJ_RDLOCK(iterator);
16717       snprintf(host, sizeof(host), "%s:%d", iterator->hostname, iterator->portno ? iterator->portno : STANDARD_SIP_PORT);
16718       ast_cli(a->fd, FORMAT, host, iterator->username, iterator->mailbox, iterator->subscribed ? "Yes" : "No");
16719       ASTOBJ_UNLOCK(iterator);
16720    } while(0));
16721 
16722    return CLI_SUCCESS;
16723 #undef FORMAT
16724 }
16725 
16726 
16727 /*! \brief Show subscription type in string format */
16728 static const char *subscription_type2str(enum subscriptiontype subtype)
16729 {
16730    int i;
16731 
16732    for (i = 1; i < ARRAY_LEN(subscription_types); i++) {
16733       if (subscription_types[i].type == subtype) {
16734          return subscription_types[i].text;
16735       }
16736    }
16737    return subscription_types[0].text;
16738 }
16739 
16740 /*! \brief Find subscription type in array */
16741 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype)
16742 {
16743    int i;
16744 
16745    for (i = 1; i < ARRAY_LEN(subscription_types); i++) {
16746       if (subscription_types[i].type == subtype) {
16747          return &subscription_types[i];
16748       }
16749    }
16750    return &subscription_types[0];
16751 }
16752 
16753 /*
16754  * We try to structure all functions that loop on data structures as
16755  * a handler for individual entries, and a mainloop that iterates
16756  * on the main data structure. This way, moving the code to containers
16757  * that support iteration through callbacks will be a lot easier.
16758  */
16759 
16760 #define FORMAT4 "%-15.15s  %-15.15s  %-15.15s  %-15.15s  %-13.13s  %-15.15s %-10.10s %-6.6d\n"
16761 #define FORMAT3 "%-15.15s  %-15.15s  %-15.15s  %-15.15s  %-13.13s  %-15.15s %-10.10s %-6.6s\n"
16762 #define FORMAT2 "%-15.15s  %-15.15s  %-15.15s  %-15.15s  %-7.7s  %-15.15s %-6.6s\n"
16763 #define FORMAT  "%-15.15s  %-15.15s  %-15.15s  %-15.15s  %-3.3s %-3.3s  %-15.15s %-10.10s\n"
16764 
16765 /*! \brief callback for show channel|subscription */
16766 static int show_channels_cb(void *__cur, void *__arg, int flags)
16767 {
16768    struct sip_pvt *cur = __cur;
16769    struct __show_chan_arg *arg = __arg;
16770    const struct sockaddr_in *dst = sip_real_dst(cur);
16771    
16772    /* XXX indentation preserved to reduce diff. Will be fixed later */
16773    if (cur->subscribed == NONE && !arg->subscriptions) {
16774       /* set if SIP transfer in progress */
16775       const char *referstatus = cur->refer ? referstatus2str(cur->refer->status) : "";
16776       char formatbuf[SIPBUFSIZE/2];
16777       
16778       ast_cli(arg->fd, FORMAT, ast_inet_ntoa(dst->sin_addr), 
16779             S_OR(cur->username, S_OR(cur->cid_num, "(None)")),
16780             cur->callid, 
16781             ast_getformatname_multiple(formatbuf, sizeof(formatbuf), cur->owner ? cur->owner->nativeformats : 0),
16782             cli_yesno(ast_test_flag(&cur->flags[1], SIP_PAGE2_CALL_ONHOLD)),
16783             cur->needdestroy ? "(d)" : "",
16784             cur->lastmsg ,
16785             referstatus
16786          );
16787       arg->numchans++;
16788    }
16789    if (cur->subscribed != NONE && arg->subscriptions) {
16790       struct ast_str *mailbox_str = ast_str_alloca(512);
16791       if (cur->subscribed == MWI_NOTIFICATION && cur->relatedpeer)
16792          peer_mailboxes_to_str(&mailbox_str, cur->relatedpeer);
16793       ast_cli(arg->fd, FORMAT4, ast_inet_ntoa(dst->sin_addr),
16794             S_OR(cur->username, S_OR(cur->cid_num, "(None)")), 
16795                cur->callid,
16796             /* the 'complete' exten/context is hidden in the refer_to field for subscriptions */
16797             cur->subscribed == MWI_NOTIFICATION ? "--" : cur->subscribeuri,
16798             cur->subscribed == MWI_NOTIFICATION ? "<none>" : ast_extension_state2str(cur->laststate), 
16799             subscription_type2str(cur->subscribed),
16800             cur->subscribed == MWI_NOTIFICATION ? S_OR(mailbox_str->str, "<none>") : "<none>",
16801             cur->expiry
16802          );
16803       arg->numchans++;
16804    }
16805    return 0;   /* don't care, we scan all channels */
16806 }
16807 
16808 /*! \brief CLI for show channels or subscriptions.
16809  * This is a new-style CLI handler so a single function contains
16810  * the prototype for the function, the 'generator' to produce multiple
16811  * entries in case it is required, and the actual handler for the command.
16812  */
16813 static char *sip_show_channels(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16814 {
16815    struct __show_chan_arg arg = { .fd = a->fd, .numchans = 0 };
16816 
16817 
16818    if (cmd == CLI_INIT) {
16819       e->command = "sip show {channels|subscriptions}";
16820       e->usage =
16821          "Usage: sip show channels\n"
16822          "       Lists all currently active SIP calls (dialogs).\n"
16823          "Usage: sip show subscriptions\n"
16824          "       Lists active SIP subscriptions.\n";
16825       return NULL;
16826    } else if (cmd == CLI_GENERATE)
16827       return NULL;
16828 
16829    if (a->argc != e->args)
16830       return CLI_SHOWUSAGE;
16831    arg.subscriptions = !strcasecmp(a->argv[e->args - 1], "subscriptions");
16832    if (!arg.subscriptions)
16833       ast_cli(arg.fd, FORMAT2, "Peer", "User/ANR", "Call ID", "Format", "Hold", "Last Message", "Expiry");
16834    else
16835       ast_cli(arg.fd, FORMAT3, "Peer", "User", "Call ID", "Extension", "Last state", "Type", "Mailbox", "Expiry");
16836 
16837    /* iterate on the container and invoke the callback on each item */
16838    ao2_t_callback(dialogs, OBJ_NODATA, show_channels_cb, &arg, "callback to show channels");
16839    
16840    /* print summary information */
16841    ast_cli(arg.fd, "%d active SIP %s%s\n", arg.numchans,
16842       (arg.subscriptions ? "subscription" : "dialog"),
16843       ESS(arg.numchans));  /* ESS(n) returns an "s" if n>1 */
16844    return CLI_SUCCESS;
16845 #undef FORMAT
16846 #undef FORMAT2
16847 #undef FORMAT3
16848 }
16849 
16850 /*! \brief Support routine for 'sip show channel' and 'sip show history' CLI
16851  * This is in charge of generating all strings that match a prefix in the
16852  * given position. As many functions of this kind, each invokation has
16853  * O(state) time complexity so be careful in using it.
16854  */
16855 static char *complete_sipch(const char *line, const char *word, int pos, int state)
16856 {
16857    int which=0;
16858    struct sip_pvt *cur;
16859    char *c = NULL;
16860    int wordlen = strlen(word);
16861    struct ao2_iterator i;
16862 
16863    if (pos != 3) {
16864       return NULL;
16865    }
16866 
16867    i = ao2_iterator_init(dialogs, 0);
16868    while ((cur = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
16869       sip_pvt_lock(cur);
16870       if (!strncasecmp(word, cur->callid, wordlen) && ++which > state) {
16871          c = ast_strdup(cur->callid);
16872          sip_pvt_unlock(cur);
16873          dialog_unref(cur, "drop ref in iterator loop break");
16874          break;
16875       }
16876       sip_pvt_unlock(cur);
16877       dialog_unref(cur, "drop ref in iterator loop");
16878    }
16879    ao2_iterator_destroy(&i);
16880    return c;
16881 }
16882 
16883 
16884 /*! \brief Do completion on peer name */
16885 static char *complete_sip_peer(const char *word, int state, int flags2)
16886 {
16887    char *result = NULL;
16888    int wordlen = strlen(word);
16889    int which = 0;
16890    struct ao2_iterator i = ao2_iterator_init(peers, 0);
16891    struct sip_peer *peer;
16892 
16893    while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
16894       /* locking of the object is not required because only the name and flags are being compared */
16895       if (!strncasecmp(word, peer->name, wordlen) &&
16896             (!flags2 || ast_test_flag(&peer->flags[1], flags2)) &&
16897             ++which > state)
16898          result = ast_strdup(peer->name);
16899       unref_peer(peer, "toss iterator peer ptr before break");
16900       if (result) {
16901          break;
16902       }
16903    }
16904    ao2_iterator_destroy(&i);
16905    return result;
16906 }
16907 
16908 /*! \brief Do completion on registered peer name */
16909 static char *complete_sip_registered_peer(const char *word, int state, int flags2)
16910 {
16911        char *result = NULL;
16912        int wordlen = strlen(word);
16913        int which = 0;
16914        struct ao2_iterator i;
16915        struct sip_peer *peer;
16916        
16917        i = ao2_iterator_init(peers, 0);
16918        while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
16919           if (!strncasecmp(word, peer->name, wordlen) &&
16920          (!flags2 || ast_test_flag(&peer->flags[1], flags2)) &&
16921          ++which > state && peer->expire > 0)
16922              result = ast_strdup(peer->name);
16923           if (result) {
16924              unref_peer(peer, "toss iterator peer ptr before break");
16925              break;
16926           }
16927           unref_peer(peer, "toss iterator peer ptr");
16928        }
16929        ao2_iterator_destroy(&i);
16930        return result;
16931 }
16932 
16933 /*! \brief Support routine for 'sip show history' CLI */
16934 static char *complete_sip_show_history(const char *line, const char *word, int pos, int state)
16935 {
16936    if (pos == 3)
16937       return complete_sipch(line, word, pos, state);
16938 
16939    return NULL;
16940 }
16941 
16942 /*! \brief Support routine for 'sip show peer' CLI */
16943 static char *complete_sip_show_peer(const char *line, const char *word, int pos, int state)
16944 {
16945    if (pos == 3) {
16946       return complete_sip_peer(word, state, 0);
16947    }
16948 
16949    return NULL;
16950 }
16951 
16952 /*! \brief Support routine for 'sip unregister' CLI */
16953 static char *complete_sip_unregister(const char *line, const char *word, int pos, int state)
16954 {
16955        if (pos == 2)
16956                return complete_sip_registered_peer(word, state, 0);
16957 
16958        return NULL;
16959 }
16960 
16961 /*! \brief Support routine for 'sip notify' CLI */
16962 static char *complete_sipnotify(const char *line, const char *word, int pos, int state)
16963 {
16964    char *c = NULL;
16965 
16966    if (pos == 2) {
16967       int which = 0;
16968       char *cat = NULL;
16969       int wordlen = strlen(word);
16970 
16971       /* do completion for notify type */
16972 
16973       if (!notify_types)
16974          return NULL;
16975       
16976       while ( (cat = ast_category_browse(notify_types, cat)) ) {
16977          if (!strncasecmp(word, cat, wordlen) && ++which > state) {
16978             c = ast_strdup(cat);
16979             break;
16980          }
16981       }
16982       return c;
16983    }
16984 
16985    if (pos > 2)
16986       return complete_sip_peer(word, state, 0);
16987 
16988    return NULL;
16989 }
16990 
16991 /*! \brief Show details of one active dialog */
16992 static char *sip_show_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16993 {
16994    struct sip_pvt *cur;
16995    size_t len;
16996    int found = 0;
16997    struct ao2_iterator i;
16998 
16999    switch (cmd) {
17000    case CLI_INIT:
17001       e->command = "sip show channel";
17002       e->usage =
17003          "Usage: sip show channel <call-id>\n"
17004          "       Provides detailed status on a given SIP dialog (identified by SIP call-id).\n";
17005       return NULL;
17006    case CLI_GENERATE:
17007       return complete_sipch(a->line, a->word, a->pos, a->n);
17008    }
17009 
17010    if (a->argc != 4)
17011       return CLI_SHOWUSAGE;
17012    len = strlen(a->argv[3]);
17013    
17014    i = ao2_iterator_init(dialogs, 0);
17015    while ((cur = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
17016       sip_pvt_lock(cur);
17017 
17018       if (!strncasecmp(cur->callid, a->argv[3], len)) {
17019          char formatbuf[SIPBUFSIZE/2];
17020          ast_cli(a->fd, "\n");
17021          if (cur->subscribed != NONE)
17022             ast_cli(a->fd, "  * Subscription (type: %s)\n", subscription_type2str(cur->subscribed));
17023          else
17024             ast_cli(a->fd, "  * SIP Call\n");
17025          ast_cli(a->fd, "  Curr. trans. direction:  %s\n", ast_test_flag(&cur->flags[0], SIP_OUTGOING) ? "Outgoing" : "Incoming");
17026          ast_cli(a->fd, "  Call-ID:                %s\n", cur->callid);
17027          ast_cli(a->fd, "  Owner channel ID:       %s\n", cur->owner ? cur->owner->name : "<none>");
17028          ast_cli(a->fd, "  Our Codec Capability:   %d\n", cur->capability);
17029          ast_cli(a->fd, "  Non-Codec Capability (DTMF):   %d\n", cur->noncodeccapability);
17030          ast_cli(a->fd, "  Their Codec Capability:   %d\n", cur->peercapability);
17031          ast_cli(a->fd, "  Joint Codec Capability:   %d\n", cur->jointcapability);
17032          ast_cli(a->fd, "  Format:                 %s\n", ast_getformatname_multiple(formatbuf, sizeof(formatbuf), cur->owner ? cur->owner->nativeformats : 0) );
17033          ast_cli(a->fd, "  T.38 support            %s\n", cli_yesno(cur->udptl != NULL));
17034          ast_cli(a->fd, "  Video support           %s\n", cli_yesno(cur->vrtp != NULL));
17035          ast_cli(a->fd, "  MaxCallBR:              %d kbps\n", cur->maxcallbitrate);
17036          ast_cli(a->fd, "  Theoretical Address:    %s:%d\n", ast_inet_ntoa(cur->sa.sin_addr), ntohs(cur->sa.sin_port));
17037          ast_cli(a->fd, "  Received Address:       %s:%d\n", ast_inet_ntoa(cur->recv.sin_addr), ntohs(cur->recv.sin_port));
17038          ast_cli(a->fd, "  SIP Transfer mode:      %s\n", transfermode2str(cur->allowtransfer));
17039          ast_cli(a->fd, "  NAT Support:            %s\n", nat2str(ast_test_flag(&cur->flags[0], SIP_NAT)));
17040          ast_cli(a->fd, "  Audio IP:               %s %s\n", ast_inet_ntoa(cur->redirip.sin_addr.s_addr ? cur->redirip.sin_addr : cur->ourip.sin_addr), cur->redirip.sin_addr.s_addr ? "(Outside bridge)" : "(local)" );
17041          ast_cli(a->fd, "  Our Tag:                %s\n", cur->tag);
17042          ast_cli(a->fd, "  Their Tag:              %s\n", cur->theirtag);
17043          ast_cli(a->fd, "  SIP User agent:         %s\n", cur->useragent);
17044          if (!ast_strlen_zero(cur->username))
17045             ast_cli(a->fd, "  Username:               %s\n", cur->username);
17046          if (!ast_strlen_zero(cur->peername))
17047             ast_cli(a->fd, "  Peername:               %s\n", cur->peername);
17048          if (!ast_strlen_zero(cur->uri))
17049             ast_cli(a->fd, "  Original uri:           %s\n", cur->uri);
17050          if (!ast_strlen_zero(cur->cid_num))
17051             ast_cli(a->fd, "  Caller-ID:              %s\n", cur->cid_num);
17052          ast_cli(a->fd, "  Need Destroy:           %s\n", cli_yesno(cur->needdestroy));
17053          ast_cli(a->fd, "  Last Message:           %s\n", cur->lastmsg);
17054          ast_cli(a->fd, "  Promiscuous Redir:      %s\n", cli_yesno(ast_test_flag(&cur->flags[0], SIP_PROMISCREDIR)));
17055          ast_cli(a->fd, "  Route:                  %s\n", cur->route ? cur->route->hop : "N/A");
17056          ast_cli(a->fd, "  DTMF Mode:              %s\n", dtmfmode2str(ast_test_flag(&cur->flags[0], SIP_DTMF)));
17057          ast_cli(a->fd, "  SIP Options:            ");
17058          if (cur->sipoptions) {
17059             int x;
17060             for (x = 0 ; x < ARRAY_LEN(sip_options); x++) {
17061                if (cur->sipoptions & sip_options[x].id)
17062                   ast_cli(a->fd, "%s ", sip_options[x].text);
17063             }
17064             ast_cli(a->fd, "\n");
17065          } else
17066             ast_cli(a->fd, "(none)\n");
17067 
17068          if (!cur->stimer)
17069             ast_cli(a->fd, "  Session-Timer:          Uninitiallized\n");
17070          else {
17071             ast_cli(a->fd, "  Session-Timer:          %s\n", cur->stimer->st_active ? "Active" : "Inactive");
17072             if (cur->stimer->st_active == TRUE) {
17073                ast_cli(a->fd, "  S-Timer Interval:       %d\n", cur->stimer->st_interval);
17074                ast_cli(a->fd, "  S-Timer Refresher:      %s\n", strefresher2str(cur->stimer->st_ref));
17075                ast_cli(a->fd, "  S-Timer Expirys:        %d\n", cur->stimer->st_expirys);
17076                ast_cli(a->fd, "  S-Timer Sched Id:       %d\n", cur->stimer->st_schedid);
17077                ast_cli(a->fd, "  S-Timer Peer Sts:       %s\n", cur->stimer->st_active_peer_ua ? "Active" : "Inactive");
17078                ast_cli(a->fd, "  S-Timer Cached Min-SE:  %d\n", cur->stimer->st_cached_min_se);
17079                ast_cli(a->fd, "  S-Timer Cached SE:      %d\n", cur->stimer->st_cached_max_se);
17080                ast_cli(a->fd, "  S-Timer Cached Ref:     %s\n", strefresher2str(cur->stimer->st_cached_ref));
17081                ast_cli(a->fd, "  S-Timer Cached Mode:    %s\n", stmode2str(cur->stimer->st_cached_mode));
17082             }
17083          }
17084 
17085          ast_cli(a->fd, "\n\n");
17086 
17087          found++;
17088       }
17089 
17090       sip_pvt_unlock(cur);
17091 
17092       ao2_t_ref(cur, -1, "toss dialog ptr set by iterator_next");
17093    }
17094    ao2_iterator_destroy(&i);
17095 
17096    if (!found) 
17097       ast_cli(a->fd, "No such SIP Call ID starting with '%s'\n", a->argv[3]);
17098 
17099    return CLI_SUCCESS;
17100 }
17101 
17102 /*! \brief Show history details of one dialog */
17103 static char *sip_show_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
17104 {
17105    struct sip_pvt *cur;
17106    size_t len;
17107    int found = 0;
17108    struct ao2_iterator i;
17109 
17110    switch (cmd) {
17111    case CLI_INIT:
17112       e->command = "sip show history";
17113       e->usage =
17114          "Usage: sip show history <call-id>\n"
17115          "       Provides detailed dialog history on a given SIP call (specified by call-id).\n";
17116       return NULL;
17117    case CLI_GENERATE:
17118       return complete_sip_show_history(a->line, a->word, a->pos, a->n);
17119    }
17120 
17121    if (a->argc != 4)
17122       return CLI_SHOWUSAGE;
17123 
17124    if (!recordhistory)
17125       ast_cli(a->fd, "\n***Note: History recording is currently DISABLED.  Use 'sip set history on' to ENABLE.\n");
17126 
17127    len = strlen(a->argv[3]);
17128 
17129    i = ao2_iterator_init(dialogs, 0);
17130    while ((cur = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
17131       sip_pvt_lock(cur);
17132       if (!strncasecmp(cur->callid, a->argv[3], len)) {
17133          struct sip_history *hist;
17134          int x = 0;
17135 
17136          ast_cli(a->fd, "\n");
17137          if (cur->subscribed != NONE)
17138             ast_cli(a->fd, "  * Subscription\n");
17139          else
17140             ast_cli(a->fd, "  * SIP Call\n");
17141          if (cur->history)
17142             AST_LIST_TRAVERSE(cur->history, hist, list)
17143                ast_cli(a->fd, "%d. %s\n", ++x, hist->event);
17144          if (x == 0)
17145             ast_cli(a->fd, "Call '%s' has no history\n", cur->callid);
17146          found++;
17147       }
17148       sip_pvt_unlock(cur);
17149       ao2_t_ref(cur, -1, "toss dialog ptr from iterator_next");
17150    }
17151    ao2_iterator_destroy(&i);
17152 
17153    if (!found) 
17154       ast_cli(a->fd, "No such SIP Call ID starting with '%s'\n", a->argv[3]);
17155 
17156    return CLI_SUCCESS;
17157 }
17158 
17159 /*! \brief Dump SIP history to debug log file at end of lifespan for SIP dialog */
17160 static void sip_dump_history(struct sip_pvt *dialog)
17161 {
17162    int x = 0;
17163    struct sip_history *hist;
17164    static int errmsg = 0;
17165 
17166    if (!dialog)
17167       return;
17168 
17169    if (!option_debug && !sipdebug) {
17170       if (!errmsg) {
17171          ast_log(LOG_NOTICE, "You must have debugging enabled (SIP or Asterisk) in order to dump SIP history.\n");
17172          errmsg = 1;
17173       }
17174       return;
17175    }
17176 
17177    ast_debug(1, "\n---------- SIP HISTORY for '%s' \n", dialog->callid);
17178    if (dialog->subscribed)
17179       ast_debug(1, "  * Subscription\n");
17180    else
17181       ast_debug(1, "  * SIP Call\n");
17182    if (dialog->history)
17183       AST_LIST_TRAVERSE(dialog->history, hist, list)
17184          ast_debug(1, "  %-3.3d. %s\n", ++x, hist->event);
17185    if (!x)
17186       ast_debug(1, "Call '%s' has no history\n", dialog->callid);
17187    ast_debug(1, "\n---------- END SIP HISTORY for '%s' \n", dialog->callid);
17188 }
17189 
17190 
17191 /*! \brief  Receive SIP INFO Message */
17192 static void handle_request_info(struct sip_pvt *p, struct sip_request *req)
17193 {
17194    char buf[1024];
17195    unsigned int event;
17196    const char *c = get_header(req, "Content-Type");
17197 
17198    /* Need to check the media/type */
17199    if (!strcasecmp(c, "application/dtmf-relay") ||
17200        !strcasecmp(c, "application/vnd.nortelnetworks.digits")) {
17201       unsigned int duration = 0;
17202 
17203       if (!p->owner) {  /* not a PBX call */
17204          transmit_response(p, "481 Call leg/transaction does not exist", req);
17205          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
17206          return;
17207       }
17208 
17209       /* Try getting the "signal=" part */
17210       if (ast_strlen_zero(c = get_body(req, "Signal", '=')) && ast_strlen_zero(c = get_body(req, "d", '='))) {
17211          ast_log(LOG_WARNING, "Unable to retrieve DTMF signal from INFO message from %s\n", p->callid);
17212          transmit_response(p, "200 OK", req); /* Should return error */
17213          return;
17214       } else {
17215          ast_copy_string(buf, c, sizeof(buf));
17216       }
17217 
17218       if (!ast_strlen_zero((c = get_body(req, "Duration", '='))))
17219          duration = atoi(c);
17220       if (!duration)
17221          duration = 100; /* 100 ms */
17222 
17223 
17224       if (ast_strlen_zero(buf)) {
17225          transmit_response(p, "200 OK", req);
17226          return;
17227       }
17228 
17229       if (buf[0] == '*')
17230          event = 10;
17231       else if (buf[0] == '#')
17232          event = 11;
17233       else if ((buf[0] >= 'A') && (buf[0] <= 'D'))
17234          event = 12 + buf[0] - 'A';
17235       else if (buf[0] == '!')
17236          event = 16;
17237       else
17238          event = atoi(buf);
17239       if (event == 16) {
17240          /* send a FLASH event */
17241          struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_FLASH, };
17242          ast_queue_frame(p->owner, &f);
17243          if (sipdebug)
17244             ast_verbose("* DTMF-relay event received: FLASH\n");
17245       } else {
17246          /* send a DTMF event */
17247          struct ast_frame f = { AST_FRAME_DTMF, };
17248          if (event < 10) {
17249             f.subclass = '0' + event;
17250          } else if (event < 11) {
17251             f.subclass = '*';
17252          } else if (event < 12) {
17253             f.subclass = '#';
17254          } else if (event < 16) {
17255             f.subclass = 'A' + (event - 12);
17256          }
17257          f.len = duration;
17258          ast_queue_frame(p->owner, &f);
17259          if (sipdebug)
17260             ast_verbose("* DTMF-relay event received: %c\n", f.subclass);
17261       }
17262       transmit_response(p, "200 OK", req);
17263       return;
17264    } else if (!strcasecmp(c, "application/dtmf")) {
17265       /*! \todo Note: Doesn't read the duration of the DTMF. Should be fixed. */
17266       unsigned int duration = 0;
17267 
17268       if (!p->owner) {  /* not a PBX call */
17269          transmit_response(p, "481 Call leg/transaction does not exist", req);
17270          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
17271          return;
17272       }
17273 
17274       get_msg_text(buf, sizeof(buf), req, TRUE);
17275       duration = 100; /* 100 ms */
17276 
17277       if (ast_strlen_zero(buf)) {
17278          transmit_response(p, "200 OK", req);
17279          return;
17280       }
17281       event = atoi(buf);
17282       if (event == 16) {
17283          /* send a FLASH event */
17284          struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_FLASH, };
17285          ast_queue_frame(p->owner, &f);
17286          if (sipdebug)
17287             ast_verbose("* DTMF-relay event received: FLASH\n");
17288       } else {
17289          /* send a DTMF event */
17290          struct ast_frame f = { AST_FRAME_DTMF, };
17291          if (event < 10) {
17292             f.subclass = '0' + event;
17293          } else if (event < 11) {
17294             f.subclass = '*';
17295          } else if (event < 12) {
17296             f.subclass = '#';
17297          } else if (event < 16) {
17298             f.subclass = 'A' + (event - 12);
17299          }
17300          f.len = duration;
17301          ast_queue_frame(p->owner, &f);
17302          if (sipdebug)
17303             ast_verbose("* DTMF-relay event received: %c\n", f.subclass);
17304       }
17305       transmit_response(p, "200 OK", req);
17306       return;
17307 
17308    } else if (!strcasecmp(c, "application/media_control+xml")) {
17309       /* Eh, we'll just assume it's a fast picture update for now */
17310       if (p->owner)
17311          ast_queue_control(p->owner, AST_CONTROL_VIDUPDATE);
17312       transmit_response(p, "200 OK", req);
17313       return;
17314    } else if (!ast_strlen_zero(c = get_header(req, "X-ClientCode"))) {
17315       /* Client code (from SNOM phone) */
17316       if (ast_test_flag(&p->flags[0], SIP_USECLIENTCODE)) {
17317          if (p->owner && p->owner->cdr)
17318             ast_cdr_setuserfield(p->owner, c);
17319          if (p->owner && ast_bridged_channel(p->owner) && ast_bridged_channel(p->owner)->cdr)
17320             ast_cdr_setuserfield(ast_bridged_channel(p->owner), c);
17321          transmit_response(p, "200 OK", req);
17322       } else {
17323          transmit_response(p, "403 Forbidden", req);
17324       }
17325       return;
17326    } else if (!ast_strlen_zero(c = get_header(req, "Record"))) {
17327       /* INFO messages generated by some phones to start/stop recording
17328          on phone calls. 
17329          OEJ: I think this should be something that is enabled/disabled
17330          per device. I don't want incoming callers to record calls in my
17331          pbx.
17332       */
17333       /* first, get the feature string, if it exists */
17334       struct ast_call_feature *feat;
17335       int j;
17336       struct ast_frame f = { AST_FRAME_DTMF, };
17337 
17338       ast_rdlock_call_features();
17339       feat = ast_find_call_feature("automon");
17340       if (!feat || ast_strlen_zero(feat->exten)) {
17341          ast_log(LOG_WARNING, "Recording requested, but no One Touch Monitor registered. (See features.conf)\n");
17342          /* 403 means that we don't support this feature, so don't request it again */
17343          transmit_response(p, "403 Forbidden", req);
17344          ast_unlock_call_features();
17345          return;
17346       } 
17347       /* Send the feature code to the PBX as DTMF, just like the handset had sent it */
17348       f.len = 100;
17349       for (j=0; j < strlen(feat->exten); j++) {
17350          f.subclass = feat->exten[j];
17351          ast_queue_frame(p->owner, &f);
17352          if (sipdebug)
17353             ast_verbose("* DTMF-relay event faked: %c\n", f.subclass);
17354       }
17355       ast_unlock_call_features();
17356 
17357       ast_debug(1, "Got a Request to Record the channel, state %s\n", c);
17358       transmit_response(p, "200 OK", req);
17359       return;
17360    } else if (ast_strlen_zero(c = get_header(req, "Content-Length")) || !strcasecmp(c, "0")) {
17361       /* This is probably just a packet making sure the signalling is still up, just send back a 200 OK */
17362       transmit_response(p, "200 OK", req);
17363       return;
17364    }
17365 
17366    /* Other type of INFO message, not really understood by Asterisk */
17367    /* if (get_msg_text(buf, sizeof(buf), req)) { */
17368 
17369    ast_log(LOG_WARNING, "Unable to parse INFO message from %s. Content %s\n", p->callid, buf);
17370    transmit_response(p, "415 Unsupported media type", req);
17371    return;
17372 }
17373 
17374 /*! \brief Enable SIP Debugging for a single IP */
17375 static char *sip_do_debug_ip(int fd, char *arg)
17376 {
17377    struct hostent *hp;
17378    struct ast_hostent ahp;
17379    int port = 0;
17380    char *p;
17381 
17382    p = arg;
17383    strsep(&p, ":");
17384    if (p)
17385       port = atoi(p);
17386    hp = ast_gethostbyname(arg, &ahp);
17387    if (hp == NULL)
17388       return CLI_SHOWUSAGE;
17389 
17390    debugaddr.sin_family = AF_INET;
17391    memcpy(&debugaddr.sin_addr, hp->h_addr, sizeof(debugaddr.sin_addr));
17392    debugaddr.sin_port = htons(port);
17393    if (port == 0)
17394       ast_cli(fd, "SIP Debugging Enabled for IP: %s\n", ast_inet_ntoa(debugaddr.sin_addr));
17395    else
17396       ast_cli(fd, "SIP Debugging Enabled for IP: %s:%d\n", ast_inet_ntoa(debugaddr.sin_addr), port);
17397 
17398    sipdebug |= sip_debug_console;
17399 
17400    return CLI_SUCCESS;
17401 }
17402 
17403 /*! \brief  Turn on SIP debugging for a given peer */
17404 static char *sip_do_debug_peer(int fd, char *arg)
17405 {
17406    struct sip_peer *peer = find_peer(arg, NULL, TRUE, FINDPEERS, FALSE, 0);
17407    if (!peer)
17408       ast_cli(fd, "No such peer '%s'\n", arg);
17409    else if (peer->addr.sin_addr.s_addr == 0)
17410       ast_cli(fd, "Unable to get IP address of peer '%s'\n", arg);
17411    else {
17412       debugaddr.sin_family = AF_INET;
17413       debugaddr.sin_addr = peer->addr.sin_addr;
17414       debugaddr.sin_port = peer->addr.sin_port;
17415       ast_cli(fd, "SIP Debugging Enabled for IP: %s:%d\n",
17416          ast_inet_ntoa(debugaddr.sin_addr), ntohs(debugaddr.sin_port));
17417       sipdebug |= sip_debug_console;
17418    }
17419    if (peer)
17420       unref_peer(peer, "sip_do_debug_peer: unref_peer, from find_peer call");
17421    return CLI_SUCCESS;
17422 }
17423 
17424 /*! \brief Turn on SIP debugging (CLI command) */
17425 static char *sip_do_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
17426 {
17427    int oldsipdebug = sipdebug & sip_debug_console;
17428    char *what;
17429 
17430    if (cmd == CLI_INIT) {
17431       e->command = "sip set debug {on|off|ip|peer}";
17432       e->usage =
17433          "Usage: sip set debug {off|on|ip addr[:port]|peer peername}\n"
17434          "       Globally disables dumping of SIP packets,\n"
17435          "       or enables it either globally or for a (single)\n"
17436          "       IP address or registered peer.\n";
17437       return NULL;
17438    } else if (cmd == CLI_GENERATE) {
17439       if (a->pos == 4 && !strcasecmp(a->argv[3], "peer")) 
17440          return complete_sip_peer(a->word, a->n, 0);
17441       return NULL;
17442         }
17443 
17444    what = a->argv[e->args-1];      /* guaranteed to exist */
17445    if (a->argc == e->args) {       /* on/off */
17446       if (!strcasecmp(what, "on")) {
17447          sipdebug |= sip_debug_console;
17448          sipdebug_text = 1;   /*! \note this can be a special debug command - "sip debug text" or something */
17449          memset(&debugaddr, 0, sizeof(debugaddr));
17450          ast_cli(a->fd, "SIP Debugging %senabled\n", oldsipdebug ? "re-" : "");
17451          return CLI_SUCCESS;
17452       } else if (!strcasecmp(what, "off")) {
17453          sipdebug &= ~sip_debug_console;
17454          sipdebug_text = 0;
17455          ast_cli(a->fd, "SIP Debugging Disabled\n");
17456          return CLI_SUCCESS;
17457       }
17458    } else if (a->argc == e->args +1) {/* ip/peer */
17459       if (!strcasecmp(what, "ip"))
17460          return sip_do_debug_ip(a->fd, a->argv[e->args]);
17461       else if (!strcasecmp(what, "peer"))
17462          return sip_do_debug_peer(a->fd, a->argv[e->args]);
17463    }
17464    return CLI_SHOWUSAGE;   /* default, failure */
17465 }
17466 
17467 /*! \brief Cli command to send SIP notify to peer */
17468 static char *sip_cli_notify(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
17469 {
17470    struct ast_variable *varlist;
17471    int i;
17472 
17473    switch (cmd) {
17474    case CLI_INIT:
17475       e->command = "sip notify";
17476       e->usage =
17477          "Usage: sip notify <type> <peer> [<peer>...]\n"
17478          "       Send a NOTIFY message to a SIP peer or peers\n"
17479          "       Message types are defined in sip_notify.conf\n";
17480       return NULL;
17481    case CLI_GENERATE:
17482       return complete_sipnotify(a->line, a->word, a->pos, a->n);
17483    }
17484 
17485    if (a->argc < 4)
17486       return CLI_SHOWUSAGE;
17487 
17488    if (!notify_types) {
17489       ast_cli(a->fd, "No %s file found, or no types listed there\n", notify_config);
17490       return CLI_FAILURE;
17491    }
17492 
17493    varlist = ast_variable_browse(notify_types, a->argv[2]);
17494 
17495    if (!varlist) {
17496       ast_cli(a->fd, "Unable to find notify type '%s'\n", a->argv[2]);
17497       return CLI_FAILURE;
17498    }
17499 
17500    for (i = 3; i < a->argc; i++) {
17501       struct sip_pvt *p;
17502 
17503       if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY, NULL))) {
17504          ast_log(LOG_WARNING, "Unable to build sip pvt data for notify (memory/socket error)\n");
17505          return CLI_FAILURE;
17506       }
17507 
17508       if (create_addr(p, a->argv[i], NULL, 1)) {
17509          /* Maybe they're not registered, etc. */
17510          dialog_unlink_all(p, TRUE, TRUE);
17511          dialog_unref(p, "unref dialog inside for loop" );
17512          /* sip_destroy(p); */
17513          ast_cli(a->fd, "Could not create address for '%s'\n", a->argv[i]);
17514          continue;
17515       }
17516 
17517       /* Notify is outgoing call */
17518       ast_set_flag(&p->flags[0], SIP_OUTGOING);
17519 
17520       /* Recalculate our side, and recalculate Call ID */
17521       ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
17522       build_via(p);
17523       ao2_t_unlink(dialogs, p, "About to change the callid -- remove the old name");
17524       build_callid_pvt(p);
17525       ao2_t_link(dialogs, p, "Linking in new name");
17526       ast_cli(a->fd, "Sending NOTIFY of type '%s' to '%s'\n", a->argv[2], a->argv[i]);
17527       dialog_ref(p, "bump the count of p, which transmit_sip_request will decrement.");
17528       sip_scheddestroy(p, SIP_TRANS_TIMEOUT);
17529       transmit_notify_custom(p, varlist);
17530    }
17531 
17532    return CLI_SUCCESS;
17533 }
17534 
17535 /*! \brief Enable/Disable SIP History logging (CLI) */
17536 static char *sip_set_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
17537 {
17538    switch (cmd) {
17539    case CLI_INIT:
17540       e->command = "sip set history {on|off}";
17541       e->usage =
17542          "Usage: sip set history {on|off}\n"
17543          "       Enables/Disables recording of SIP dialog history for debugging purposes.\n"
17544          "       Use 'sip show history' to view the history of a call number.\n";
17545       return NULL;
17546    case CLI_GENERATE:
17547       return NULL;
17548    }
17549 
17550    if (a->argc != e->args)
17551       return CLI_SHOWUSAGE;
17552 
17553    if (!strncasecmp(a->argv[e->args - 1], "on", 2)) {
17554       recordhistory = TRUE;
17555       ast_cli(a->fd, "SIP History Recording Enabled (use 'sip show history')\n");
17556    } else if (!strncasecmp(a->argv[e->args - 1], "off", 3)) {
17557       recordhistory = FALSE;
17558       ast_cli(a->fd, "SIP History Recording Disabled\n");
17559    } else {
17560       return CLI_SHOWUSAGE;
17561    }
17562    return CLI_SUCCESS;
17563 }
17564 
17565 /*! \brief Authenticate for outbound registration */
17566 static int do_register_auth(struct sip_pvt *p, struct sip_request *req, enum sip_auth_type code)
17567 {
17568    char *header, *respheader;
17569    char digest[1024];
17570 
17571    p->authtries++;
17572    auth_headers(code, &header, &respheader);
17573    memset(digest, 0, sizeof(digest));
17574    if (reply_digest(p, req, header, SIP_REGISTER, digest, sizeof(digest))) {
17575       /* There's nothing to use for authentication */
17576       /* No digest challenge in request */
17577       if (sip_debug_test_pvt(p) && p->registry)
17578          ast_verbose("No authentication challenge, sending blank registration to domain/host name %s\n", p->registry->hostname);
17579          /* No old challenge */
17580       return -1;
17581    }
17582    if (p->do_history)
17583       append_history(p, "RegistryAuth", "Try: %d", p->authtries);
17584    if (sip_debug_test_pvt(p) && p->registry)
17585       ast_verbose("Responding to challenge, registration to domain/host name %s\n", p->registry->hostname);
17586    return transmit_register(p->registry, SIP_REGISTER, digest, respheader); 
17587 }
17588 
17589 /*! \brief Add authentication on outbound SIP packet */
17590 static int do_proxy_auth(struct sip_pvt *p, struct sip_request *req, enum sip_auth_type code, int sipmethod, int init)
17591 {
17592    char *header, *respheader;
17593    char digest[1024];
17594 
17595    if (!p->options && !(p->options = ast_calloc(1, sizeof(*p->options))))
17596       return -2;
17597 
17598    p->authtries++;
17599    auth_headers(code, &header, &respheader);
17600    ast_debug(2, "Auth attempt %d on %s\n", p->authtries, sip_methods[sipmethod].text);
17601    memset(digest, 0, sizeof(digest));
17602    if (reply_digest(p, req, header, sipmethod, digest, sizeof(digest) )) {
17603       /* No way to authenticate */
17604       return -1;
17605    }
17606    /* Now we have a reply digest */
17607    p->options->auth = digest;
17608    p->options->authheader = respheader;
17609    return transmit_invite(p, sipmethod, sipmethod == SIP_INVITE, init); 
17610 }
17611 
17612 /*! \brief  reply to authentication for outbound registrations
17613 \return  Returns -1 if we have no auth 
17614 \note This is used for register= servers in sip.conf, SIP proxies we register
17615    with  for receiving calls from.  */
17616 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod,  char *digest, int digest_len)
17617 {
17618    char tmp[512];
17619    char *c;
17620    char oldnonce[256];
17621 
17622    /* table of recognised keywords, and places where they should be copied */
17623    const struct x {
17624       const char *key;
17625       const ast_string_field *field;
17626    } *i, keys[] = {
17627       { "realm=", &p->realm },
17628       { "nonce=", &p->nonce },
17629       { "opaque=", &p->opaque },
17630       { "qop=", &p->qop },
17631       { "domain=", &p->domain },
17632       { NULL, 0 },
17633    };
17634 
17635    ast_copy_string(tmp, get_header(req, header), sizeof(tmp));
17636    if (ast_strlen_zero(tmp)) 
17637       return -1;
17638    if (strncasecmp(tmp, "Digest ", strlen("Digest "))) {
17639       ast_log(LOG_WARNING, "missing Digest.\n");
17640       return -1;
17641    }
17642    c = tmp + strlen("Digest ");
17643    ast_copy_string(oldnonce, p->nonce, sizeof(oldnonce));
17644    while (c && *(c = ast_skip_blanks(c))) {  /* lookup for keys */
17645       for (i = keys; i->key != NULL; i++) {
17646          char *src, *separator;
17647          if (strncasecmp(c, i->key, strlen(i->key)) != 0)
17648             continue;
17649          /* Found. Skip keyword, take text in quotes or up to the separator. */
17650          c += strlen(i->key);
17651          if (*c == '"') {
17652             src = ++c;
17653             separator = "\"";
17654          } else {
17655             src = c;
17656             separator = ",";
17657          }
17658          strsep(&c, separator); /* clear separator and move ptr */
17659          ast_string_field_ptr_set(p, i->field, src);
17660          break;
17661       }
17662       if (i->key == NULL) /* not found, try ',' */
17663          strsep(&c, ",");
17664    }
17665    /* Reset nonce count */
17666    if (strcmp(p->nonce, oldnonce)) 
17667       p->noncecount = 0;
17668 
17669    /* Save auth data for following registrations */
17670    if (p->registry) {
17671       struct sip_registry *r = p->registry;
17672 
17673       if (strcmp(r->nonce, p->nonce)) {
17674          ast_string_field_set(r, realm, p->realm);
17675          ast_string_field_set(r, nonce, p->nonce);
17676          ast_string_field_set(r, domain, p->domain);
17677          ast_string_field_set(r, opaque, p->opaque);
17678          ast_string_field_set(r, qop, p->qop);
17679          r->noncecount = 0;
17680       }
17681    }
17682    return build_reply_digest(p, sipmethod, digest, digest_len); 
17683 }
17684 
17685 /*! \brief  Build reply digest 
17686 \return  Returns -1 if we have no auth 
17687 \note Build digest challenge for authentication of registrations and calls
17688    Also used for authentication of BYE 
17689 */
17690 static int build_reply_digest(struct sip_pvt *p, int method, char* digest, int digest_len)
17691 {
17692    char a1[256];
17693    char a2[256];
17694    char a1_hash[256];
17695    char a2_hash[256];
17696    char resp[256];
17697    char resp_hash[256];
17698    char uri[256];
17699    char opaque[256] = "";
17700    char cnonce[80];
17701    const char *username;
17702    const char *secret;
17703    const char *md5secret;
17704    struct sip_auth *auth = NULL; /* Realm authentication */
17705 
17706    if (!ast_strlen_zero(p->domain))
17707       ast_copy_string(uri, p->domain, sizeof(uri));
17708    else if (!ast_strlen_zero(p->uri))
17709       ast_copy_string(uri, p->uri, sizeof(uri));
17710    else
17711       snprintf(uri, sizeof(uri), "sip:%s@%s", p->username, ast_inet_ntoa(p->sa.sin_addr));
17712 
17713    snprintf(cnonce, sizeof(cnonce), "%08lx", ast_random());
17714 
17715    /* Check if we have separate auth credentials */
17716    if(!(auth = find_realm_authentication(p->peerauth, p->realm))) /* Start with peer list */
17717       auth = find_realm_authentication(authl, p->realm); /* If not, global list */
17718 
17719    if (auth) {
17720       ast_debug(3, "use realm [%s] from peer [%s][%s]\n", auth->username, p->peername, p->username);
17721       username = auth->username;
17722       secret = auth->secret;
17723       md5secret = auth->md5secret;
17724       if (sipdebug)
17725          ast_debug(1, "Using realm %s authentication for call %s\n", p->realm, p->callid);
17726    } else {
17727       /* No authentication, use peer or register= config */
17728       username = p->authname;
17729       secret =  p->peersecret;
17730       md5secret = p->peermd5secret;
17731    }
17732    if (ast_strlen_zero(username))   /* We have no authentication */
17733       return -1;
17734 
17735    /* Calculate SIP digest response */
17736    snprintf(a1, sizeof(a1), "%s:%s:%s", username, p->realm, secret);
17737    snprintf(a2, sizeof(a2), "%s:%s", sip_methods[method].text, uri);
17738    if (!ast_strlen_zero(md5secret))
17739       ast_copy_string(a1_hash, md5secret, sizeof(a1_hash));
17740    else
17741       ast_md5_hash(a1_hash, a1);
17742    ast_md5_hash(a2_hash, a2);
17743 
17744    p->noncecount++;
17745    if (!ast_strlen_zero(p->qop))
17746       snprintf(resp, sizeof(resp), "%s:%s:%08x:%s:%s:%s", a1_hash, p->nonce, p->noncecount, cnonce, "auth", a2_hash);
17747    else
17748       snprintf(resp, sizeof(resp), "%s:%s:%s", a1_hash, p->nonce, a2_hash);
17749    ast_md5_hash(resp_hash, resp);
17750 
17751    /* only include the opaque string if it's set */
17752    if (!ast_strlen_zero(p->opaque)) {
17753      snprintf(opaque, sizeof(opaque), ", opaque=\"%s\"", p->opaque);
17754    }
17755 
17756    /* XXX We hard code our qop to "auth" for now.  XXX */
17757    if (!ast_strlen_zero(p->qop))
17758       snprintf(digest, digest_len, "Digest username=\"%s\", realm=\"%s\", algorithm=MD5, uri=\"%s\", nonce=\"%s\", response=\"%s\"%s, qop=auth, cnonce=\"%s\", nc=%08x", username, p->realm, uri, p->nonce, resp_hash, opaque, cnonce, p->noncecount);
17759    else
17760       snprintf(digest, digest_len, "Digest username=\"%s\", realm=\"%s\", algorithm=MD5, uri=\"%s\", nonce=\"%s\", response=\"%s\"%s", username, p->realm, uri, p->nonce, resp_hash, opaque);
17761 
17762    append_history(p, "AuthResp", "Auth response sent for %s in realm %s - nc %d", username, p->realm, p->noncecount);
17763 
17764    return 0;
17765 }
17766    
17767 /*! \brief Read SIP header (dialplan function) */
17768 static int func_header_read(struct ast_channel *chan, const char *function, char *data, char *buf, size_t len) 
17769 {
17770    struct sip_pvt *p;
17771    const char *content = NULL;
17772    AST_DECLARE_APP_ARGS(args,
17773       AST_APP_ARG(header);
17774       AST_APP_ARG(number);
17775    );
17776    int i, number, start = 0;
17777 
17778    if (ast_strlen_zero(data)) {
17779       ast_log(LOG_WARNING, "This function requires a header name.\n");
17780       return -1;
17781    }
17782 
17783    ast_channel_lock(chan);
17784    if (!IS_SIP_TECH(chan->tech)) {
17785       ast_log(LOG_WARNING, "This function can only be used on SIP channels.\n");
17786       ast_channel_unlock(chan);
17787       return -1;
17788    }
17789 
17790    AST_STANDARD_APP_ARGS(args, data);
17791    if (!args.number) {
17792       number = 1;
17793    } else {
17794       sscanf(args.number, "%30d", &number);
17795       if (number < 1)
17796          number = 1;
17797    }
17798 
17799    p = chan->tech_pvt;
17800 
17801    /* If there is no private structure, this channel is no longer alive */
17802    if (!p) {
17803       ast_channel_unlock(chan);
17804       return -1;
17805    }
17806 
17807    for (i = 0; i < number; i++)
17808       content = __get_header(&p->initreq, args.header, &start);
17809 
17810    if (ast_strlen_zero(content)) {
17811       ast_channel_unlock(chan);
17812       return -1;
17813    }
17814 
17815    ast_copy_string(buf, content, len);
17816    ast_channel_unlock(chan);
17817 
17818    return 0;
17819 }
17820 
17821 static struct ast_custom_function sip_header_function = {
17822    .name = "SIP_HEADER",
17823    .read = func_header_read,
17824 };
17825 
17826 /*! \brief  Dial plan function to check if domain is local */
17827 static int func_check_sipdomain(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
17828 {
17829    if (ast_strlen_zero(data)) {
17830       ast_log(LOG_WARNING, "CHECKSIPDOMAIN requires an argument - A domain name\n");
17831       return -1;
17832    }
17833    if (check_sip_domain(data, NULL, 0))
17834       ast_copy_string(buf, data, len);
17835    else
17836       buf[0] = '\0';
17837    return 0;
17838 }
17839 
17840 static struct ast_custom_function checksipdomain_function = {
17841    .name = "CHECKSIPDOMAIN",
17842    .read = func_check_sipdomain,
17843 };
17844 
17845 /*! \brief  ${SIPPEER()} Dialplan function - reads peer data */
17846 static int function_sippeer(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
17847 {
17848    struct sip_peer *peer;
17849    char *colname;
17850 
17851    if ((colname = strchr(data, ':'))) {   /*! \todo Will be deprecated after 1.4 */
17852       static int deprecation_warning = 0;
17853       *colname++ = '\0';
17854       if (deprecation_warning++ % 10 == 0)
17855          ast_log(LOG_WARNING, "SIPPEER(): usage of ':' to separate arguments is deprecated.  Please use ',' instead.\n");
17856    } else if ((colname = strchr(data, ',')))
17857       *colname++ = '\0';
17858    else
17859       colname = "ip";
17860 
17861    if (!(peer = find_peer(data, NULL, TRUE, FINDPEERS, FALSE, 0)))
17862       return -1;
17863 
17864    if (!strcasecmp(colname, "ip")) {
17865       ast_copy_string(buf, peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "", len);
17866    } else  if (!strcasecmp(colname, "port")) {
17867       snprintf(buf, len, "%d", ntohs(peer->addr.sin_port));
17868    } else  if (!strcasecmp(colname, "status")) {
17869       peer_status(peer, buf, len);
17870    } else  if (!strcasecmp(colname, "language")) {
17871       ast_copy_string(buf, peer->language, len);
17872    } else  if (!strcasecmp(colname, "regexten")) {
17873       ast_copy_string(buf, peer->regexten, len);
17874    } else  if (!strcasecmp(colname, "limit")) {
17875       snprintf(buf, len, "%d", peer->call_limit);
17876    } else  if (!strcasecmp(colname, "busylevel")) {
17877       snprintf(buf, len, "%d", peer->busy_level);
17878    } else  if (!strcasecmp(colname, "curcalls")) {
17879       snprintf(buf, len, "%d", peer->inUse);
17880    } else  if (!strcasecmp(colname, "accountcode")) {
17881       ast_copy_string(buf, peer->accountcode, len);
17882    } else  if (!strcasecmp(colname, "callgroup")) {
17883       ast_print_group(buf, len, peer->callgroup);
17884    } else  if (!strcasecmp(colname, "pickupgroup")) {
17885       ast_print_group(buf, len, peer->pickupgroup);
17886    } else  if (!strcasecmp(colname, "useragent")) {
17887       ast_copy_string(buf, peer->useragent, len);
17888    } else  if (!strcasecmp(colname, "mailbox")) {
17889       struct ast_str *mailbox_str = ast_str_alloca(512);
17890       peer_mailboxes_to_str(&mailbox_str, peer);
17891       ast_copy_string(buf, mailbox_str->str, len);
17892    } else  if (!strcasecmp(colname, "context")) {
17893       ast_copy_string(buf, peer->context, len);
17894    } else  if (!strcasecmp(colname, "expire")) {
17895       snprintf(buf, len, "%d", peer->expire);
17896    } else  if (!strcasecmp(colname, "dynamic")) {
17897       ast_copy_string(buf, peer->host_dynamic ? "yes" : "no", len);
17898    } else  if (!strcasecmp(colname, "callerid_name")) {
17899       ast_copy_string(buf, peer->cid_name, len);
17900    } else  if (!strcasecmp(colname, "callerid_num")) {
17901       ast_copy_string(buf, peer->cid_num, len);
17902    } else  if (!strcasecmp(colname, "codecs")) {
17903       ast_getformatname_multiple(buf, len -1, peer->capability);
17904    } else  if (!strncasecmp(colname, "chanvar[", 8)) {
17905       char *chanvar=colname + 8;
17906       struct ast_variable *v;
17907    
17908       chanvar = strsep(&chanvar, "]");
17909       for (v = peer->chanvars ; v ; v = v->next) {
17910          if (!strcasecmp(v->name, chanvar)) {
17911             ast_copy_string(buf, v->value, len);
17912          }
17913       }
17914    } else  if (!strncasecmp(colname, "codec[", 6)) {
17915       char *codecnum;
17916       int codec = 0;
17917       
17918       codecnum = colname + 6; /* move past the '[' */
17919       codecnum = strsep(&codecnum, "]"); /* trim trailing ']' if any */
17920       if((codec = ast_codec_pref_index(&peer->prefs, atoi(codecnum)))) {
17921          ast_copy_string(buf, ast_getformatname(codec), len);
17922       } else {
17923          buf[0] = '\0';
17924       }
17925    } else {
17926       buf[0] = '\0';
17927    }
17928 
17929    unref_peer(peer, "unref_peer from function_sippeer, just before return");
17930 
17931    return 0;
17932 }
17933 
17934 /*! \brief Structure to declare a dialplan function: SIPPEER */
17935 static struct ast_custom_function sippeer_function = {
17936    .name = "SIPPEER",
17937    .read = function_sippeer,
17938 };
17939 
17940 /*! \brief ${SIPCHANINFO()} Dialplan function - reads sip channel data */
17941 static int function_sipchaninfo_read(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
17942 {
17943    struct sip_pvt *p;
17944    static int deprecated = 0;
17945 
17946    *buf = 0;
17947    
17948    if (!data) {
17949       ast_log(LOG_WARNING, "This function requires a parameter name.\n");
17950       return -1;
17951    }
17952 
17953    ast_channel_lock(chan);
17954    if (!IS_SIP_TECH(chan->tech)) {
17955       ast_log(LOG_WARNING, "This function can only be used on SIP channels.\n");
17956       ast_channel_unlock(chan);
17957       return -1;
17958    }
17959 
17960    if (deprecated++ % 20 == 0) {
17961       /* Deprecated in 1.6.1 */
17962       ast_log(LOG_WARNING, "SIPCHANINFO() is deprecated.  Please transition to using CHANNEL().\n");
17963    }
17964 
17965    p = chan->tech_pvt;
17966 
17967    /* If there is no private structure, this channel is no longer alive */
17968    if (!p) {
17969       ast_channel_unlock(chan);
17970       return -1;
17971    }
17972 
17973    if (!strcasecmp(data, "peerip")) {
17974       ast_copy_string(buf, p->sa.sin_addr.s_addr ? ast_inet_ntoa(p->sa.sin_addr) : "", len);
17975    } else  if (!strcasecmp(data, "recvip")) {
17976       ast_copy_string(buf, p->recv.sin_addr.s_addr ? ast_inet_ntoa(p->recv.sin_addr) : "", len);
17977    } else  if (!strcasecmp(data, "from")) {
17978       ast_copy_string(buf, p->from, len);
17979    } else  if (!strcasecmp(data, "uri")) {
17980       ast_copy_string(buf, p->uri, len);
17981    } else  if (!strcasecmp(data, "useragent")) {
17982       ast_copy_string(buf, p->useragent, len);
17983    } else  if (!strcasecmp(data, "peername")) {
17984       ast_copy_string(buf, p->peername, len);
17985    } else if (!strcasecmp(data, "t38passthrough")) {
17986       if (p->t38.state == T38_DISABLED) {
17987          ast_copy_string(buf, "0", len);
17988       } else { /* T38 is offered or enabled in this call */
17989          ast_copy_string(buf, "1", len);
17990       }
17991    } else {
17992       ast_channel_unlock(chan);
17993       return -1;
17994    }
17995    ast_channel_unlock(chan);
17996 
17997    return 0;
17998 }
17999 
18000 /*! \brief Structure to declare a dialplan function: SIPCHANINFO */
18001 static struct ast_custom_function sipchaninfo_function = {
18002    .name = "SIPCHANINFO",
18003    .read = function_sipchaninfo_read,
18004 };
18005 
18006 /*! \brief Parse 302 Moved temporalily response 
18007    \todo XXX Doesn't redirect over TLS on sips: uri's.
18008       If we get a redirect to a SIPS: uri, this needs to be going back to the
18009       dialplan (this is a request for a secure signalling path).
18010       Note that transport=tls is deprecated, but we need to support it on incoming requests.
18011 */
18012 static void parse_moved_contact(struct sip_pvt *p, struct sip_request *req)
18013 {
18014    char tmp[SIPBUFSIZE];
18015    char *s, *e, *t, *trans;
18016    char *domain;
18017    enum sip_transport transport = SIP_TRANSPORT_UDP;
18018 
18019    ast_copy_string(tmp, get_header(req, "Contact"), sizeof(tmp));
18020    if ((t = strchr(tmp, ',')))
18021       *t = '\0';
18022 
18023    s = get_in_brackets(tmp);
18024    if ((trans = strcasestr(s, ";transport="))) do {
18025       trans += 11;
18026 
18027       if ((e = strchr(trans, ';')))
18028          *e = '\0';
18029 
18030       if (!strncasecmp(trans, "tcp", 3))
18031          transport = SIP_TRANSPORT_TCP;
18032       else if (!strncasecmp(trans, "tls", 3))
18033          transport = SIP_TRANSPORT_TLS;
18034       else {
18035          if (strncasecmp(trans, "udp", 3))
18036             ast_debug(1, "received contact with an invalid transport, '%s'\n", s);
18037          /* This will assume UDP for all unknown transports */
18038          transport = SIP_TRANSPORT_UDP;
18039       }
18040    } while(0);
18041    s = remove_uri_parameters(s);
18042 
18043    if (p->socket.tcptls_session) {
18044       ao2_ref(p->socket.tcptls_session, -1);
18045       p->socket.tcptls_session = NULL;
18046    }
18047 
18048    set_socket_transport(&p->socket, transport);
18049 
18050    if (ast_test_flag(&p->flags[0], SIP_PROMISCREDIR)) {
18051       char *host = NULL;
18052       if (!strncasecmp(s, "sip:", 4))
18053          s += 4;
18054       else if (!strncasecmp(s, "sips:", 5))
18055          s += 5;
18056       e = strchr(s, '/');
18057       if (e)
18058          *e = '\0';
18059       if ((host = strchr(s, '@'))) {
18060          *host++ = '\0';
18061          ast_debug(2, "Found promiscuous redirection to 'SIP/%s::::%s@%s'\n", s, get_transport(transport), host);
18062          if (p->owner)
18063             ast_string_field_build(p->owner, call_forward, "SIP/%s::::%s@%s", s, get_transport(transport), host);
18064       } else {
18065          ast_debug(2, "Found promiscuous redirection to 'SIP/::::%s@%s'\n", get_transport(transport), s);
18066          if (p->owner)
18067             ast_string_field_build(p->owner, call_forward, "SIP/::::%s@%s", get_transport(transport), s);
18068       }
18069    } else {
18070       e = strchr(tmp, '@');
18071       if (e) {
18072          *e++ = '\0';
18073          domain = e;
18074       } else {
18075          /* No username part */
18076          domain = tmp;
18077       }
18078       e = strchr(tmp, '/');   /* WHEN do we hae a forward slash in the URI? */
18079       if (e)
18080          *e = '\0';
18081 
18082       if (!strncasecmp(s, "sip:", 4))
18083          s += 4;
18084       else if (!strncasecmp(s, "sips:", 5))
18085          s += 5;
18086       e = strchr(s, ';');  /* And username ; parameters? */
18087       if (e)
18088          *e = '\0';  
18089       ast_uri_decode(s);
18090       ast_debug(2, "Received 302 Redirect to extension '%s' (domain %s)\n", s, domain);
18091       if (p->owner) {
18092          pbx_builtin_setvar_helper(p->owner, "SIPDOMAIN", domain);
18093          ast_string_field_set(p->owner, call_forward, s);
18094       }
18095    }
18096 }
18097 
18098 /*! \brief Check pending actions on SIP call 
18099  *
18100  * \note both sip_pvt and sip_pvt's owner channel (if present)
18101  *  must be locked for this function.
18102  */
18103 static void check_pendings(struct sip_pvt *p)
18104 {
18105    if (ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
18106       /* if we can't BYE, then this is really a pending CANCEL */
18107       if (p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA) {
18108          p->invitestate = INV_CANCELLED;
18109          transmit_request(p, SIP_CANCEL, p->lastinvite, XMIT_RELIABLE, FALSE);
18110          /* Actually don't destroy us yet, wait for the 487 on our original 
18111             INVITE, but do set an autodestruct just in case we never get it. */
18112       } else {
18113          /* We have a pending outbound invite, don't send something
18114             new in-transaction */
18115          if (p->pendinginvite)
18116             return;
18117 
18118          if (p->owner) {
18119             ast_softhangup_nolock(p->owner, AST_SOFTHANGUP_DEV);
18120          }
18121          /* Perhaps there is an SD change INVITE outstanding */
18122          transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, TRUE);
18123       }
18124       ast_clear_flag(&p->flags[0], SIP_PENDINGBYE);   
18125       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
18126    } else if (ast_test_flag(&p->flags[0], SIP_NEEDREINVITE)) {
18127       /* if we can't REINVITE, hold it for later */
18128       if (p->pendinginvite || p->invitestate == INV_CALLING || p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA || p->waitid > 0) {
18129          ast_debug(2, "NOT Sending pending reinvite (yet) on '%s'\n", p->callid);
18130       } else {
18131          ast_debug(2, "Sending pending reinvite on '%s'\n", p->callid);
18132          /* Didn't get to reinvite yet, so do it now */
18133          transmit_reinvite_with_sdp(p, (p->t38.state == T38_LOCAL_REINVITE ? TRUE : FALSE), FALSE);
18134          ast_clear_flag(&p->flags[0], SIP_NEEDREINVITE); 
18135       }
18136    }
18137 }
18138 
18139 /*! \brief Reset the NEEDREINVITE flag after waiting when we get 491 on a Re-invite
18140    to avoid race conditions between asterisk servers.
18141    Called from the scheduler.
18142 */
18143 static int sip_reinvite_retry(const void *data)
18144 {
18145    struct sip_pvt *p = (struct sip_pvt *) data;
18146    struct ast_channel *owner;
18147 
18148    sip_pvt_lock(p); /* called from schedule thread which requires a lock */
18149    while ((owner = p->owner) && ast_channel_trylock(owner)) {
18150       sip_pvt_unlock(p);
18151       usleep(1);
18152       sip_pvt_lock(p);
18153    }
18154    ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
18155    p->waitid = -1;
18156    check_pendings(p);
18157    sip_pvt_unlock(p);
18158    if (owner) {
18159       ast_channel_unlock(owner);
18160    }
18161    dialog_unref(p, "unref the dialog ptr from sip_reinvite_retry, because it held a dialog ptr");
18162    return 0;
18163 }
18164 
18165 
18166 /*! \brief Handle SIP response to INVITE dialogue */
18167 static void handle_response_invite(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
18168 {
18169    int outgoing = ast_test_flag(&p->flags[0], SIP_OUTGOING);
18170    int res = 0;
18171    int xmitres = 0;
18172    int reinvite = (p->owner && p->owner->_state == AST_STATE_UP);
18173    char *p_hdrval;
18174    int rtn;
18175 
18176    if (reinvite)
18177       ast_debug(4, "SIP response %d to RE-invite on %s call %s\n", resp, outgoing ? "outgoing" : "incoming", p->callid);
18178    else
18179       ast_debug(4, "SIP response %d to standard invite\n", resp);
18180 
18181    if (p->alreadygone) { /* This call is already gone */
18182       ast_debug(1, "Got response on call that is already terminated: %s (ignoring)\n", p->callid);
18183       return;
18184    }
18185 
18186    /* Acknowledge sequence number - This only happens on INVITE from SIP-call */
18187    /* Don't auto congest anymore since we've gotten something useful back */
18188    AST_SCHED_DEL_UNREF(sched, p->initid, dialog_unref(p, "when you delete the initid sched, you should dec the refcount for the stored dialog ptr"));
18189 
18190    /* RFC3261 says we must treat every 1xx response (but not 100)
18191       that we don't recognize as if it was 183.
18192    */
18193    if (resp > 100 && resp < 200 && resp!=101 && resp != 180 && resp != 182 && resp != 183)
18194       resp = 183;
18195 
18196    /* Any response between 100 and 199 is PROCEEDING */
18197    if (resp >= 100 && resp < 200 && p->invitestate == INV_CALLING)
18198       p->invitestate = INV_PROCEEDING;
18199  
18200    /* Final response, not 200 ? */
18201    if (resp >= 300 && (p->invitestate == INV_CALLING || p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA ))
18202       p->invitestate = INV_COMPLETED;
18203    
18204    /* Final response, clear out pending invite */
18205    if ((resp == 200 || resp >= 300) && p->pendinginvite && seqno == p->pendinginvite)
18206       p->pendinginvite = 0;
18207 
18208    switch (resp) {
18209    case 100:   /* Trying */
18210    case 101:   /* Dialog establishment */
18211       if (!req->ignore && p->invitestate != INV_CANCELLED && sip_cancel_destroy(p))
18212          ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
18213       check_pendings(p);
18214       break;
18215 
18216    case 180:   /* 180 Ringing */
18217    case 182:       /* 182 Queued */
18218       if (!req->ignore && p->invitestate != INV_CANCELLED && sip_cancel_destroy(p))
18219          ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
18220       if (!req->ignore && p->owner) {
18221          ast_queue_control(p->owner, AST_CONTROL_RINGING);
18222          if (p->owner->_state != AST_STATE_UP) {
18223             ast_setstate(p->owner, AST_STATE_RINGING);
18224          }
18225       }
18226       if (find_sdp(req)) {
18227          if (p->invitestate != INV_CANCELLED)
18228             p->invitestate = INV_EARLY_MEDIA;
18229          res = process_sdp(p, req, SDP_T38_NONE);
18230          if (!req->ignore && p->owner) {
18231             /* Queue a progress frame only if we have SDP in 180 or 182 */
18232             ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
18233          }
18234       }
18235       check_pendings(p);
18236       break;
18237 
18238    case 183:   /* Session progress */
18239       if (!req->ignore && (p->invitestate != INV_CANCELLED) && sip_cancel_destroy(p))
18240          ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
18241       if (find_sdp(req)) {
18242          if (p->invitestate != INV_CANCELLED)
18243             p->invitestate = INV_EARLY_MEDIA;
18244          res = process_sdp(p, req, SDP_T38_NONE);
18245          if (!req->ignore && p->owner) {
18246             /* Queue a progress frame */
18247             ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
18248          }
18249       } else {
18250          /* Alcatel PBXs are known to send 183s with no SDP after sending
18251           * a 100 Trying response. We're just going to treat this sort of thing
18252           * the same as we would treat a 180 Ringing
18253           */
18254          if (!req->ignore && p->owner) {
18255             ast_queue_control(p->owner, AST_CONTROL_RINGING);
18256          }
18257       }
18258       check_pendings(p);
18259       break;
18260 
18261    case 200:   /* 200 OK on invite - someone's answering our call */
18262       if (!req->ignore && (p->invitestate != INV_CANCELLED) && sip_cancel_destroy(p))
18263          ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
18264       p->authtries = 0;
18265       if (find_sdp(req)) {
18266          if ((res = process_sdp(p, req, SDP_T38_ACCEPT)) && !req->ignore)
18267             if (!reinvite)
18268                /* This 200 OK's SDP is not acceptable, so we need to ack, then hangup */
18269                /* For re-invites, we try to recover */
18270                ast_set_flag(&p->flags[0], SIP_PENDINGBYE);  
18271       }
18272 
18273       /* Parse contact header for continued conversation */
18274       /* When we get 200 OK, we know which device (and IP) to contact for this call */
18275       /* This is important when we have a SIP proxy between us and the phone */
18276       if (outgoing) {
18277          update_call_counter(p, DEC_CALL_RINGING);
18278          parse_ok_contact(p, req);
18279          /* Save Record-Route for any later requests we make on this dialogue */
18280          if (!reinvite)
18281             build_route(p, req, 1);
18282 
18283          if(set_address_from_contact(p)) {
18284             /* Bad contact - we don't know how to reach this device */
18285             /* We need to ACK, but then send a bye */
18286             if (!p->route && !req->ignore)
18287                ast_set_flag(&p->flags[0], SIP_PENDINGBYE);  
18288          } 
18289 
18290       }
18291 
18292       if (!req->ignore && p->owner) {
18293          if (!reinvite) {
18294             ast_queue_control(p->owner, AST_CONTROL_ANSWER);
18295             if (sip_cfg.callevents)
18296                manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
18297                   "Channel: %s\r\nChanneltype: %s\r\nUniqueid: %s\r\nSIPcallid: %s\r\nSIPfullcontact: %s\r\nPeername: %s\r\n",
18298                   p->owner->name, "SIP", p->owner->uniqueid, p->callid, p->fullcontact, p->peername);
18299          } else { /* RE-invite */
18300             ast_queue_frame(p->owner, &ast_null_frame);
18301          }
18302       } else {
18303           /* It's possible we're getting an 200 OK after we've tried to disconnect
18304               by sending CANCEL */
18305          /* First send ACK, then send bye */
18306          if (!req->ignore)
18307             ast_set_flag(&p->flags[0], SIP_PENDINGBYE);  
18308       }
18309 
18310       /* Check for Session-Timers related headers */
18311       if (st_get_mode(p) != SESSION_TIMER_MODE_REFUSE && p->outgoing_call == TRUE && !reinvite) {
18312          p_hdrval = (char*)get_header(req, "Session-Expires");
18313          if (!ast_strlen_zero(p_hdrval)) {
18314             /* UAS supports Session-Timers */
18315             enum st_refresher tmp_st_ref = SESSION_TIMER_REFRESHER_AUTO;
18316             int tmp_st_interval = 0;
18317             rtn = parse_session_expires(p_hdrval, &tmp_st_interval, &tmp_st_ref);
18318             if (rtn != 0) {
18319                ast_set_flag(&p->flags[0], SIP_PENDINGBYE);  
18320             }
18321             if (tmp_st_ref == SESSION_TIMER_REFRESHER_UAC || 
18322                tmp_st_ref == SESSION_TIMER_REFRESHER_UAS) {
18323                p->stimer->st_ref = tmp_st_ref;
18324             } 
18325             if (tmp_st_interval) {
18326                p->stimer->st_interval = tmp_st_interval;
18327             }
18328             p->stimer->st_active = TRUE;
18329             p->stimer->st_active_peer_ua = TRUE;
18330             start_session_timer(p);
18331          } else {
18332             /* UAS doesn't support Session-Timers */
18333             if (st_get_mode(p) == SESSION_TIMER_MODE_ORIGINATE) {
18334                p->stimer->st_ref = SESSION_TIMER_REFRESHER_UAC;
18335                p->stimer->st_active_peer_ua = FALSE;
18336                start_session_timer(p);
18337             }
18338          }
18339       }
18340 
18341 
18342       /* If I understand this right, the branch is different for a non-200 ACK only */
18343       p->invitestate = INV_TERMINATED;
18344       ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
18345       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, TRUE);
18346       check_pendings(p);
18347       break;
18348 
18349    case 407: /* Proxy authentication */
18350    case 401: /* Www auth */
18351       /* First we ACK */
18352       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
18353       if (p->options)
18354          p->options->auth_type = resp;
18355 
18356       /* Then we AUTH */
18357       ast_string_field_set(p, theirtag, NULL);  /* forget their old tag, so we don't match tags when getting response */
18358       if (!req->ignore) {
18359          if (p->authtries < MAX_AUTHTRIES)
18360             p->invitestate = INV_CALLING;
18361          if (p->authtries == MAX_AUTHTRIES || do_proxy_auth(p, req, resp, SIP_INVITE, 1)) {
18362             ast_log(LOG_NOTICE, "Failed to authenticate on INVITE to '%s'\n", get_header(&p->initreq, "From"));
18363             pvt_set_needdestroy(p, "failed to authenticate on INVITE");
18364             sip_alreadygone(p);
18365             if (p->owner)
18366                ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
18367          }
18368       }
18369       break;
18370 
18371    case 403: /* Forbidden */
18372       /* First we ACK */
18373       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
18374       ast_log(LOG_WARNING, "Received response: \"Forbidden\" from '%s'\n", get_header(&p->initreq, "From"));
18375       if (!req->ignore && p->owner)
18376          ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
18377       pvt_set_needdestroy(p, "received 403 response");
18378       sip_alreadygone(p);
18379       break;
18380 
18381    case 404: /* Not found */
18382       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
18383       if (p->owner && !req->ignore)
18384          ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
18385       sip_alreadygone(p);
18386       break;
18387 
18388    case 408: /* Request timeout */
18389    case 481: /* Call leg does not exist */
18390       /* Could be REFER caused INVITE with replaces */
18391       ast_log(LOG_WARNING, "Re-invite to non-existing call leg on other UA. SIP dialog '%s'. Giving up.\n", p->callid);
18392       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
18393       if (p->owner)
18394          ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
18395       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
18396       break;
18397 
18398    case 422: /* Session-Timers: Session interval too small */
18399       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
18400       ast_string_field_set(p, theirtag, NULL);
18401       proc_422_rsp(p, req);
18402       break;
18403 
18404    case 428: /* Use identity header - rfc 4474 - not supported by Asterisk yet */
18405       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
18406       append_history(p, "Identity", "SIP identity is required. Not supported by Asterisk.");
18407       ast_log(LOG_WARNING, "SIP identity required by proxy. SIP dialog '%s'. Giving up.\n", p->callid);
18408       if (p->owner)
18409          ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
18410       break;
18411 
18412       
18413 
18414    case 487: /* Cancelled transaction */
18415       /* We have sent CANCEL on an outbound INVITE 
18416          This transaction is already scheduled to be killed by sip_hangup().
18417       */
18418       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
18419       if (p->owner && !req->ignore) {
18420          ast_queue_hangup_with_cause(p->owner, AST_CAUSE_NORMAL_CLEARING);
18421          append_history(p, "Hangup", "Got 487 on CANCEL request from us. Queued AST hangup request");
18422       } else if (!req->ignore) {
18423          update_call_counter(p, DEC_CALL_LIMIT);
18424          append_history(p, "Hangup", "Got 487 on CANCEL request from us on call without owner. Killing this dialog.");
18425          pvt_set_needdestroy(p, "received 487 response");
18426          sip_alreadygone(p);
18427       }
18428       break;
18429    case 415: /* Unsupported media type */
18430    case 488: /* Not acceptable here */
18431    case 606: /* Not Acceptable */
18432       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
18433       if (p->udptl && p->t38.state == T38_LOCAL_REINVITE) {
18434          change_t38_state(p, T38_DISABLED);
18435          /* Try to reset RTP timers */
18436          ast_rtp_set_rtptimers_onhold(p->rtp);
18437 
18438          /* Trigger a reinvite back to audio */
18439          transmit_reinvite_with_sdp(p, FALSE, FALSE);
18440       } else {
18441          /* We can't set up this call, so give up */
18442          if (p->owner && !req->ignore)
18443             ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
18444          pvt_set_needdestroy(p, "received 488 response");
18445          /* If there's no dialog to end, then mark p as already gone */
18446          if (!reinvite)
18447             sip_alreadygone(p);
18448       }
18449       break;
18450    case 491: /* Pending */
18451       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
18452       if (p->owner && !req->ignore) {
18453          if (p->owner->_state != AST_STATE_UP) {
18454             ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
18455             pvt_set_needdestroy(p, "received 491 response");
18456          } else {
18457             /* This is a re-invite that failed. */
18458             /* Reset the flag after a while 
18459              */
18460             int wait;
18461             /* RFC 3261, if owner of call, wait between 2.1 to 4 seconds,
18462              * if not owner of call, wait 0 to 2 seconds */
18463             if (p->outgoing_call) {
18464                wait = 2100 + ast_random() % 2000;
18465             } else {
18466                wait = ast_random() % 2000;
18467             }
18468             p->waitid = ast_sched_add(sched, wait, sip_reinvite_retry, dialog_ref(p, "passing dialog ptr into sched structure based on waitid for sip_reinvite_retry."));
18469             ast_log(LOG_WARNING, "just did sched_add waitid(%d) for sip_reinvite_retry for dialog %s in handle_response_invite\n", p->waitid, p->callid);
18470             ast_debug(2, "Reinvite race. Waiting %d secs before retry\n", wait);
18471          }
18472       }
18473       break;
18474 
18475    case 501: /* Not implemented */
18476       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
18477       if (p->owner)
18478          ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
18479       break;
18480    }
18481    if (xmitres == XMIT_ERROR)
18482       ast_log(LOG_WARNING, "Could not transmit message in dialog %s\n", p->callid);
18483 }
18484 
18485 /* \brief Handle SIP response in NOTIFY transaction
18486        We've sent a NOTIFY, now handle responses to it
18487   */
18488 static void handle_response_notify(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
18489 {
18490    switch (resp) {
18491    case 200:   /* Notify accepted */
18492       /* They got the notify, this is the end */
18493       if (p->owner) {
18494          if (!p->refer) {
18495             ast_log(LOG_WARNING, "Notify answer on an owned channel? - %s\n", p->owner->name);
18496             ast_queue_hangup_with_cause(p->owner, AST_CAUSE_NORMAL_UNSPECIFIED);
18497          } else {
18498             ast_debug(4, "Got OK on REFER Notify message\n");
18499          }
18500       } else {
18501          if (p->subscribed == NONE) {
18502             ast_debug(4, "Got 200 accepted on NOTIFY\n");
18503             pvt_set_needdestroy(p, "received 200 response");
18504          }
18505          if (ast_test_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE)) {
18506             /* Ready to send the next state we have on queue */
18507             ast_clear_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE);
18508             cb_extensionstate((char *)p->context, (char *)p->exten, p->laststate, (void *) p);
18509          }
18510       }
18511       break;
18512    case 401:   /* Not www-authorized on SIP method */
18513    case 407:   /* Proxy auth */
18514       if (!p->notify_headers) {
18515          break; /* Only device notify can use NOTIFY auth */
18516       }
18517       ast_string_field_set(p, theirtag, NULL);
18518       if (ast_strlen_zero(p->authname)) {
18519          ast_log(LOG_WARNING, "Asked to authenticate NOTIFY to %s:%d but we have no matching peer or realm auth!\n", ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
18520          pvt_set_needdestroy(p, "unable to authenticate NOTIFY");
18521       }
18522       if (p->authtries > 1 || do_proxy_auth(p, req, resp, SIP_NOTIFY, 0)) {
18523          ast_log(LOG_NOTICE, "Failed to authenticate on NOTIFY to '%s'\n", get_header(&p->initreq, "From"));
18524          pvt_set_needdestroy(p, "failed to authenticate NOTIFY");
18525       }
18526       break;
18527    }
18528 }
18529 
18530 /* \brief Handle SIP response in SUBSCRIBE transaction */
18531 static void handle_response_subscribe(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
18532 {
18533    if (!p->mwi) {
18534       return;
18535    }
18536 
18537    switch (resp) {
18538    case 200: /* Subscription accepted */
18539       ast_debug(3, "Got 200 OK on subscription for MWI\n");
18540       if (p->options) {
18541          ast_free(p->options);
18542          p->options = NULL;
18543       }
18544       p->mwi->subscribed = 1;
18545       if ((p->mwi->resub = ast_sched_add(sched, mwi_expiry * 1000, sip_subscribe_mwi_do, ASTOBJ_REF(p->mwi))) < 0) {
18546          ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
18547       }
18548       break;
18549    case 401:
18550    case 407:
18551       ast_string_field_set(p, theirtag, NULL);
18552       if (p->authtries > 1 || do_proxy_auth(p, req, resp, SIP_SUBSCRIBE, 0)) {
18553          ast_log(LOG_NOTICE, "Failed to authenticate on SUBSCRIBE to '%s'\n", get_header(&p->initreq, "From"));
18554          p->mwi->call = NULL;
18555          ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
18556          pvt_set_needdestroy(p, "failed to authenticate SUBSCRIBE");
18557       }
18558       break;
18559    case 403:
18560       transmit_response_with_date(p, "200 OK", req);
18561       ast_log(LOG_WARNING, "Authentication failed while trying to subscribe for MWI.\n");
18562       p->mwi->call = NULL;
18563       ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
18564       pvt_set_needdestroy(p, "received 403 response");
18565       sip_alreadygone(p);
18566       break;
18567    case 404:
18568       ast_log(LOG_WARNING, "Subscription failed for MWI. The remote side said that a mailbox may not have been configured.\n");
18569       p->mwi->call = NULL;
18570       ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
18571       pvt_set_needdestroy(p, "received 404 response");
18572       break;
18573    case 481:
18574       ast_log(LOG_WARNING, "Subscription failed for MWI. The remote side said that our dialog did not exist.\n");
18575       p->mwi->call = NULL;
18576       ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
18577       pvt_set_needdestroy(p, "received 481 response");
18578       break;
18579    case 500:
18580    case 501:
18581       ast_log(LOG_WARNING, "Subscription failed for MWI. The remote side may have suffered a heart attack.\n");
18582       p->mwi->call = NULL;
18583       ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
18584       pvt_set_needdestroy(p, "received 500/501 response");
18585       break;
18586    }
18587 }
18588 
18589 /* \brief Handle SIP response in REFER transaction
18590    We've sent a REFER, now handle responses to it 
18591   */
18592 static void handle_response_refer(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
18593 {
18594    /* If no refer structure exists, then do nothing */
18595    if (!p->refer)
18596       return;
18597 
18598    switch (resp) {
18599    case 202:   /* Transfer accepted */
18600       /* We need  to do something here */
18601       /* The transferee is now sending INVITE to target */
18602       p->refer->status = REFER_ACCEPTED;
18603       /* Now wait for next message */
18604       ast_debug(3, "Got 202 accepted on transfer\n");
18605       /* We should hang along, waiting for NOTIFY's here */
18606       break;
18607 
18608    case 401:   /* Not www-authorized on SIP method */
18609    case 407:   /* Proxy auth */
18610       if (ast_strlen_zero(p->authname)) {
18611          ast_log(LOG_WARNING, "Asked to authenticate REFER to %s:%d but we have no matching peer or realm auth!\n",
18612             ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
18613          pvt_set_needdestroy(p, "unable to authenticate REFER");
18614       }
18615       if (p->authtries > 1 || do_proxy_auth(p, req, resp, SIP_REFER, 0)) {
18616          ast_log(LOG_NOTICE, "Failed to authenticate on REFER to '%s'\n", get_header(&p->initreq, "From"));
18617          p->refer->status = REFER_NOAUTH;
18618          pvt_set_needdestroy(p, "failed to authenticat REFER");
18619       }
18620       break;
18621    case 481: /* Call leg does not exist */
18622 
18623       /* A transfer with Replaces did not work */
18624       /* OEJ: We should Set flag, cancel the REFER, go back
18625       to original call - but right now we can't */
18626       ast_log(LOG_WARNING, "Remote host can't match REFER request to call '%s'. Giving up.\n", p->callid);
18627       if (p->owner)
18628          ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
18629       pvt_set_needdestroy(p, "received 481 response");
18630       break;
18631 
18632    case 500:   /* Server error */
18633    case 501:   /* Method not implemented */
18634       /* Return to the current call onhold */
18635       /* Status flag needed to be reset */
18636       ast_log(LOG_NOTICE, "SIP transfer to %s failed, call miserably fails. \n", p->refer->refer_to);
18637       pvt_set_needdestroy(p, "received 500/501 response");
18638       p->refer->status = REFER_FAILED;
18639       break;
18640    case 603:   /* Transfer declined */
18641       ast_log(LOG_NOTICE, "SIP transfer to %s declined, call miserably fails. \n", p->refer->refer_to);
18642       p->refer->status = REFER_FAILED;
18643       pvt_set_needdestroy(p, "received 603 response");
18644       break;
18645    }
18646 }
18647 
18648 /*! \brief Handle responses on REGISTER to services */
18649 static int handle_response_register(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
18650 {
18651    int expires, expires_ms;
18652    struct sip_registry *r;
18653    r=p->registry;
18654    
18655    switch (resp) {
18656    case 401:   /* Unauthorized */
18657       if (p->authtries == MAX_AUTHTRIES || do_register_auth(p, req, resp)) {
18658          ast_log(LOG_NOTICE, "Failed to authenticate on REGISTER to '%s@%s' (Tries %d)\n", p->registry->username, p->registry->hostname, p->authtries);
18659          pvt_set_needdestroy(p, "failed to authenticate REGISTER");
18660       }
18661       break;
18662    case 403:   /* Forbidden */
18663       ast_log(LOG_WARNING, "Forbidden - wrong password on authentication for REGISTER for '%s' to '%s'\n", p->registry->username, p->registry->hostname);
18664       AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 403"));
18665       r->regstate = REG_STATE_NOAUTH;
18666       pvt_set_needdestroy(p, "received 403 response");
18667       break;
18668    case 404:   /* Not found */
18669       ast_log(LOG_WARNING, "Got 404 Not found on SIP register to service %s@%s, giving up\n", p->registry->username, p->registry->hostname);
18670       pvt_set_needdestroy(p, "received 404 response");
18671       if (r->call)
18672          r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 404");
18673       r->regstate = REG_STATE_REJECTED;
18674       AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 404"));
18675       break;
18676    case 407:   /* Proxy auth */
18677       if (p->authtries == MAX_AUTHTRIES || do_register_auth(p, req, resp)) {
18678          ast_log(LOG_NOTICE, "Failed to authenticate on REGISTER to '%s' (tries '%d')\n", get_header(&p->initreq, "From"), p->authtries);
18679          pvt_set_needdestroy(p, "failed to authenticate REGISTER");
18680       }
18681       break;
18682    case 408:   /* Request timeout */
18683       /* Got a timeout response, so reset the counter of failed responses */
18684       if (r) {
18685          r->regattempts = 0;
18686       } else {
18687          ast_log(LOG_WARNING, "Got a 408 response to our REGISTER on call %s after we had destroyed the registry object\n", p->callid);
18688       }
18689       break;
18690    case 423:   /* Interval too brief */
18691       r->expiry = atoi(get_header(req, "Min-Expires"));
18692       ast_log(LOG_WARNING, "Got 423 Interval too brief for service %s@%s, minimum is %d seconds\n", p->registry->username, p->registry->hostname, r->expiry);
18693       AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 423"));
18694       if (r->call) {
18695          r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 423");
18696          pvt_set_needdestroy(p, "received 423 response");
18697       }
18698       if (r->expiry > max_expiry) {
18699          ast_log(LOG_WARNING, "Required expiration time from %s@%s is too high, giving up\n", p->registry->username, p->registry->hostname);
18700          r->expiry = r->configured_expiry;
18701          r->regstate = REG_STATE_REJECTED;
18702       } else {
18703          r->regstate = REG_STATE_UNREGISTERED;
18704          transmit_register(r, SIP_REGISTER, NULL, NULL);
18705       }
18706       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));
18707       break;
18708    case 479:   /* SER: Not able to process the URI - address is wrong in register*/
18709       ast_log(LOG_WARNING, "Got error 479 on register to %s@%s, giving up (check config)\n", p->registry->username, p->registry->hostname);
18710       pvt_set_needdestroy(p, "received 479 response");
18711       if (r->call)
18712          r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 479");
18713       r->regstate = REG_STATE_REJECTED;
18714       AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 479"));
18715       break;
18716    case 200:   /* 200 OK */
18717       if (!r) {
18718          ast_log(LOG_WARNING, "Got 200 OK on REGISTER, but there isn't a registry entry for '%s' (we probably already got the OK)\n", S_OR(p->peername, p->username));
18719          pvt_set_needdestroy(p, "received erroneous 200 response");
18720          return 0;
18721       }
18722       
18723       r->regstate = REG_STATE_REGISTERED;
18724       r->regtime = ast_tvnow();     /* Reset time of last succesful registration */
18725       manager_event(EVENT_FLAG_SYSTEM, "Registry", "ChannelType: SIP\r\nDomain: %s\r\nStatus: %s\r\n", r->hostname, regstate2str(r->regstate));
18726       r->regattempts = 0;
18727       ast_debug(1, "Registration successful\n");
18728       if (r->timeout > -1) {
18729          ast_debug(1, "Cancelling timeout %d\n", r->timeout);
18730       }
18731       AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 200"));
18732       if (r->call)
18733          r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 200");
18734       p->registry = registry_unref(p->registry, "unref registry entry p->registry");
18735       /* Let this one hang around until we have all the responses */
18736       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
18737       /* p->needdestroy = 1; */
18738       
18739       /* set us up for re-registering
18740        * figure out how long we got registered for
18741        * according to section 6.13 of RFC, contact headers override
18742        * expires headers, so check those first */
18743       expires = 0;
18744 
18745       /* XXX todo: try to save the extra call */
18746       if (!ast_strlen_zero(get_header(req, "Contact"))) {
18747          const char *contact = NULL;
18748          const char *tmptmp = NULL;
18749          int start = 0;
18750          for(;;) {
18751             contact = __get_header(req, "Contact", &start);
18752             /* this loop ensures we get a contact header about our register request */
18753             if(!ast_strlen_zero(contact)) {
18754                if( (tmptmp=strstr(contact, p->our_contact))) {
18755                   contact=tmptmp;
18756                   break;
18757                }
18758             } else
18759                break;
18760          }
18761          tmptmp = strcasestr(contact, "expires=");
18762          if (tmptmp) {
18763             if (sscanf(tmptmp + 8, "%30d;", &expires) != 1)
18764                expires = 0;
18765          }
18766          
18767       }
18768       if (!expires) 
18769          expires=atoi(get_header(req, "expires"));
18770       if (!expires)
18771          expires=default_expiry;
18772       
18773       expires_ms = expires * 1000;
18774       if (expires <= EXPIRY_GUARD_LIMIT)
18775          expires_ms -= MAX((expires_ms * EXPIRY_GUARD_PCT), EXPIRY_GUARD_MIN);
18776       else
18777          expires_ms -= EXPIRY_GUARD_SECS * 1000;
18778       if (sipdebug)
18779          ast_log(LOG_NOTICE, "Outbound Registration: Expiry for %s is %d sec (Scheduling reregistration in %d s)\n", r->hostname, expires, expires_ms/1000); 
18780       
18781       r->refresh= (int) expires_ms / 1000;
18782       
18783       /* Schedule re-registration before we expire */
18784       AST_SCHED_REPLACE_UNREF(r->expire, sched, expires_ms, sip_reregister, r, 
18785                         registry_unref(_data,"unref in REPLACE del fail"), 
18786                         registry_unref(r,"unref in REPLACE add fail"), 
18787                         registry_addref(r,"The Addition side of REPLACE")); 
18788    }
18789    return 1;
18790 }
18791 
18792 /*! \brief Handle qualification responses (OPTIONS) */
18793 static void handle_response_peerpoke(struct sip_pvt *p, int resp, struct sip_request *req)
18794 {
18795    struct sip_peer *peer = /* ref_peer( */ p->relatedpeer /* , "bump refcount on p, as it is being used in this function(handle_response_peerpoke)")*/ ; /* hope this is already refcounted! */
18796    int statechanged, is_reachable, was_reachable;
18797    int pingtime = ast_tvdiff_ms(ast_tvnow(), peer->ps);
18798 
18799    /*
18800     * Compute the response time to a ping (goes in peer->lastms.)
18801     * -1 means did not respond, 0 means unknown,
18802     * 1..maxms is a valid response, >maxms means late response.
18803     */
18804    if (pingtime < 1) /* zero = unknown, so round up to 1 */
18805       pingtime = 1;
18806 
18807    /* Now determine new state and whether it has changed.
18808     * Use some helper variables to simplify the writing
18809     * of the expressions.
18810     */
18811    was_reachable = peer->lastms > 0 && peer->lastms <= peer->maxms;
18812    is_reachable = pingtime <= peer->maxms;
18813    statechanged = peer->lastms == 0 /* yes, unknown before */
18814       || was_reachable != is_reachable;
18815 
18816    peer->lastms = pingtime;
18817    peer->call = dialog_unref(peer->call, "unref dialog peer->call");
18818    if (statechanged) {
18819       const char *s = is_reachable ? "Reachable" : "Lagged";
18820       char str_lastms[20];
18821       snprintf(str_lastms, sizeof(str_lastms), "%d", pingtime);
18822 
18823       ast_log(LOG_NOTICE, "Peer '%s' is now %s. (%dms / %dms)\n",
18824          peer->name, s, pingtime, peer->maxms);
18825       ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", peer->name);
18826       if (sip_cfg.peer_rtupdate) {
18827          ast_update_realtime(ast_check_realtime("sipregs") ? "sipregs" : "sippeers", "name", peer->name, "lastms", str_lastms, SENTINEL);
18828       }
18829       manager_event(EVENT_FLAG_SYSTEM, "PeerStatus",
18830          "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: %s\r\nTime: %d\r\n",
18831          peer->name, s, pingtime);
18832       if (is_reachable && sip_cfg.regextenonqualify)
18833          register_peer_exten(peer, TRUE);
18834    }
18835 
18836    pvt_set_needdestroy(p, "got OPTIONS response");
18837 
18838    /* Try again eventually */
18839    AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched,
18840          is_reachable ? peer->qualifyfreq : DEFAULT_FREQ_NOTOK,
18841          sip_poke_peer_s, peer,
18842          unref_peer(_data, "removing poke peer ref"),
18843          unref_peer(peer, "removing poke peer ref"),
18844          ref_peer(peer, "adding poke peer ref"));
18845 }
18846 
18847 /*! \brief Immediately stop RTP, VRTP and UDPTL as applicable */
18848 static void stop_media_flows(struct sip_pvt *p)
18849 {
18850    /* Immediately stop RTP, VRTP and UDPTL as applicable */
18851    if (p->rtp)
18852       ast_rtp_stop(p->rtp);
18853    if (p->vrtp)
18854       ast_rtp_stop(p->vrtp);
18855    if (p->trtp)
18856       ast_rtp_stop(p->trtp);
18857    if (p->udptl)
18858       ast_udptl_stop(p->udptl);
18859 }
18860 
18861 /*! \brief Handle SIP response in dialogue
18862    \note only called by handle_incoming */
18863 static void handle_response(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
18864 {
18865    struct ast_channel *owner;
18866    int sipmethod;
18867    int res = 1;
18868    const char *c = get_header(req, "Cseq");
18869    /* GCC 4.2 complains if I try to cast c as a char * when passing it to ast_skip_nonblanks, so make a copy of it */
18870    char *c_copy = ast_strdupa(c);
18871    /* Skip the Cseq and its subsequent spaces */
18872    const char *msg = ast_skip_blanks(ast_skip_nonblanks(c_copy));
18873 
18874    if (!msg)
18875       msg = "";
18876 
18877    sipmethod = find_sip_method(msg);
18878 
18879    owner = p->owner;
18880    if (owner) 
18881       owner->hangupcause = hangup_sip2cause(resp);
18882 
18883    if (p->socket.type == SIP_TRANSPORT_UDP) {
18884       int ack_res;
18885 
18886       /* Acknowledge whatever it is destined for */
18887       if ((resp >= 100) && (resp <= 199)) {
18888          ack_res = __sip_semi_ack(p, seqno, 0, sipmethod);
18889       } else {
18890          ack_res = __sip_ack(p, seqno, 0, sipmethod);
18891       }
18892 
18893       if (ack_res == FALSE) {
18894          append_history(p, "Ignore", "Ignoring this retransmit\n");
18895          return;
18896       }
18897    }
18898 
18899    /* If this is a NOTIFY for a subscription clear the flag that indicates that we have a NOTIFY pending */
18900    if (!p->owner && sipmethod == SIP_NOTIFY && p->pendinginvite) 
18901       p->pendinginvite = 0;
18902 
18903    /* Get their tag if we haven't already */
18904    if (ast_strlen_zero(p->theirtag) || (resp >= 200)) {
18905       char tag[128];
18906 
18907       gettag(req, "To", tag, sizeof(tag));
18908       ast_string_field_set(p, theirtag, tag);
18909    }
18910    /* This needs to be configurable on a channel/peer level,
18911       not mandatory for all communication. Sadly enough, NAT implementations
18912       are not so stable so we can always rely on these headers. 
18913       Temporarily disabled, while waiting for fix.
18914       Fix assigned to Rizzo :-)
18915    */
18916    /* check_via_response(p, req); */
18917 
18918    /* RFC 3261 Section 15 specifies that if we receive a 408 or 481
18919     * in response to a BYE, then we should end the current dialog
18920     * and session.  It is known that at least one phone manufacturer
18921     * potentially will send a 404 in response to a BYE, so we'll be
18922     * liberal in what we accept and end the dialog and session if we
18923     * receive any of those responses to a BYE.
18924     */
18925    if ((resp == 404 || resp == 408 || resp == 481) && sipmethod == SIP_BYE) {
18926       pvt_set_needdestroy(p, "received 4XX response to a BYE");
18927       return;
18928    }
18929 
18930    if (p->relatedpeer && p->method == SIP_OPTIONS) {
18931       /* We don't really care what the response is, just that it replied back. 
18932          Well, as long as it's not a 100 response...  since we might
18933          need to hang around for something more "definitive" */
18934       if (resp != 100)
18935          handle_response_peerpoke(p, resp, req);
18936    } else if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
18937       switch(resp) {
18938       case 100:   /* 100 Trying */
18939       case 101:   /* 101 Dialog establishment */
18940       case 183:   /* 183 Session Progress */
18941       case 180:   /* 180 Ringing */
18942       case 182:   /* 182 Queued */
18943          if (sipmethod == SIP_INVITE)
18944             handle_response_invite(p, resp, rest, req, seqno);
18945          break;
18946       case 200:   /* 200 OK */
18947          p->authtries = 0; /* Reset authentication counter */
18948          if (sipmethod == SIP_MESSAGE || sipmethod == SIP_INFO) {
18949             /* We successfully transmitted a message 
18950                or a video update request in INFO */
18951             /* Nothing happens here - the message is inside a dialog */
18952          } else if (sipmethod == SIP_INVITE) {
18953             handle_response_invite(p, resp, rest, req, seqno);
18954          } else if (sipmethod == SIP_NOTIFY) {
18955             handle_response_notify(p, resp, rest, req, seqno);
18956          } else if (sipmethod == SIP_REGISTER) {
18957             res = handle_response_register(p, resp, rest, req, seqno);
18958          } else if (sipmethod == SIP_SUBSCRIBE) {
18959             ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
18960             handle_response_subscribe(p, resp, rest, req, seqno);
18961          } else if (sipmethod == SIP_BYE) {     /* Ok, we're ready to go */
18962             pvt_set_needdestroy(p, "received 200 response");
18963             ast_clear_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
18964          }
18965          break;
18966       case 202:   /* Transfer accepted */
18967          if (sipmethod == SIP_REFER) 
18968             handle_response_refer(p, resp, rest, req, seqno);
18969          break;
18970       case 401: /* Not www-authorized on SIP method */
18971       case 407: /* Proxy auth required */
18972          if (sipmethod == SIP_INVITE)
18973             handle_response_invite(p, resp, rest, req, seqno);
18974          else if (sipmethod == SIP_NOTIFY)
18975             handle_response_notify(p, resp, rest, req, seqno);
18976          else if (sipmethod == SIP_REFER)
18977             handle_response_refer(p, resp, rest, req, seqno);
18978          else if (sipmethod == SIP_SUBSCRIBE)
18979             handle_response_subscribe(p, resp, rest, req, seqno);
18980          else if (p->registry && sipmethod == SIP_REGISTER)
18981             res = handle_response_register(p, resp, rest, req, seqno);
18982          else if (sipmethod == SIP_BYE) {
18983             if (p->options)
18984                p->options->auth_type = resp;
18985             if (ast_strlen_zero(p->authname)) {
18986                ast_log(LOG_WARNING, "Asked to authenticate %s, to %s:%d but we have no matching peer!\n",
18987                      msg, ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
18988                pvt_set_needdestroy(p, "unable to authenticate BYE");
18989             } else if ((p->authtries == MAX_AUTHTRIES) || do_proxy_auth(p, req, resp,  sipmethod, 0)) {
18990                ast_log(LOG_NOTICE, "Failed to authenticate on %s to '%s'\n", msg, get_header(&p->initreq, "From"));
18991                pvt_set_needdestroy(p, "failed to authenticate BYE");
18992             }
18993          } else {
18994             ast_log(LOG_WARNING, "Got authentication request (%d) on %s to '%s'\n", resp, sip_methods[sipmethod].text, get_header(req, "To"));
18995             pvt_set_needdestroy(p, "received 407 response");
18996          }
18997          break;
18998       case 403: /* Forbidden - we failed authentication */
18999          if (sipmethod == SIP_INVITE)
19000             handle_response_invite(p, resp, rest, req, seqno);
19001          else if (sipmethod == SIP_SUBSCRIBE)
19002             handle_response_subscribe(p, resp, rest, req, seqno);
19003          else if (p->registry && sipmethod == SIP_REGISTER) 
19004             res = handle_response_register(p, resp, rest, req, seqno);
19005          else {
19006             ast_log(LOG_WARNING, "Forbidden - maybe wrong password on authentication for %s\n", msg);
19007             pvt_set_needdestroy(p, "received 403 response");
19008          }
19009          break;
19010       case 404: /* Not found */
19011          if (p->registry && sipmethod == SIP_REGISTER)
19012             res = handle_response_register(p, resp, rest, req, seqno);
19013          else if (sipmethod == SIP_INVITE)
19014             handle_response_invite(p, resp, rest, req, seqno);
19015          else if (sipmethod == SIP_SUBSCRIBE)
19016             handle_response_subscribe(p, resp, rest, req, seqno);
19017          else if (owner)
19018             ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
19019          break;
19020       case 423: /* Interval too brief */
19021          if (sipmethod == SIP_REGISTER)
19022             res = handle_response_register(p, resp, rest, req, seqno);
19023          break;
19024       case 408: /* Request timeout - terminate dialog */
19025          if (sipmethod == SIP_INVITE)
19026             handle_response_invite(p, resp, rest, req, seqno);
19027          else if (sipmethod == SIP_REGISTER) 
19028             res = handle_response_register(p, resp, rest, req, seqno);
19029          else if (sipmethod == SIP_BYE) {
19030             pvt_set_needdestroy(p, "received 408 response");
19031             ast_debug(4, "Got timeout on bye. Thanks for the answer. Now, kill this call\n");
19032          } else {
19033             if (owner)
19034                ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
19035             pvt_set_needdestroy(p, "received 408 response");
19036          }
19037          break;
19038 
19039       case 422: /* Session-Timers: Session Interval Too Small */
19040          if (sipmethod == SIP_INVITE) {
19041             handle_response_invite(p, resp, rest, req, seqno);
19042          }
19043          break;
19044 
19045       case 481: /* Call leg does not exist */
19046          if (sipmethod == SIP_INVITE) {
19047             handle_response_invite(p, resp, rest, req, seqno);
19048          } else if (sipmethod == SIP_REFER) {
19049             handle_response_refer(p, resp, rest, req, seqno);
19050          } else if (sipmethod == SIP_SUBSCRIBE) {
19051             handle_response_subscribe(p, resp, rest, req, seqno);
19052          } else if (sipmethod == SIP_NOTIFY) {
19053             pvt_set_needdestroy(p, "received 481 response");
19054          } else if (sipmethod == SIP_BYE) {
19055             /* The other side has no transaction to bye,
19056             just assume it's all right then */
19057             ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
19058          } else if (sipmethod == SIP_CANCEL) {
19059             /* The other side has no transaction to cancel,
19060             just assume it's all right then */
19061             ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
19062          } else {
19063             ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
19064             /* Guessing that this is not an important request */
19065          }
19066          break;
19067       case 487:
19068          if (sipmethod == SIP_INVITE)
19069             handle_response_invite(p, resp, rest, req, seqno);
19070          break;
19071       case 415: /* Unsupported media type */
19072       case 488: /* Not acceptable here - codec error */
19073       case 606: /* Not Acceptable */
19074          if (sipmethod == SIP_INVITE)
19075             handle_response_invite(p, resp, rest, req, seqno);
19076          break;
19077       case 491: /* Pending */
19078          if (sipmethod == SIP_INVITE)
19079             handle_response_invite(p, resp, rest, req, seqno);
19080          else {
19081             ast_debug(1, "Got 491 on %s, unsupported. Call ID %s\n", sip_methods[sipmethod].text, p->callid);
19082             pvt_set_needdestroy(p, "received 491 response");
19083          }
19084          break;
19085       case 501: /* Not Implemented */
19086          if (sipmethod == SIP_INVITE)
19087             handle_response_invite(p, resp, rest, req, seqno);
19088          else if (sipmethod == SIP_REFER)
19089             handle_response_refer(p, resp, rest, req, seqno);
19090          else
19091             ast_log(LOG_WARNING, "Host '%s' does not implement '%s'\n", ast_inet_ntoa(p->sa.sin_addr), msg);
19092          break;
19093       case 603:   /* Declined transfer */
19094          if (sipmethod == SIP_REFER) {
19095             handle_response_refer(p, resp, rest, req, seqno);
19096             break;
19097          }
19098          /* Fallthrough */
19099       default:
19100          if ((resp >= 300) && (resp < 700)) {
19101             /* Fatal response */
19102             if ((resp != 487))
19103                ast_verb(3, "Got SIP response %d \"%s\" back from %s\n", resp, rest, ast_inet_ntoa(p->sa.sin_addr));
19104    
19105             if (sipmethod == SIP_INVITE)
19106                stop_media_flows(p); /* Immediately stop RTP, VRTP and UDPTL as applicable */
19107 
19108             /* XXX Locking issues?? XXX */
19109             switch(resp) {
19110             case 300: /* Multiple Choices */
19111             case 301: /* Moved permanently */
19112             case 302: /* Moved temporarily */
19113             case 305: /* Use Proxy */
19114                parse_moved_contact(p, req);
19115                /* Fall through */
19116             case 486: /* Busy here */
19117             case 600: /* Busy everywhere */
19118             case 603: /* Decline */
19119                if (p->owner)
19120                   ast_queue_control(p->owner, AST_CONTROL_BUSY);
19121                break;
19122             case 482: /* Loop Detected */
19123                /*
19124                   \note Asterisk has historically tried to do a call forward when it
19125                   gets a 482, but that behavior isn't necessarily the best course of
19126                   action. Go ahead and do it anyway by default, but allow the option
19127                   to immediately pass to the next line in the dialplan. */
19128                if (p->owner && ast_test_flag(&p->flags[1], SIP_PAGE2_FORWARD_LOOP_DETECTED)) {
19129                      ast_debug(1, "Hairpin detected, setting up call forward for what it's worth\n");
19130                      ast_string_field_build(p->owner, call_forward,
19131                            "Local/%s@%s", p->username, p->context);
19132                }
19133                /* Fall through */
19134             case 480: /* Temporarily Unavailable */
19135             case 404: /* Not Found */
19136             case 410: /* Gone */
19137             case 400: /* Bad Request */
19138             case 500: /* Server error */
19139                if (sipmethod == SIP_REFER) {
19140                   handle_response_refer(p, resp, rest, req, seqno);
19141                   break;
19142                } else if (sipmethod == SIP_SUBSCRIBE) {
19143                   handle_response_subscribe(p, resp, rest, req, seqno);
19144                   break;
19145                }
19146                /* Fall through */
19147             case 502: /* Bad gateway */
19148             case 503: /* Service Unavailable */
19149             case 504: /* Server Timeout */
19150                if (owner)
19151                   ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
19152                break;
19153             default:
19154                /* Send hangup */ 
19155                if (owner && sipmethod != SIP_MESSAGE && sipmethod != SIP_INFO && sipmethod != SIP_BYE)
19156                   ast_queue_hangup_with_cause(p->owner, AST_CAUSE_PROTOCOL_ERROR);
19157                break;
19158             }
19159             /* ACK on invite */
19160             if (sipmethod == SIP_INVITE) 
19161                transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
19162             if (sipmethod != SIP_MESSAGE && sipmethod != SIP_INFO) 
19163                sip_alreadygone(p);
19164             if (!p->owner) {
19165                pvt_set_needdestroy(p, "transaction completed");
19166             }
19167          } else if ((resp >= 100) && (resp < 200)) {
19168             if (sipmethod == SIP_INVITE) {
19169                if (!req->ignore && sip_cancel_destroy(p))
19170                   ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
19171                if (find_sdp(req))
19172                   process_sdp(p, req, SDP_T38_NONE);
19173                if (p->owner) {
19174                   /* Queue a progress frame */
19175                   ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
19176                }
19177             }
19178          } else
19179             ast_log(LOG_NOTICE, "Don't know how to handle a %d %s response from %s\n", resp, rest, p->owner ? p->owner->name : ast_inet_ntoa(p->sa.sin_addr));
19180       }
19181    } else { 
19182       /* Responses to OUTGOING SIP requests on INCOMING calls 
19183          get handled here. As well as out-of-call message responses */
19184       if (req->debug)
19185          ast_verbose("SIP Response message for INCOMING dialog %s arrived\n", msg);
19186 
19187       if (sipmethod == SIP_INVITE && resp == 200) {
19188          /* Tags in early session is replaced by the tag in 200 OK, which is 
19189          the final reply to our INVITE */
19190          char tag[128];
19191 
19192          gettag(req, "To", tag, sizeof(tag));
19193          ast_string_field_set(p, theirtag, tag);
19194       }
19195 
19196       switch(resp) {
19197       case 200:
19198          if (sipmethod == SIP_INVITE) {
19199             handle_response_invite(p, resp, rest, req, seqno);
19200          } else if (sipmethod == SIP_CANCEL) {
19201             ast_debug(1, "Got 200 OK on CANCEL\n");
19202 
19203             /* Wait for 487, then destroy */
19204          } else if (sipmethod == SIP_NOTIFY) {
19205             /* They got the notify, this is the end */
19206             if (p->owner) {
19207                if (p->refer) {
19208                   ast_debug(1, "Got 200 OK on NOTIFY for transfer\n");
19209                } else
19210                   ast_log(LOG_WARNING, "Notify answer on an owned channel?\n");
19211                /* ast_queue_hangup(p->owner); Disabled */
19212             } else {
19213                if (!p->subscribed && !p->refer) {
19214                   pvt_set_needdestroy(p, "transaction completed");
19215                }
19216                if (ast_test_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE)) {
19217                   /* Ready to send the next state we have on queue */
19218                   ast_clear_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE);
19219                   cb_extensionstate((char *)p->context, (char *)p->exten, p->laststate, (void *) p);
19220                }
19221             }
19222          } else if (sipmethod == SIP_BYE) {
19223             pvt_set_needdestroy(p, "transaction completed");
19224          } else if (sipmethod == SIP_MESSAGE || sipmethod == SIP_INFO) {
19225             /* We successfully transmitted a message or
19226                a video update request in INFO */
19227             ;
19228          }
19229          break;
19230       case 202:   /* Transfer accepted */
19231          if (sipmethod == SIP_REFER) 
19232             handle_response_refer(p, resp, rest, req, seqno);
19233          break;
19234       case 401:   /* www-auth */
19235       case 407:
19236          if (sipmethod == SIP_REFER)
19237             handle_response_refer(p, resp, rest, req, seqno);
19238          else if (sipmethod == SIP_INVITE) 
19239             handle_response_invite(p, resp, rest, req, seqno);
19240          else if (sipmethod == SIP_BYE) {
19241             if (p->authtries == MAX_AUTHTRIES || do_proxy_auth(p, req, resp, sipmethod, 0)) {
19242                ast_log(LOG_NOTICE, "Failed to authenticate on %s to '%s'\n", msg, get_header(&p->initreq, "From"));
19243                pvt_set_needdestroy(p, "failed to authenticate BYE");
19244             }
19245          }
19246          break;
19247       case 481:   /* Call leg does not exist */
19248          if (sipmethod == SIP_INVITE) {
19249             /* Re-invite failed */
19250             handle_response_invite(p, resp, rest, req, seqno);
19251          } else if (sipmethod == SIP_BYE) {
19252             pvt_set_needdestroy(p, "received 481 response");
19253          } else if (sipmethod == SIP_NOTIFY) {
19254             pvt_set_needdestroy(p, "received 481 response");
19255          } else if (sipdebug) {
19256             ast_debug(1, "Remote host can't match request %s to call '%s'. Giving up\n", sip_methods[sipmethod].text, p->callid);
19257          }
19258          break;
19259       case 501: /* Not Implemented */
19260          if (sipmethod == SIP_INVITE) 
19261             handle_response_invite(p, resp, rest, req, seqno);
19262          else if (sipmethod == SIP_REFER) 
19263             handle_response_refer(p, resp, rest, req, seqno);
19264          break;
19265       case 603:   /* Declined transfer */
19266          if (sipmethod == SIP_REFER) {
19267             handle_response_refer(p, resp, rest, req, seqno);
19268             break;
19269          }
19270          /* Fallthrough */
19271       default: /* Errors without handlers */
19272          if ((resp >= 100) && (resp < 200)) {
19273             if (sipmethod == SIP_INVITE) {   /* re-invite */
19274                if (!req->ignore && sip_cancel_destroy(p))
19275                   ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
19276             }
19277          }
19278          if ((resp >= 300) && (resp < 700)) {
19279             if ((resp != 487))
19280                ast_verb(3, "Incoming call: Got SIP response %d \"%s\" back from %s\n", resp, rest, ast_inet_ntoa(p->sa.sin_addr));
19281             switch(resp) {
19282             case 415: /* Unsupported media type */
19283             case 488: /* Not acceptable here - codec error */
19284             case 603: /* Decline */
19285             case 500: /* Server error */
19286             case 502: /* Bad gateway */
19287             case 503: /* Service Unavailable */
19288             case 504: /* Server timeout */
19289 
19290                /* re-invite failed */
19291                if (sipmethod == SIP_INVITE && sip_cancel_destroy(p))
19292                   ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
19293                break;
19294             }
19295          }
19296          break;
19297       }
19298    }
19299 }
19300 
19301 
19302 /*! \brief Park SIP call support function 
19303    Starts in a new thread, then parks the call
19304    XXX Should we add a wait period after streaming audio and before hangup?? Sometimes the
19305       audio can't be heard before hangup
19306 */
19307 static void *sip_park_thread(void *stuff)
19308 {
19309    struct ast_channel *transferee, *transferer; /* Chan1: The transferee, Chan2: The transferer */
19310    struct sip_dual *d;
19311    struct sip_request req = {0,};
19312    int ext;
19313    int res;
19314 
19315    d = stuff;
19316    transferee = d->chan1;
19317    transferer = d->chan2;
19318    copy_request(&req, &d->req);
19319 
19320    if (!transferee || !transferer) {
19321       ast_log(LOG_ERROR, "Missing channels for parking! Transferer %s Transferee %s\n", transferer ? "<available>" : "<missing>", transferee ? "<available>" : "<missing>" );
19322       deinit_req(&d->req);
19323       ast_free(d);
19324       return NULL;
19325    }
19326    ast_debug(4, "SIP Park: Transferer channel %s, Transferee %s\n", transferer->name, transferee->name);
19327 
19328    ast_channel_lock(transferee);
19329    if (ast_do_masquerade(transferee)) {
19330       ast_log(LOG_WARNING, "Masquerade failed.\n");
19331       transmit_response(transferer->tech_pvt, "503 Internal error", &req);
19332       ast_channel_unlock(transferee);
19333       deinit_req(&d->req);
19334       ast_free(d);
19335       return NULL;
19336    } 
19337    ast_channel_unlock(transferee);
19338 
19339    res = ast_park_call(transferee, transferer, 0, &ext);
19340    
19341 
19342 #ifdef WHEN_WE_KNOW_THAT_THE_CLIENT_SUPPORTS_MESSAGE
19343    if (!res) {
19344       transmit_message_with_text(transferer->tech_pvt, "Unable to park call.\n");
19345    } else {
19346       /* Then tell the transferer what happened */
19347       sprintf(buf, "Call parked on extension '%d'", ext);
19348       transmit_message_with_text(transferer->tech_pvt, buf);
19349    }
19350 #endif
19351 
19352    /* Any way back to the current call??? */
19353    /* Transmit response to the REFER request */
19354    if (!res)   {
19355       /* Transfer succeeded */
19356       append_history(transferer->tech_pvt, "SIPpark", "Parked call on %d", ext);
19357       transmit_notify_with_sipfrag(transferer->tech_pvt, d->seqno, "200 OK", TRUE);
19358       transferer->hangupcause = AST_CAUSE_NORMAL_CLEARING;
19359       ast_hangup(transferer); /* This will cause a BYE */
19360       ast_debug(1, "SIP Call parked on extension '%d'\n", ext);
19361    } else {
19362       transmit_notify_with_sipfrag(transferer->tech_pvt, d->seqno, "503 Service Unavailable", TRUE);
19363       append_history(transferer->tech_pvt, "SIPpark", "Parking failed\n");
19364       ast_debug(1, "SIP Call parked failed \n");
19365       /* Do not hangup call */
19366    }
19367    deinit_req(&d->req);
19368    ast_free(d);
19369    return NULL;
19370 }
19371 
19372 /*! \brief Park a call using the subsystem in res_features.c 
19373    This is executed in a separate thread
19374 */
19375 static int sip_park(struct ast_channel *chan1, struct ast_channel *chan2, struct sip_request *req, int seqno)
19376 {
19377    struct sip_dual *d;
19378    struct ast_channel *transferee, *transferer;
19379       /* Chan2m: The transferer, chan1m: The transferee */
19380    pthread_t th;
19381 
19382    transferee = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, chan1->accountcode, chan1->exten, chan1->context, chan1->amaflags, "Parking/%s", chan1->name);
19383    transferer = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, chan2->accountcode, chan2->exten, chan2->context, chan2->amaflags, "SIPPeer/%s", chan2->name);
19384    if ((!transferer) || (!transferee)) {
19385       if (transferee) {
19386          transferee->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
19387          ast_hangup(transferee);
19388       }
19389       if (transferer) {
19390          transferer->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
19391          ast_hangup(transferer);
19392       }
19393       return -1;
19394    }
19395 
19396    /* Make formats okay */
19397    transferee->readformat = chan1->readformat;
19398    transferee->writeformat = chan1->writeformat;
19399 
19400    /* Prepare for taking over the channel */
19401    ast_channel_masquerade(transferee, chan1);
19402 
19403    /* Setup the extensions and such */
19404    ast_copy_string(transferee->context, chan1->context, sizeof(transferee->context));
19405    ast_copy_string(transferee->exten, chan1->exten, sizeof(transferee->exten));
19406    transferee->priority = chan1->priority;
19407       
19408    /* We make a clone of the peer channel too, so we can play
19409       back the announcement */
19410 
19411    /* Make formats okay */
19412    transferer->readformat = chan2->readformat;
19413    transferer->writeformat = chan2->writeformat;
19414    if (!ast_strlen_zero(chan2->parkinglot))
19415       ast_string_field_set(transferer, parkinglot, chan2->parkinglot);
19416 
19417    /* Prepare for taking over the channel.  Go ahead and grab this channel
19418     * lock here to avoid a deadlock with callbacks into the channel driver
19419     * that hold the channel lock and want the pvt lock.  */
19420    while (ast_channel_trylock(chan2)) {
19421       struct sip_pvt *pvt = chan2->tech_pvt;
19422       sip_pvt_unlock(pvt);
19423       usleep(1);
19424       sip_pvt_lock(pvt);
19425    }
19426    ast_channel_masquerade(transferer, chan2);
19427    ast_channel_unlock(chan2);
19428 
19429    /* Setup the extensions and such */
19430    ast_copy_string(transferer->context, chan2->context, sizeof(transferer->context));
19431    ast_copy_string(transferer->exten, chan2->exten, sizeof(transferer->exten));
19432    transferer->priority = chan2->priority;
19433 
19434    ast_channel_lock(transferer);
19435    if (ast_do_masquerade(transferer)) {
19436       ast_log(LOG_WARNING, "Masquerade failed :(\n");
19437       ast_channel_unlock(transferer);
19438       transferer->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
19439       ast_hangup(transferer);
19440       return -1;
19441    }
19442    ast_channel_unlock(transferer);
19443    if (!transferer || !transferee) {
19444       if (!transferer) { 
19445          ast_debug(1, "No transferer channel, giving up parking\n");
19446       }
19447       if (!transferee) {
19448          ast_debug(1, "No transferee channel, giving up parking\n");
19449       }
19450       return -1;
19451    }
19452    if (!(d = ast_calloc(1, sizeof(*d)))) {
19453       return -1;
19454    }
19455 
19456    /* Save original request for followup */
19457    copy_request(&d->req, req);
19458    d->chan1 = transferee;  /* Transferee */
19459    d->chan2 = transferer;  /* Transferer */
19460    d->seqno = seqno;
19461    if (ast_pthread_create_detached_background(&th, NULL, sip_park_thread, d) < 0) {
19462       /* Could not start thread */
19463       deinit_req(&d->req);
19464       ast_free(d);   /* We don't need it anymore. If thread is created, d will be free'd
19465                by sip_park_thread() */
19466       return -1;
19467    }
19468    return 0;
19469 }
19470 
19471 /*! \brief Turn off generator data 
19472    XXX Does this function belong in the SIP channel?
19473 */
19474 static void ast_quiet_chan(struct ast_channel *chan) 
19475 {
19476    if (chan && chan->_state == AST_STATE_UP) {
19477       if (ast_test_flag(chan, AST_FLAG_MOH))
19478          ast_moh_stop(chan);
19479       else if (chan->generatordata)
19480          ast_deactivate_generator(chan);
19481    }
19482 }
19483 
19484 /*! \brief Attempt transfer of SIP call 
19485    This fix for attended transfers on a local PBX */
19486 static int attempt_transfer(struct sip_dual *transferer, struct sip_dual *target)
19487 {
19488    int res = 0;
19489    struct ast_channel *peera = NULL,   
19490       *peerb = NULL,
19491       *peerc = NULL,
19492       *peerd = NULL;
19493 
19494 
19495    /* We will try to connect the transferee with the target and hangup
19496       all channels to the transferer */   
19497    ast_debug(4, "Sip transfer:--------------------\n");
19498    if (transferer->chan1)
19499       ast_debug(4, "-- Transferer to PBX channel: %s State %s\n", transferer->chan1->name, ast_state2str(transferer->chan1->_state));
19500    else
19501       ast_debug(4, "-- No transferer first channel - odd??? \n");
19502    if (target->chan1)
19503       ast_debug(4, "-- Transferer to PBX second channel (target): %s State %s\n", target->chan1->name, ast_state2str(target->chan1->_state));
19504    else
19505       ast_debug(4, "-- No target first channel ---\n");
19506    if (transferer->chan2)
19507       ast_debug(4, "-- Bridged call to transferee: %s State %s\n", transferer->chan2->name, ast_state2str(transferer->chan2->_state));
19508    else
19509       ast_debug(4, "-- No bridged call to transferee\n");
19510    if (target->chan2)
19511       ast_debug(4, "-- Bridged call to transfer target: %s State %s\n", target->chan2 ? target->chan2->name : "<none>", target->chan2 ? ast_state2str(target->chan2->_state) : "(none)");
19512    else
19513       ast_debug(4, "-- No target second channel ---\n");
19514    ast_debug(4, "-- END Sip transfer:--------------------\n");
19515    if (transferer->chan2) { /* We have a bridge on the transferer's channel */
19516       peera = transferer->chan1; /* Transferer - PBX -> transferee channel * the one we hangup */
19517       peerb = target->chan1;     /* Transferer - PBX -> target channel - This will get lost in masq */
19518       peerc = transferer->chan2; /* Asterisk to Transferee */
19519       peerd = target->chan2;     /* Asterisk to Target */
19520       ast_debug(3, "SIP transfer: Four channels to handle\n");
19521    } else if (target->chan2) {   /* Transferer has no bridge (IVR), but transferee */
19522       peera = target->chan1;     /* Transferer to PBX -> target channel */
19523       peerb = transferer->chan1; /* Transferer to IVR*/
19524       peerc = target->chan2;     /* Asterisk to Target */
19525       peerd = transferer->chan2; /* Nothing */
19526       ast_debug(3, "SIP transfer: Three channels to handle\n");
19527    }
19528 
19529    if (peera && peerb && peerc && (peerb != peerc)) {
19530       ast_quiet_chan(peera);     /* Stop generators */
19531       ast_quiet_chan(peerb);  
19532       ast_quiet_chan(peerc);
19533       if (peerd)
19534          ast_quiet_chan(peerd);
19535 
19536       ast_debug(4, "SIP transfer: trying to masquerade %s into %s\n", peerc->name, peerb->name);
19537       if (ast_channel_masquerade(peerb, peerc)) {
19538          ast_log(LOG_WARNING, "Failed to masquerade %s into %s\n", peerb->name, peerc->name);
19539          res = -1;
19540       } else
19541          ast_debug(4, "SIP transfer: Succeeded to masquerade channels.\n");
19542       return res;
19543    } else {
19544       ast_log(LOG_NOTICE, "SIP Transfer attempted with no appropriate bridged calls to transfer\n");
19545       if (transferer->chan1)
19546          ast_softhangup_nolock(transferer->chan1, AST_SOFTHANGUP_DEV);
19547       if (target->chan1)
19548          ast_softhangup_nolock(target->chan1, AST_SOFTHANGUP_DEV);
19549       return -1;
19550    }
19551    return 0;
19552 }
19553 
19554 /*! \brief Get tag from packet 
19555  *
19556  * \return Returns the pointer to the provided tag buffer,
19557  *         or NULL if the tag was not found.
19558  */
19559 static const char *gettag(const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize)
19560 {
19561    const char *thetag;
19562 
19563    if (!tagbuf)
19564       return NULL;
19565    tagbuf[0] = '\0';    /* reset the buffer */
19566    thetag = get_header(req, header);
19567    thetag = strcasestr(thetag, ";tag=");
19568    if (thetag) {
19569       thetag += 5;
19570       ast_copy_string(tagbuf, thetag, tagbufsize);
19571       return strsep(&tagbuf, ";");
19572    }
19573    return NULL;
19574 }
19575 
19576 /*! \brief Handle incoming notifications */
19577 static int handle_request_notify(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e)
19578 {
19579    /* This is mostly a skeleton for future improvements */
19580    /* Mostly created to return proper answers on notifications on outbound REFER's */
19581    int res = 0;
19582    const char *event = get_header(req, "Event");
19583    char *eventid = NULL;
19584    char *sep;
19585 
19586    if( (sep = strchr(event, ';')) ) {  /* XXX bug here - overwriting string ? */
19587       *sep++ = '\0';
19588       eventid = sep;
19589    }
19590    
19591    if (sipdebug)
19592       ast_debug(2, "Got NOTIFY Event: %s\n", event);
19593 
19594    if (!strcmp(event, "refer")) {
19595       /* Save nesting depth for now, since there might be other events we will
19596          support in the future */
19597 
19598       /* Handle REFER notifications */
19599 
19600       char buf[1024];
19601       char *cmd, *code;
19602       int respcode;
19603       int success = TRUE;
19604 
19605       /* EventID for each transfer... EventID is basically the REFER cseq 
19606 
19607        We are getting notifications on a call that we transfered
19608        We should hangup when we are getting a 200 OK in a sipfrag
19609        Check if we have an owner of this event */
19610       
19611       /* Check the content type */
19612       if (strncasecmp(get_header(req, "Content-Type"), "message/sipfrag", strlen("message/sipfrag"))) {
19613          /* We need a sipfrag */
19614          transmit_response(p, "400 Bad request", req);
19615          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19616          return -1;
19617       }
19618 
19619       /* Get the text of the attachment */
19620       if (get_msg_text(buf, sizeof(buf), req, TRUE)) {
19621          ast_log(LOG_WARNING, "Unable to retrieve attachment from NOTIFY %s\n", p->callid);
19622          transmit_response(p, "400 Bad request", req);
19623          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19624          return -1;
19625       }
19626 
19627       /*
19628       From the RFC...
19629       A minimal, but complete, implementation can respond with a single
19630       NOTIFY containing either the body:
19631          SIP/2.0 100 Trying
19632       
19633       if the subscription is pending, the body:
19634          SIP/2.0 200 OK
19635       if the reference was successful, the body:
19636          SIP/2.0 503 Service Unavailable
19637       if the reference failed, or the body:
19638          SIP/2.0 603 Declined
19639 
19640       if the REFER request was accepted before approval to follow the
19641       reference could be obtained and that approval was subsequently denied
19642       (see Section 2.4.7).
19643       
19644       If there are several REFERs in the same dialog, we need to
19645       match the ID of the event header...
19646       */
19647       ast_debug(3, "* SIP Transfer NOTIFY Attachment: \n---%s\n---\n", buf);
19648       cmd = ast_skip_blanks(buf);
19649       code = cmd;
19650       /* We are at SIP/2.0 */
19651       while(*code && (*code > 32)) {   /* Search white space */
19652          code++;
19653       }
19654       *code++ = '\0';
19655       code = ast_skip_blanks(code);
19656       sep = code;
19657       sep++;
19658       while(*sep && (*sep > 32)) {  /* Search white space */
19659          sep++;
19660       }
19661       *sep++ = '\0';       /* Response string */
19662       respcode = atoi(code);
19663       switch (respcode) {
19664       case 100:   /* Trying: */
19665       case 101:   /* dialog establishment */
19666          /* Don't do anything yet */
19667          break;
19668       case 183:   /* Ringing: */
19669          /* Don't do anything yet */
19670          break;
19671       case 200:   /* OK: The new call is up, hangup this call */
19672          /* Hangup the call that we are replacing */
19673          break;
19674       case 301: /* Moved permenantly */
19675       case 302: /* Moved temporarily */
19676          /* Do we get the header in the packet in this case? */
19677          success = FALSE;
19678          break;
19679       case 503:   /* Service Unavailable: The new call failed */
19680             /* Cancel transfer, continue the call */
19681          success = FALSE;
19682          break;
19683       case 603:   /* Declined: Not accepted */
19684             /* Cancel transfer, continue the current call */
19685          success = FALSE;
19686          break;
19687       }
19688       if (!success) {
19689          ast_log(LOG_NOTICE, "Transfer failed. Sorry. Nothing further to do with this call\n");
19690       }
19691       
19692       /* Confirm that we received this packet */
19693       transmit_response(p, "200 OK", req);
19694    } else if (p->mwi && !strcmp(event, "message-summary")) {
19695       char *c = ast_strdupa(get_body(req, "Voice-Message", ':'));
19696 
19697       if (!ast_strlen_zero(c)) {
19698          char *old = strsep(&c, " ");
19699          char *new = strsep(&old, "/");
19700          struct ast_event *event;
19701 
19702          if ((event = ast_event_new(AST_EVENT_MWI,
19703                      AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, p->mwi->mailbox,
19704                      AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, "SIP_Remote",
19705                      AST_EVENT_IE_NEWMSGS, AST_EVENT_IE_PLTYPE_UINT, atoi(new),
19706                      AST_EVENT_IE_OLDMSGS, AST_EVENT_IE_PLTYPE_UINT, atoi(old),
19707                      AST_EVENT_IE_END))) {
19708             ast_event_queue_and_cache(event);
19709          }
19710       }
19711 
19712       transmit_response(p, "200 OK", req);
19713    } else if (!strcmp(event, "keep-alive")) {
19714        /* Used by Sipura/Linksys for NAT pinhole,
19715         * just confirm that we received the packet. */
19716       transmit_response(p, "200 OK", req);
19717    } else {
19718       /* We don't understand this event. */
19719       transmit_response(p, "489 Bad event", req);
19720       res = -1;
19721    }
19722 
19723    if (!p->lastinvite)
19724       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19725 
19726    return res;
19727 }
19728 
19729 /*! \brief Handle incoming OPTIONS request 
19730    An OPTIONS request should be answered like an INVITE from the same UA, including SDP
19731 */
19732 static int handle_request_options(struct sip_pvt *p, struct sip_request *req)
19733 {
19734    int res;
19735 
19736    /*! XXX get_destination assumes we're already authenticated. This means that a request from
19737       a known device (peer) will end up in the wrong context if this is out-of-dialog.
19738       However, we want to handle OPTIONS as light as possible, so we might want to have
19739       a configuration option whether we care or not. Some devices use this for testing
19740       capabilities, which means that we need to match device to answer with proper 
19741       capabilities (including SDP).
19742       \todo Fix handle_request_options device handling with optional authentication
19743          (this needs to be fixed in 1.4 as well)
19744    */
19745 
19746    if (p->lastinvite) {
19747       /* if this is a request in an active dialog, just confirm that the dialog exists. */
19748       transmit_response_with_allow(p, "200 OK", req, 0);
19749       return 0;
19750    }
19751 
19752    res = get_destination(p, req);
19753    build_contact(p);
19754 
19755    if (ast_strlen_zero(p->context))
19756       ast_string_field_set(p, context, sip_cfg.default_context);
19757 
19758    if (ast_shutting_down())
19759       transmit_response_with_allow(p, "503 Unavailable", req, 0);
19760    else if (res < 0)
19761       transmit_response_with_allow(p, "404 Not Found", req, 0);
19762    else 
19763       transmit_response_with_allow(p, "200 OK", req, 0);
19764 
19765    /* Destroy if this OPTIONS was the opening request, but not if
19766       it's in the middle of a normal call flow. */
19767    sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19768 
19769    return res;
19770 }
19771 
19772 /*! \brief Handle the transfer part of INVITE with a replaces: header, 
19773     meaning a target pickup or an attended transfer.
19774     Used only once.
19775    XXX 'ignore' is unused.
19776 
19777    \note this function is called by handle_request_invite(). Four locks
19778    held at the beginning of this function, p, p->owner, p->refer->refer_call->owner...
19779    only p's lock should remain at the end of this function.  p's lock is held by sipsock_read()
19780  */
19781 static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, struct sockaddr_in *sin, int *nounlock)
19782 {
19783    int earlyreplace = 0;
19784    int oneleggedreplace = 0;     /* Call with no bridge, propably IVR or voice message */
19785    struct ast_channel *c = p->owner;   /* Our incoming call */
19786    struct ast_channel *replacecall = p->refer->refer_call->owner; /* The channel we're about to take over */
19787    struct ast_channel *targetcall;     /* The bridge to the take-over target */
19788 
19789    struct ast_channel *test;
19790 
19791    /* Check if we're in ring state */
19792    if (replacecall->_state == AST_STATE_RING)
19793       earlyreplace = 1;
19794 
19795    /* Check if we have a bridge */
19796    if (!(targetcall = ast_bridged_channel(replacecall))) {
19797       /* We have no bridge */
19798       if (!earlyreplace) {
19799          ast_debug(2, " Attended transfer attempted to replace call with no bridge (maybe ringing). Channel %s!\n", replacecall->name);
19800          oneleggedreplace = 1;
19801       }
19802    } 
19803    if (targetcall && targetcall->_state == AST_STATE_RINGING)
19804       ast_debug(4, "SIP transfer: Target channel is in ringing state\n");
19805 
19806    if (targetcall) 
19807       ast_debug(4, "SIP transfer: Invite Replace incoming channel should bridge to channel %s while hanging up channel %s\n", targetcall->name, replacecall->name); 
19808    else
19809       ast_debug(4, "SIP transfer: Invite Replace incoming channel should replace and hang up channel %s (one call leg)\n", replacecall->name); 
19810 
19811    if (req->ignore) {
19812       ast_log(LOG_NOTICE, "Ignoring this INVITE with replaces in a stupid way.\n");
19813       /* We should answer something here. If we are here, the
19814          call we are replacing exists, so an accepted 
19815          can't harm */
19816       transmit_response_with_sdp(p, "200 OK", req, XMIT_RELIABLE, FALSE);
19817       /* Do something more clever here */
19818       if (c) {
19819          *nounlock = 1;
19820          ast_channel_unlock(c);
19821       }
19822       ast_channel_unlock(replacecall);
19823       sip_pvt_unlock(p->refer->refer_call);
19824       return 1;
19825    } 
19826    if (!c) {
19827       /* What to do if no channel ??? */
19828       ast_log(LOG_ERROR, "Unable to create new channel.  Invite/replace failed.\n");
19829       transmit_response_reliable(p, "503 Service Unavailable", req);
19830       append_history(p, "Xfer", "INVITE/Replace Failed. No new channel.");
19831       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19832       ast_channel_unlock(replacecall);
19833       sip_pvt_unlock(p->refer->refer_call);
19834       return 1;
19835    }
19836    append_history(p, "Xfer", "INVITE/Replace received");
19837    /* We have three channels to play with
19838       channel c: New incoming call
19839       targetcall: Call from PBX to target
19840       p->refer->refer_call: SIP pvt dialog from transferer to pbx.
19841       replacecall: The owner of the previous
19842       We need to masq C into refer_call to connect to 
19843       targetcall;
19844       If we are talking to internal audio stream, target call is null.
19845    */
19846 
19847    /* Fake call progress */
19848    transmit_response(p, "100 Trying", req);
19849    ast_setstate(c, AST_STATE_RING);
19850 
19851    /* Masquerade the new call into the referred call to connect to target call 
19852       Targetcall is not touched by the masq */
19853 
19854    /* Answer the incoming call and set channel to UP state */
19855    transmit_response_with_sdp(p, "200 OK", req, XMIT_RELIABLE, FALSE);
19856       
19857    ast_setstate(c, AST_STATE_UP);
19858    
19859    /* Stop music on hold and other generators */
19860    ast_quiet_chan(replacecall);
19861    ast_quiet_chan(targetcall);
19862    ast_debug(4, "Invite/Replaces: preparing to masquerade %s into %s\n", c->name, replacecall->name);
19863 
19864    /* Make sure that the masq does not free our PVT for the old call */
19865    if (! earlyreplace && ! oneleggedreplace )
19866       ast_set_flag(&p->refer->refer_call->flags[0], SIP_DEFER_BYE_ON_TRANSFER);  /* Delay hangup */
19867 
19868    /* Prepare the masquerade - if this does not happen, we will be gone */
19869    if(ast_channel_masquerade(replacecall, c))
19870       ast_log(LOG_ERROR, "Failed to masquerade C into Replacecall\n");
19871    else
19872       ast_debug(4, "Invite/Replaces: Going to masquerade %s into %s\n", c->name, replacecall->name);
19873 
19874    /* C should now be in place of replacecall */
19875    if (ast_do_masquerade(replacecall)) {
19876       ast_log(LOG_WARNING, "Failed to perform masquerade with INVITE replaces\n");
19877    }
19878 
19879    if (earlyreplace || oneleggedreplace ) {
19880       c->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
19881    }
19882 
19883    ast_setstate(c, AST_STATE_DOWN);
19884    ast_debug(4, "After transfer:----------------------------\n");
19885    ast_debug(4, " -- C:        %s State %s\n", c->name, ast_state2str(c->_state));
19886    if (replacecall)
19887       ast_debug(4, " -- replacecall:        %s State %s\n", replacecall->name, ast_state2str(replacecall->_state));
19888    if (p->owner) {
19889       ast_debug(4, " -- P->owner: %s State %s\n", p->owner->name, ast_state2str(p->owner->_state));
19890       test = ast_bridged_channel(p->owner);
19891       if (test)
19892          ast_debug(4, " -- Call bridged to P->owner: %s State %s\n", test->name, ast_state2str(test->_state));
19893       else
19894          ast_debug(4, " -- No call bridged to C->owner \n");
19895    } else 
19896       ast_debug(4, " -- No channel yet \n");
19897    ast_debug(4, "End After transfer:----------------------------\n");
19898 
19899    /* unlock sip pvt and owner so hangup can do its thing */
19900    ast_channel_unlock(replacecall);
19901    ast_channel_unlock(c);
19902    sip_pvt_unlock(p->refer->refer_call);
19903    sip_pvt_unlock(p);
19904    *nounlock = 1;
19905 
19906    /* The call should be down with no ast_channel, so hang it up */
19907    c->tech_pvt = dialog_unref(c->tech_pvt, "unref dialog c->tech_pvt");
19908    ast_hangup(c);
19909    sip_pvt_lock(p); /* lock PVT structure again after hangup */
19910 
19911    return 0;
19912 }
19913 
19914 /*! \brief helper routine for sip_uri_cmp to compare URI parameters
19915  *
19916  * This takes the parameters from two SIP URIs and determines
19917  * if the URIs match. The rules for parameters *suck*. Here's a breakdown
19918  * 1. If a parameter appears in both URIs, then they must have the same value
19919  *    in order for the URIs to match
19920  * 2. If one URI has a user, maddr, ttl, or method parameter, then the other
19921  *    URI must also have that parameter and must have the same value
19922  *    in order for the URIs to match
19923  * 3. All other headers appearing in only one URI are not considered when
19924  *    determining if URIs match
19925  *
19926  * \param input1 Parameters from URI 1
19927  * \param input2 Parameters from URI 2
19928  * \retval 0 URIs' parameters match
19929  * \retval nonzero URIs' parameters do not match
19930  */
19931 static int sip_uri_params_cmp(const char *input1, const char *input2)
19932 {
19933    char *params1 = NULL;
19934    char *params2 = NULL;
19935    char *pos1;
19936    char *pos2;
19937    int zerolength1 = 0;
19938    int zerolength2 = 0;
19939    int maddrmatch = 0;
19940    int ttlmatch = 0;
19941    int usermatch = 0;
19942    int methodmatch = 0;
19943 
19944    if (ast_strlen_zero(input1)) {
19945       zerolength1 = 1;
19946    } else {
19947       params1 = ast_strdupa(input1);
19948    }
19949    if (ast_strlen_zero(input2)) {
19950       zerolength2 = 1;
19951    } else {
19952       params2 = ast_strdupa(input2);
19953    }
19954 
19955    /* Quick optimization. If both params are zero-length, then
19956     * they match
19957     */
19958    if (zerolength1 && zerolength2) {
19959       return 0;
19960    }
19961 
19962    for (pos1 = strsep(&params1, ";"); pos1; pos1 = strsep(&params1, ";")) {
19963       char *value1 = pos1;
19964       char *name1 = strsep(&value1, "=");
19965       char *params2dup = NULL;
19966       int matched = 0;
19967       if (!value1) {
19968          value1 = "";
19969       }
19970       /* Checkpoint reached. We have the name and value parsed for param1
19971        * We have to duplicate params2 each time through this loop
19972        * or else the inner loop below will not work properly.
19973        */
19974       if (!zerolength2) {
19975          params2dup = ast_strdupa(params2);
19976       }
19977       for (pos2 = strsep(&params2dup, ";"); pos2; pos2 = strsep(&params2dup, ";")) {
19978          char *name2 = pos2;
19979          char *value2 = strchr(pos2, '=');
19980          if (!value2) {
19981             value2 = "";
19982          } else {
19983             *value2++ = '\0';
19984          }
19985          if (!strcasecmp(name1, name2)) {
19986             if (strcasecmp(value1, value2)) {
19987                goto fail;
19988             } else {
19989                matched = 1;
19990                break;
19991             }
19992          }
19993       }
19994       /* Check to see if the parameter is one of the 'must-match' parameters */
19995       if (!strcasecmp(name1, "maddr")) {
19996          if (matched) {
19997             maddrmatch = 1;
19998          } else {
19999             goto fail;
20000          }
20001       } else if (!strcasecmp(name1, "ttl")) {
20002          if (matched) {
20003             ttlmatch = 1;
20004          } else {
20005             goto fail;
20006          }
20007       } else if (!strcasecmp(name1, "user")) {
20008          if (matched) {
20009             usermatch = 1;
20010          } else {
20011             goto fail;
20012          }
20013       } else if (!strcasecmp(name1, "method")) {
20014          if (matched) {
20015             methodmatch = 1;
20016          } else {
20017             goto fail;
20018          }
20019       }
20020    }
20021 
20022    /* We've made it out of that horrible O(m*n) construct and there are no
20023     * failures yet. We're not done yet, though, because params2 could have
20024     * an maddr, ttl, user, or method header and params1 did not.
20025     */
20026    for (pos2 = strsep(&params2, ";"); pos2; pos2 = strsep(&params2, ";")) {
20027       char *value2 = pos2;
20028       char *name2 = strsep(&value2, "=");
20029       if (!value2) {
20030          value2 = "";
20031       }
20032       if ((!strcasecmp(name2, "maddr") && !maddrmatch) ||
20033             (!strcasecmp(name2, "ttl") && !ttlmatch) ||
20034             (!strcasecmp(name2, "user") && !usermatch) ||
20035             (!strcasecmp(name2, "method") && !methodmatch)) {
20036          goto fail;
20037       }
20038    }
20039    return 0;
20040 
20041 fail:
20042    return 1;
20043 }
20044 
20045 /*! \brief helper routine for sip_uri_cmp
20046  *
20047  * This takes the "headers" from two SIP URIs and determines
20048  * if the URIs match. The rules for headers is simple. If a header
20049  * appears in one URI, then it must also appear in the other URI. The
20050  * order in which the headers appear does not matter.
20051  *
20052  * \param input1 Headers from URI 1
20053  * \param input2 Headers from URI 2
20054  * \return Return 0 if the URIs' headers match, 1 if they do not
20055  */
20056 static int sip_uri_headers_cmp(const char *input1, const char *input2)
20057 {
20058    char *headers1 = NULL;
20059    char *headers2 = NULL;
20060    int zerolength1 = 0;
20061    int zerolength2 = 0;
20062    int different = 0;
20063    char *header1;
20064 
20065    if (ast_strlen_zero(input1)) {
20066       zerolength1 = 1;
20067    } else {
20068       headers1 = ast_strdupa(input1);
20069    }
20070    
20071    if (ast_strlen_zero(input2)) {
20072       zerolength2 = 1;
20073    } else {
20074       headers2 = ast_strdupa(input2);
20075    }
20076 
20077    if ((zerolength1 && !zerolength2) ||
20078          (zerolength2 && !zerolength1))
20079       return 1;
20080 
20081    if (zerolength1 && zerolength2)
20082       return 0;
20083 
20084    /* At this point, we can definitively state that both inputs are
20085     * not zero-length. First, one more optimization. If the length
20086     * of the headers is not equal, then we definitely have no match
20087     */
20088    if (strlen(headers1) != strlen(headers2)) {
20089       return 1;
20090    }
20091 
20092    for (header1 = strsep(&headers1, "&"); header1; header1 = strsep(&headers1, "&")) {
20093       if (!strcasestr(headers2, header1)) {
20094          different = 1;
20095          break;
20096       }
20097    }
20098 
20099    return different;
20100 }
20101 
20102 static int sip_uri_cmp(const char *input1, const char *input2)
20103 {
20104    char *uri1 = ast_strdupa(input1);
20105    char *uri2 = ast_strdupa(input2);
20106    char *host1;
20107    char *host2;
20108    char *params1;
20109    char *params2;
20110    char *headers1;
20111    char *headers2;
20112 
20113    /* Strip off "sip:" from the URI. We know this is present
20114     * because it was checked back in parse_request()
20115     */
20116    strsep(&uri1, ":");
20117    strsep(&uri2, ":");
20118 
20119    if ((host1 = strchr(uri1, '@'))) {
20120       *host1++ = '\0';
20121    }
20122    if ((host2 = strchr(uri2, '@'))) {
20123       *host2++ = '\0';
20124    }
20125 
20126    /* Check for mismatched username and passwords. This is the
20127     * only case-sensitive comparison of a SIP URI
20128     */
20129    if ((host1 && !host2) ||
20130          (host2 && !host1) ||
20131          (host1 && host2 && strcmp(uri1, uri2))) {
20132       return 1;
20133    }
20134 
20135    if (!host1)
20136       host1 = uri1;
20137    if (!host2)
20138       host2 = uri2;
20139 
20140    /* Strip off the parameters and headers so we can compare
20141     * host and port
20142     */
20143 
20144    if ((params1 = strchr(host1, ';'))) {
20145       *params1++ = '\0';
20146    }
20147    if ((params2 = strchr(host2, ';'))) {
20148       *params2++ = '\0';
20149    }
20150 
20151    /* Headers come after parameters, but there may be headers without
20152     * parameters, thus the S_OR
20153     */
20154    if ((headers1 = strchr(S_OR(params1, host1), '?'))) {
20155       *headers1++ = '\0';
20156    }
20157    if ((headers2 = strchr(S_OR(params2, host2), '?'))) {
20158       *headers2++ = '\0';
20159    }
20160 
20161    /* Now the host/port are properly isolated. We can get by with a string comparison
20162     * because the SIP URI checking rules have some interesting exceptions that make
20163     * this possible. I will note 2 in particular
20164     * 1. hostnames which resolve to the same IP address as well as a hostname and its
20165     *    IP address are not considered a match with SIP URI's.
20166     * 2. If one URI specifies a port and the other does not, then the URIs do not match.
20167     *    This includes if one URI explicitly contains port 5060 and the other implies it
20168     *    by not having a port specified.
20169     */
20170 
20171    if (strcasecmp(host1, host2)) {
20172       return 1;
20173    }
20174 
20175    /* Headers have easier rules to follow, so do those first */
20176    if (sip_uri_headers_cmp(headers1, headers2)) {
20177       return 1;
20178    }
20179 
20180    /* And now the parameters. Ugh */
20181    return sip_uri_params_cmp(params1, params2);
20182 }
20183 
20184 static int do_magic_pickup(struct ast_channel *channel, const char *extension, const char *context)
20185 {
20186    struct ast_str *str = ast_str_alloca(AST_MAX_EXTENSION + AST_MAX_CONTEXT + 2);
20187    struct ast_app *pickup = pbx_findapp("Pickup");
20188 
20189    if (!pickup) {
20190       ast_log(LOG_ERROR, "Unable to perform pickup: Application 'Pickup' not loaded (app_directed_pickup.so).\n");
20191       return -1;
20192    }
20193 
20194    ast_str_set(&str, 0, "%s@%s", extension, sip_cfg.notifycid == IGNORE_CONTEXT ? "PICKUPMARK" : context);
20195 
20196    ast_debug(2, "About to call Pickup(%s)\n", str->str);
20197 
20198    /* There is no point in capturing the return value since pickup_exec
20199       doesn't return anything meaningful unless the passed data is an empty
20200       string (which in our case it will not be) */
20201    pbx_exec(channel, pickup, str->str);
20202 
20203    return 0;
20204 }
20205 
20206 /*! \brief Called to deny a T38 reinvite if the core does not respond to our request */
20207 static int sip_t38_abort(const void *data)
20208 {
20209    struct sip_pvt *p = (struct sip_pvt *) data;
20210 
20211    sip_pvt_lock(p);
20212    /* an application may have taken ownership of the T.38 negotiation on this
20213     * channel while we were waiting to grab the lock... if it did, the scheduler
20214     * id will have been reset to -1, which is our indication that we do *not*
20215     * want to abort the negotiation process
20216     */
20217    if (p->t38id != -1) {
20218       change_t38_state(p, T38_DISABLED);
20219       transmit_response_reliable(p, "488 Not acceptable here", &p->initreq);
20220       p->t38id = -1;
20221       dialog_unref(p, "unref the dialog ptr from sip_t38_abort, because it held a dialog ptr");
20222    }
20223    sip_pvt_unlock(p);
20224    return 0;
20225 }
20226 
20227 /*! \brief Handle incoming INVITE request
20228 \note    If the INVITE has a Replaces header, it is part of an
20229  * attended transfer. If so, we do not go through the dial
20230  * plan but tries to find the active call and masquerade
20231  * into it 
20232  */
20233 static int handle_request_invite(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, struct sockaddr_in *sin, int *recount, char *e, int *nounlock)
20234 {
20235    int res = 1;
20236    int gotdest;
20237    const char *p_replaces;
20238    char *replace_id = NULL;
20239    int refer_locked = 0;
20240    const char *required;
20241    unsigned int required_profile = 0;
20242    struct ast_channel *c = NULL;    /* New channel */
20243    int reinvite = 0;
20244    int rtn;
20245 
20246    const char *p_uac_se_hdr;       /* UAC's Session-Expires header string                      */
20247    const char *p_uac_min_se;       /* UAC's requested Min-SE interval (char string)            */
20248    int uac_max_se = -1;            /* UAC's Session-Expires in integer format                  */
20249    int uac_min_se = -1;            /* UAC's Min-SE in integer format                           */
20250    int st_active = FALSE;          /* Session-Timer on/off boolean                             */
20251    int st_interval = 0;            /* Session-Timer negotiated refresh interval                */
20252    enum st_refresher st_ref;       /* Session-Timer session refresher                          */
20253    int dlg_min_se = -1;
20254    struct {
20255       char exten[AST_MAX_EXTENSION];
20256       char context[AST_MAX_CONTEXT];
20257    } pickup = {
20258       .exten = "",
20259    };
20260    st_ref = SESSION_TIMER_REFRESHER_AUTO;
20261 
20262    /* Find out what they support */
20263    if (!p->sipoptions) {
20264       const char *supported = get_header(req, "Supported");
20265       if (!ast_strlen_zero(supported))
20266          parse_sip_options(p, supported);
20267    }
20268 
20269    /* Find out what they require */
20270    required = get_header(req, "Require");
20271    if (!ast_strlen_zero(required)) {
20272       required_profile = parse_sip_options(NULL, required);
20273       if (required_profile && !(required_profile & (SIP_OPT_REPLACES | SIP_OPT_TIMER))) {
20274          /* At this point we only support REPLACES and Session-Timer */
20275          transmit_response_with_unsupported(p, "420 Bad extension (unsupported)", req, required);
20276          ast_log(LOG_WARNING, "Received SIP INVITE with unsupported required extension: %s\n", required);
20277          p->invitestate = INV_COMPLETED;
20278          if (!p->lastinvite)
20279             sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20280          res = -1;
20281          goto request_invite_cleanup;
20282       }
20283    }
20284 
20285    /* The option tags may be present in Supported: or Require: headers.
20286    Include the Require: option tags for further processing as well */
20287    p->sipoptions |= required_profile;
20288    p->reqsipoptions = required_profile;
20289 
20290    /* Check if this is a loop */
20291    if (ast_test_flag(&p->flags[0], SIP_OUTGOING) && p->owner && (p->invitestate != INV_TERMINATED && p->invitestate != INV_CONFIRMED)) {
20292       /* This is a call to ourself.  Send ourselves an error code and stop
20293          processing immediately, as SIP really has no good mechanism for
20294          being able to call yourself */
20295       /* If pedantic is on, we need to check the tags. If they're different, this is
20296          in fact a forked call through a SIP proxy somewhere. */
20297       int different;
20298       char *initial_rlPart2 = REQ_OFFSET_TO_STR(&p->initreq, rlPart2);
20299       char *this_rlPart2 = REQ_OFFSET_TO_STR(req, rlPart2);
20300       if (sip_cfg.pedanticsipchecking)
20301          different = sip_uri_cmp(initial_rlPart2, this_rlPart2);
20302       else
20303          different = strcmp(initial_rlPart2, this_rlPart2);
20304       if (!different) {
20305          transmit_response(p, "482 Loop Detected", req);
20306          p->invitestate = INV_COMPLETED;
20307          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20308          res = 0;
20309          goto request_invite_cleanup;
20310       } else {
20311          /*! This is a spiral. What we need to do is to just change the outgoing INVITE
20312           * so that it now routes to the new Request URI. Since we created the INVITE ourselves
20313           * that should be all we need to do.
20314           * 
20315           * \todo XXX This needs to be reviewed.  YOu don't change the request URI really, you route the packet
20316           * correctly instead...
20317           */
20318          char *uri = ast_strdupa(this_rlPart2);
20319          char *at = strchr(uri, '@');
20320          char *peerorhost;
20321          ast_debug(2, "Potential spiral detected. Original RURI was %s, new RURI is %s\n", initial_rlPart2, this_rlPart2);
20322          transmit_response(p, "100 Trying", req);
20323          if (at) {
20324             *at = '\0';
20325          }
20326          /* Parse out "sip:" */
20327          if ((peerorhost = strchr(uri, ':'))) {
20328             *peerorhost++ = '\0';
20329          }
20330          ast_string_field_set(p, theirtag, NULL);
20331          /* Treat this as if there were a call forward instead...
20332           */
20333          ast_string_field_set(p->owner, call_forward, peerorhost);
20334          ast_queue_control(p->owner, AST_CONTROL_BUSY);
20335          res = 0;
20336          goto request_invite_cleanup;
20337       }
20338    }
20339 
20340    if (!req->ignore && p->pendinginvite) {
20341       if (!ast_test_flag(&p->flags[0], SIP_OUTGOING) && (p->invitestate == INV_COMPLETED || p->invitestate == INV_TERMINATED)) {
20342          /* What do these circumstances mean? We have received an INVITE for an "incoming" dialog for which we
20343           * have sent a final response. We have not yet received an ACK, though (which is why p->pendinginvite is non-zero).
20344           * We also know that the INVITE is not a retransmission, because otherwise the "ignore" flag would be set.
20345           * This means that either we are receiving a reinvite for a terminated dialog, or we are receiving an INVITE with
20346           * credentials based on one we challenged earlier.
20347           *
20348           * The action to take in either case is to treat the INVITE as though it contains an implicit ACK for the previous
20349           * transaction. Calling __sip_ack will take care of this by clearing the p->pendinginvite and removing the response
20350           * from the previous transaction from the list of outstanding packets.
20351           */
20352          __sip_ack(p, p->pendinginvite, 1, 0);
20353       } else {
20354          /* We already have a pending invite. Sorry. You are on hold. */
20355          p->glareinvite = seqno;     /* must hold on to this seqno to process ack and retransmit correctly */
20356          if (p->rtp && find_sdp(req)) {
20357             struct sockaddr_in sin;
20358             if (get_ip_and_port_from_sdp(req, SDP_AUDIO, &sin)) {
20359                ast_log(LOG_WARNING, "Failed to set an alternate media source on glared reinvite. Audio may not work properly on this call.\n");
20360             } else {
20361                ast_rtp_set_alt_peer(p->rtp, &sin);
20362             }
20363             if (p->vrtp) {
20364                if (get_ip_and_port_from_sdp(req, SDP_VIDEO, &sin)) {
20365                   ast_log(LOG_WARNING, "Failed to set an alternate media source on glared reinvite. Video may not work properly on this call.\n");
20366                } else {
20367                   ast_rtp_set_alt_peer(p->vrtp, &sin);
20368                }
20369             }
20370          }
20371          transmit_response_reliable(p, "491 Request Pending", req);
20372          ast_debug(1, "Got INVITE on call where we already have pending INVITE, deferring that - %s\n", p->callid);
20373          /* Don't destroy dialog here */
20374          res = 0;
20375          goto request_invite_cleanup;
20376       }
20377    }
20378 
20379    p_replaces = get_header(req, "Replaces");
20380    if (!ast_strlen_zero(p_replaces)) {
20381       /* We have a replaces header */
20382       char *ptr;
20383       char *fromtag = NULL;
20384       char *totag = NULL;
20385       char *start, *to;
20386       int error = 0;
20387 
20388       if (p->owner) {
20389          ast_debug(3, "INVITE w Replaces on existing call? Refusing action. [%s]\n", p->callid);
20390          transmit_response_reliable(p, "400 Bad request", req);   /* The best way to not not accept the transfer */
20391          /* Do not destroy existing call */
20392          res = -1;
20393          goto request_invite_cleanup;
20394       }
20395 
20396       if (sipdebug)
20397          ast_debug(3, "INVITE part of call transfer. Replaces [%s]\n", p_replaces);
20398       /* Create a buffer we can manipulate */
20399       replace_id = ast_strdupa(p_replaces);
20400       ast_uri_decode(replace_id);
20401 
20402       if (!p->refer && !sip_refer_allocate(p)) {
20403          transmit_response_reliable(p, "500 Server Internal Error", req);
20404          append_history(p, "Xfer", "INVITE/Replace Failed. Out of memory.");
20405          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20406          p->invitestate = INV_COMPLETED;
20407          res = -1;
20408          goto request_invite_cleanup;
20409       }
20410 
20411       /*  Todo: (When we find phones that support this)
20412          if the replaces header contains ";early-only"
20413          we can only replace the call in early
20414          stage, not after it's up.
20415 
20416          If it's not in early mode, 486 Busy.
20417       */
20418 
20419       /* Skip leading whitespace */
20420       replace_id = ast_skip_blanks(replace_id);
20421 
20422       start = replace_id;
20423       while ( (ptr = strsep(&start, ";")) ) {
20424          ptr = ast_skip_blanks(ptr); /* XXX maybe unnecessary ? */
20425          if ( (to = strcasestr(ptr, "to-tag=") ) )
20426             totag = to + 7;   /* skip the keyword */
20427          else if ( (to = strcasestr(ptr, "from-tag=") ) ) {
20428             fromtag = to + 9; /* skip the keyword */
20429             fromtag = strsep(&fromtag, "&"); /* trim what ? */
20430          }
20431       }
20432 
20433       if (sipdebug)
20434          ast_debug(4, "Invite/replaces: Will use Replace-Call-ID : %s Fromtag: %s Totag: %s\n",
20435                  replace_id,
20436                  fromtag ? fromtag : "<no from tag>",
20437                  totag ? totag : "<no to tag>");
20438 
20439       /* Try to find call that we are replacing.
20440          If we have a Replaces header, we need to cancel that call if we succeed with this call.
20441          First we cheat a little and look for a magic call-id from phones that support
20442          dialog-info+xml so we can do technology independent pickup... */
20443       if (strncmp(replace_id, "pickup-", 7) == 0) {
20444          struct sip_pvt *subscription = NULL;
20445          replace_id += 7; /* Worst case we are looking at \0 */
20446 
20447          if ((subscription = get_sip_pvt_byid_locked(replace_id, totag, fromtag)) == NULL) {
20448             ast_log(LOG_NOTICE, "Unable to find subscription with call-id: %s\n", replace_id);
20449             transmit_response_reliable(p, "481 Call Leg Does Not Exist (Replaces)", req);
20450             error = 1;
20451          } else {
20452             ast_log(LOG_NOTICE, "Trying to pick up %s@%s\n", subscription->exten, subscription->context);
20453             ast_copy_string(pickup.exten, subscription->exten, sizeof(pickup.exten));
20454             ast_copy_string(pickup.context, subscription->context, sizeof(pickup.context));
20455             sip_pvt_unlock(subscription);
20456             if (subscription->owner) {
20457                ast_channel_unlock(subscription->owner);
20458             }
20459          }
20460       }
20461 
20462       /* This locks both refer_call pvt and refer_call pvt's owner!!!*/
20463       if (!error && ast_strlen_zero(pickup.exten) && (p->refer->refer_call = get_sip_pvt_byid_locked(replace_id, totag, fromtag)) == NULL) {
20464          ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-existent call id (%s)!\n", replace_id);
20465          transmit_response_reliable(p, "481 Call Leg Does Not Exist (Replaces)", req);
20466          error = 1;
20467       } else {
20468          refer_locked = 1;
20469       }
20470 
20471       /* The matched call is the call from the transferer to Asterisk .
20472          We want to bridge the bridged part of the call to the 
20473          incoming invite, thus taking over the refered call */
20474 
20475       if (p->refer->refer_call == p) {
20476          ast_log(LOG_NOTICE, "INVITE with replaces into it's own call id (%s == %s)!\n", replace_id, p->callid);
20477          p->refer->refer_call = dialog_unref(p->refer->refer_call, "unref dialog p->refer->refer_call");
20478          transmit_response_reliable(p, "400 Bad request", req);   /* The best way to not not accept the transfer */
20479          error = 1;
20480       }
20481 
20482       if (!error && ast_strlen_zero(pickup.exten) && !p->refer->refer_call->owner) {
20483          /* Oops, someting wrong anyway, no owner, no call */
20484          ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-existing call id (%s)!\n", replace_id);
20485          /* Check for better return code */
20486          transmit_response_reliable(p, "481 Call Leg Does Not Exist (Replace)", req);
20487          error = 1;
20488       }
20489 
20490       if (!error && ast_strlen_zero(pickup.exten) && p->refer->refer_call->owner->_state != AST_STATE_RINGING && p->refer->refer_call->owner->_state != AST_STATE_RING && p->refer->refer_call->owner->_state != AST_STATE_UP) {
20491          ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-ringing or active call id (%s)!\n", replace_id);
20492          transmit_response_reliable(p, "603 Declined (Replaces)", req);
20493          error = 1;
20494       }
20495 
20496       if (error) {   /* Give up this dialog */
20497          append_history(p, "Xfer", "INVITE/Replace Failed.");
20498          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20499          sip_pvt_unlock(p);
20500          if (p->refer->refer_call) {
20501             sip_pvt_unlock(p->refer->refer_call);
20502             if (p->refer->refer_call->owner) {
20503                ast_channel_unlock(p->refer->refer_call->owner);
20504             }
20505          }
20506          refer_locked = 0;
20507          p->invitestate = INV_COMPLETED;
20508          res = -1;
20509          goto request_invite_cleanup;
20510       }
20511    }
20512 
20513    /* Check if this is an INVITE that sets up a new dialog or
20514       a re-invite in an existing dialog */
20515 
20516    if (!req->ignore) {
20517       int newcall = (p->initreq.headers ? TRUE : FALSE);
20518 
20519       if (sip_cancel_destroy(p))
20520          ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
20521       /* This also counts as a pending invite */
20522       p->pendinginvite = seqno;
20523       check_via(p, req);
20524 
20525       copy_request(&p->initreq, req);     /* Save this INVITE as the transaction basis */
20526       if (sipdebug)
20527          ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
20528       if (!p->owner) {  /* Not a re-invite */
20529          if (debug)
20530             ast_verbose("Using INVITE request as basis request - %s\n", p->callid);
20531          if (newcall)
20532             append_history(p, "Invite", "New call: %s", p->callid);
20533          parse_ok_contact(p, req);
20534       } else { /* Re-invite on existing call */
20535          ast_clear_flag(&p->flags[0], SIP_OUTGOING);  /* This is now an inbound dialog */
20536          /* Handle SDP here if we already have an owner */
20537          if (find_sdp(req)) {
20538             if (process_sdp(p, req, SDP_T38_INITIATE)) {
20539                transmit_response_reliable(p, "488 Not acceptable here", req);
20540                if (!p->lastinvite)
20541                   sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20542                res = -1;
20543                goto request_invite_cleanup;
20544             }
20545             ast_queue_control(p->owner, AST_CONTROL_SRCUPDATE);
20546          } else {
20547             p->jointcapability = p->capability;
20548             ast_debug(1, "Hm....  No sdp for the moment\n");
20549             /* Some devices signal they want to be put off hold by sending a re-invite
20550                *without* an SDP, which is supposed to mean "Go back to your state"
20551                and since they put os on remote hold, we go back to off hold */
20552             if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
20553                ast_queue_control(p->owner, AST_CONTROL_UNHOLD);
20554                /* Activate a re-invite */
20555                ast_queue_frame(p->owner, &ast_null_frame);
20556                change_hold_state(p, req, FALSE, 0);
20557             }
20558          }
20559          if (p->do_history) /* This is a response, note what it was for */
20560             append_history(p, "ReInv", "Re-invite received");
20561       }
20562    } else if (debug)
20563       ast_verbose("Ignoring this INVITE request\n");
20564 
20565    if (!p->lastinvite && !req->ignore && !p->owner) {
20566       /* This is a new invite */
20567       /* Handle authentication if this is our first invite */
20568       res = check_user(p, req, SIP_INVITE, e, XMIT_RELIABLE, sin);
20569       if (res == AUTH_CHALLENGE_SENT) {
20570          p->invitestate = INV_COMPLETED;     /* Needs to restart in another INVITE transaction */
20571          res = 0;
20572          goto request_invite_cleanup;
20573       }
20574       if (res < 0) { /* Something failed in authentication */
20575          if (res == AUTH_FAKE_AUTH) {
20576             ast_log(LOG_NOTICE, "Sending fake auth rejection for device %s\n", get_header(req, "From"));
20577             transmit_fake_auth_response(p, SIP_INVITE, req, XMIT_RELIABLE);
20578          } else {
20579             ast_log(LOG_NOTICE, "Failed to authenticate device %s\n", get_header(req, "From"));
20580             transmit_response_reliable(p, "403 Forbidden", req);
20581          }
20582          p->invitestate = INV_COMPLETED;
20583          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20584          ast_string_field_set(p, theirtag, NULL);
20585          res = 0;
20586          goto request_invite_cleanup;
20587       }
20588 
20589       /* If T38 is needed but not present, then make it magically appear */
20590       if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) && !p->udptl) {
20591          if ((p->udptl = ast_udptl_new_with_bindaddr(sched, io, 0, bindaddr.sin_addr))) {
20592             p->t38_maxdatagram = global_t38_maxdatagram;
20593             set_t38_capabilities(p);
20594          } else {
20595             /* udptl creation failed, T38 can not be supported on this dialog */
20596             ast_debug(1, "UDPTL creation failed on dialog.\n");
20597             ast_clear_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT);
20598          }
20599       }
20600 
20601       req->authenticated = 1;
20602 
20603       /* We have a succesful authentication, process the SDP portion if there is one */
20604       if (find_sdp(req)) {
20605          if (process_sdp(p, req, SDP_T38_INITIATE)) {
20606             /* Unacceptable codecs */
20607             transmit_response_reliable(p, "488 Not acceptable here", req);
20608             p->invitestate = INV_COMPLETED;
20609             sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20610             ast_debug(1, "No compatible codecs for this SIP call.\n");
20611             res = -1;
20612             goto request_invite_cleanup;
20613          }
20614       } else { /* No SDP in invite, call control session */
20615          p->jointcapability = p->capability;
20616          ast_debug(2, "No SDP in Invite, third party call control\n");
20617       }
20618 
20619       /* Queue NULL frame to prod ast_rtp_bridge if appropriate */
20620       /* This seems redundant ... see !p-owner above */
20621       if (p->owner)
20622          ast_queue_frame(p->owner, &ast_null_frame);
20623 
20624 
20625       /* Initialize the context if it hasn't been already */
20626       if (ast_strlen_zero(p->context))
20627          ast_string_field_set(p, context, sip_cfg.default_context);
20628 
20629 
20630       /* Check number of concurrent calls -vs- incoming limit HERE */
20631       ast_debug(1, "Checking SIP call limits for device %s\n", p->username);
20632       if ((res = update_call_counter(p, INC_CALL_LIMIT))) {
20633          if (res < 0) {
20634             ast_log(LOG_NOTICE, "Failed to place call for device %s, too many calls\n", p->username);
20635             transmit_response_reliable(p, "480 Temporarily Unavailable (Call limit) ", req);
20636             sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20637             p->invitestate = INV_COMPLETED;
20638          }
20639          res = 0;
20640          goto request_invite_cleanup;
20641       }
20642       gotdest = get_destination(p, NULL); /* Get destination right away */
20643       get_rdnis(p, NULL);        /* Get redirect information */
20644       extract_uri(p, req);       /* Get the Contact URI */
20645       build_contact(p);       /* Build our contact header */
20646 
20647       if (p->rtp) {
20648          ast_rtp_setdtmf(p->rtp, ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
20649          ast_rtp_setdtmfcompensate(p->rtp, ast_test_flag(&p->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
20650       }
20651 
20652       if (!replace_id && gotdest) { /* No matching extension found */
20653          if (gotdest == 1 && ast_test_flag(&p->flags[1], SIP_PAGE2_ALLOWOVERLAP))
20654             transmit_response_reliable(p, "484 Address Incomplete", req);
20655          else {
20656             char *decoded_exten = ast_strdupa(p->exten);
20657 
20658             transmit_response_reliable(p, "404 Not Found", req);
20659             ast_uri_decode(decoded_exten);
20660             ast_log(LOG_NOTICE, "Call from '%s' to extension"
20661                " '%s' rejected because extension not found in context '%s'.\n",
20662                S_OR(p->username, p->peername), decoded_exten, p->context);
20663          }
20664          p->invitestate = INV_COMPLETED;
20665          update_call_counter(p, DEC_CALL_LIMIT);
20666          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20667          res = 0;
20668          goto request_invite_cleanup;
20669       } else {
20670 
20671          /* If no extension was specified, use the s one */
20672          /* Basically for calling to IP/Host name only */
20673          if (ast_strlen_zero(p->exten))
20674             ast_string_field_set(p, exten, "s");
20675          /* Initialize our tag */
20676 
20677          make_our_tag(p->tag, sizeof(p->tag));
20678          /* First invitation - create the channel.  Allocation
20679           * failures are handled below. */
20680          c = sip_new(p, AST_STATE_DOWN, S_OR(p->peername, NULL));
20681          *recount = 1;
20682 
20683          /* Save Record-Route for any later requests we make on this dialogue */
20684          build_route(p, req, 0);
20685 
20686          if (c) {
20687             /* Pre-lock the call */
20688             ast_channel_lock(c);
20689          }
20690       }
20691    } else {
20692       if (sipdebug) {
20693          if (!req->ignore)
20694             ast_debug(2, "Got a SIP re-invite for call %s\n", p->callid);
20695          else
20696             ast_debug(2, "Got a SIP re-transmit of INVITE for call %s\n", p->callid);
20697       }
20698       if (!req->ignore)
20699          reinvite = 1;
20700       c = p->owner;
20701    }
20702 
20703    /* Session-Timers */
20704    if ((p->sipoptions & SIP_OPT_TIMER) && !ast_strlen_zero(get_header(req, "Session-Expires"))) {
20705       /* The UAC has requested session-timers for this session. Negotiate
20706       the session refresh interval and who will be the refresher */
20707       ast_debug(2, "Incoming INVITE with 'timer' option supported and \"Session-Expires\" header.\n");
20708 
20709       /* Allocate Session-Timers struct w/in the dialog */
20710       if (!p->stimer)
20711          sip_st_alloc(p);
20712 
20713       /* Parse the Session-Expires header */
20714       p_uac_se_hdr = get_header(req, "Session-Expires");
20715       rtn = parse_session_expires(p_uac_se_hdr, &uac_max_se, &st_ref);
20716       if (rtn != 0) {
20717          transmit_response_reliable(p, "400 Session-Expires Invalid Syntax", req);
20718          p->invitestate = INV_COMPLETED;
20719          if (!p->lastinvite) {
20720             sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20721          }
20722          res = -1;
20723          goto request_invite_cleanup;
20724       }
20725 
20726       /* Parse the Min-SE header */
20727       p_uac_min_se = get_header(req, "Min-SE");
20728       if (!ast_strlen_zero(p_uac_min_se)) {
20729          rtn = parse_minse(p_uac_min_se, &uac_min_se); 
20730          if (rtn != 0) {
20731             transmit_response_reliable(p, "400 Min-SE Invalid Syntax", req);
20732             p->invitestate = INV_COMPLETED;
20733             if (!p->lastinvite) {
20734                sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20735             }
20736             res = -1;
20737             goto request_invite_cleanup;
20738          }
20739       }
20740 
20741       dlg_min_se = st_get_se(p, FALSE);
20742       switch (st_get_mode(p)) {
20743       case SESSION_TIMER_MODE_ACCEPT:
20744       case SESSION_TIMER_MODE_ORIGINATE:
20745          if (uac_max_se > 0 && uac_max_se < dlg_min_se) {
20746             transmit_response_with_minse(p, "422 Session Interval Too Small", req, dlg_min_se);
20747             p->invitestate = INV_COMPLETED;
20748             if (!p->lastinvite) {
20749                sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20750             }
20751             res = -1;
20752             goto request_invite_cleanup;
20753          }
20754 
20755          p->stimer->st_active_peer_ua = TRUE;
20756          st_active = TRUE;
20757          if (st_ref == SESSION_TIMER_REFRESHER_AUTO) {
20758             st_ref = st_get_refresher(p);
20759          }
20760 
20761          if (uac_max_se > 0) {
20762             int dlg_max_se = st_get_se(p, TRUE);
20763             if (dlg_max_se >= uac_min_se) {
20764                st_interval = (uac_max_se < dlg_max_se) ? uac_max_se : dlg_max_se;
20765             } else {
20766                st_interval = uac_max_se;
20767             }
20768          } else {
20769             /* Set to default max value */
20770             st_interval = global_max_se;
20771          }
20772          break;
20773 
20774       case SESSION_TIMER_MODE_REFUSE:
20775          if (p->reqsipoptions & SIP_OPT_TIMER) {
20776             transmit_response_with_unsupported(p, "420 Option Disabled", req, required);
20777             ast_log(LOG_WARNING, "Received SIP INVITE with supported but disabled option: %s\n", required);
20778             p->invitestate = INV_COMPLETED;
20779             if (!p->lastinvite) {
20780                sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20781             }
20782             res = -1;
20783             goto request_invite_cleanup;
20784          }
20785          break;
20786 
20787       default:
20788          ast_log(LOG_ERROR, "Internal Error %d at %s:%d\n", st_get_mode(p), __FILE__, __LINE__);
20789          break;
20790       }
20791    } else {
20792       /* The UAC did not request session-timers.  Asterisk (UAS), will now decide
20793       (based on session-timer-mode in sip.conf) whether to run session-timers for
20794       this session or not. */
20795       switch (st_get_mode(p)) {
20796       case SESSION_TIMER_MODE_ORIGINATE:
20797          st_active = TRUE;
20798          st_interval = st_get_se(p, TRUE);
20799          st_ref = SESSION_TIMER_REFRESHER_UAS;
20800          p->stimer->st_active_peer_ua = FALSE;
20801          break;
20802 
20803       default:
20804          break;
20805       }
20806    }
20807 
20808    if (reinvite == 0) {
20809       /* Session-Timers: Start session refresh timer based on negotiation/config */
20810       if (st_active == TRUE) {
20811          p->stimer->st_active   = TRUE;
20812          p->stimer->st_interval = st_interval;
20813          p->stimer->st_ref      = st_ref;
20814          start_session_timer(p);
20815       }
20816    } else {
20817       if (p->stimer->st_active == TRUE) {
20818          /* Session-Timers:  A re-invite request sent within a dialog will serve as 
20819          a refresh request, no matter whether the re-invite was sent for refreshing 
20820          the session or modifying it.*/
20821          ast_debug (2, "Restarting session-timers on a refresh - %s\n", p->callid);
20822 
20823          /* The UAC may be adjusting the session-timers mid-session */
20824          if (st_interval > 0) {
20825             p->stimer->st_interval = st_interval;
20826             p->stimer->st_ref      = st_ref;
20827          }
20828 
20829          restart_session_timer(p);
20830          if (p->stimer->st_expirys > 0) {
20831             p->stimer->st_expirys--;
20832          }
20833       }
20834    }
20835 
20836    if (!req->ignore && p)
20837       p->lastinvite = seqno;
20838 
20839    if (c && replace_id) {  /* Attended transfer or call pickup - we're the target */
20840       if (!ast_strlen_zero(pickup.exten)) {
20841          append_history(p, "Xfer", "INVITE/Replace received");
20842 
20843          /* Let the caller know we're giving it a shot */
20844          transmit_response(p, "100 Trying", req);
20845          p->invitestate = INV_PROCEEDING;
20846          ast_setstate(c, AST_STATE_RING);
20847 
20848          /* Do the pickup itself */
20849          ast_channel_unlock(c);
20850          *nounlock = 1;
20851          do_magic_pickup(c, pickup.exten, pickup.context);
20852 
20853          /* Now we're either masqueraded or we failed to pickup, in either case we... */
20854          sip_pvt_unlock(p);
20855          ast_hangup(c);
20856          sip_pvt_lock(p);
20857 
20858          res = 0;
20859          goto request_invite_cleanup;
20860       } else {
20861          /* Go and take over the target call */
20862          if (sipdebug)
20863             ast_debug(4, "Sending this call to the invite/replcaes handler %s\n", p->callid);
20864          res = handle_invite_replaces(p, req, debug, seqno, sin, nounlock);
20865          refer_locked = 0;
20866          goto request_invite_cleanup;
20867       }
20868    }
20869 
20870 
20871    if (c) { /* We have a call  -either a new call or an old one (RE-INVITE) */
20872       enum ast_channel_state c_state = c->_state;
20873 
20874       if (c_state != AST_STATE_UP && reinvite &&
20875          (p->invitestate == INV_TERMINATED || p->invitestate == INV_CONFIRMED)) {
20876          /* If these conditions are true, and the channel is still in the 'ringing'
20877           * state, then this likely means that we have a situation where the initial
20878           * INVITE transaction has completed *but* the channel's state has not yet been
20879           * changed to UP. The reason this could happen is if the reinvite is received
20880           * on the SIP socket prior to an application calling ast_read on this channel
20881           * to read the answer frame we earlier queued on it. In this case, the reinvite
20882           * is completely legitimate so we need to handle this the same as if the channel 
20883           * were already UP. Thus we are purposely falling through to the AST_STATE_UP case.
20884           */
20885          c_state = AST_STATE_UP;
20886       }
20887 
20888       switch(c_state) {
20889       case AST_STATE_DOWN:
20890          ast_debug(2, "%s: New call is still down.... Trying... \n", c->name);
20891          transmit_provisional_response(p, "100 Trying", req, 0);
20892          p->invitestate = INV_PROCEEDING;
20893          ast_setstate(c, AST_STATE_RING);
20894          if (strcmp(p->exten, ast_pickup_ext())) { /* Call to extension -start pbx on this call */
20895             enum ast_pbx_result result;
20896 
20897             result = ast_pbx_start(c);
20898 
20899             switch(result) {
20900             case AST_PBX_FAILED:
20901                ast_log(LOG_WARNING, "Failed to start PBX :(\n");
20902                p->invitestate = INV_COMPLETED;
20903                transmit_response_reliable(p, "503 Unavailable", req);
20904                break;
20905             case AST_PBX_CALL_LIMIT:
20906                ast_log(LOG_WARNING, "Failed to start PBX (call limit reached) \n");
20907                p->invitestate = INV_COMPLETED;
20908                transmit_response_reliable(p, "480 Temporarily Unavailable", req);
20909                break;
20910             case AST_PBX_SUCCESS:
20911                /* nothing to do */
20912                break;
20913             }
20914 
20915             if (result) {
20916 
20917                /* Unlock locks so ast_hangup can do its magic */
20918                ast_channel_unlock(c);
20919                sip_pvt_unlock(p);
20920                ast_hangup(c);
20921                sip_pvt_lock(p);
20922                c = NULL;
20923             }
20924          } else { /* Pickup call in call group */
20925             ast_channel_unlock(c);
20926             *nounlock = 1;
20927             if (ast_pickup_call(c)) {
20928                ast_log(LOG_NOTICE, "Nothing to pick up for %s\n", p->callid);
20929                transmit_response_reliable(p, "503 Unavailable", req);
20930                sip_alreadygone(p);
20931                /* Unlock locks so ast_hangup can do its magic */
20932                sip_pvt_unlock(p);
20933                c->hangupcause = AST_CAUSE_CALL_REJECTED;
20934             } else {
20935                sip_pvt_unlock(p);
20936                ast_setstate(c, AST_STATE_DOWN);
20937                c->hangupcause = AST_CAUSE_NORMAL_CLEARING;
20938             }
20939             p->invitestate = INV_COMPLETED;
20940             ast_hangup(c);
20941             sip_pvt_lock(p);
20942             c = NULL;
20943          }
20944          break;
20945       case AST_STATE_RING:
20946          transmit_provisional_response(p, "100 Trying", req, 0);
20947          p->invitestate = INV_PROCEEDING;
20948          break;
20949       case AST_STATE_RINGING:
20950          transmit_provisional_response(p, "180 Ringing", req, 0);
20951          p->invitestate = INV_PROCEEDING;
20952          break;
20953       case AST_STATE_UP:
20954          ast_debug(2, "%s: This call is UP.... \n", c->name);
20955 
20956          transmit_response(p, "100 Trying", req);
20957 
20958          if (p->t38.state == T38_PEER_REINVITE) {
20959             p->t38id = ast_sched_add(sched, 5000, sip_t38_abort, dialog_ref(p, "passing dialog ptr into sched structure based on t38id for sip_t38_abort."));
20960          } else if (p->t38.state == T38_ENABLED) {
20961             ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
20962             transmit_response_with_t38_sdp(p, "200 OK", req, (reinvite ? XMIT_RELIABLE : (req->ignore ?  XMIT_UNRELIABLE : XMIT_CRITICAL)));
20963          } else if (p->t38.state == T38_DISABLED) {
20964             /* If this is not a re-invite or something to ignore - it's critical */
20965             ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
20966             transmit_response_with_sdp(p, "200 OK", req, (reinvite ? XMIT_RELIABLE : (req->ignore ?  XMIT_UNRELIABLE : XMIT_CRITICAL)), p->session_modify == TRUE ? FALSE:TRUE); 
20967          }
20968 
20969          p->invitestate = INV_TERMINATED;
20970          break;
20971       default:
20972          ast_log(LOG_WARNING, "Don't know how to handle INVITE in state %d\n", c->_state);
20973          transmit_response(p, "100 Trying", req);
20974          break;
20975       }
20976    } else {
20977       if (p && (p->autokillid == -1)) {
20978          const char *msg;
20979 
20980          if (!p->jointcapability)
20981             msg = "488 Not Acceptable Here (codec error)";
20982          else {
20983             ast_log(LOG_NOTICE, "Unable to create/find SIP channel for this INVITE\n");
20984             msg = "503 Unavailable";
20985          }
20986          transmit_response_reliable(p, msg, req);
20987          p->invitestate = INV_COMPLETED;
20988          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20989       }
20990    }
20991 
20992 request_invite_cleanup:
20993 
20994    if (refer_locked && p->refer && p->refer->refer_call) {
20995       sip_pvt_unlock(p->refer->refer_call);
20996       if (p->refer->refer_call->owner) {
20997          ast_channel_unlock(p->refer->refer_call->owner);
20998       }
20999    }
21000 
21001    return res;
21002 }
21003 
21004 /*! \brief  Find all call legs and bridge transferee with target 
21005  * called from handle_request_refer */
21006 static int local_attended_transfer(struct sip_pvt *transferer, struct sip_dual *current, struct sip_request *req, int seqno)
21007 {
21008    struct sip_dual target;    /* Chan 1: Call from tranferer to Asterisk */
21009                /* Chan 2: Call from Asterisk to target */
21010    int res = 0;
21011    struct sip_pvt *targetcall_pvt;
21012 
21013    /* Check if the call ID of the replaces header does exist locally */
21014    if (!(targetcall_pvt = get_sip_pvt_byid_locked(transferer->refer->replaces_callid, transferer->refer->replaces_callid_totag, 
21015       transferer->refer->replaces_callid_fromtag))) {
21016       if (transferer->refer->localtransfer) {
21017          /* We did not find the refered call. Sorry, can't accept then */
21018          /* Let's fake a response from someone else in order
21019             to follow the standard */
21020          transmit_notify_with_sipfrag(transferer, seqno, "481 Call leg/transaction does not exist", TRUE);
21021          append_history(transferer, "Xfer", "Refer failed");
21022          ast_clear_flag(&transferer->flags[0], SIP_GOTREFER);  
21023          transferer->refer->status = REFER_FAILED;
21024          return -1;
21025       }
21026       /* Fall through for remote transfers that we did not find locally */
21027       ast_debug(3, "SIP attended transfer: Not our call - generating INVITE with replaces\n");
21028       return 0;
21029    }
21030 
21031    /* Ok, we can accept this transfer */
21032    append_history(transferer, "Xfer", "Refer accepted");
21033    if (!targetcall_pvt->owner) { /* No active channel */
21034       ast_debug(4, "SIP attended transfer: Error: No owner of target call\n");
21035       /* Cancel transfer */
21036       transmit_notify_with_sipfrag(transferer, seqno, "503 Service Unavailable", TRUE);
21037       append_history(transferer, "Xfer", "Refer failed");
21038       ast_clear_flag(&transferer->flags[0], SIP_GOTREFER);
21039       transferer->refer->status = REFER_FAILED;
21040       sip_pvt_unlock(targetcall_pvt);
21041       if (targetcall_pvt)
21042          ao2_t_ref(targetcall_pvt, -1, "Drop targetcall_pvt pointer");
21043       return -1;
21044    }
21045 
21046    /* We have a channel, find the bridge */
21047    target.chan1 = targetcall_pvt->owner;           /* Transferer to Asterisk */
21048    target.chan2 = ast_bridged_channel(targetcall_pvt->owner);  /* Asterisk to target */
21049 
21050    if (!target.chan2 || !(target.chan2->_state == AST_STATE_UP || target.chan2->_state == AST_STATE_RINGING) ) {
21051       /* Wrong state of new channel */
21052       if (target.chan2) 
21053          ast_debug(4, "SIP attended transfer: Error: Wrong state of target call: %s\n", ast_state2str(target.chan2->_state));
21054       else if (target.chan1->_state != AST_STATE_RING)
21055          ast_debug(4, "SIP attended transfer: Error: No target channel\n");
21056       else
21057          ast_debug(4, "SIP attended transfer: Attempting transfer in ringing state\n");
21058    }
21059 
21060    /* Transfer */
21061    if (sipdebug) {
21062       if (current->chan2)  /* We have two bridges */
21063          ast_debug(4, "SIP attended transfer: trying to bridge %s and %s\n", target.chan1->name, current->chan2->name);
21064       else        /* One bridge, propably transfer of IVR/voicemail etc */
21065          ast_debug(4, "SIP attended transfer: trying to make %s take over (masq) %s\n", target.chan1->name, current->chan1->name);
21066    }
21067 
21068    ast_set_flag(&transferer->flags[0], SIP_DEFER_BYE_ON_TRANSFER);   /* Delay hangup */
21069 
21070    /* Perform the transfer */
21071    manager_event(EVENT_FLAG_CALL, "Transfer", "TransferMethod: SIP\r\nTransferType: Attended\r\nChannel: %s\r\nUniqueid: %s\r\nSIP-Callid: %s\r\nTargetChannel: %s\r\nTargetUniqueid: %s\r\n",
21072       transferer->owner->name,
21073       transferer->owner->uniqueid,
21074       transferer->callid,
21075       target.chan1->name,
21076       target.chan1->uniqueid);
21077    res = attempt_transfer(current, &target);
21078    sip_pvt_unlock(targetcall_pvt);
21079    if (res) {
21080       /* Failed transfer */
21081       transmit_notify_with_sipfrag(transferer, seqno, "486 Busy Here", TRUE);
21082       append_history(transferer, "Xfer", "Refer failed");
21083       if (targetcall_pvt->owner)
21084          ast_channel_unlock(targetcall_pvt->owner);
21085       ast_clear_flag(&transferer->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
21086    } else {
21087       /* Transfer succeeded! */
21088       const char *xfersound = pbx_builtin_getvar_helper(target.chan1, "ATTENDED_TRANSFER_COMPLETE_SOUND");
21089 
21090       /* Tell transferer that we're done. */
21091       transmit_notify_with_sipfrag(transferer, seqno, "200 OK", TRUE);
21092       append_history(transferer, "Xfer", "Refer succeeded");
21093       transferer->refer->status = REFER_200OK;
21094       if (target.chan2 && !ast_strlen_zero(xfersound) && ast_streamfile(target.chan2, xfersound, target.chan2->language) >= 0) {
21095          ast_waitstream(target.chan2, "");
21096       }
21097       if (targetcall_pvt->owner) {
21098          ast_debug(1, "SIP attended transfer: Unlocking channel %s\n", targetcall_pvt->owner->name);
21099          ast_channel_unlock(targetcall_pvt->owner);
21100       }
21101    }
21102    if (targetcall_pvt)
21103       ao2_t_ref(targetcall_pvt, -1, "drop targetcall_pvt");
21104    return 1;
21105 }
21106 
21107 
21108 /*! \brief Handle incoming REFER request */
21109 /*! \page SIP_REFER SIP transfer Support (REFER)
21110 
21111    REFER is used for call transfer in SIP. We get a REFER
21112    to place a new call with an INVITE somwhere and then
21113    keep the transferor up-to-date of the transfer. If the
21114    transfer fails, get back on line with the orginal call. 
21115 
21116    - REFER can be sent outside or inside of a dialog.
21117      Asterisk only accepts REFER inside of a dialog.
21118 
21119    - If we get a replaces header, it is an attended transfer
21120 
21121    \par Blind transfers
21122    The transferor provides the transferee
21123    with the transfer targets contact. The signalling between
21124    transferer or transferee should not be cancelled, so the
21125    call is recoverable if the transfer target can not be reached 
21126    by the transferee.
21127 
21128    In this case, Asterisk receives a TRANSFER from
21129    the transferor, thus is the transferee. We should
21130    try to set up a call to the contact provided
21131    and if that fails, re-connect the current session.
21132    If the new call is set up, we issue a hangup.
21133    In this scenario, we are following section 5.2
21134    in the SIP CC Transfer draft. (Transfer without
21135    a GRUU)
21136 
21137    \par Transfer with consultation hold
21138    In this case, the transferor
21139    talks to the transfer target before the transfer takes place.
21140    This is implemented with SIP hold and transfer.
21141    Note: The invite From: string could indicate a transfer.
21142    (Section 6. Transfer with consultation hold)
21143    The transferor places the transferee on hold, starts a call
21144    with the transfer target to alert them to the impending
21145    transfer, terminates the connection with the target, then
21146    proceeds with the transfer (as in Blind transfer above)
21147 
21148    \par Attended transfer
21149    The transferor places the transferee
21150    on hold, calls the transfer target to alert them,
21151    places the target on hold, then proceeds with the transfer
21152    using a Replaces header field in the Refer-to header. This
21153    will force the transfee to send an Invite to the target,
21154    with a replaces header that instructs the target to
21155    hangup the call between the transferor and the target.
21156    In this case, the Refer/to: uses the AOR address. (The same
21157    URI that the transferee used to establish the session with
21158    the transfer target (To: ). The Require: replaces header should
21159    be in the INVITE to avoid the wrong UA in a forked SIP proxy
21160    scenario to answer and have no call to replace with.
21161 
21162    The referred-by header is *NOT* required, but if we get it,
21163    can be copied into the INVITE to the transfer target to 
21164    inform the target about the transferor
21165 
21166    "Any REFER request has to be appropriately authenticated.".
21167    
21168    We can't destroy dialogs, since we want the call to continue.
21169    
21170    */
21171 static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, int *nounlock)
21172 {
21173    struct sip_dual current;   /* Chan1: Call between asterisk and transferer */
21174                /* Chan2: Call between asterisk and transferee */
21175 
21176    int res = 0;
21177    current.req.data = NULL;
21178 
21179    if (req->debug)
21180       ast_verbose("Call %s got a SIP call transfer from %s: (REFER)!\n", p->callid, ast_test_flag(&p->flags[0], SIP_OUTGOING) ? "callee" : "caller");
21181 
21182    if (!p->owner) {
21183       /* This is a REFER outside of an existing SIP dialog */
21184       /* We can't handle that, so decline it */
21185       ast_debug(3, "Call %s: Declined REFER, outside of dialog...\n", p->callid);
21186       transmit_response(p, "603 Declined (No dialog)", req);
21187       if (!req->ignore) {
21188          append_history(p, "Xfer", "Refer failed. Outside of dialog.");
21189          sip_alreadygone(p);
21190          pvt_set_needdestroy(p, "outside of dialog");
21191       }
21192       return 0;
21193    }
21194 
21195 
21196    /* Check if transfer is allowed from this device */
21197    if (p->allowtransfer == TRANSFER_CLOSED ) {
21198       /* Transfer not allowed, decline */
21199       transmit_response(p, "603 Declined (policy)", req);
21200       append_history(p, "Xfer", "Refer failed. Allowtransfer == closed.");
21201       /* Do not destroy SIP session */
21202       return 0;
21203    }
21204 
21205    if (!req->ignore && ast_test_flag(&p->flags[0], SIP_GOTREFER)) {
21206       /* Already have a pending REFER */
21207       transmit_response(p, "491 Request pending", req);
21208       append_history(p, "Xfer", "Refer failed. Request pending.");
21209       return 0;
21210    }
21211 
21212    /* Allocate memory for call transfer data */
21213    if (!p->refer && !sip_refer_allocate(p)) {
21214       transmit_response(p, "500 Internal Server Error", req);
21215       append_history(p, "Xfer", "Refer failed. Memory allocation error.");
21216       return -3;
21217    }
21218 
21219    res = get_refer_info(p, req); /* Extract headers */
21220 
21221    p->refer->status = REFER_SENT;
21222 
21223    if (res != 0) {
21224       switch (res) {
21225       case -2: /* Syntax error */
21226          transmit_response(p, "400 Bad Request (Refer-to missing)", req);
21227          append_history(p, "Xfer", "Refer failed. Refer-to missing.");
21228          if (req->debug)
21229             ast_debug(1, "SIP transfer to black hole can't be handled (no refer-to: )\n");
21230          break;
21231       case -3:
21232          transmit_response(p, "603 Declined (Non sip: uri)", req);
21233          append_history(p, "Xfer", "Refer failed. Non SIP uri");
21234          if (req->debug)
21235             ast_debug(1, "SIP transfer to non-SIP uri denied\n");
21236          break;
21237       default:
21238          /* Refer-to extension not found, fake a failed transfer */
21239          transmit_response(p, "202 Accepted", req);
21240          append_history(p, "Xfer", "Refer failed. Bad extension.");
21241          transmit_notify_with_sipfrag(p, seqno, "404 Not found", TRUE);
21242          ast_clear_flag(&p->flags[0], SIP_GOTREFER);  
21243          if (req->debug)
21244             ast_debug(1, "SIP transfer to bad extension: %s\n", p->refer->refer_to);
21245          break;
21246       } 
21247       return 0;
21248    }
21249    if (ast_strlen_zero(p->context))
21250       ast_string_field_set(p, context, sip_cfg.default_context);
21251 
21252    /* If we do not support SIP domains, all transfers are local */
21253    if (sip_cfg.allow_external_domains && check_sip_domain(p->refer->refer_to_domain, NULL, 0)) {
21254       p->refer->localtransfer = 1;
21255       if (sipdebug)
21256          ast_debug(3, "This SIP transfer is local : %s\n", p->refer->refer_to_domain);
21257    } else if (AST_LIST_EMPTY(&domain_list) || check_sip_domain(p->refer->refer_to_domain, NULL, 0)) {
21258       /* This PBX doesn't bother with SIP domains or domain is local, so this transfer is local */
21259       p->refer->localtransfer = 1;
21260    } else if (sipdebug)
21261          ast_debug(3, "This SIP transfer is to a remote SIP extension (remote domain %s)\n", p->refer->refer_to_domain);
21262 
21263    /* Is this a repeat of a current request? Ignore it */
21264    /* Don't know what else to do right now. */
21265    if (req->ignore) 
21266       return res;
21267 
21268    /* If this is a blind transfer, we have the following
21269    channels to work with:
21270    - chan1, chan2: The current call between transferer and transferee (2 channels)
21271    - target_channel: A new call from the transferee to the target (1 channel)
21272    We need to stay tuned to what happens in order to be able
21273    to bring back the call to the transferer */
21274 
21275    /* If this is a attended transfer, we should have all call legs within reach:
21276    - chan1, chan2: The call between the transferer and transferee (2 channels)
21277    - target_channel, targetcall_pvt: The call between the transferer and the target (2 channels)
21278    We want to bridge chan2 with targetcall_pvt!
21279    
21280    The replaces call id in the refer message points
21281    to the call leg between Asterisk and the transferer.
21282    So we need to connect the target and the transferee channel
21283    and hangup the two other channels silently 
21284    
21285    If the target is non-local, the call ID could be on a remote
21286    machine and we need to send an INVITE with replaces to the
21287    target. We basically handle this as a blind transfer
21288    and let the sip_call function catch that we need replaces
21289    header in the INVITE.
21290    */
21291 
21292 
21293    /* Get the transferer's channel */
21294    current.chan1 = p->owner;
21295 
21296    /* Find the other part of the bridge (2) - transferee */
21297    current.chan2 = ast_bridged_channel(current.chan1);
21298    
21299    if (sipdebug)
21300       ast_debug(3, "SIP %s transfer: Transferer channel %s, transferee channel %s\n", p->refer->attendedtransfer ? "attended" : "blind", current.chan1->name, current.chan2 ? current.chan2->name : "<none>");
21301 
21302    if (!current.chan2 && !p->refer->attendedtransfer) {
21303       /* No bridged channel, propably IVR or echo or similar... */
21304       /* Guess we should masquerade or something here */
21305       /* Until we figure it out, refuse transfer of such calls */
21306       if (sipdebug)
21307          ast_debug(3, "Refused SIP transfer on non-bridged channel.\n");
21308       p->refer->status = REFER_FAILED;
21309       append_history(p, "Xfer", "Refer failed. Non-bridged channel.");
21310       transmit_response(p, "603 Declined", req);
21311       return -1;
21312    }
21313 
21314    if (current.chan2) {
21315       if (sipdebug)
21316          ast_debug(4, "Got SIP transfer, applying to bridged peer '%s'\n", current.chan2->name);
21317 
21318       ast_queue_control(current.chan1, AST_CONTROL_UNHOLD);
21319    }
21320 
21321    ast_set_flag(&p->flags[0], SIP_GOTREFER);
21322 
21323    /* From here on failures will be indicated with NOTIFY requests */
21324    transmit_response(p, "202 Accepted", req);
21325 
21326    /* Attended transfer: Find all call legs and bridge transferee with target*/
21327    if (p->refer->attendedtransfer) {
21328       if ((res = local_attended_transfer(p, &current, req, seqno)))
21329          return res; /* We're done with the transfer */
21330       /* Fall through for remote transfers that we did not find locally */
21331       if (sipdebug)
21332          ast_debug(4, "SIP attended transfer: Still not our call - generating INVITE with replaces\n");
21333       /* Fallthrough if we can't find the call leg internally */
21334    }
21335 
21336 
21337    /* Parking a call */
21338    if (p->refer->localtransfer && !strcmp(p->refer->refer_to, ast_parking_ext())) {
21339       /* Must release c's lock now, because it will not longer be accessible after the transfer! */
21340       *nounlock = 1;
21341       ast_channel_unlock(current.chan1);
21342       copy_request(&current.req, req);
21343       ast_clear_flag(&p->flags[0], SIP_GOTREFER);
21344       p->refer->status = REFER_200OK;
21345       append_history(p, "Xfer", "REFER to call parking.");
21346       manager_event(EVENT_FLAG_CALL, "Transfer", "TransferMethod: SIP\r\nTransferType: Blind\r\nChannel: %s\r\nUniqueid: %s\r\nSIP-Callid: %s\r\nTargetChannel: %s\r\nTargetUniqueid: %s\r\nTransferExten: %s\r\nTransfer2Parking: Yes\r\n",
21347          current.chan1->name,
21348          current.chan1->uniqueid,
21349          p->callid,
21350          current.chan2->name,
21351          current.chan2->uniqueid,
21352          p->refer->refer_to);
21353       if (sipdebug)
21354          ast_debug(4, "SIP transfer to parking: trying to park %s. Parked by %s\n", current.chan2->name, current.chan1->name);
21355       if ((res = sip_park(current.chan2, current.chan1, req, seqno))) {
21356          transmit_notify_with_sipfrag(p, seqno, "500 Internal Server Error", TRUE);
21357       }
21358       return res;
21359    } 
21360 
21361    /* Blind transfers and remote attended xfers */
21362    if (current.chan1 && current.chan2) {
21363       ast_debug(3, "chan1->name: %s\n", current.chan1->name);
21364       pbx_builtin_setvar_helper(current.chan1, "BLINDTRANSFER", current.chan2->name);
21365    }
21366    if (current.chan2) {
21367       pbx_builtin_setvar_helper(current.chan2, "BLINDTRANSFER", current.chan1->name);
21368       pbx_builtin_setvar_helper(current.chan2, "SIPDOMAIN", p->refer->refer_to_domain);
21369       pbx_builtin_setvar_helper(current.chan2, "SIPTRANSFER", "yes");
21370       /* One for the new channel */
21371       pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER", "yes");
21372       /* Attended transfer to remote host, prepare headers for the INVITE */
21373       if (p->refer->referred_by) 
21374          pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER_REFERER", p->refer->referred_by);
21375    }
21376    /* Generate a Replaces string to be used in the INVITE during attended transfer */
21377    if (!ast_strlen_zero(p->refer->replaces_callid)) {
21378       char tempheader[SIPBUFSIZE];
21379       snprintf(tempheader, sizeof(tempheader), "%s%s%s%s%s", p->refer->replaces_callid, 
21380             p->refer->replaces_callid_totag ? ";to-tag=" : "", 
21381             p->refer->replaces_callid_totag, 
21382             p->refer->replaces_callid_fromtag ? ";from-tag=" : "",
21383             p->refer->replaces_callid_fromtag);
21384       if (current.chan2)
21385          pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER_REPLACES", tempheader);
21386    }
21387    /* Must release lock now, because it will not longer
21388       be accessible after the transfer! */
21389    *nounlock = 1;
21390    ast_channel_unlock(current.chan1);
21391 
21392    /* Connect the call */
21393 
21394    /* FAKE ringing if not attended transfer */
21395    if (!p->refer->attendedtransfer)
21396       transmit_notify_with_sipfrag(p, seqno, "183 Ringing", FALSE); 
21397 
21398    /* For blind transfer, this will lead to a new call */
21399    /* For attended transfer to remote host, this will lead to
21400       a new SIP call with a replaces header, if the dial plan allows it 
21401    */
21402    if (!current.chan2) {
21403       /* We have no bridge, so we're talking with Asterisk somehow */
21404       /* We need to masquerade this call */
21405       /* What to do to fix this situation:
21406          * Set up the new call in a new channel 
21407          * Let the new channel masq into this channel
21408          Please add that code here :-)
21409       */
21410       p->refer->status = REFER_FAILED;
21411       transmit_notify_with_sipfrag(p, seqno, "503 Service Unavailable (can't handle one-legged xfers)", TRUE);
21412       ast_clear_flag(&p->flags[0], SIP_GOTREFER);  
21413       append_history(p, "Xfer", "Refer failed (only bridged calls).");
21414       return -1;
21415    }
21416    ast_set_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER);   /* Delay hangup */
21417 
21418 
21419    /* For blind transfers, move the call to the new extensions. For attended transfers on multiple
21420       servers - generate an INVITE with Replaces. Either way, let the dial plan decided  */
21421    /* indicate before masquerade so the indication actually makes it to the real channel
21422       when using local channels with MOH passthru */
21423    ast_indicate(current.chan2, AST_CONTROL_UNHOLD);
21424    res = ast_async_goto(current.chan2, p->refer->refer_to_context, p->refer->refer_to, 1);
21425 
21426    if (!res) {
21427       manager_event(EVENT_FLAG_CALL, "Transfer", "TransferMethod: SIP\r\nTransferType: Blind\r\nChannel: %s\r\nUniqueid: %s\r\nSIP-Callid: %s\r\nTargetChannel: %s\r\nTargetUniqueid: %s\r\nTransferExten: %s\r\nTransferContext: %s\r\n",
21428          current.chan1->name,
21429          current.chan1->uniqueid,
21430          p->callid,
21431          current.chan2->name,
21432          current.chan2->uniqueid,
21433          p->refer->refer_to, p->refer->refer_to_context);
21434       /* Success  - we have a new channel */
21435       ast_debug(3, "%s transfer succeeded. Telling transferer.\n", p->refer->attendedtransfer? "Attended" : "Blind");
21436       transmit_notify_with_sipfrag(p, seqno, "200 Ok", TRUE);
21437       if (p->refer->localtransfer)
21438          p->refer->status = REFER_200OK;
21439       if (p->owner)
21440          p->owner->hangupcause = AST_CAUSE_NORMAL_CLEARING;
21441       append_history(p, "Xfer", "Refer succeeded.");
21442       ast_clear_flag(&p->flags[0], SIP_GOTREFER);  
21443       /* Do not hangup call, the other side do that when we say 200 OK */
21444       /* We could possibly implement a timer here, auto congestion */
21445       res = 0;
21446    } else {
21447       ast_clear_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER); /* Don't delay hangup */
21448       ast_debug(3, "%s transfer failed. Resuming original call.\n", p->refer->attendedtransfer? "Attended" : "Blind");
21449       append_history(p, "Xfer", "Refer failed.");
21450       /* Failure of some kind */
21451       p->refer->status = REFER_FAILED;
21452       transmit_notify_with_sipfrag(p, seqno, "503 Service Unavailable", TRUE);
21453       ast_clear_flag(&p->flags[0], SIP_GOTREFER);  
21454       res = -1;
21455    }
21456    return res;
21457 }
21458 
21459 /*! \brief Handle incoming CANCEL request */
21460 static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req)
21461 {
21462       
21463    check_via(p, req);
21464    sip_alreadygone(p);
21465 
21466    /* At this point, we could have cancelled the invite at the same time
21467       as the other side sends a CANCEL. Our final reply with error code
21468       might not have been received by the other side before the CANCEL
21469       was sent, so let's just give up retransmissions and waiting for
21470       ACK on our error code. The call is hanging up any way. */
21471    if (p->invitestate == INV_TERMINATED)
21472       __sip_pretend_ack(p);
21473    else
21474       p->invitestate = INV_CANCELLED;
21475    
21476    if (p->owner && p->owner->_state == AST_STATE_UP) {
21477       /* This call is up, cancel is ignored, we need a bye */
21478       transmit_response(p, "200 OK", req);
21479       ast_debug(1, "Got CANCEL on an answered call. Ignoring... \n");
21480       return 0;
21481    }
21482 
21483    if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) 
21484       update_call_counter(p, DEC_CALL_LIMIT);
21485 
21486    stop_media_flows(p); /* Immediately stop RTP, VRTP and UDPTL as applicable */
21487    if (p->owner)
21488       ast_queue_hangup(p->owner);
21489    else
21490       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
21491    if (p->initreq.len > 0) {
21492       struct sip_pkt *pkt, *prev_pkt;
21493       /* If the CANCEL we are receiving is a retransmission, and we already have scheduled
21494        * a reliable 487, then we don't want to schedule another one on top of the previous
21495        * one.
21496        *
21497        * As odd as this may sound, we can't rely on the previously-transmitted "reliable" 
21498        * response in this situation. What if we've sent all of our reliable responses 
21499        * already and now all of a sudden, we get this second CANCEL?
21500        *
21501        * The only way to do this correctly is to cancel our previously-scheduled reliably-
21502        * transmitted response and send a new one in its place.
21503        */
21504       for (pkt = p->packets, prev_pkt = NULL; pkt; prev_pkt = pkt, pkt = pkt->next) {
21505          if (pkt->seqno == p->lastinvite && pkt->response_code == 487) {
21506             AST_SCHED_DEL(sched, pkt->retransid);
21507             UNLINK(pkt, p->packets, prev_pkt);
21508             ast_free(pkt);
21509             break;
21510          }
21511       }
21512       transmit_response_reliable(p, "487 Request Terminated", &p->initreq);
21513       transmit_response(p, "200 OK", req);
21514       return 1;
21515    } else {
21516       transmit_response(p, "481 Call Leg Does Not Exist", req);
21517       return 0;
21518    }
21519 }
21520 
21521 static int acf_channel_read(struct ast_channel *chan, const char *funcname, char *preparse, char *buf, size_t buflen)
21522 {
21523    struct sip_pvt *p = chan->tech_pvt;
21524    char *all = "", *parse = ast_strdupa(preparse);
21525    int res = 0;
21526    AST_DECLARE_APP_ARGS(args,
21527       AST_APP_ARG(param);
21528       AST_APP_ARG(type);
21529       AST_APP_ARG(field);
21530    );
21531    AST_STANDARD_APP_ARGS(args, parse);
21532 
21533    /* Sanity check */
21534    if (!IS_SIP_TECH(chan->tech)) {
21535       ast_log(LOG_ERROR, "Cannot call %s on a non-SIP channel\n", funcname);
21536       return 0;
21537    }
21538 
21539    memset(buf, 0, buflen);
21540 
21541    if (p == NULL) {
21542       return -1;
21543    }
21544 
21545    if (!strcasecmp(args.param, "peerip")) {
21546       ast_copy_string(buf, p->sa.sin_addr.s_addr ? ast_inet_ntoa(p->sa.sin_addr) : "", buflen);
21547    } else if (!strcasecmp(args.param, "recvip")) {
21548       ast_copy_string(buf, p->recv.sin_addr.s_addr ? ast_inet_ntoa(p->recv.sin_addr) : "", buflen);
21549    } else if (!strcasecmp(args.param, "from")) {
21550       ast_copy_string(buf, p->from, buflen);
21551    } else if (!strcasecmp(args.param, "uri")) {
21552       ast_copy_string(buf, p->uri, buflen);
21553    } else if (!strcasecmp(args.param, "useragent")) {
21554       ast_copy_string(buf, p->useragent, buflen);
21555    } else if (!strcasecmp(args.param, "peername")) {
21556       ast_copy_string(buf, p->peername, buflen);
21557    } else if (!strcasecmp(args.param, "t38passthrough")) {
21558       ast_copy_string(buf, (p->t38.state == T38_DISABLED) ? "0" : "1", buflen);
21559    } else if (!strcasecmp(args.param, "rtpdest")) {
21560       struct sockaddr_in sin;
21561       struct ast_rtp *stream = NULL;
21562 
21563       if (ast_strlen_zero(args.type))
21564          args.type = "audio";
21565 
21566       if (!strcasecmp(args.type, "audio")) {
21567          stream = p->rtp;
21568       } else if (!strcasecmp(args.type, "video")) {
21569          stream = p->vrtp;
21570       } else if (!strcasecmp(args.type, "text")) {
21571          stream = p->trtp;
21572       } else {
21573          return -1;
21574       }
21575 
21576       if (!stream) {
21577          return -1;
21578       }
21579 
21580       ast_rtp_get_peer(stream, &sin);
21581       snprintf(buf, buflen, "%s:%d", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
21582    } else if (!strcasecmp(args.param, "rtpqos")) {
21583       struct ast_rtp_quality qos;
21584       struct ast_rtp *rtp = p->rtp;
21585       
21586       memset(&qos, 0, sizeof(qos));
21587 
21588       if (ast_strlen_zero(args.type))
21589          args.type = "audio";
21590       if (ast_strlen_zero(args.field))
21591          args.field = "all";
21592       
21593       if (!strcasecmp(args.type, "AUDIO")) {
21594          all = ast_rtp_get_quality(rtp = p->rtp, &qos, RTPQOS_SUMMARY);
21595       } else if (!strcasecmp(args.type, "VIDEO")) {
21596          all = ast_rtp_get_quality(rtp = p->vrtp, &qos, RTPQOS_SUMMARY);
21597       } else if (!strcasecmp(args.type, "TEXT")) {
21598          all = ast_rtp_get_quality(rtp = p->trtp, &qos, RTPQOS_SUMMARY);
21599       } else {
21600          return -1;
21601       }
21602       
21603       if (!strcasecmp(args.field, "local_ssrc"))
21604          snprintf(buf, buflen, "%u", qos.local_ssrc);
21605       else if (!strcasecmp(args.field, "local_lostpackets"))
21606          snprintf(buf, buflen, "%u", qos.local_lostpackets);
21607       else if (!strcasecmp(args.field, "local_jitter"))
21608          snprintf(buf, buflen, "%.0f", qos.local_jitter * 1000.0);
21609       else if (!strcasecmp(args.field, "local_count"))
21610          snprintf(buf, buflen, "%u", qos.local_count);
21611       else if (!strcasecmp(args.field, "remote_ssrc"))
21612          snprintf(buf, buflen, "%u", qos.remote_ssrc);
21613       else if (!strcasecmp(args.field, "remote_lostpackets"))
21614          snprintf(buf, buflen, "%u", qos.remote_lostpackets);
21615       else if (!strcasecmp(args.field, "remote_jitter"))
21616          snprintf(buf, buflen, "%.0f", qos.remote_jitter * 1000.0);
21617       else if (!strcasecmp(args.field, "remote_count"))
21618          snprintf(buf, buflen, "%u", qos.remote_count);
21619       else if (!strcasecmp(args.field, "rtt"))
21620          snprintf(buf, buflen, "%.0f", qos.rtt * 1000.0);
21621       else if (!strcasecmp(args.field, "all"))
21622          ast_copy_string(buf, all, buflen);
21623       else if (!ast_rtp_get_qos(rtp, args.field, buf, buflen))
21624           ;
21625       else {
21626          ast_log(LOG_WARNING, "Unrecognized argument '%s' to %s\n", preparse, funcname);
21627          return -1;
21628       }
21629    } else {
21630       res = -1;
21631    }
21632    return res;
21633 }
21634 
21635 /*! \brief Handle incoming BYE request */
21636 static int handle_request_bye(struct sip_pvt *p, struct sip_request *req)
21637 {
21638    struct ast_channel *c=NULL;
21639    int res;
21640    struct ast_channel *bridged_to;
21641    
21642    /* If we have an INCOMING invite that we haven't answered, terminate that transaction */
21643    if (p->pendinginvite && !ast_test_flag(&p->flags[0], SIP_OUTGOING) && !req->ignore) {
21644       transmit_response_reliable(p, "487 Request Terminated", &p->initreq);
21645    }
21646 
21647    __sip_pretend_ack(p);
21648 
21649    p->invitestate = INV_TERMINATED;
21650 
21651    copy_request(&p->initreq, req);
21652    if (sipdebug)
21653       ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
21654    check_via(p, req);
21655    sip_alreadygone(p);
21656 
21657    /* Get RTCP quality before end of call */
21658    if (p->do_history || p->owner) {
21659       struct ast_channel *bridge = p->owner ? ast_bridged_channel(p->owner) : NULL;
21660       char *videoqos, *textqos;
21661 
21662       /* We need to get the lock on bridge because ast_rtp_set_vars will attempt
21663        * to lock the bridge. This may get hairy...
21664        */
21665       while (bridge && ast_channel_trylock(bridge)) {
21666          ast_channel_unlock(p->owner);
21667          do {
21668             /* Can't use DEADLOCK_AVOIDANCE since p is an ao2 object */
21669             sip_pvt_unlock(p);
21670             usleep(1);
21671             sip_pvt_lock(p);
21672          } while (p->owner && ast_channel_trylock(p->owner));
21673          bridge = p->owner ? ast_bridged_channel(p->owner) : NULL;
21674       }
21675 
21676       if (p->rtp) {  
21677          if (p->do_history) {
21678             char *audioqos,
21679                  *audioqos_jitter,
21680                  *audioqos_loss,
21681                  *audioqos_rtt;
21682 
21683             audioqos        = ast_rtp_get_quality(p->rtp, NULL, RTPQOS_SUMMARY);
21684             audioqos_jitter = ast_rtp_get_quality(p->rtp, NULL, RTPQOS_JITTER);
21685             audioqos_loss   = ast_rtp_get_quality(p->rtp, NULL, RTPQOS_LOSS);
21686             audioqos_rtt    = ast_rtp_get_quality(p->rtp, NULL, RTPQOS_RTT);
21687 
21688             append_history(p, "RTCPaudio", "Quality:%s", audioqos);
21689             append_history(p, "RTCPaudioJitter", "Quality:%s", audioqos_jitter);
21690             append_history(p, "RTCPaudioLoss", "Quality:%s", audioqos_loss);
21691             append_history(p, "RTCPaudioRTT", "Quality:%s", audioqos_rtt);
21692          }
21693          
21694          if (p->owner) {
21695             ast_rtp_set_vars(p->owner, p->rtp);
21696          }
21697       }
21698 
21699       if (bridge) {
21700          struct sip_pvt *q = bridge->tech_pvt;
21701 
21702          if (IS_SIP_TECH(bridge->tech) && q && q->rtp)
21703             ast_rtp_set_vars(bridge, q->rtp);
21704          ast_channel_unlock(bridge);
21705       }
21706 
21707       if (p->vrtp) {
21708          videoqos = ast_rtp_get_quality(p->vrtp, NULL, RTPQOS_SUMMARY);
21709          if (p->do_history)
21710             append_history(p, "RTCPvideo", "Quality:%s", videoqos);
21711          if (p->owner)
21712             pbx_builtin_setvar_helper(p->owner, "RTPVIDEOQOS", videoqos);
21713       }
21714 
21715       if (p->trtp) {
21716          textqos = ast_rtp_get_quality(p->trtp, NULL, RTPQOS_SUMMARY);
21717          if (p->do_history)
21718             append_history(p, "RTCPtext", "Quality:%s", textqos);
21719          if (p->owner)
21720             pbx_builtin_setvar_helper(p->owner, "RTPTEXTQOS", textqos);
21721       }
21722    }
21723 
21724    stop_media_flows(p); /* Immediately stop RTP, VRTP and UDPTL as applicable */
21725    stop_session_timer(p); /* Stop Session-Timer */
21726 
21727    if (!ast_strlen_zero(get_header(req, "Also"))) {
21728       ast_log(LOG_NOTICE, "Client '%s' using deprecated BYE/Also transfer method.  Ask vendor to support REFER instead\n",
21729          ast_inet_ntoa(p->recv.sin_addr));
21730       if (ast_strlen_zero(p->context))
21731          ast_string_field_set(p, context, sip_cfg.default_context);
21732       res = get_also_info(p, req);
21733       if (!res) {
21734          c = p->owner;
21735          if (c) {
21736             bridged_to = ast_bridged_channel(c);
21737             if (bridged_to) {
21738                /* Don't actually hangup here... */
21739                ast_queue_control(c, AST_CONTROL_UNHOLD);
21740                ast_async_goto(bridged_to, p->context, p->refer->refer_to, 1);
21741             } else
21742                ast_queue_hangup(p->owner);
21743          }
21744       } else {
21745          ast_log(LOG_WARNING, "Invalid transfer information from '%s'\n", ast_inet_ntoa(p->recv.sin_addr));
21746          if (p->owner)
21747             ast_queue_hangup_with_cause(p->owner, AST_CAUSE_PROTOCOL_ERROR);
21748       }
21749    } else if (p->owner) {
21750       ast_queue_hangup(p->owner);
21751       ast_debug(3, "Received bye, issuing owner hangup\n");
21752    } else {
21753       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
21754       ast_debug(3, "Received bye, no owner, selfdestruct soon.\n");
21755    }
21756    ast_clear_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
21757    transmit_response(p, "200 OK", req);
21758 
21759    return 1;
21760 }
21761 
21762 /*! \brief Handle incoming MESSAGE request */
21763 static int handle_request_message(struct sip_pvt *p, struct sip_request *req)
21764 {
21765    if (!req->ignore) {
21766       if (req->debug)
21767          ast_verbose("Receiving message!\n");
21768       receive_message(p, req);
21769    } else
21770       transmit_response(p, "202 Accepted", req);
21771    return 1;
21772 }
21773 
21774 static void add_peer_mwi_subs(struct sip_peer *peer)
21775 {
21776    struct sip_mailbox *mailbox;
21777 
21778    AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
21779       mailbox->event_sub = ast_event_subscribe(AST_EVENT_MWI, mwi_event_cb, peer,
21780          AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, mailbox->mailbox,
21781          AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, S_OR(mailbox->context, "default"),
21782          AST_EVENT_IE_END);
21783    }
21784 }
21785 
21786 /*! \brief  Handle incoming SUBSCRIBE request */
21787 static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e)
21788 {
21789    int gotdest = 0;
21790    int res = 0;
21791    int firststate = AST_EXTENSION_REMOVED;
21792    struct sip_peer *authpeer = NULL;
21793    const char *eventheader = get_header(req, "Event");   /* Get Event package name */
21794    int resubscribe = (p->subscribed != NONE) && !req->ignore;
21795    char *temp, *event;
21796 
21797    if (p->initreq.headers) {  
21798       /* We already have a dialog */
21799       if (p->initreq.method != SIP_SUBSCRIBE) {
21800          /* This is a SUBSCRIBE within another SIP dialog, which we do not support */
21801          /* For transfers, this could happen, but since we haven't seen it happening, let us just refuse this */
21802          transmit_response(p, "403 Forbidden (within dialog)", req);
21803          /* Do not destroy session, since we will break the call if we do */
21804          ast_debug(1, "Got a subscription within the context of another call, can't handle that - %s (Method %s)\n", p->callid, sip_methods[p->initreq.method].text);
21805          return 0;
21806       } else if (req->debug) {
21807          if (resubscribe)
21808             ast_debug(1, "Got a re-subscribe on existing subscription %s\n", p->callid);
21809          else
21810             ast_debug(1, "Got a new subscription %s (possibly with auth) or retransmission\n", p->callid);
21811       }
21812    }
21813 
21814    /* Check if we have a global disallow setting on subscriptions. 
21815       if so, we don't have to check peer settings after auth, which saves a lot of processing
21816    */
21817    if (!sip_cfg.allowsubscribe) {
21818       transmit_response(p, "403 Forbidden (policy)", req);
21819       pvt_set_needdestroy(p, "forbidden");
21820       return 0;
21821    }
21822 
21823    if (!req->ignore && !resubscribe) { /* Set up dialog, new subscription */
21824       const char *to = get_header(req, "To");
21825       char totag[128];
21826 
21827       /* Check to see if a tag was provided, if so this is actually a resubscription of a dialog we no longer know about */
21828       if (!ast_strlen_zero(to) && gettag(req, "To", totag, sizeof(totag))) {
21829          if (req->debug)
21830             ast_verbose("Received resubscription for a dialog we no longer know about. Telling remote side to subscribe again.\n");
21831          transmit_response(p, "481 Subscription does not exist", req);
21832          pvt_set_needdestroy(p, "subscription does not exist");
21833          return 0;
21834       }
21835 
21836       /* Use this as the basis */
21837       if (req->debug)
21838          ast_verbose("Creating new subscription\n");
21839 
21840       copy_request(&p->initreq, req);
21841       if (sipdebug)
21842          ast_debug(4, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
21843       check_via(p, req);
21844       build_route(p, req, 0);
21845    } else if (req->debug && req->ignore)
21846       ast_verbose("Ignoring this SUBSCRIBE request\n");
21847 
21848    /* Find parameters to Event: header value and remove them for now */
21849    if (ast_strlen_zero(eventheader)) {
21850       transmit_response(p, "489 Bad Event", req);
21851       ast_debug(2, "Received SIP subscribe for unknown event package: <none>\n");
21852       pvt_set_needdestroy(p, "unknown event package in subscribe");
21853       return 0;
21854    }
21855 
21856    if ( (strchr(eventheader, ';'))) {
21857       event = ast_strdupa(eventheader);   /* Since eventheader is a const, we can't change it */
21858       temp = strchr(event, ';');       
21859       *temp = '\0';           /* Remove any options for now */
21860                      /* We might need to use them later :-) */
21861    } else
21862       event = (char *) eventheader;    /* XXX is this legal ? */
21863 
21864    /* Handle authentication if we're new and not a retransmission. We can't just
21865     * use if !req->ignore, because then we'll end up sending
21866     * a 200 OK if someone retransmits without sending auth */
21867    if (p->subscribed == NONE || resubscribe) {
21868       res = check_user_full(p, req, SIP_SUBSCRIBE, e, 0, sin, &authpeer);
21869 
21870       /* if an authentication response was sent, we are done here */
21871       if (res == AUTH_CHALLENGE_SENT)  /* authpeer = NULL here */
21872          return 0;
21873       if (res < 0) {
21874          if (res == AUTH_FAKE_AUTH) {
21875             ast_log(LOG_NOTICE, "Sending fake auth rejection for device %s\n", get_header(req, "From"));
21876             transmit_fake_auth_response(p, SIP_SUBSCRIBE, req, XMIT_UNRELIABLE);
21877          } else {
21878             ast_log(LOG_NOTICE, "Failed to authenticate device %s for SUBSCRIBE\n", get_header(req, "From"));
21879             transmit_response_reliable(p, "403 Forbidden", req);
21880          }
21881 
21882          pvt_set_needdestroy(p, "authentication failed");
21883          return 0;
21884       }
21885    }
21886 
21887    /* At this point, authpeer cannot be NULL. Remember we hold a reference,
21888     * so we must release it when done.
21889     * XXX must remove all the checks for authpeer == NULL.
21890     */
21891 
21892    /* Check if this device  is allowed to subscribe at all */
21893    if (!ast_test_flag(&p->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)) {
21894       transmit_response(p, "403 Forbidden (policy)", req);
21895       pvt_set_needdestroy(p, "subscription not allowed");
21896       if (authpeer)
21897          unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 1)");
21898       return 0;
21899    }
21900 
21901    if (strcmp(event, "message-summary")) {
21902       /* Get destination right away */
21903       gotdest = get_destination(p, NULL);
21904    }
21905 
21906    /* Get full contact header - this needs to be used as a request URI in NOTIFY's */
21907    parse_ok_contact(p, req);
21908 
21909    build_contact(p);
21910    if (gotdest) {
21911       transmit_response(p, "404 Not Found", req);
21912       pvt_set_needdestroy(p, "subscription target not found");
21913       if (authpeer)
21914          unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 2)");
21915       return 0;
21916    }
21917 
21918    /* Initialize tag for new subscriptions */   
21919    if (ast_strlen_zero(p->tag))
21920       make_our_tag(p->tag, sizeof(p->tag));
21921 
21922    if (!strcmp(event, "presence") || !strcmp(event, "dialog")) { /* Presence, RFC 3842 */
21923       unsigned int pidf_xml;
21924       const char *accept;
21925       int start = 0;
21926       enum subscriptiontype subscribed = NONE;
21927       const char *unknown_acceptheader = NULL;
21928 
21929       if (authpeer)  /* We do not need the authpeer any more */
21930          unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 2)");
21931 
21932       /* Header from Xten Eye-beam Accept: multipart/related, application/rlmi+xml, application/pidf+xml, application/xpidf+xml */
21933 
21934       accept = __get_header(req, "Accept", &start);
21935       while ((subscribed == NONE) && !ast_strlen_zero(accept)) {
21936          pidf_xml = strstr(accept, "application/pidf+xml") ? 1 : 0;
21937 
21938          /* Older versions of Polycom firmware will claim pidf+xml, but really
21939           * they only support xpidf+xml. */
21940          if (pidf_xml && strstr(p->useragent, "Polycom")) {
21941             subscribed = XPIDF_XML;
21942          } else if (pidf_xml) {
21943             subscribed = PIDF_XML;         /* RFC 3863 format */
21944          } else if (strstr(accept, "application/dialog-info+xml")) {
21945             subscribed = DIALOG_INFO_XML;
21946             /* IETF draft: draft-ietf-sipping-dialog-package-05.txt */
21947          } else if (strstr(accept, "application/cpim-pidf+xml")) {
21948             subscribed = CPIM_PIDF_XML;    /* RFC 3863 format */
21949          } else if (strstr(accept, "application/xpidf+xml")) {
21950             subscribed = XPIDF_XML;        /* Early pre-RFC 3863 format with MSN additions (Microsoft Messenger) */
21951          } else {
21952             unknown_acceptheader = accept;
21953          }
21954          /* check to see if there is another Accept header present */
21955          accept = __get_header(req, "Accept", &start);
21956       }
21957 
21958       if (!start) {
21959          if (p->subscribed == NONE) { /* if the subscribed field is not already set, and there is no accept header... */
21960             transmit_response(p, "489 Bad Event", req);
21961             ast_log(LOG_WARNING,"SUBSCRIBE failure: no Accept header: pvt: "
21962                "stateid: %d, laststate: %d, dialogver: %d, subscribecont: "
21963                "'%s', subscribeuri: '%s'\n",
21964                p->stateid,
21965                p->laststate,
21966                p->dialogver,
21967                p->subscribecontext,
21968                p->subscribeuri);
21969             pvt_set_needdestroy(p, "no Accept header");
21970             return 0;
21971          }
21972          /* if p->subscribed is non-zero, then accept is not obligatory; according to rfc 3265 section 3.1.3, at least.
21973             so, we'll just let it ride, keeping the value from a previous subscription, and not abort the subscription */
21974       } else if (subscribed == NONE) {
21975          /* Can't find a format for events that we know about */
21976          char mybuf[200];
21977          if (!ast_strlen_zero(unknown_acceptheader)) {
21978             snprintf(mybuf, sizeof(mybuf), "489 Bad Event (format %s)", unknown_acceptheader);
21979          } else {
21980             snprintf(mybuf, sizeof(mybuf), "489 Bad Event");
21981          }
21982          transmit_response(p, mybuf, req);
21983          ast_log(LOG_WARNING,"SUBSCRIBE failure: unrecognized format:"
21984             "'%s' pvt: subscribed: %d, stateid: %d, laststate: %d,"
21985             "dialogver: %d, subscribecont: '%s', subscribeuri: '%s'\n",
21986             unknown_acceptheader,
21987             (int)p->subscribed,
21988             p->stateid,
21989             p->laststate,
21990             p->dialogver,
21991             p->subscribecontext,
21992             p->subscribeuri);
21993          pvt_set_needdestroy(p, "unrecognized format");
21994          return 0;
21995       } else {
21996          p->subscribed = subscribed;
21997       }
21998    } else if (!strcmp(event, "message-summary")) {
21999       int start = 0;
22000       int found_supported = 0;
22001       const char *acceptheader;
22002 
22003       acceptheader = __get_header(req, "Accept", &start);
22004       while (!found_supported && !ast_strlen_zero(acceptheader)) {
22005          found_supported = strcmp(acceptheader, "application/simple-message-summary") ? 0 : 1;
22006          if (!found_supported && (option_debug > 2)) {
22007             ast_log(LOG_DEBUG, "Received SIP mailbox subscription for unknown format: %s\n", acceptheader);
22008          }
22009          acceptheader = __get_header(req, "Accept", &start);
22010       }
22011       if (start && !found_supported) {
22012          /* Format requested that we do not support */
22013          transmit_response(p, "406 Not Acceptable", req);
22014          ast_debug(2, "Received SIP mailbox subscription for unknown format: %s\n", acceptheader);
22015          pvt_set_needdestroy(p, "unknown format");
22016          if (authpeer)
22017             unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 3)");
22018          return 0;
22019       }
22020 
22021       /* Looks like they actually want a mailbox status 
22022         This version of Asterisk supports mailbox subscriptions
22023         The subscribed URI needs to exist in the dial plan
22024         In most devices, this is configurable to the voicemailmain extension you use
22025       */
22026       if (!authpeer || AST_LIST_EMPTY(&authpeer->mailboxes)) {
22027          transmit_response(p, "404 Not found (no mailbox)", req);
22028          pvt_set_needdestroy(p, "received 404 response");
22029          ast_log(LOG_NOTICE, "Received SIP subscribe for peer without mailbox: %s\n", authpeer->name);
22030          if (authpeer)
22031             unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 4)");
22032          return 0;
22033       }
22034 
22035       p->subscribed = MWI_NOTIFICATION;
22036       if (ast_test_flag(&authpeer->flags[1], SIP_PAGE2_SUBSCRIBEMWIONLY)) {
22037          add_peer_mwi_subs(authpeer);
22038       }
22039       if (authpeer->mwipvt && authpeer->mwipvt != p) {   /* Destroy old PVT if this is a new one */
22040          /* We only allow one subscription per peer */
22041          dialog_unlink_all(authpeer->mwipvt, TRUE, TRUE);
22042          authpeer->mwipvt = dialog_unref(authpeer->mwipvt, "unref dialog authpeer->mwipvt");
22043          /* sip_destroy(authpeer->mwipvt); */
22044       }
22045       if (authpeer->mwipvt)
22046          dialog_unref(authpeer->mwipvt, "Unref previously stored mwipvt dialog pointer");
22047       authpeer->mwipvt = dialog_ref(p, "setting peers' mwipvt to p");      /* Link from peer to pvt UH- should this be dialog_ref()? */
22048       if (p->relatedpeer)
22049          unref_peer(p->relatedpeer, "Unref previously stored relatedpeer ptr");
22050       p->relatedpeer = ref_peer(authpeer, "setting dialog's relatedpeer pointer");  /* already refcounted...Link from pvt to peer UH- should this be dialog_ref()? */
22051       /* Do not release authpeer here */
22052    } else { /* At this point, Asterisk does not understand the specified event */
22053       transmit_response(p, "489 Bad Event", req);
22054       ast_debug(2, "Received SIP subscribe for unknown event package: %s\n", event);
22055       pvt_set_needdestroy(p, "unknown event package");
22056       if (authpeer)
22057          unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 5)");
22058       return 0;
22059    }
22060 
22061    /* Add subscription for extension state from the PBX core */
22062    if (p->subscribed != MWI_NOTIFICATION && !resubscribe) {
22063       if (p->stateid > -1) {
22064          ast_extension_state_del(p->stateid, cb_extensionstate);
22065          /* we need to dec the refcount, now that the extensionstate is removed */
22066          dialog_unref(p, "the extensionstate containing this dialog ptr was deleted");
22067       }
22068       p->stateid = ast_extension_state_add(p->context, p->exten, cb_extensionstate, dialog_ref(p,"copying dialog ptr into extension state struct"));
22069    }
22070 
22071    if (!req->ignore && p)
22072       p->lastinvite = seqno;
22073    if (p && !p->needdestroy) {
22074       p->expiry = atoi(get_header(req, "Expires"));
22075 
22076       /* check if the requested expiry-time is within the approved limits from sip.conf */
22077       if (p->expiry > max_expiry)
22078          p->expiry = max_expiry;
22079       if (p->expiry < min_expiry && p->expiry > 0)
22080          p->expiry = min_expiry;
22081 
22082       if (sipdebug) {
22083          if (p->subscribed == MWI_NOTIFICATION && p->relatedpeer)
22084             ast_debug(2, "Adding subscription for mailbox notification - peer %s\n", p->relatedpeer->name);
22085          else
22086             ast_debug(2, "Adding subscription for extension %s context %s for peer %s\n", p->exten, p->context, p->username);
22087       }
22088       if (p->autokillid > -1 && sip_cancel_destroy(p))   /* Remove subscription expiry for renewals */
22089          ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
22090       if (p->expiry > 0)
22091          sip_scheddestroy(p, (p->expiry + 10) * 1000);   /* Set timer for destruction of call at expiration */
22092 
22093       if (p->subscribed == MWI_NOTIFICATION) {
22094          ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
22095          transmit_response(p, "200 OK", req);
22096          if (p->relatedpeer) {   /* Send first notification */
22097             ao2_lock(p->relatedpeer); /* was WRLOCK */
22098             sip_send_mwi_to_peer(p->relatedpeer, NULL, 0);
22099             ao2_unlock(p->relatedpeer);
22100          }
22101       } else {
22102 
22103          if ((firststate = ast_extension_state(NULL, p->context, p->exten)) < 0) {
22104 
22105             ast_log(LOG_NOTICE, "Got SUBSCRIBE for extension %s@%s from %s, but there is no hint for that extension.\n", p->exten, p->context, ast_inet_ntoa(p->sa.sin_addr));
22106             transmit_response(p, "404 Not found", req);
22107             pvt_set_needdestroy(p, "no extension for SUBSCRIBE");
22108             return 0;
22109          }
22110          ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
22111          transmit_response(p, "200 OK", req);
22112          transmit_state_notify(p, firststate, 1, FALSE); /* Send first notification */
22113          append_history(p, "Subscribestatus", "%s", ast_extension_state2str(firststate));
22114          /* hide the 'complete' exten/context in the refer_to field for later display */
22115          ast_string_field_build(p, subscribeuri, "%s@%s", p->exten, p->context);
22116          /* Deleted the slow iteration of all sip dialogs to find old subscribes from this peer for exten@context */
22117 
22118       }
22119       if (!p->expiry) {
22120          pvt_set_needdestroy(p, "forcing expiration");
22121       }
22122    }
22123    return 1;
22124 }
22125 
22126 /*! \brief Handle incoming REGISTER request */
22127 static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, char *e)
22128 {
22129    enum check_auth_result res;
22130 
22131    /* If this is not the intial request, and the initial request isn't
22132     * a register, something screwy happened, so bail */
22133    if (p->initreq.headers && p->initreq.method != SIP_REGISTER) {
22134       ast_log(LOG_WARNING, "Ignoring spurious REGISTER with Call-ID: %s\n", p->callid);
22135       return -1;
22136    }
22137 
22138    /* Use this as the basis */
22139    copy_request(&p->initreq, req);
22140    if (sipdebug)
22141       ast_debug(4, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
22142    check_via(p, req);
22143    if ((res = register_verify(p, sin, req, e)) < 0) {
22144       const char *reason;
22145 
22146       switch (res) {
22147       case AUTH_SECRET_FAILED:
22148          reason = "Wrong password";
22149          break;
22150       case AUTH_USERNAME_MISMATCH:
22151          reason = "Username/auth name mismatch";
22152          break;
22153       case AUTH_NOT_FOUND:
22154          reason = "No matching peer found";
22155          break;
22156       case AUTH_UNKNOWN_DOMAIN:
22157          reason = "Not a local domain";
22158          break;
22159       case AUTH_PEER_NOT_DYNAMIC:
22160          reason = "Peer is not supposed to register";
22161          break;
22162       case AUTH_ACL_FAILED:
22163          reason = "Device does not match ACL";
22164          break;
22165       case AUTH_BAD_TRANSPORT:
22166          reason = "Device not configured to use this transport type";
22167          break;
22168       default:
22169          reason = "Unknown failure";
22170          break;
22171       }
22172       ast_log(LOG_NOTICE, "Registration from '%s' failed for '%s' - %s\n",
22173          get_header(req, "To"), ast_inet_ntoa(sin->sin_addr),
22174          reason);
22175       append_history(p, "RegRequest", "Failed : Account %s : %s", get_header(req, "To"), reason);
22176    } else {
22177       req->authenticated = 1;
22178       append_history(p, "RegRequest", "Succeeded : Account %s", get_header(req, "To"));
22179    }
22180 
22181    if (res < 1) {
22182       /* Destroy the session, but keep us around for just a bit in case they don't
22183          get our 200 OK */
22184       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
22185    }
22186    return res;
22187 }
22188 
22189 /*!
22190  * \brief Handle incoming SIP requests (methods)
22191  * \note
22192  * This is where all incoming requests go first.
22193  * \note
22194  * called with p and p->owner locked
22195  */
22196 static int handle_incoming(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int *recount, int *nounlock)
22197 {
22198    /* Called with p->lock held, as well as p->owner->lock if appropriate, keeping things
22199       relatively static */
22200    const char *cmd;
22201    const char *cseq;
22202    const char *useragent;
22203    const char *via;
22204    const char *callid;
22205    int via_pos = 0;
22206    int seqno;
22207    int len;
22208    int respid;
22209    int res = 0;
22210    int debug = sip_debug_test_pvt(p);
22211    char *e;
22212    int error = 0;
22213    int oldmethod = p->method;
22214    int acked = 0;
22215 
22216    /* RFC 3261 - 8.1.1 A valid SIP request must contain To, From, CSeq, Call-ID and Via.
22217     * 8.2.6.2 Response must have To, From, Call-ID CSeq, and Via related to the request,
22218     * so we can check to make sure these fields exist for all requests and responses */
22219    cseq = get_header(req, "Cseq");
22220    cmd = REQ_OFFSET_TO_STR(req, header[0]);
22221    /* Save the via_pos so we can check later that responses only have 1 Via header */
22222    via = __get_header(req, "Via", &via_pos);
22223    /* This must exist already because we've called find_call by now */
22224    callid = get_header(req, "Call-ID");
22225 
22226    /* Must have Cseq */
22227    if (ast_strlen_zero(cmd) || ast_strlen_zero(cseq) || ast_strlen_zero(via)) {
22228       ast_log(LOG_ERROR, "Dropping this SIP message with Call-ID '%s', it's incomplete.\n", callid);
22229       error = 1;
22230    }
22231    if (!error && sscanf(cseq, "%30d%n", &seqno, &len) != 1) {
22232       ast_log(LOG_ERROR, "No seqno in '%s'. Dropping incomplete message.\n", cmd);
22233       error = 1;
22234    }
22235    if (error) {
22236       if (!p->initreq.headers) { /* New call */
22237          pvt_set_needdestroy(p, "no headers");
22238       }
22239       return -1;
22240    }
22241    /* Get the command XXX */
22242 
22243    cmd = REQ_OFFSET_TO_STR(req, rlPart1);
22244    e = ast_skip_blanks(REQ_OFFSET_TO_STR(req, rlPart2));
22245 
22246    /* Save useragent of the client */
22247    useragent = get_header(req, "User-Agent");
22248    if (!ast_strlen_zero(useragent))
22249       ast_string_field_set(p, useragent, useragent);
22250 
22251    /* Find out SIP method for incoming request */
22252    if (req->method == SIP_RESPONSE) {  /* Response to our request */
22253       /* ignore means "don't do anything with it" but still have to 
22254        * respond appropriately.
22255        * But in this case this is a response already, so we really
22256        * have nothing to do with this message, and even setting the
22257        * ignore flag is pointless.
22258        */
22259       if (ast_strlen_zero(e)) {
22260          return 0;
22261       }
22262       if (sscanf(e, "%30d %n", &respid, &len) != 1) {
22263          ast_log(LOG_WARNING, "Invalid response: '%s'\n", e);
22264          return 0;
22265       }
22266       if (respid <= 0) {
22267          ast_log(LOG_WARNING, "Invalid SIP response code: '%d'\n", respid);
22268          return 0;
22269       }
22270       /* RFC 3261 - 8.1.3.3 If more than one Via header field value is present in a reponse
22271        * the UAC SHOULD discard the message. This is not perfect, as it will not catch multiple
22272        * headers joined with a comma. Fixing that would pretty much involve writing a new parser */
22273       if (!ast_strlen_zero(__get_header(req, "via", &via_pos))) {
22274          ast_log(LOG_WARNING, "Misrouted SIP response '%s' with Call-ID '%s', too many vias\n", e, callid);
22275          return 0;
22276       }
22277       if (p->ocseq && (p->ocseq < seqno)) {
22278          if (option_debug)
22279             ast_log(LOG_DEBUG, "Ignoring out of order response %d (expecting %d)\n", seqno, p->ocseq);
22280          return -1;
22281       } else {
22282          if ((respid == 200) || ((respid >= 300) && (respid <= 399))) {
22283             extract_uri(p, req);
22284          }
22285          handle_response(p, respid, e + len, req, seqno);
22286       }
22287       return 0;
22288    }
22289 
22290    /* New SIP request coming in 
22291       (could be new request in existing SIP dialog as well...) 
22292     */         
22293    
22294    p->method = req->method;   /* Find out which SIP method they are using */
22295    ast_debug(4, "**** Received %s (%d) - Command in SIP %s\n", sip_methods[p->method].text, sip_methods[p->method].id, cmd); 
22296 
22297    if (p->icseq && (p->icseq > seqno) ) {
22298       if (p->pendinginvite && seqno == p->pendinginvite && (req->method == SIP_ACK || req->method == SIP_CANCEL)) {
22299          ast_debug(2, "Got CANCEL or ACK on INVITE with transactions in between.\n");
22300       }  else {
22301          ast_debug(1, "Ignoring too old SIP packet packet %d (expecting >= %d)\n", seqno, p->icseq);
22302          if (req->method != SIP_ACK)
22303             transmit_response(p, "500 Server error", req);  /* We must respond according to RFC 3261 sec 12.2 */
22304          return -1;
22305       }
22306    } else if (p->icseq &&
22307          p->icseq == seqno &&
22308          req->method != SIP_ACK &&
22309          (p->method != SIP_CANCEL || p->alreadygone)) {
22310       /* ignore means "don't do anything with it" but still have to 
22311          respond appropriately.  We do this if we receive a repeat of
22312          the last sequence number  */
22313       req->ignore = 1;
22314       ast_debug(3, "Ignoring SIP message because of retransmit (%s Seqno %d, ours %d)\n", sip_methods[p->method].text, p->icseq, seqno);
22315    }
22316       
22317    if (seqno >= p->icseq)
22318       /* Next should follow monotonically (but not necessarily 
22319          incrementally -- thanks again to the genius authors of SIP --
22320          increasing */
22321       p->icseq = seqno;
22322 
22323    /* Find their tag if we haven't got it */
22324    if (ast_strlen_zero(p->theirtag)) {
22325       char tag[128];
22326 
22327       gettag(req, "From", tag, sizeof(tag));
22328       ast_string_field_set(p, theirtag, tag);
22329    }
22330    snprintf(p->lastmsg, sizeof(p->lastmsg), "Rx: %s", cmd);
22331 
22332    if (sip_cfg.pedanticsipchecking) {
22333       /* If this is a request packet without a from tag, it's not
22334          correct according to RFC 3261  */
22335       /* Check if this a new request in a new dialog with a totag already attached to it,
22336          RFC 3261 - section 12.2 - and we don't want to mess with recovery  */
22337       if (!p->initreq.headers && req->has_to_tag) {
22338          /* If this is a first request and it got a to-tag, it is not for us */
22339          if (!req->ignore && req->method == SIP_INVITE) {
22340             transmit_response_reliable(p, "481 Call/Transaction Does Not Exist", req);
22341             /* Will cease to exist after ACK */
22342          } else if (req->method != SIP_ACK) {
22343             transmit_response(p, "481 Call/Transaction Does Not Exist", req);
22344             sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
22345          } else {
22346             ast_debug(1, "Got ACK for unknown dialog... strange.\n");
22347          }
22348          return res;
22349       }
22350    }
22351 
22352    if (!e && (p->method == SIP_INVITE || p->method == SIP_SUBSCRIBE || p->method == SIP_REGISTER || p->method == SIP_NOTIFY)) {
22353       transmit_response(p, "400 Bad request", req);
22354       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
22355       return -1;
22356    }
22357 
22358    /* Handle various incoming SIP methods in requests */
22359    switch (p->method) {
22360    case SIP_OPTIONS:
22361       res = handle_request_options(p, req);
22362       break;
22363    case SIP_INVITE:
22364       res = handle_request_invite(p, req, debug, seqno, sin, recount, e, nounlock);
22365       break;
22366    case SIP_REFER:
22367       res = handle_request_refer(p, req, debug, seqno, nounlock);
22368       break;
22369    case SIP_CANCEL:
22370       res = handle_request_cancel(p, req);
22371       break;
22372    case SIP_BYE:
22373       res = handle_request_bye(p, req);
22374       break;
22375    case SIP_MESSAGE:
22376       res = handle_request_message(p, req);
22377       break;
22378    case SIP_SUBSCRIBE:
22379       res = handle_request_subscribe(p, req, sin, seqno, e);
22380       break;
22381    case SIP_REGISTER:
22382       res = handle_request_register(p, req, sin, e);
22383       break;
22384    case SIP_INFO:
22385       if (req->debug)
22386          ast_verbose("Receiving INFO!\n");
22387       if (!req->ignore) 
22388          handle_request_info(p, req);
22389       else  /* if ignoring, transmit response */
22390          transmit_response(p, "200 OK", req);
22391       break;
22392    case SIP_NOTIFY:
22393       res = handle_request_notify(p, req, sin, seqno, e);
22394       break;
22395    case SIP_ACK:
22396       /* Make sure we don't ignore this */
22397       if (seqno == p->pendinginvite) {
22398          p->invitestate = INV_TERMINATED;
22399          p->pendinginvite = 0;
22400          acked = __sip_ack(p, seqno, 1 /* response */, 0);
22401          if (find_sdp(req)) {
22402             if (process_sdp(p, req, SDP_T38_NONE))
22403                return -1;
22404          }
22405          check_pendings(p);
22406       } else if (p->glareinvite == seqno) {
22407          /* handle ack for the 491 pending sent for glareinvite */
22408          p->glareinvite = 0;
22409          acked = __sip_ack(p, seqno, 1, 0);
22410       }
22411       if (!acked) {
22412          /* Got an ACK that did not match anything. Ignore
22413           * silently and restore previous method */
22414          p->method = oldmethod;
22415       }
22416       if (!p->lastinvite && ast_strlen_zero(p->randdata)) {
22417          pvt_set_needdestroy(p, "unmatched ACK");
22418       }
22419       break;
22420    default:
22421       transmit_response_with_allow(p, "501 Method Not Implemented", req, 0);
22422       ast_log(LOG_NOTICE, "Unknown SIP command '%s' from '%s'\n", 
22423          cmd, ast_inet_ntoa(p->sa.sin_addr));
22424       /* If this is some new method, and we don't have a call, destroy it now */
22425       if (!p->initreq.headers) {
22426          pvt_set_needdestroy(p, "unimplemented method");
22427       }
22428       break;
22429    }
22430    return res;
22431 }
22432 
22433 static void process_request_queue(struct sip_pvt *p, int *recount, int *nounlock)
22434 {
22435    struct sip_request *req;
22436 
22437    while ((req = AST_LIST_REMOVE_HEAD(&p->request_queue, next))) {
22438       if (handle_incoming(p, req, &p->recv, recount, nounlock) == -1) {
22439          /* Request failed */
22440          if (option_debug) {
22441             ast_log(LOG_DEBUG, "SIP message could not be handled, bad request: %-70.70s\n", p->callid[0] ? p->callid : "<no callid>");
22442          }
22443       }
22444       ast_free(req);
22445    }
22446 }
22447 
22448 static int scheduler_process_request_queue(const void *data)
22449 {
22450    struct sip_pvt *p = (struct sip_pvt *) data;
22451    int recount = 0;
22452    int nounlock = 0;
22453    int lockretry;
22454 
22455    for (lockretry = 10; lockretry > 0; lockretry--) {
22456       sip_pvt_lock(p);
22457 
22458       /* lock the owner if it has one -- we may need it */
22459       /* because this is deadlock-prone, we need to try and unlock if failed */
22460       if (!p->owner || !ast_channel_trylock(p->owner)) {
22461          break;   /* locking succeeded */
22462       }
22463 
22464       if (lockretry != 1) {
22465          sip_pvt_unlock(p);
22466          /* Sleep for a very short amount of time */
22467          usleep(1);
22468       }
22469    }
22470 
22471    if (!lockretry) {
22472       int retry = !AST_LIST_EMPTY(&p->request_queue);
22473 
22474       /* we couldn't get the owner lock, which is needed to process
22475          the queued requests, so return a non-zero value, which will
22476          cause the scheduler to run this request again later if there
22477          still requests to be processed
22478       */
22479       sip_pvt_unlock(p);
22480       if (!retry) {
22481          dialog_unref(p, "The ref to a dialog passed to this sched callback is going out of scope; unref it.");
22482       }
22483       return retry;
22484    };
22485 
22486    process_request_queue(p, &recount, &nounlock);
22487    p->request_queue_sched_id = -1;
22488 
22489    if (p->owner && !nounlock) {
22490       ast_channel_unlock(p->owner);
22491    }
22492    sip_pvt_unlock(p);
22493 
22494    if (recount) {
22495       ast_update_use_count();
22496    }
22497 
22498    dialog_unref(p, "The ref to a dialog passed to this sched callback is going out of scope; unref it.");
22499 
22500    return 0;
22501 }
22502 
22503 static int queue_request(struct sip_pvt *p, const struct sip_request *req)
22504 {
22505    struct sip_request *newreq;
22506 
22507    if (!(newreq = ast_calloc(1, sizeof(*newreq)))) {
22508       return -1;
22509    }
22510 
22511    copy_request(newreq, req);
22512    AST_LIST_INSERT_TAIL(&p->request_queue, newreq, next);
22513    if (p->request_queue_sched_id == -1) {
22514       if ((p->request_queue_sched_id = ast_sched_add(sched, 10, scheduler_process_request_queue, dialog_ref(p, "Increment refcount to pass dialog pointer to sched callback"))) == -1) {
22515          dialog_unref(p, "Decrement refcount due to sched_add failure");
22516       }
22517    }
22518 
22519    return 0;
22520 }
22521 
22522 /*! \brief Read data from SIP UDP socket
22523 \note sipsock_read locks the owner channel while we are processing the SIP message
22524 \return 1 on error, 0 on success
22525 \note Successful messages is connected to SIP call and forwarded to handle_incoming() 
22526 */
22527 static int sipsock_read(int *id, int fd, short events, void *ignore)
22528 {
22529    struct sip_request req;
22530    struct sockaddr_in sin = { 0, };
22531    int res;
22532    socklen_t len = sizeof(sin);
22533    static char readbuf[65535];
22534 
22535    memset(&req, 0, sizeof(req));
22536    res = recvfrom(fd, readbuf, sizeof(readbuf) - 1, 0, (struct sockaddr *)&sin, &len);
22537    if (res < 0) {
22538 #if !defined(__FreeBSD__)
22539       if (errno == EAGAIN)
22540          ast_log(LOG_NOTICE, "SIP: Received packet with bad UDP checksum\n");
22541       else 
22542 #endif
22543       if (errno != ECONNREFUSED)
22544          ast_log(LOG_WARNING, "Recv error: %s\n", strerror(errno));
22545       return 1;
22546    }
22547 
22548    readbuf[res] = '\0';
22549 
22550    if (!(req.data = ast_str_create(SIP_MIN_PACKET))) {
22551       return 1;
22552    }
22553 
22554    if (ast_str_set(&req.data, 0, "%s", readbuf) == AST_DYNSTR_BUILD_FAILED) {
22555       return -1;
22556    }
22557 
22558    req.len = res;
22559    req.socket.fd = sipsock;
22560    set_socket_transport(&req.socket, SIP_TRANSPORT_UDP);
22561    req.socket.tcptls_session  = NULL;
22562    req.socket.port = bindaddr.sin_port;
22563 
22564    handle_request_do(&req, &sin);
22565    deinit_req(&req);
22566 
22567    return 1;
22568 }
22569 
22570 /*! \brief Handle incoming SIP message - request or response 
22571 
22572    This is used for all transports (udp, tcp and tcp/tls)
22573 */
22574 static int handle_request_do(struct sip_request *req, struct sockaddr_in *sin) 
22575 {
22576    struct sip_pvt *p;
22577    int recount = 0;
22578    int nounlock = 0;
22579    int lockretry;
22580 
22581    if (sip_debug_test_addr(sin)) /* Set the debug flag early on packet level */
22582       req->debug = 1;
22583    if (sip_cfg.pedanticsipchecking)
22584       req->len = lws2sws(req->data->str, req->len);   /* Fix multiline headers */
22585    if (req->debug) {
22586       ast_verbose("\n<--- SIP read from %s:%s:%d --->\n%s\n<------------->\n", 
22587          get_transport(req->socket.type), ast_inet_ntoa(sin->sin_addr), 
22588          ntohs(sin->sin_port), req->data->str);
22589    }
22590 
22591    if (parse_request(req) == -1) { /* Bad packet, can't parse */
22592       ast_str_reset(req->data); /* nulling this out is NOT a good idea here. */
22593       return 1;
22594    }
22595    req->method = find_sip_method(REQ_OFFSET_TO_STR(req, rlPart1));
22596 
22597    if (req->debug)
22598       ast_verbose("--- (%d headers %d lines)%s ---\n", req->headers, req->lines, (req->headers + req->lines == 0) ? " Nat keepalive" : "");
22599 
22600    if (req->headers < 2) { /* Must have at least two headers */
22601       ast_str_reset(req->data); /* nulling this out is NOT a good idea here. */
22602       return 1;
22603    }
22604 
22605    /* Process request, with netlock held, and with usual deadlock avoidance */
22606    for (lockretry = 10; lockretry > 0; lockretry--) {
22607       ast_mutex_lock(&netlock);
22608 
22609       /* Find the active SIP dialog or create a new one */
22610       p = find_call(req, sin, req->method);  /* returns p locked */
22611       if (p == NULL) {
22612          ast_debug(1, "Invalid SIP message - rejected , no callid, len %d\n", req->len);
22613          ast_mutex_unlock(&netlock);
22614          return 1;
22615       }
22616 
22617       copy_socket_data(&p->socket, &req->socket);
22618 
22619       /* Go ahead and lock the owner if it has one -- we may need it */
22620       /* becaues this is deadlock-prone, we need to try and unlock if failed */
22621       if (!p->owner || !ast_channel_trylock(p->owner))
22622          break;   /* locking succeeded */
22623 
22624       if (lockretry != 1) {
22625          sip_pvt_unlock(p);
22626          ao2_t_ref(p, -1, "release p (from find_call) inside lockretry loop"); /* we'll look for it again, but p is dead now */
22627          ast_mutex_unlock(&netlock);
22628          /* Sleep for a very short amount of time */
22629          usleep(1);
22630       }
22631    }
22632    p->recv = *sin;
22633 
22634    /* if we have an owner, then this request has been authenticated */
22635    if (p->owner) {
22636       req->authenticated = 1;
22637    }
22638 
22639    if (p->do_history) /* This is a request or response, note what it was for */
22640       append_history(p, "Rx", "%s / %s / %s", req->data->str, get_header(req, "CSeq"), REQ_OFFSET_TO_STR(req, rlPart2));
22641 
22642    if (!lockretry) {
22643       if (!queue_request(p, req)) {
22644          /* the request has been queued for later handling */
22645          sip_pvt_unlock(p);
22646          ao2_t_ref(p, -1, "release p (from find_call) after queueing request");
22647          ast_mutex_unlock(&netlock);
22648          return 1;
22649       }
22650 
22651       if (p->owner)
22652          ast_log(LOG_ERROR, "Channel lock for %s could not be obtained, and request was unable to be queued.\n", S_OR(p->owner->name, "- no channel name ??? - "));
22653       ast_log(LOG_ERROR, "SIP transaction failed: %s \n", p->callid);
22654       if (req->method != SIP_ACK)
22655          transmit_response(p, "503 Server error", req);  /* We must respond according to RFC 3261 sec 12.2 */
22656       /* XXX We could add retry-after to make sure they come back */
22657       append_history(p, "LockFail", "Owner lock failed, transaction failed.");
22658       sip_pvt_unlock(p);
22659       ao2_t_ref(p, -1, "release p (from find_call) at end of lockretry"); /* p is gone after the return */
22660       ast_mutex_unlock(&netlock);
22661       return 1;
22662    }
22663 
22664    /* if there are queued requests on this sip_pvt, process them first, so that everything is
22665       handled in order
22666    */
22667    if (!AST_LIST_EMPTY(&p->request_queue)) {
22668       AST_SCHED_DEL_UNREF(sched, p->request_queue_sched_id, dialog_unref(p, "when you delete the request_queue_sched_id sched, you should dec the refcount for the stored dialog ptr"));
22669       process_request_queue(p, &recount, &nounlock);
22670    }
22671 
22672    if (handle_incoming(p, req, sin, &recount, &nounlock) == -1) {
22673       /* Request failed */
22674       ast_debug(1, "SIP message could not be handled, bad request: %-70.70s\n", p->callid[0] ? p->callid : "<no callid>");
22675    }
22676       
22677    if (recount)
22678       ast_update_use_count();
22679 
22680    if (p->owner && !nounlock)
22681       ast_channel_unlock(p->owner);
22682    sip_pvt_unlock(p);
22683    ao2_t_ref(p, -1, "throw away dialog ptr from find_call at end of routine"); /* p is gone after the return */
22684    ast_mutex_unlock(&netlock);
22685    return 1;
22686 }
22687 
22688 /*! \brief Returns the port to use for this socket
22689  *
22690  * \param type The type of transport used
22691  * \param port Port we are checking to see if it's the standard port.
22692  * \note port is expected in host byte order
22693  */
22694 static int sip_standard_port(enum sip_transport type, int port)
22695 {
22696    if (type & SIP_TRANSPORT_TLS)
22697       return port == STANDARD_TLS_PORT;
22698    else
22699       return port == STANDARD_SIP_PORT;
22700 }
22701 
22702 static int threadinfo_locate_cb(void *obj, void *arg, int flags)
22703 {
22704    struct sip_threadinfo *th = obj;
22705    struct sockaddr_in *s = arg;
22706 
22707    if (!inaddrcmp(&th->tcptls_session->remote_address, s)) {
22708       return CMP_MATCH | CMP_STOP;
22709    }
22710 
22711    return 0;
22712 }
22713 
22714 /*! 
22715  * \brief Find thread for TCP/TLS session (based on IP/Port 
22716  *
22717  * \note This function returns an astobj2 reference
22718  */
22719 static struct ast_tcptls_session_instance *sip_tcp_locate(struct sockaddr_in *s)
22720 {
22721    struct sip_threadinfo *th;
22722    struct ast_tcptls_session_instance *tcptls_instance = NULL;
22723 
22724    if ((th = ao2_callback(threadt, 0, threadinfo_locate_cb, s))) {
22725       tcptls_instance = (ao2_ref(th->tcptls_session, +1), th->tcptls_session);
22726       ao2_t_ref(th, -1, "decrement ref from callback");
22727    }
22728    return tcptls_instance;
22729 }
22730 
22731 /*! \todo Get socket for dialog, prepare if needed, and return file handle  */
22732 static int sip_prepare_socket(struct sip_pvt *p) 
22733 {
22734    struct sip_socket *s = &p->socket;
22735    static const char name[] = "SIP socket";
22736    struct sip_threadinfo *th = NULL;
22737    struct ast_tcptls_session_instance *tcptls_session;
22738    struct ast_tcptls_session_args tmp_ca = {
22739       .name = name,
22740       .accept_fd = -1,
22741    };
22742    struct ast_tcptls_session_args *ca;
22743 
22744    /* check to see if a socket is already active */
22745    if ((s->fd != -1) && (s->type == SIP_TRANSPORT_UDP)) {
22746       return s->fd;
22747    }
22748    if ((s->type & (SIP_TRANSPORT_TCP | SIP_TRANSPORT_TLS)) &&
22749          (s->tcptls_session) &&
22750          (s->tcptls_session->fd != -1)) {
22751       return s->tcptls_session->fd;
22752    }
22753 
22754    /*! \todo Check this... This might be wrong, depending on the proxy configuration
22755       If proxy is in "force" mode its correct.
22756     */
22757    if (p->outboundproxy && p->outboundproxy->transport) {
22758       s->type = p->outboundproxy->transport;
22759    }
22760 
22761    if (s->type == SIP_TRANSPORT_UDP) {
22762       s->fd = sipsock;
22763       return s->fd;
22764    }
22765 
22766    /* At this point we are dealing with a TCP/TLS connection
22767     * 1. We need to check to see if a connectin thread exists
22768     *    for this address, if so use that.
22769     * 2. If a thread does not exist for this address, but the tcptls_session
22770     *    exists on the socket, the connection was closed.
22771     * 3. If no tcptls_session thread exists for the address, and no tcptls_session
22772     *    already exists on the socket, create a new one and launch a new thread.
22773     */
22774 
22775    /* 1.  check for existing threads */
22776    tmp_ca.remote_address = *(sip_real_dst(p));
22777    if ((tcptls_session = sip_tcp_locate(&tmp_ca.remote_address))) {
22778       s->fd = tcptls_session->fd;
22779       if (s->tcptls_session) {
22780          ao2_ref(s->tcptls_session, -1);
22781          s->tcptls_session = NULL;
22782       }
22783       s->tcptls_session = tcptls_session;
22784       return s->fd;
22785    /* 2.  Thread not found, if tcptls_session already exists, it once had a thread and is now terminated */
22786    } else if (s->tcptls_session) {
22787       return s->fd; /* XXX whether reconnection is ever necessary here needs to be investigated further */
22788    }
22789 
22790    /* 3.  Create a new TCP/TLS client connection */
22791    /* create new session arguments for the client connection */
22792    if (!(ca = ao2_alloc(sizeof(*ca), sip_tcptls_client_args_destructor)) ||
22793       !(ca->name = ast_strdup(name))) {
22794       goto create_tcptls_session_fail;
22795    }
22796    ca->accept_fd = -1;
22797    ca->remote_address = *(sip_real_dst(p));
22798    /* if type is TLS, we need to create a tls cfg for this session arg */
22799    if (s->type == SIP_TRANSPORT_TLS) {
22800       if (!(ca->tls_cfg = ast_calloc(1, sizeof(*ca->tls_cfg)))) {
22801          goto create_tcptls_session_fail;
22802       }
22803       memcpy(ca->tls_cfg, &default_tls_cfg, sizeof(*ca->tls_cfg));
22804 
22805       if (!(ca->tls_cfg->certfile = ast_strdup(default_tls_cfg.certfile)) ||
22806          !(ca->tls_cfg->cipher = ast_strdup(default_tls_cfg.cipher)) ||
22807          !(ca->tls_cfg->cafile = ast_strdup(default_tls_cfg.cafile)) ||
22808          !(ca->tls_cfg->capath = ast_strdup(default_tls_cfg.capath))) {
22809 
22810          goto create_tcptls_session_fail;
22811       }
22812 
22813       /* this host is used as the common name in ssl/tls */
22814       if (!ast_strlen_zero(p->tohost)) {
22815          ast_copy_string(ca->hostname, p->tohost, sizeof(ca->hostname));
22816       }
22817    }
22818    /* Create a client connection for address, this does not start the connection, just sets it up. */
22819    if (!(s->tcptls_session = ast_tcptls_client_create(ca))) {
22820       goto create_tcptls_session_fail;
22821    }
22822 
22823    s->fd = s->tcptls_session->fd;
22824 
22825    /* client connections need to have the sip_threadinfo object created before
22826     * the thread is detached.  This ensures the alert_pipe is up before it will
22827     * be used.  Note that this function links the new threadinfo object into the
22828     * threadt container. */
22829    if (!(th = sip_threadinfo_create(s->tcptls_session, s->type))) {
22830       goto create_tcptls_session_fail;
22831 
22832    }
22833 
22834    /* Give the new thread a reference to the tcptls_session */
22835    ao2_ref(s->tcptls_session, +1);
22836 
22837    if (ast_pthread_create_background(&ca->master, NULL, sip_tcp_worker_fn, s->tcptls_session)) {
22838       ast_debug(1, "Unable to launch '%s'.", ca->name);
22839       ao2_ref(s->tcptls_session, -1); /* take away the thread ref we just gave it */
22840       goto create_tcptls_session_fail;
22841    }
22842 
22843    return s->fd;
22844 
22845 create_tcptls_session_fail:
22846    if (ca) {
22847       ao2_t_ref(ca, -1, "failed to create client, getting rid of client tcptls_session arguments");
22848    }
22849    if (s->tcptls_session) {
22850       close(tcptls_session->fd);
22851       s->fd = tcptls_session->fd = -1;
22852       ao2_ref(s->tcptls_session, -1);
22853       s->tcptls_session = NULL;
22854    }
22855    if (th) {
22856       ao2_t_unlink(threadt, th, "Removing tcptls thread info object, thread failed to open");
22857    }
22858 
22859    return -1;
22860 }
22861 
22862 /*!
22863  * \brief Small function to parse a config line for a host with a transport
22864  *        i.e. tls://www.google.com:8056
22865  */
22866 static int sip_parse_host(char *line, int lineno, char **hostname, int *portnum, enum sip_transport *transport)
22867 {
22868    char *port;
22869 
22870    if ((*hostname = strstr(line, "://"))) {
22871       *hostname += 3;
22872 
22873       if (!strncasecmp(line, "tcp", 3))
22874          *transport = SIP_TRANSPORT_TCP;
22875       else if (!strncasecmp(line, "tls", 3))
22876          *transport = SIP_TRANSPORT_TLS;
22877       else if (!strncasecmp(line, "udp", 3))
22878          *transport = SIP_TRANSPORT_UDP;
22879       else
22880          ast_log(LOG_NOTICE, "'%.3s' is not a valid transport type on line %d of sip.conf. defaulting to udp.\n", line, lineno);
22881    } else {
22882       *hostname = line;
22883       *transport = SIP_TRANSPORT_UDP;
22884    }
22885 
22886    if ((line = strrchr(*hostname, '@')))
22887       line++;
22888    else
22889       line = *hostname;
22890 
22891    if ((port = strrchr(line, ':'))) {
22892       *port++ = '\0';
22893 
22894       if (!sscanf(port, "%5u", portnum)) {
22895          ast_log(LOG_NOTICE, "'%s' is not a valid port number on line %d of sip.conf. using default.\n", port, lineno);
22896          port = NULL;
22897       }
22898    }
22899 
22900    if (!port) {
22901       if (*transport & SIP_TRANSPORT_TLS) {
22902          *portnum = STANDARD_TLS_PORT;
22903       } else {
22904          *portnum = STANDARD_SIP_PORT;
22905       }
22906    }
22907 
22908    return 0;
22909 }
22910 
22911 /*!
22912  * \brief Get cached MWI info
22913  * \retval 0 At least one message is waiting
22914  * \retval 1 no messages waiting
22915  */
22916 static int get_cached_mwi(struct sip_peer *peer, int *new, int *old)
22917 {
22918    struct sip_mailbox *mailbox;
22919 
22920    AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
22921       struct ast_event *event;
22922       event = ast_event_get_cached(AST_EVENT_MWI,
22923          AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, mailbox->mailbox,
22924          AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, S_OR(mailbox->context, "default"),
22925          AST_EVENT_IE_END);
22926       if (!event)
22927          continue;
22928       *new += ast_event_get_ie_uint(event, AST_EVENT_IE_NEWMSGS);
22929       *old += ast_event_get_ie_uint(event, AST_EVENT_IE_OLDMSGS);
22930       ast_event_destroy(event);
22931    }
22932 
22933    return (*new || *old) ? 0 : 1;
22934 }
22935 
22936 /*! \brief Send message waiting indication to alert peer that they've got voicemail */
22937 static int sip_send_mwi_to_peer(struct sip_peer *peer, const struct ast_event *event, int cache_only)
22938 {
22939    /* Called with peerl lock, but releases it */
22940    struct sip_pvt *p;
22941    int newmsgs = 0, oldmsgs = 0;
22942 
22943    if (ast_test_flag((&peer->flags[1]), SIP_PAGE2_SUBSCRIBEMWIONLY) && !peer->mwipvt)
22944       return 0;
22945 
22946    /* Do we have an IP address? If not, skip this peer */
22947    if (!peer->addr.sin_addr.s_addr && !peer->defaddr.sin_addr.s_addr) 
22948       return 0;
22949 
22950    if (event) {
22951       newmsgs = ast_event_get_ie_uint(event, AST_EVENT_IE_NEWMSGS);
22952       oldmsgs = ast_event_get_ie_uint(event, AST_EVENT_IE_OLDMSGS);
22953    } else if (!cache_only) { /* Fall back to manually checking the mailbox */
22954       struct ast_str *mailbox_str = ast_str_alloca(512);
22955       peer_mailboxes_to_str(&mailbox_str, peer);
22956       ast_app_inboxcount(mailbox_str->str, &newmsgs, &oldmsgs);
22957    } else {
22958       get_cached_mwi(peer, &newmsgs, &oldmsgs);
22959    }
22960    
22961    if (peer->mwipvt) {
22962       /* Base message on subscription */
22963       p = dialog_ref(peer->mwipvt, "sip_send_mwi_to_peer: Setting dialog ptr p from peer->mwipvt-- should this be done?");
22964    } else {
22965       /* Build temporary dialog for this message */
22966       if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY, NULL))) 
22967          return -1;
22968       /* If we don't set the socket type to 0, then create_addr_from_peer will fail immediately if the peer
22969        * uses any transport other than UDP. We set the type to 0 here and then let create_addr_from_peer copy 
22970        * the peer's socket information to the sip_pvt we just allocated
22971        */
22972       set_socket_transport(&p->socket, 0);
22973       if (create_addr_from_peer(p, peer)) {
22974          /* Maybe they're not registered, etc. */
22975          dialog_unlink_all(p, TRUE, TRUE);
22976          dialog_unref(p, "unref dialog p just created via sip_alloc");
22977          /* sip_destroy(p); */
22978          return 0;
22979       }
22980       /* Recalculate our side, and recalculate Call ID */
22981       ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
22982       build_via(p);
22983       ao2_t_unlink(dialogs, p, "About to change the callid -- remove the old name");
22984       build_callid_pvt(p);
22985       ao2_t_link(dialogs, p, "Linking in under new name");
22986       /* Destroy this session after 32 secs */
22987       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
22988    }
22989 
22990    /* Send MWI */
22991    ast_set_flag(&p->flags[0], SIP_OUTGOING);
22992    /* the following will decrement the refcount on p as it finishes */
22993    transmit_notify_with_mwi(p, newmsgs, oldmsgs, peer->vmexten);
22994    dialog_unref(p, "unref dialog ptr p just before it goes out of scope at the end of sip_send_mwi_to_peer.");
22995    return 0;
22996 }
22997 
22998 /*! \brief helper function for the monitoring thread -- seems to be called with the assumption that the dialog is locked */
22999 static void check_rtp_timeout(struct sip_pvt *dialog, time_t t)
23000 {
23001    /* If we have no RTP or no active owner, no need to check timers */
23002    if (!dialog->rtp || !dialog->owner)
23003       return;
23004    /* If the call is not in UP state or redirected outside Asterisk, no need to check timers */
23005 
23006    if (dialog->owner->_state != AST_STATE_UP || dialog->redirip.sin_addr.s_addr)
23007       return;
23008 
23009    /* If the call is involved in a T38 fax session do not check RTP timeout */
23010    if (dialog->t38.state == T38_ENABLED)
23011       return;
23012 
23013    /* If we have no timers set, return now */
23014    if ((ast_rtp_get_rtpkeepalive(dialog->rtp) == 0) && (ast_rtp_get_rtptimeout(dialog->rtp) == 0) && (ast_rtp_get_rtpholdtimeout(dialog->rtp) == 0))
23015       return;
23016 
23017    /* Check AUDIO RTP keepalives */
23018    if (dialog->lastrtptx && ast_rtp_get_rtpkeepalive(dialog->rtp) &&
23019           (t > dialog->lastrtptx + ast_rtp_get_rtpkeepalive(dialog->rtp))) {
23020       /* Need to send an empty RTP packet */
23021       dialog->lastrtptx = time(NULL);
23022       ast_rtp_sendcng(dialog->rtp, 0);
23023    }
23024 
23025    /*! \todo Check video RTP keepalives
23026 
23027       Do we need to move the lastrtptx to the RTP structure to have one for audio and one
23028       for video? It really does belong to the RTP structure.
23029    */
23030 
23031    /* Check AUDIO RTP timers */
23032    if (dialog->lastrtprx && (ast_rtp_get_rtptimeout(dialog->rtp) || ast_rtp_get_rtpholdtimeout(dialog->rtp)) &&
23033           (t > dialog->lastrtprx + ast_rtp_get_rtptimeout(dialog->rtp))) {
23034 
23035       /* Might be a timeout now -- see if we're on hold */
23036       struct sockaddr_in sin;
23037       ast_rtp_get_peer(dialog->rtp, &sin);
23038       if (!ast_test_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD) || (ast_rtp_get_rtpholdtimeout(dialog->rtp) &&
23039            (t > dialog->lastrtprx + ast_rtp_get_rtpholdtimeout(dialog->rtp)))) {
23040          /* Needs a hangup */
23041          if (ast_rtp_get_rtptimeout(dialog->rtp)) {
23042             while (dialog->owner && ast_channel_trylock(dialog->owner)) {
23043                sip_pvt_unlock(dialog);
23044                usleep(1);
23045                sip_pvt_lock(dialog);
23046             }
23047             if (!dialog->owner) {
23048                return; /* channel hangup can occur during deadlock avoidance. */
23049             }
23050             ast_log(LOG_NOTICE, "Disconnecting call '%s' for lack of RTP activity in %ld seconds\n",
23051                dialog->owner->name, (long) (t - dialog->lastrtprx));
23052             /* Issue a softhangup */
23053             ast_softhangup_nolock(dialog->owner, AST_SOFTHANGUP_DEV);
23054             ast_channel_unlock(dialog->owner);
23055             /* forget the timeouts for this call, since a hangup
23056                has already been requested and we don't want to
23057                repeatedly request hangups
23058             */
23059             ast_rtp_set_rtptimeout(dialog->rtp, 0);
23060             ast_rtp_set_rtpholdtimeout(dialog->rtp, 0);
23061             if (dialog->vrtp) {
23062                ast_rtp_set_rtptimeout(dialog->vrtp, 0);
23063                ast_rtp_set_rtpholdtimeout(dialog->vrtp, 0);
23064             }
23065          }
23066       }
23067    }
23068 }
23069 
23070 /*! \brief The SIP monitoring thread 
23071 \note This thread monitors all the SIP sessions and peers that needs notification of mwi
23072    (and thus do not have a separate thread) indefinitely 
23073 */
23074 static void *do_monitor(void *data)
23075 {
23076    int res;
23077    time_t t;
23078    int reloading;
23079 
23080    /* Add an I/O event to our SIP UDP socket */
23081    if (sipsock > -1) 
23082       sipsock_read_id = ast_io_add(io, sipsock, sipsock_read, AST_IO_IN, NULL);
23083 
23084    /* From here on out, we die whenever asked */
23085    for(;;) {
23086       /* Check for a reload request */
23087       ast_mutex_lock(&sip_reload_lock);
23088       reloading = sip_reloading;
23089       sip_reloading = FALSE;
23090       ast_mutex_unlock(&sip_reload_lock);
23091       if (reloading) {
23092          ast_verb(1, "Reloading SIP\n");
23093          sip_do_reload(sip_reloadreason);
23094 
23095          /* Change the I/O fd of our UDP socket */
23096          if (sipsock > -1) {
23097             if (sipsock_read_id)
23098                sipsock_read_id = ast_io_change(io, sipsock_read_id, sipsock, NULL, 0, NULL);
23099             else
23100                sipsock_read_id = ast_io_add(io, sipsock, sipsock_read, AST_IO_IN, NULL);
23101          } else if (sipsock_read_id) {
23102             ast_io_remove(io, sipsock_read_id);
23103             sipsock_read_id = NULL;
23104          }
23105       }
23106 
23107       /* Check for dialogs needing to be killed */
23108       t = time(NULL);
23109       /* don't scan the dialogs list if it hasn't been a reasonable period
23110          of time since the last time we did it (when MWI is being sent, we can
23111          get back to this point every millisecond or less)
23112       */
23113       ao2_t_callback(dialogs, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, dialog_needdestroy, &t,
23114             "callback to remove dialogs w/needdestroy");
23115 
23116       /* the old methodology would be to restart the search for dialogs to delete with every 
23117          dialog that was found and destroyed, probably because the list contents would change,
23118          so we'd need to restart. This isn't the best thing to do with callbacks. */
23119 
23120       /* XXX TODO The scheduler usage in this module does not have sufficient 
23121        * synchronization being done between running the scheduler and places 
23122        * scheduling tasks.  As it is written, any scheduled item may not run 
23123        * any sooner than about  1 second, regardless of whether a sooner time 
23124        * was asked for. */
23125 
23126       pthread_testcancel();
23127       /* Wait for sched or io */
23128       res = ast_sched_wait(sched);
23129       if ((res < 0) || (res > 1000))
23130          res = 1000;
23131       res = ast_io_wait(io, res);
23132       if (res > 20)
23133          ast_debug(1, "chan_sip: ast_io_wait ran %d all at once\n", res);
23134       ast_mutex_lock(&monlock);
23135       res = ast_sched_runq(sched);
23136       if (res >= 20)
23137          ast_debug(1, "chan_sip: ast_sched_runq ran %d all at once\n", res);
23138       ast_mutex_unlock(&monlock);
23139    }
23140 
23141    /* Never reached */
23142    return NULL;
23143 }
23144 
23145 /*! \brief Start the channel monitor thread */
23146 static int restart_monitor(void)
23147 {
23148    /* If we're supposed to be stopped -- stay stopped */
23149    if (monitor_thread == AST_PTHREADT_STOP)
23150       return 0;
23151    ast_mutex_lock(&monlock);
23152    if (monitor_thread == pthread_self()) {
23153       ast_mutex_unlock(&monlock);
23154       ast_log(LOG_WARNING, "Cannot kill myself\n");
23155       return -1;
23156    }
23157    if (monitor_thread != AST_PTHREADT_NULL) {
23158       /* Wake up the thread */
23159       pthread_kill(monitor_thread, SIGURG);
23160    } else {
23161       /* Start a new monitor */
23162       if (ast_pthread_create_background(&monitor_thread, NULL, do_monitor, NULL) < 0) {
23163          ast_mutex_unlock(&monlock);
23164          ast_log(LOG_ERROR, "Unable to start monitor thread.\n");
23165          return -1;
23166       }
23167    }
23168    ast_mutex_unlock(&monlock);
23169    return 0;
23170 }
23171 
23172 
23173 /*! \brief Session-Timers: Restart session timer */
23174 static void restart_session_timer(struct sip_pvt *p)
23175 {
23176    if (!p->stimer) {
23177       ast_log(LOG_WARNING, "Null stimer in restart_session_timer - %s\n", p->callid);
23178       return;
23179    }
23180 
23181    if (p->stimer->st_active == TRUE) {
23182       AST_SCHED_DEL_UNREF(sched, p->stimer->st_schedid,
23183             dialog_unref(p, "Removing session timer ref"));
23184       ast_debug(2, "Session timer stopped: %d - %s\n", p->stimer->st_schedid, p->callid);
23185       start_session_timer(p);
23186    }
23187 }
23188 
23189 
23190 /*! \brief Session-Timers: Stop session timer */
23191 static void stop_session_timer(struct sip_pvt *p)
23192 {
23193    if (!p->stimer) {
23194       ast_log(LOG_WARNING, "Null stimer in stop_session_timer - %s\n", p->callid);
23195       return;
23196    }
23197 
23198    if (p->stimer->st_active == TRUE) {
23199       p->stimer->st_active = FALSE;
23200       AST_SCHED_DEL_UNREF(sched, p->stimer->st_schedid,
23201             dialog_unref(p, "removing session timer ref"));
23202       ast_debug(2, "Session timer stopped: %d - %s\n", p->stimer->st_schedid, p->callid);
23203    }
23204 }
23205 
23206 
23207 /*! \brief Session-Timers: Start session timer */
23208 static void start_session_timer(struct sip_pvt *p)
23209 {
23210    if (!p->stimer) {
23211       ast_log(LOG_WARNING, "Null stimer in start_session_timer - %s\n", p->callid);
23212       return;
23213    }
23214 
23215    p->stimer->st_schedid  = ast_sched_add(sched, p->stimer->st_interval * 1000 / 2, proc_session_timer, 
23216          dialog_ref(p, "adding session timer ref"));
23217    if (p->stimer->st_schedid < 0) {
23218       dialog_unref(p, "removing session timer ref");
23219       ast_log(LOG_ERROR, "ast_sched_add failed.\n");
23220    }
23221    ast_debug(2, "Session timer started: %d - %s\n", p->stimer->st_schedid, p->callid);
23222 }
23223 
23224 
23225 /*! \brief Session-Timers: Process session refresh timeout event */
23226 static int proc_session_timer(const void *vp)
23227 {
23228    struct sip_pvt *p = (struct sip_pvt *) vp;
23229    int sendreinv = FALSE;
23230    int res = 0;
23231 
23232    if (!p->stimer) {
23233       ast_log(LOG_WARNING, "Null stimer in proc_session_timer - %s\n", p->callid);
23234       goto return_unref;
23235    }
23236 
23237    ast_debug(2, "Session timer expired: %d - %s\n", p->stimer->st_schedid, p->callid);
23238 
23239    if (!p->owner) {
23240       goto return_unref;
23241    }
23242 
23243    if ((p->stimer->st_active != TRUE) || (p->owner->_state != AST_STATE_UP)) {
23244       goto return_unref;
23245    }
23246 
23247    switch (p->stimer->st_ref) {
23248    case SESSION_TIMER_REFRESHER_UAC:
23249       if (p->outgoing_call == TRUE) {
23250          sendreinv = TRUE;
23251       }
23252       break;
23253    case SESSION_TIMER_REFRESHER_UAS:
23254       if (p->outgoing_call != TRUE) {
23255          sendreinv = TRUE;
23256       }
23257       break;
23258    default:
23259       ast_log(LOG_ERROR, "Unknown session refresher %d\n", p->stimer->st_ref);
23260       goto return_unref;
23261    }
23262 
23263    if (sendreinv == TRUE) {
23264       res = 1;
23265       transmit_reinvite_with_sdp(p, FALSE, TRUE);
23266    } else {
23267       p->stimer->st_expirys++;
23268       if (p->stimer->st_expirys >= 2) {
23269          if (p->stimer->quit_flag) {
23270             goto return_unref;
23271          }
23272          ast_log(LOG_WARNING, "Session-Timer expired - %s\n", p->callid);
23273          sip_pvt_lock(p);
23274          while (p->owner && ast_channel_trylock(p->owner)) {
23275             sip_pvt_unlock(p);
23276             usleep(1);
23277             if (p->stimer && p->stimer->quit_flag) {
23278                goto return_unref;
23279             }
23280             sip_pvt_lock(p);
23281          }
23282 
23283          ast_softhangup_nolock(p->owner, AST_SOFTHANGUP_DEV);
23284          ast_channel_unlock(p->owner);
23285          sip_pvt_unlock(p);
23286       }
23287    }
23288 
23289 return_unref:
23290    if (!res) {
23291       /* An error occurred.  Stop session timer processing */
23292       if (p->stimer) {
23293          p->stimer->st_schedid = -1;
23294          stop_session_timer(p);
23295       }
23296 
23297       /* If we are not asking to be rescheduled, then we need to release our
23298        * reference to the dialog. */
23299       dialog_unref(p, "removing session timer ref");
23300    }
23301 
23302    return res;
23303 }
23304 
23305 
23306 /*! \brief Session-Timers: Function for parsing Min-SE header */
23307 int parse_minse (const char *p_hdrval, int *const p_interval)
23308 {
23309    if (ast_strlen_zero(p_hdrval)) {
23310       ast_log(LOG_WARNING, "Null Min-SE header\n");
23311       return -1;
23312    }
23313 
23314    *p_interval = 0;
23315    p_hdrval = ast_skip_blanks(p_hdrval);
23316    if (!sscanf(p_hdrval, "%30d", p_interval)) {
23317       ast_log(LOG_WARNING, "Parsing of Min-SE header failed %s\n", p_hdrval);
23318       return -1;
23319    }
23320 
23321    ast_debug(2, "Received Min-SE: %d\n", *p_interval);
23322    return 0;
23323 }
23324 
23325 
23326 /*! \brief Session-Timers: Function for parsing Session-Expires header */
23327 int parse_session_expires(const char *p_hdrval, int *const p_interval, enum st_refresher *const p_ref)
23328 {
23329    char *p_token;
23330    int  ref_idx;
23331    char *p_se_hdr;
23332 
23333    if (ast_strlen_zero(p_hdrval)) {
23334       ast_log(LOG_WARNING, "Null Session-Expires header\n");
23335       return -1;
23336    }
23337 
23338    *p_ref = SESSION_TIMER_REFRESHER_AUTO;
23339    *p_interval = 0;
23340 
23341    p_se_hdr = ast_strdupa(p_hdrval);
23342    p_se_hdr = ast_skip_blanks(p_se_hdr);
23343 
23344    while ((p_token = strsep(&p_se_hdr, ";"))) {
23345       p_token = ast_skip_blanks(p_token);
23346       if (!sscanf(p_token, "%30d", p_interval)) {
23347          ast_log(LOG_WARNING, "Parsing of Session-Expires failed\n");
23348          return -1;
23349       }
23350 
23351       ast_debug(2, "Session-Expires: %d\n", *p_interval);
23352 
23353       if (!p_se_hdr)
23354          continue;
23355 
23356       p_se_hdr = ast_skip_blanks(p_se_hdr);
23357       ref_idx = strlen("refresher=");
23358       if (!strncasecmp(p_se_hdr, "refresher=", ref_idx)) {
23359          p_se_hdr += ref_idx;
23360          p_se_hdr = ast_skip_blanks(p_se_hdr);
23361 
23362          if (!strncasecmp(p_se_hdr, "uac", strlen("uac"))) {
23363             *p_ref = SESSION_TIMER_REFRESHER_UAC;
23364             ast_debug(2, "Refresher: UAC\n");
23365          } else if (!strncasecmp(p_se_hdr, "uas", strlen("uas"))) {
23366             *p_ref = SESSION_TIMER_REFRESHER_UAS;
23367             ast_debug(2, "Refresher: UAS\n");
23368          } else {
23369             ast_log(LOG_WARNING, "Invalid refresher value %s\n", p_se_hdr);
23370             return -1;
23371          }
23372          break;
23373       }
23374    }
23375    return 0;
23376 }
23377 
23378 
23379 /*! \brief Handle 422 response to INVITE with session-timer requested
23380 
23381    Session-Timers:   An INVITE originated by Asterisk that asks for session-timers support
23382    from the UAS can result into a 422 response. This is how a UAS or an intermediary proxy 
23383    server tells Asterisk that the session refresh interval offered by Asterisk is too low 
23384    for them.  The proc_422_rsp() function handles a 422 response.  It extracts the Min-SE 
23385    header that comes back in 422 and sends a new INVITE accordingly. */
23386 static void proc_422_rsp(struct sip_pvt *p, struct sip_request *rsp)
23387 {
23388    int rtn;
23389    const char *p_hdrval;
23390    int minse;
23391 
23392    p_hdrval = get_header(rsp, "Min-SE");
23393    if (ast_strlen_zero(p_hdrval)) {
23394       ast_log(LOG_WARNING, "422 response without a Min-SE header %s\n", p_hdrval);
23395       return;
23396    }
23397    rtn = parse_minse(p_hdrval, &minse);
23398    if (rtn != 0) {
23399       ast_log(LOG_WARNING, "Parsing of Min-SE header failed %s\n", p_hdrval);
23400       return;
23401    }
23402    p->stimer->st_interval = minse;
23403    transmit_invite(p, SIP_INVITE, 1, 2); 
23404 }
23405 
23406 
23407 /*! \brief Get Max or Min SE (session timer expiry)
23408  * \param p pointer to the SIP dialog 
23409  * \param max if true, get max se, otherwise min se
23410 */
23411 int st_get_se(struct sip_pvt *p, int max)
23412 {
23413    if (max == TRUE) {
23414       if (p->stimer->st_cached_max_se) {
23415          return p->stimer->st_cached_max_se;
23416       } else if (p->peername) {
23417          struct sip_peer *pp = find_peer(p->peername, NULL, TRUE, FINDPEERS, FALSE, 0);
23418          if (pp) {
23419             p->stimer->st_cached_max_se = pp->stimer.st_max_se;
23420             unref_peer(pp, "unref peer pointer from find_peer call in st_get_se");
23421             return (p->stimer->st_cached_max_se);
23422          }
23423       }
23424       p->stimer->st_cached_max_se = global_max_se;
23425       return (p->stimer->st_cached_max_se);
23426    } else {
23427       if (p->stimer->st_cached_min_se) {
23428          return p->stimer->st_cached_min_se;
23429       } else if (p->peername) {
23430          struct sip_peer *pp = find_peer(p->peername, NULL, TRUE, FINDPEERS, FALSE, 0);
23431          if (pp) {
23432             p->stimer->st_cached_min_se = pp->stimer.st_min_se;
23433             unref_peer(pp, "unref peer pointer from find_peer call in st_get_se (2)");
23434             return (p->stimer->st_cached_min_se);
23435          }
23436       }
23437       p->stimer->st_cached_min_se = global_min_se;
23438       return (p->stimer->st_cached_min_se);
23439    }
23440 }
23441 
23442 
23443 /*! \brief Get the entity (UAC or UAS) that's acting as the session-timer refresher 
23444  * \param p pointer to the SIP dialog 
23445 */
23446 enum st_refresher st_get_refresher(struct sip_pvt *p)
23447 {
23448    if (p->stimer->st_cached_ref != SESSION_TIMER_REFRESHER_AUTO) 
23449       return p->stimer->st_cached_ref;
23450 
23451    if (p->peername) {
23452       struct sip_peer *pp = find_peer(p->peername, NULL, TRUE, FINDPEERS, FALSE, 0);
23453       if (pp) {
23454          p->stimer->st_cached_ref = pp->stimer.st_ref;
23455          unref_peer(pp, "unref peer pointer from find_peer call in st_get_refresher");
23456          return pp->stimer.st_ref;
23457       }
23458    }
23459    
23460    p->stimer->st_cached_ref = global_st_refresher;
23461    return global_st_refresher;
23462 }
23463 
23464 
23465 /*! \brief Get the session-timer mode 
23466  * \param p pointer to the SIP dialog 
23467 */
23468 enum st_mode st_get_mode(struct sip_pvt *p)
23469 {
23470    if (!p->stimer) 
23471       sip_st_alloc(p);
23472 
23473    if (p->stimer->st_cached_mode != SESSION_TIMER_MODE_INVALID) 
23474       return p->stimer->st_cached_mode;
23475 
23476    if (p->peername) {
23477       struct sip_peer *pp = find_peer(p->peername, NULL, TRUE, FINDPEERS, FALSE, 0);
23478       if (pp) {
23479          p->stimer->st_cached_mode = pp->stimer.st_mode_oper;
23480          unref_peer(pp, "unref peer pointer from find_peer call in st_get_mode");
23481          return pp->stimer.st_mode_oper;
23482       }
23483    }
23484 
23485    p->stimer->st_cached_mode = global_st_mode;
23486    return global_st_mode;
23487 }
23488 
23489 
23490 /*! \brief React to lack of answer to Qualify poke */
23491 static int sip_poke_noanswer(const void *data)
23492 {
23493    struct sip_peer *peer = (struct sip_peer *)data;
23494 
23495    peer->pokeexpire = -1;
23496 
23497    if (peer->lastms > -1) {
23498       ast_log(LOG_NOTICE, "Peer '%s' is now UNREACHABLE!  Last qualify: %d\n", peer->name, peer->lastms);
23499       if (sip_cfg.peer_rtupdate) {
23500          ast_update_realtime(ast_check_realtime("sipregs") ? "sipregs" : "sippeers", "name", peer->name, "lastms", "-1", SENTINEL);
23501       }
23502       manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: Unreachable\r\nTime: %d\r\n", peer->name, -1);
23503       if (sip_cfg.regextenonqualify) {
23504          register_peer_exten(peer, FALSE);
23505       }
23506    }
23507 
23508    if (peer->call) {
23509       dialog_unlink_all(peer->call, TRUE, TRUE);
23510       peer->call = dialog_unref(peer->call, "unref dialog peer->call");
23511       /* peer->call = sip_destroy(peer->call);*/
23512    }
23513 
23514    /* Don't send a devstate change if nothing changed. */
23515    if (peer->lastms > -1) {
23516       peer->lastms = -1;
23517       ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", peer->name);
23518    }
23519 
23520    /* Try again quickly */
23521    AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched,
23522          DEFAULT_FREQ_NOTOK, sip_poke_peer_s, peer,
23523          unref_peer(_data, "removing poke peer ref"),
23524          unref_peer(peer, "removing poke peer ref"),
23525          ref_peer(peer, "adding poke peer ref"));
23526 
23527    /* Release the ref held by the running scheduler entry */
23528    unref_peer(peer, "release peer poke noanswer ref");
23529 
23530    return 0;
23531 }
23532 
23533 /*! \brief Check availability of peer, also keep NAT open
23534 \note This is done with 60 seconds between each ping,
23535    unless forced by cli or manager. If peer is unreachable,
23536    we check every 10th second by default. 
23537 */
23538 static int sip_poke_peer(struct sip_peer *peer, int force)
23539 {
23540    struct sip_pvt *p;
23541    int xmitres = 0;
23542    
23543    if ((!peer->maxms && !force) || !peer->addr.sin_addr.s_addr) {
23544       /* IF we have no IP, or this isn't to be monitored, return
23545         immediately after clearing things out */
23546       AST_SCHED_DEL_UNREF(sched, peer->pokeexpire,
23547             unref_peer(peer, "removing poke peer ref"));
23548       
23549       peer->lastms = 0;
23550       if (peer->call) {
23551          peer->call = dialog_unref(peer->call, "unref dialog peer->call");
23552       }
23553       return 0;
23554    }
23555    if (peer->call) {
23556       if (sipdebug) {
23557          ast_log(LOG_NOTICE, "Still have a QUALIFY dialog active, deleting\n");
23558       }
23559       dialog_unlink_all(peer->call, TRUE, TRUE);
23560       peer->call = dialog_unref(peer->call, "unref dialog peer->call");
23561       /* peer->call = sip_destroy(peer->call); */
23562    }
23563    if (!(p = sip_alloc(NULL, NULL, 0, SIP_OPTIONS, NULL))) {
23564       return -1;
23565    }
23566    peer->call = dialog_ref(p, "copy sip alloc from p to peer->call");
23567    
23568    p->sa = peer->addr;
23569    p->recv = peer->addr;
23570    copy_socket_data(&p->socket, &peer->socket);
23571    ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
23572    ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
23573 
23574    /* Send OPTIONs to peer's fullcontact */
23575    if (!ast_strlen_zero(peer->fullcontact))
23576       ast_string_field_set(p, fullcontact, peer->fullcontact);
23577 
23578    if (!ast_strlen_zero(peer->tohost))
23579       ast_string_field_set(p, tohost, peer->tohost);
23580    else
23581       ast_string_field_set(p, tohost, ast_inet_ntoa(peer->addr.sin_addr));
23582 
23583    /* Recalculate our side, and recalculate Call ID */
23584    ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
23585    build_via(p);
23586    ao2_t_unlink(dialogs, p, "About to change the callid -- remove the old name");
23587    build_callid_pvt(p);
23588    ao2_t_link(dialogs, p, "Linking in under new name");
23589 
23590    AST_SCHED_DEL_UNREF(sched, peer->pokeexpire,
23591          unref_peer(peer, "removing poke peer ref"));
23592    
23593    if (p->relatedpeer)
23594       p->relatedpeer = unref_peer(p->relatedpeer,"unsetting the relatedpeer field in the dialog, before it is set to something else.");
23595    p->relatedpeer = ref_peer(peer, "setting the relatedpeer field in the dialog");
23596    ast_set_flag(&p->flags[0], SIP_OUTGOING);
23597 #ifdef VOCAL_DATA_HACK
23598    ast_copy_string(p->username, "__VOCAL_DATA_SHOULD_READ_THE_SIP_SPEC__", sizeof(p->username));
23599    xmitres = transmit_invite(p, SIP_INVITE, 0, 2); /* sinks the p refcount */
23600 #else
23601    xmitres = transmit_invite(p, SIP_OPTIONS, 0, 2); /* sinks the p refcount */
23602 #endif
23603    peer->ps = ast_tvnow();
23604    if (xmitres == XMIT_ERROR) {
23605       sip_poke_noanswer(peer);   /* Immediately unreachable, network problems */
23606    } else if (!force) {
23607       AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched, peer->maxms * 2, sip_poke_noanswer, peer,
23608             unref_peer(_data, "removing poke peer ref"),
23609             unref_peer(peer, "removing poke peer ref"),
23610             ref_peer(peer, "adding poke peer ref"));
23611    }
23612    dialog_unref(p, "unref dialog at end of sip_poke_peer, obtained from sip_alloc, just before it goes out of scope");
23613    return 0;
23614 }
23615 
23616 /*! \brief Part of PBX channel interface
23617 \note
23618 \par  Return values:---
23619 
23620    If we have qualify on and the device is not reachable, regardless of registration
23621    state we return AST_DEVICE_UNAVAILABLE
23622 
23623    For peers with call limit:
23624       - not registered        AST_DEVICE_UNAVAILABLE
23625       - registered, no call         AST_DEVICE_NOT_INUSE
23626       - registered, active calls    AST_DEVICE_INUSE
23627       - registered, call limit reached AST_DEVICE_BUSY
23628       - registered, onhold       AST_DEVICE_ONHOLD
23629       - registered, ringing         AST_DEVICE_RINGING
23630 
23631    For peers without call limit:
23632       - not registered        AST_DEVICE_UNAVAILABLE
23633       - registered            AST_DEVICE_NOT_INUSE
23634       - fixed IP (!dynamic)         AST_DEVICE_NOT_INUSE
23635    
23636    Peers that does not have a known call and can't be reached by OPTIONS
23637       - unreachable           AST_DEVICE_UNAVAILABLE
23638 
23639    If we return AST_DEVICE_UNKNOWN, the device state engine will try to find
23640    out a state by walking the channel list.
23641 
23642    The queue system (\ref app_queue.c) treats a member as "active"
23643    if devicestate is != AST_DEVICE_UNAVAILBALE && != AST_DEVICE_INVALID
23644 
23645    When placing a call to the queue member, queue system sets a member to busy if
23646    != AST_DEVICE_NOT_INUSE and != AST_DEVICE_UNKNOWN
23647 
23648 */
23649 static int sip_devicestate(void *data)
23650 {
23651    char *host;
23652    char *tmp;
23653    struct sip_peer *p;
23654 
23655    int res = AST_DEVICE_INVALID;
23656 
23657    /* make sure data is not null. Maybe unnecessary, but better be safe */
23658    host = ast_strdupa(data ? data : "");
23659    if ((tmp = strchr(host, '@')))
23660       host = tmp + 1;
23661 
23662    ast_debug(3, "Checking device state for peer %s\n", host);
23663 
23664    /* If find_peer asks for a realtime peer, then this breaks rtautoclear.  This
23665     * is because when a peer tries to autoexpire, the last thing it does is to
23666     * queue up an event telling the system that the devicestate has changed
23667     * (presumably to unavailable).  If we ask for a realtime peer here, this would
23668     * load it BACK into memory, thus defeating the point of trying to clear dead
23669     * hosts out of memory.
23670     */
23671    if ((p = find_peer(host, NULL, FALSE, FINDALLDEVICES, TRUE, 0))) {
23672       if (p->addr.sin_addr.s_addr || p->defaddr.sin_addr.s_addr) {
23673          /* we have an address for the peer */
23674       
23675          /* Check status in this order
23676             - Hold
23677             - Ringing
23678             - Busy (enforced only by call limit)
23679             - Inuse (we have a call)
23680             - Unreachable (qualify)
23681             If we don't find any of these state, report AST_DEVICE_NOT_INUSE
23682             for registered devices */
23683 
23684          if (p->onHold)
23685             /* First check for hold or ring states */
23686             res = AST_DEVICE_ONHOLD;
23687          else if (p->inRinging) {
23688             if (p->inRinging == p->inUse)
23689                res = AST_DEVICE_RINGING;
23690             else
23691                res = AST_DEVICE_RINGINUSE;
23692          } else if (p->call_limit && (p->inUse == p->call_limit))
23693             /* check call limit */
23694             res = AST_DEVICE_BUSY;
23695          else if (p->call_limit && p->busy_level && p->inUse >= p->busy_level)
23696             /* We're forcing busy before we've reached the call limit */
23697             res = AST_DEVICE_BUSY;
23698          else if (p->call_limit && p->inUse)
23699             /* Not busy, but we do have a call */
23700             res = AST_DEVICE_INUSE;
23701          else if (p->maxms && ((p->lastms > p->maxms) || (p->lastms < 0))) 
23702             /* We don't have a call. Are we reachable at all? Requires qualify= */
23703             res = AST_DEVICE_UNAVAILABLE;
23704          else  /* Default reply if we're registered and have no other data */
23705             res = AST_DEVICE_NOT_INUSE;
23706       } else {
23707          /* there is no address, it's unavailable */
23708          res = AST_DEVICE_UNAVAILABLE;
23709       }
23710       unref_peer(p, "unref_peer, from sip_devicestate, release ref from find_peer");
23711    } else {
23712       res = AST_DEVICE_UNKNOWN;
23713    }
23714 
23715    return res;
23716 }
23717 
23718 /*! \brief PBX interface function -build SIP pvt structure 
23719  * SIP calls initiated by the PBX arrive here. 
23720  *
23721  * \verbatim   
23722  *    SIP Dial string syntax
23723  *    SIP/exten@host!dnid
23724  * or SIP/host/exten!dnid
23725  * or SIP/host!dnid
23726  * \endverbatim
23727 */
23728 static struct ast_channel *sip_request_call(const char *type, int format, void *data, int *cause)
23729 {
23730    struct sip_pvt *p;
23731    struct ast_channel *tmpc = NULL;
23732    char *ext = NULL, *host;
23733    char tmp[256];
23734    char *dest = data;
23735    char *dnid;
23736    char *secret = NULL;
23737    char *md5secret = NULL;
23738    char *authname = NULL;
23739    char *trans = NULL;
23740    enum sip_transport transport = 0;
23741    int oldformat = format;
23742 
23743    /* mask request with some set of allowed formats.
23744     * XXX this needs to be fixed.
23745     * The original code uses AST_FORMAT_AUDIO_MASK, but it is
23746     * unclear what to use here. We have global_capabilities, which is
23747     * configured from sip.conf, and sip_tech.capabilities, which is
23748     * hardwired to all audio formats.
23749     */
23750    format &= AST_FORMAT_AUDIO_MASK;
23751    if (!format) {
23752       ast_log(LOG_NOTICE, "Asked to get a channel of unsupported format %s while capability is %s\n", ast_getformatname(oldformat), ast_getformatname(global_capability));
23753       *cause = AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;   /* Can't find codec to connect to host */
23754       return NULL;
23755    }
23756    ast_debug(1, "Asked to create a SIP channel with formats: %s\n", ast_getformatname_multiple(tmp, sizeof(tmp), oldformat));
23757 
23758    if (ast_strlen_zero(dest)) {
23759       ast_log(LOG_ERROR, "Unable to create channel with empty destination.\n");
23760       *cause = AST_CAUSE_CHANNEL_UNACCEPTABLE;
23761       return NULL;
23762    }
23763 
23764    if (!(p = sip_alloc(NULL, NULL, 0, SIP_INVITE, NULL))) {
23765       ast_log(LOG_ERROR, "Unable to build sip pvt data for '%s' (Out of memory or socket error)\n", dest);
23766       *cause = AST_CAUSE_SWITCH_CONGESTION;
23767       return NULL;
23768    }
23769 
23770    p->outgoing_call = TRUE;
23771 
23772    if (!(p->options = ast_calloc(1, sizeof(*p->options)))) {
23773       dialog_unlink_all(p, TRUE, TRUE);
23774       dialog_unref(p, "unref dialog p from mem fail");
23775       /* sip_destroy(p); */
23776       ast_log(LOG_ERROR, "Unable to build option SIP data structure - Out of memory\n");
23777       *cause = AST_CAUSE_SWITCH_CONGESTION;
23778       return NULL;
23779    }
23780 
23781    /* Save the destination, the SIP dial string */
23782    ast_copy_string(tmp, dest, sizeof(tmp));
23783 
23784 
23785    /* Find DNID and take it away */
23786    dnid = strchr(tmp, '!');
23787    if (dnid != NULL) {
23788       *dnid++ = '\0';
23789       ast_string_field_set(p, todnid, dnid);
23790    }
23791 
23792    /* Find at sign - @ */
23793    host = strchr(tmp, '@');
23794    if (host) {
23795       *host++ = '\0';
23796       ext = tmp;
23797       secret = strchr(ext, ':');
23798    }
23799    if (secret) {
23800       *secret++ = '\0';
23801       md5secret = strchr(secret, ':');
23802    }
23803    if (md5secret) {
23804       *md5secret++ = '\0';
23805       authname = strchr(md5secret, ':');
23806    }
23807    if (authname) {
23808       *authname++ = '\0';
23809       trans = strchr(authname, ':');
23810    }
23811    if (trans) {
23812       *trans++ = '\0';
23813       if (!strcasecmp(trans, "tcp"))
23814          transport = SIP_TRANSPORT_TCP;
23815       else if (!strcasecmp(trans, "tls"))
23816          transport = SIP_TRANSPORT_TLS;
23817       else {
23818          if (strcasecmp(trans, "udp"))
23819             ast_log(LOG_WARNING, "'%s' is not a valid transport option to Dial() for SIP calls, using udp by default.\n", trans);
23820          transport = SIP_TRANSPORT_UDP;
23821       }
23822    } else { /* use default */
23823       transport = SIP_TRANSPORT_UDP;
23824    }
23825 
23826    if (!host) {
23827       ext = strchr(tmp, '/');
23828       if (ext) 
23829          *ext++ = '\0';
23830       host = tmp;
23831    }
23832 
23833    set_socket_transport(&p->socket, transport);
23834 
23835    /* We now have 
23836       host = peer name, DNS host name or DNS domain (for SRV) 
23837       ext = extension (user part of URI)
23838       dnid = destination of the call (applies to the To: header)
23839    */
23840    if (create_addr(p, host, NULL, 1)) {
23841       *cause = AST_CAUSE_UNREGISTERED;
23842       ast_debug(3, "Cant create SIP call - target device not registered\n");
23843       dialog_unlink_all(p, TRUE, TRUE);
23844       dialog_unref(p, "unref dialog p UNREGISTERED");
23845       /* sip_destroy(p); */
23846       return NULL;
23847    }
23848    if (ast_strlen_zero(p->peername) && ext)
23849       ast_string_field_set(p, peername, ext);
23850    /* Recalculate our side, and recalculate Call ID */
23851    ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
23852    build_via(p);
23853    ao2_t_unlink(dialogs, p, "About to change the callid -- remove the old name");
23854    build_callid_pvt(p);
23855    ao2_t_link(dialogs, p, "Linking in under new name");
23856    
23857    /* We have an extension to call, don't use the full contact here */
23858    /* This to enable dialing registered peers with extension dialling,
23859       like SIP/peername/extension   
23860       SIP/peername will still use the full contact 
23861     */
23862    if (ext) {
23863       ast_string_field_set(p, username, ext);
23864       ast_string_field_set(p, fullcontact, NULL);
23865    }
23866    if (secret && !ast_strlen_zero(secret))
23867       ast_string_field_set(p, peersecret, secret);
23868 
23869    if (md5secret && !ast_strlen_zero(md5secret))
23870       ast_string_field_set(p, peermd5secret, md5secret);
23871 
23872    if (authname && !ast_strlen_zero(authname))
23873       ast_string_field_set(p, authname, authname);
23874 #if 0
23875    printf("Setting up to call extension '%s' at '%s'\n", ext ? ext : "<none>", host);
23876 #endif
23877    p->prefcodec = oldformat;           /* Format for this call */
23878    p->jointcapability = oldformat & p->capability;
23879    sip_pvt_lock(p);
23880    tmpc = sip_new(p, AST_STATE_DOWN, host);  /* Place the call */
23881    if (sip_cfg.callevents)
23882       manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
23883          "Channel: %s\r\nChanneltype: %s\r\nSIPcallid: %s\r\nSIPfullcontact: %s\r\nPeername: %s\r\n",
23884          p->owner? p->owner->name : "", "SIP", p->callid, p->fullcontact, p->peername);
23885    sip_pvt_unlock(p);
23886    if (!tmpc) {
23887       dialog_unlink_all(p, TRUE, TRUE);
23888       /* sip_destroy(p); */
23889    }
23890    dialog_unref(p, "toss pvt ptr at end of sip_request_call");
23891    ast_update_use_count();
23892    restart_monitor();
23893    return tmpc;
23894 }
23895 
23896 /*! \brief Parse insecure= setting in sip.conf and set flags according to setting */
23897 static void set_insecure_flags (struct ast_flags *flags, const char *value, int lineno)
23898 {
23899    if (ast_strlen_zero(value))
23900       return;
23901 
23902    if (!ast_false(value)) {
23903       char buf[64];
23904       char *word, *next;
23905 
23906       ast_copy_string(buf, value, sizeof(buf));
23907       next = buf;
23908       while ((word = strsep(&next, ","))) {
23909          if (!strcasecmp(word, "port"))
23910             ast_set_flag(&flags[0], SIP_INSECURE_PORT);
23911          else if (!strcasecmp(word, "invite"))
23912             ast_set_flag(&flags[0], SIP_INSECURE_INVITE);
23913          else
23914             ast_log(LOG_WARNING, "Unknown insecure mode '%s' on line %d\n", value, lineno);
23915       }
23916    }
23917 }
23918 
23919 /*!
23920   \brief Handle T.38 configuration options common to users and peers
23921   \returns non-zero if any config options were handled, zero otherwise
23922 */
23923 static int handle_t38_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v,
23924                int *maxdatagram)
23925 {
23926    int res = 1;
23927 
23928    if (!strcasecmp(v->name, "t38pt_udptl")) {
23929       char *buf = ast_strdupa(v->value);
23930       char *word, *next = buf;
23931 
23932       ast_set_flag(&mask[1], SIP_PAGE2_T38SUPPORT);
23933 
23934       while ((word = strsep(&next, ","))) {
23935          if (ast_true(word) || !strcasecmp(word, "fec")) {
23936             ast_clear_flag(&flags[1], SIP_PAGE2_T38SUPPORT);
23937             ast_set_flag(&flags[1], SIP_PAGE2_T38SUPPORT_UDPTL_FEC);
23938          } else if (!strcasecmp(word, "redundancy")) {
23939             ast_clear_flag(&flags[1], SIP_PAGE2_T38SUPPORT);
23940             ast_set_flag(&flags[1], SIP_PAGE2_T38SUPPORT_UDPTL_REDUNDANCY);
23941          } else if (!strcasecmp(word, "none")) {
23942             ast_clear_flag(&flags[1], SIP_PAGE2_T38SUPPORT);
23943             ast_set_flag(&flags[1], SIP_PAGE2_T38SUPPORT_UDPTL);
23944          } else if (!strncasecmp(word, "maxdatagram=", 12)) {
23945             if (sscanf(&word[12], "%30u", maxdatagram) != 1) {
23946                ast_log(LOG_WARNING, "Invalid maxdatagram '%s' at line %d of %s\n", v->value, v->lineno, config);
23947                *maxdatagram = global_t38_maxdatagram;
23948             }
23949          }
23950       }
23951    } else if (!strcasecmp(v->name, "t38pt_usertpsource")) {
23952       ast_set_flag(&mask[1], SIP_PAGE2_UDPTL_DESTINATION);
23953       ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_UDPTL_DESTINATION);
23954    } else if (!strcasecmp(v->name, "forwardloopdetected")) {
23955       ast_set_flag(&mask[1], SIP_PAGE2_FORWARD_LOOP_DETECTED);
23956       ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_FORWARD_LOOP_DETECTED);
23957    } else {
23958       res = 0;
23959    }
23960 
23961    return res;
23962 }
23963 
23964 /*!
23965   \brief Handle flag-type options common to configuration of devices - peers
23966   \param flags array of two struct ast_flags
23967   \param mask array of two struct ast_flags
23968   \param v linked list of config variables to process
23969   \returns non-zero if any config options were handled, zero otherwise
23970 */
23971 static int handle_common_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v)
23972 {
23973    int res = 1;
23974 
23975    if (!strcasecmp(v->name, "trustrpid")) {
23976       ast_set_flag(&mask[0], SIP_TRUSTRPID);
23977       ast_set2_flag(&flags[0], ast_true(v->value), SIP_TRUSTRPID);
23978    } else if (!strcasecmp(v->name, "sendrpid")) {
23979       ast_set_flag(&mask[0], SIP_SENDRPID);
23980       ast_set2_flag(&flags[0], ast_true(v->value), SIP_SENDRPID);
23981    } else if (!strcasecmp(v->name, "g726nonstandard")) {
23982       ast_set_flag(&mask[0], SIP_G726_NONSTANDARD);
23983       ast_set2_flag(&flags[0], ast_true(v->value), SIP_G726_NONSTANDARD);
23984    } else if (!strcasecmp(v->name, "useclientcode")) {
23985       ast_set_flag(&mask[0], SIP_USECLIENTCODE);
23986       ast_set2_flag(&flags[0], ast_true(v->value), SIP_USECLIENTCODE);
23987    } else if (!strcasecmp(v->name, "dtmfmode")) {
23988       ast_set_flag(&mask[0], SIP_DTMF);
23989       ast_clear_flag(&flags[0], SIP_DTMF);
23990       if (!strcasecmp(v->value, "inband"))
23991          ast_set_flag(&flags[0], SIP_DTMF_INBAND);
23992       else if (!strcasecmp(v->value, "rfc2833"))
23993          ast_set_flag(&flags[0], SIP_DTMF_RFC2833);
23994       else if (!strcasecmp(v->value, "info"))
23995          ast_set_flag(&flags[0], SIP_DTMF_INFO);
23996       else if (!strcasecmp(v->value, "shortinfo"))
23997          ast_set_flag(&flags[0], SIP_DTMF_SHORTINFO);
23998       else if (!strcasecmp(v->value, "auto"))
23999          ast_set_flag(&flags[0], SIP_DTMF_AUTO);
24000       else {
24001          ast_log(LOG_WARNING, "Unknown dtmf mode '%s' on line %d, using rfc2833\n", v->value, v->lineno);
24002          ast_set_flag(&flags[0], SIP_DTMF_RFC2833);
24003       }
24004    } else if (!strcasecmp(v->name, "nat")) {
24005       ast_set_flag(&mask[0], SIP_NAT);
24006       ast_clear_flag(&flags[0], SIP_NAT);
24007       if (!strcasecmp(v->value, "never"))
24008          ast_set_flag(&flags[0], SIP_NAT_NEVER);
24009       else if (!strcasecmp(v->value, "route"))
24010          ast_set_flag(&flags[0], SIP_NAT_ROUTE);
24011       else if (ast_true(v->value))
24012          ast_set_flag(&flags[0], SIP_NAT_ALWAYS);
24013       else
24014          ast_set_flag(&flags[0], SIP_NAT_RFC3581);
24015    } else if (!strcasecmp(v->name, "directmedia") || !strcasecmp(v->name, "canreinvite")) {
24016       ast_set_flag(&mask[0], SIP_REINVITE);
24017       ast_clear_flag(&flags[0], SIP_REINVITE);
24018       if (ast_true(v->value)) {
24019          ast_set_flag(&flags[0], SIP_DIRECT_MEDIA | SIP_DIRECT_MEDIA_NAT);
24020       } else if (!ast_false(v->value)) {
24021          char buf[64];
24022          char *word, *next = buf;
24023 
24024          ast_copy_string(buf, v->value, sizeof(buf));
24025          while ((word = strsep(&next, ","))) {
24026             if (!strcasecmp(word, "update")) {
24027                ast_set_flag(&flags[0], SIP_REINVITE_UPDATE | SIP_DIRECT_MEDIA);
24028             } else if (!strcasecmp(word, "nonat")) {
24029                ast_set_flag(&flags[0], SIP_DIRECT_MEDIA);
24030                ast_clear_flag(&flags[0], SIP_DIRECT_MEDIA_NAT);
24031             } else {
24032                ast_log(LOG_WARNING, "Unknown directmedia mode '%s' on line %d\n", v->value, v->lineno);
24033             }
24034          }
24035       }
24036    } else if (!strcasecmp(v->name, "insecure")) {
24037       ast_set_flag(&mask[0], SIP_INSECURE);
24038       ast_clear_flag(&flags[0], SIP_INSECURE);
24039       set_insecure_flags(&flags[0], v->value, v->lineno);   
24040    } else if (!strcasecmp(v->name, "progressinband")) {
24041       ast_set_flag(&mask[0], SIP_PROG_INBAND);
24042       ast_clear_flag(&flags[0], SIP_PROG_INBAND);
24043       if (ast_true(v->value))
24044          ast_set_flag(&flags[0], SIP_PROG_INBAND_YES);
24045       else if (strcasecmp(v->value, "never"))
24046          ast_set_flag(&flags[0], SIP_PROG_INBAND_NO);
24047    } else if (!strcasecmp(v->name, "promiscredir")) {
24048       ast_set_flag(&mask[0], SIP_PROMISCREDIR);
24049       ast_set2_flag(&flags[0], ast_true(v->value), SIP_PROMISCREDIR);
24050    } else if (!strcasecmp(v->name, "videosupport")) {
24051       if (!strcasecmp(v->value, "always")) {
24052          ast_set_flag(&mask[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS);
24053          ast_set_flag(&flags[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS);
24054       } else {
24055          ast_set_flag(&mask[1], SIP_PAGE2_VIDEOSUPPORT);
24056          ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_VIDEOSUPPORT);
24057       }
24058    } else if (!strcasecmp(v->name, "textsupport")) {
24059       ast_set_flag(&mask[1], SIP_PAGE2_TEXTSUPPORT);
24060       ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_TEXTSUPPORT);
24061       res = 1;
24062    } else if (!strcasecmp(v->name, "allowoverlap")) {
24063       ast_set_flag(&mask[1], SIP_PAGE2_ALLOWOVERLAP);
24064       ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_ALLOWOVERLAP);
24065    } else if (!strcasecmp(v->name, "allowsubscribe")) {
24066       ast_set_flag(&mask[1], SIP_PAGE2_ALLOWSUBSCRIBE);
24067       ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_ALLOWSUBSCRIBE);
24068    } else if (!strcasecmp(v->name, "ignoresdpversion")) {
24069       ast_set_flag(&mask[1], SIP_PAGE2_IGNORESDPVERSION);
24070       ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_IGNORESDPVERSION);
24071    } else if (!strcasecmp(v->name, "faxdetect")) {
24072       ast_set_flag(&mask[1], SIP_PAGE2_FAX_DETECT);
24073       if (ast_true(v->value)) {
24074          ast_set_flag(&flags[1], SIP_PAGE2_FAX_DETECT_BOTH);
24075       } else if (ast_false(v->value)) {
24076          ast_clear_flag(&flags[1], SIP_PAGE2_FAX_DETECT_BOTH);
24077       } else {
24078          char *buf = ast_strdupa(v->value);
24079          char *word, *next = buf;
24080 
24081          while ((word = strsep(&next, ","))) {
24082             if (!strcasecmp(word, "cng")) {
24083                ast_set_flag(&flags[1], SIP_PAGE2_FAX_DETECT_CNG);
24084             } else if (!strcasecmp(word, "t38")) {
24085                ast_set_flag(&flags[1], SIP_PAGE2_FAX_DETECT_T38);
24086             } else {
24087                ast_log(LOG_WARNING, "Unknown faxdetect mode '%s' on line %d.\n", word, v->lineno);
24088             }
24089          }
24090       }
24091    } else if (!strcasecmp(v->name, "rfc2833compensate")) {
24092       ast_set_flag(&mask[1], SIP_PAGE2_RFC2833_COMPENSATE);
24093       ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_RFC2833_COMPENSATE);
24094    } else if (!strcasecmp(v->name, "buggymwi")) {
24095       ast_set_flag(&mask[1], SIP_PAGE2_BUGGY_MWI);
24096       ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_BUGGY_MWI);
24097    } else
24098       res = 0;
24099 
24100    return res;
24101 }
24102 
24103 /*! \brief Add SIP domain to list of domains we are responsible for */
24104 static int add_sip_domain(const char *domain, const enum domain_mode mode, const char *context)
24105 {
24106    struct domain *d;
24107 
24108    if (ast_strlen_zero(domain)) {
24109       ast_log(LOG_WARNING, "Zero length domain.\n");
24110       return 1;
24111    }
24112 
24113    if (!(d = ast_calloc(1, sizeof(*d))))
24114       return 0;
24115 
24116    ast_copy_string(d->domain, domain, sizeof(d->domain));
24117 
24118    if (!ast_strlen_zero(context))
24119       ast_copy_string(d->context, context, sizeof(d->context));
24120 
24121    d->mode = mode;
24122 
24123    AST_LIST_LOCK(&domain_list);
24124    AST_LIST_INSERT_TAIL(&domain_list, d, list);
24125    AST_LIST_UNLOCK(&domain_list);
24126 
24127    if (sipdebug)  
24128       ast_debug(1, "Added local SIP domain '%s'\n", domain);
24129 
24130    return 1;
24131 }
24132 
24133 /*! \brief  check_sip_domain: Check if domain part of uri is local to our server */
24134 static int check_sip_domain(const char *domain, char *context, size_t len)
24135 {
24136    struct domain *d;
24137    int result = 0;
24138 
24139    AST_LIST_LOCK(&domain_list);
24140    AST_LIST_TRAVERSE(&domain_list, d, list) {
24141       if (strcasecmp(d->domain, domain))
24142          continue;
24143 
24144       if (len && !ast_strlen_zero(d->context))
24145          ast_copy_string(context, d->context, len);
24146       
24147       result = 1;
24148       break;
24149    }
24150    AST_LIST_UNLOCK(&domain_list);
24151 
24152    return result;
24153 }
24154 
24155 /*! \brief Clear our domain list (at reload) */
24156 static void clear_sip_domains(void)
24157 {
24158    struct domain *d;
24159 
24160    AST_LIST_LOCK(&domain_list);
24161    while ((d = AST_LIST_REMOVE_HEAD(&domain_list, list)))
24162       ast_free(d);
24163    AST_LIST_UNLOCK(&domain_list);
24164 }
24165 
24166 
24167 /*! \brief Add realm authentication in list */
24168 static struct sip_auth *add_realm_authentication(struct sip_auth *authlist, const char *configuration, int lineno)
24169 {
24170    char authcopy[256];
24171    char *username=NULL, *realm=NULL, *secret=NULL, *md5secret=NULL;
24172    struct sip_auth *a, *b, *auth;
24173 
24174    if (ast_strlen_zero(configuration))
24175       return authlist;
24176 
24177    ast_debug(1, "Auth config ::  %s\n", configuration);
24178 
24179    ast_copy_string(authcopy, configuration, sizeof(authcopy));
24180    username = authcopy;
24181 
24182    /* split user[:secret] and relm */
24183    realm = strrchr(username, '@');
24184    if (realm)
24185       *realm++ = '\0';
24186    if (ast_strlen_zero(username) || ast_strlen_zero(realm)) {
24187       ast_log(LOG_WARNING, "Format for authentication entry is user[:secret]@realm at line %d\n", lineno);
24188       return authlist;
24189    }
24190 
24191    /* parse username at ':' for secret, or '#" for md5secret */
24192    if ((secret = strchr(username, ':'))) {
24193       *secret++ = '\0';
24194    } else if ((md5secret = strchr(username, '#'))) {
24195       *md5secret++ = '\0';
24196    }
24197 
24198    if (!(auth = ast_calloc(1, sizeof(*auth))))
24199       return authlist;
24200 
24201    ast_copy_string(auth->realm, realm, sizeof(auth->realm));
24202    ast_copy_string(auth->username, username, sizeof(auth->username));
24203    if (secret)
24204       ast_copy_string(auth->secret, secret, sizeof(auth->secret));
24205    if (md5secret)
24206       ast_copy_string(auth->md5secret, md5secret, sizeof(auth->md5secret));
24207 
24208    /* find the end of the list */
24209    for (b = NULL, a = authlist; a ; b = a, a = a->next)
24210       ;
24211    if (b)
24212       b->next = auth;   /* Add structure add end of list */
24213    else
24214       authlist = auth;
24215 
24216    ast_verb(3, "Added authentication for realm %s\n", realm);
24217 
24218    return authlist;
24219 
24220 }
24221 
24222 /*! \brief Clear realm authentication list (at reload) */
24223 static int clear_realm_authentication(struct sip_auth *authlist)
24224 {
24225    struct sip_auth *a = authlist;
24226    struct sip_auth *b;
24227 
24228    while (a) {
24229       b = a;
24230       a = a->next;
24231       ast_free(b);
24232    }
24233 
24234    return 1;
24235 }
24236 
24237 /*! \brief Find authentication for a specific realm */
24238 static struct sip_auth *find_realm_authentication(struct sip_auth *authlist, const char *realm)
24239 {
24240    struct sip_auth *a;
24241 
24242    for (a = authlist; a; a = a->next) {
24243       if (!strcasecmp(a->realm, realm))
24244          break;
24245    }
24246 
24247    return a;
24248 }
24249 
24250 /*! \brief
24251  * implement the setvar config line
24252  */
24253 static struct ast_variable *add_var(const char *buf, struct ast_variable *list)
24254 {
24255    struct ast_variable *tmpvar = NULL;
24256    char *varname = ast_strdupa(buf), *varval = NULL;
24257    
24258    if ((varval = strchr(varname, '='))) {
24259       *varval++ = '\0';
24260       if ((tmpvar = ast_variable_new(varname, varval, ""))) {
24261          tmpvar->next = list;
24262          list = tmpvar;
24263       }
24264    }
24265    return list;
24266 }
24267 
24268 /*! \brief Set peer defaults before configuring specific configurations */
24269 static void set_peer_defaults(struct sip_peer *peer)
24270 {
24271    if (peer->expire == 0) {
24272       /* Don't reset expire or port time during reload 
24273          if we have an active registration 
24274       */
24275       peer->expire = -1;
24276       peer->pokeexpire = -1;
24277       peer->addr.sin_port = htons(STANDARD_SIP_PORT);
24278       set_socket_transport(&peer->socket, SIP_TRANSPORT_UDP);
24279    }
24280    peer->type = SIP_TYPE_PEER;
24281    ast_copy_flags(&peer->flags[0], &global_flags[0], SIP_FLAGS_TO_COPY);
24282    ast_copy_flags(&peer->flags[1], &global_flags[1], SIP_PAGE2_FLAGS_TO_COPY);
24283    ast_string_field_set(peer, context, sip_cfg.default_context);
24284    ast_string_field_set(peer, subscribecontext, sip_cfg.default_subscribecontext);
24285    ast_string_field_set(peer, language, default_language);
24286    ast_string_field_set(peer, mohinterpret, default_mohinterpret);
24287    ast_string_field_set(peer, mohsuggest, default_mohsuggest);
24288    peer->addr.sin_family = AF_INET;
24289    peer->defaddr.sin_family = AF_INET;
24290    peer->capability = global_capability;
24291    peer->maxcallbitrate = default_maxcallbitrate;
24292    peer->rtptimeout = global_rtptimeout;
24293    peer->rtpholdtimeout = global_rtpholdtimeout;
24294    peer->rtpkeepalive = global_rtpkeepalive;
24295    peer->allowtransfer = sip_cfg.allowtransfer;
24296    peer->autoframing = global_autoframing;
24297    peer->t38_maxdatagram = global_t38_maxdatagram;
24298    peer->qualifyfreq = global_qualifyfreq;
24299    if (global_callcounter)
24300       peer->call_limit=INT_MAX;
24301    ast_string_field_set(peer, vmexten, default_vmexten);
24302    ast_string_field_set(peer, secret, "");
24303    ast_string_field_set(peer, remotesecret, "");
24304    ast_string_field_set(peer, md5secret, "");
24305    ast_string_field_set(peer, cid_num, "");
24306    ast_string_field_set(peer, cid_name, "");
24307    ast_string_field_set(peer, fromdomain, "");
24308    ast_string_field_set(peer, fromuser, "");
24309    ast_string_field_set(peer, regexten, "");
24310    peer->callgroup = 0;
24311    peer->pickupgroup = 0;
24312    peer->maxms = default_qualify;
24313    peer->prefs = default_prefs;
24314    peer->stimer.st_mode_oper = global_st_mode;  /* Session-Timers */
24315    peer->stimer.st_ref = global_st_refresher;
24316    peer->stimer.st_min_se = global_min_se;
24317    peer->stimer.st_max_se = global_max_se;
24318    peer->timer_t1 = global_t1;
24319    peer->timer_b = global_timer_b;
24320    clear_peer_mailboxes(peer);
24321    peer->transports = default_transports;
24322    peer->default_outbound_transport = default_primary_transport;
24323 }
24324 
24325 /*! \brief Create temporary peer (used in autocreatepeer mode) */
24326 static struct sip_peer *temp_peer(const char *name)
24327 {
24328    struct sip_peer *peer;
24329 
24330    if (!(peer = ao2_t_alloc(sizeof(*peer), sip_destroy_peer_fn, "allocate a peer struct")))
24331       return NULL;
24332 
24333    if (ast_string_field_init(peer, 512)) {
24334       ao2_t_ref(peer, -1, "failed to string_field_init, drop peer");
24335       return NULL;
24336    }
24337 
24338    ast_atomic_fetchadd_int(&apeerobjs, 1);
24339    set_peer_defaults(peer);
24340 
24341    ast_copy_string(peer->name, name, sizeof(peer->name));
24342 
24343    peer->selfdestruct = TRUE;
24344    peer->host_dynamic = TRUE;
24345    peer->prefs = default_prefs;
24346    reg_source_db(peer);
24347 
24348    return peer;
24349 }
24350 
24351 /*! \todo document this function */
24352 static void add_peer_mailboxes(struct sip_peer *peer, const char *value)
24353 {
24354    char *next, *mbox, *context;
24355 
24356    next = ast_strdupa(value);
24357 
24358    while ((mbox = context = strsep(&next, ","))) {
24359       struct sip_mailbox *mailbox;
24360       int duplicate = 0;
24361 
24362       strsep(&context, "@");
24363 
24364       if (ast_strlen_zero(mbox)) {
24365          continue;
24366       }
24367 
24368       /* Check whether the mailbox is already in the list */
24369       AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
24370          if (!strcmp(mailbox->mailbox, mbox) && !strcmp(S_OR(mailbox->context, ""), S_OR(context, ""))) {
24371             duplicate = 1;
24372             mailbox->delme = 1;
24373             break;
24374          }
24375       }
24376       if (duplicate) {
24377          continue;
24378       }
24379 
24380       if (!(mailbox = ast_calloc(1, sizeof(*mailbox)))) {
24381          continue;
24382       }
24383 
24384       mailbox->mailbox = ast_strdup(mbox);
24385       mailbox->context = ast_strdup(context);
24386 
24387       AST_LIST_INSERT_TAIL(&peer->mailboxes, mailbox, entry);
24388    }
24389 }
24390 
24391 /*! \brief Build peer from configuration (file or realtime static/dynamic) */
24392 static struct sip_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime, int devstate_only)
24393 {
24394    struct sip_peer *peer = NULL;
24395    struct ast_ha *oldha = NULL;
24396    int found = 0;
24397    int firstpass = 1;
24398    uint16_t port = 0;
24399    int format = 0;      /* Ama flags */
24400    time_t regseconds = 0;
24401    struct ast_flags peerflags[2] = {{(0)}};
24402    struct ast_flags mask[2] = {{(0)}};
24403    char callback[256] = "";
24404    struct sip_peer tmp_peer;
24405    const char *srvlookup = NULL;
24406    static int deprecation_warning = 1;
24407    int alt_fullcontact = alt ? 1 : 0;
24408    struct ast_str *fullcontact = ast_str_alloca(512);
24409 
24410    if (!realtime || ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
24411       /* Note we do NOT use find_peer here, to avoid realtime recursion */
24412       /* We also use a case-sensitive comparison (unlike find_peer) so
24413          that case changes made to the peer name will be properly handled
24414          during reload
24415       */
24416       ast_copy_string(tmp_peer.name, name, sizeof(tmp_peer.name));
24417       peer = ao2_t_find(peers, &tmp_peer, OBJ_POINTER | OBJ_UNLINK, "find and unlink peer from peers table");
24418    }
24419 
24420    if (peer) {
24421       /* Already in the list, remove it and it will be added back (or FREE'd)  */
24422       found++;
24423       if (!(peer->the_mark))
24424          firstpass = 0;
24425    } else {
24426       if (!(peer = ao2_t_alloc(sizeof(*peer), sip_destroy_peer_fn, "allocate a peer struct")))
24427          return NULL;
24428 
24429       if (ast_string_field_init(peer, 512)) {
24430          ao2_t_ref(peer, -1, "failed to string_field_init, drop peer");
24431          return NULL;
24432       }
24433 
24434       if (realtime && !ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
24435          ast_atomic_fetchadd_int(&rpeerobjs, 1);
24436          ast_debug(3, "-REALTIME- peer built. Name: %s. Peer objects: %d\n", name, rpeerobjs);
24437       } else
24438          ast_atomic_fetchadd_int(&speerobjs, 1);
24439    }
24440 
24441    /* Note that our peer HAS had its reference count increased */
24442    if (firstpass) {
24443       peer->lastmsgssent = -1;
24444       oldha = peer->ha;
24445       peer->ha = NULL;
24446       set_peer_defaults(peer);   /* Set peer defaults */
24447       peer->type = 0;
24448    }
24449    if (!found && name)
24450       ast_copy_string(peer->name, name, sizeof(peer->name));
24451 
24452    /* If we have channel variables, remove them (reload) */
24453    if (peer->chanvars) {
24454       ast_variables_destroy(peer->chanvars);
24455       peer->chanvars = NULL;
24456       /* XXX should unregister ? */
24457    }
24458 
24459    if (found)
24460       peer->portinuri = 0;
24461 
24462    /* If we have realm authentication information, remove them (reload) */
24463    clear_realm_authentication(peer->auth);
24464    peer->auth = NULL;
24465    /* clear the transport information.  We will detect if a default value is required after parsing the config */
24466    peer->default_outbound_transport = 0;
24467    peer->transports = 0;
24468 
24469    if (!devstate_only) {
24470       struct sip_mailbox *mailbox;
24471       AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
24472          mailbox->delme = 1;
24473       }
24474    }
24475 
24476    for (; v || ((v = alt) && !(alt=NULL)); v = v->next) {
24477       if (!devstate_only) {
24478          if (handle_common_options(&peerflags[0], &mask[0], v)) {
24479             continue;
24480          }
24481          if (handle_t38_options(&peerflags[0], &mask[0], v, &peer->t38_maxdatagram)) {
24482             continue;
24483          }
24484          if (!strcasecmp(v->name, "transport") && !ast_strlen_zero(v->value)) {
24485             char *val = ast_strdupa(v->value);
24486             char *trans;
24487 
24488             while ((trans = strsep(&val, ","))) {
24489                trans = ast_skip_blanks(trans);
24490 
24491                if (!strncasecmp(trans, "udp", 3)) {
24492                   peer->transports |= SIP_TRANSPORT_UDP;
24493                } else if (!strncasecmp(trans, "tcp", 3)) {
24494                   peer->transports |= SIP_TRANSPORT_TCP;
24495                } else if (!strncasecmp(trans, "tls", 3)) {
24496                   peer->transports |= SIP_TRANSPORT_TLS;
24497                } else {
24498                   ast_log(LOG_NOTICE, "'%s' is not a valid transport type. if no other is specified, udp will be used.\n", trans);
24499                }
24500 
24501                if (!peer->default_outbound_transport) { /*!< The first transport listed should be default outbound */
24502                   peer->default_outbound_transport = peer->transports;
24503                }
24504             }
24505          } else if (realtime && !strcasecmp(v->name, "regseconds")) {
24506             ast_get_time_t(v->value, &regseconds, 0, NULL);
24507          } else if (realtime && !strcasecmp(v->name, "name")) {
24508             ast_copy_string(peer->name, v->value, sizeof(peer->name));
24509          } else if (realtime && !strcasecmp(v->name, "useragent")) {
24510             ast_string_field_set(peer, useragent, v->value);
24511          } else if (!strcasecmp(v->name, "type")) {
24512             if (!strcasecmp(v->value, "peer")) {
24513                peer->type |= SIP_TYPE_PEER;
24514             } else if (!strcasecmp(v->value, "user")) {
24515                peer->type |= SIP_TYPE_USER;
24516             } else if (!strcasecmp(v->value, "friend")) {
24517                peer->type = SIP_TYPE_USER | SIP_TYPE_PEER;
24518             }
24519          } else if (!strcasecmp(v->name, "remotesecret")) {
24520             ast_string_field_set(peer, remotesecret, v->value);
24521          } else if (!strcasecmp(v->name, "secret")) {
24522             ast_string_field_set(peer, secret, v->value);
24523          } else if (!strcasecmp(v->name, "md5secret")) {
24524             ast_string_field_set(peer, md5secret, v->value);
24525          } else if (!strcasecmp(v->name, "auth")) {
24526             peer->auth = add_realm_authentication(peer->auth, v->value, v->lineno);
24527          } else if (!strcasecmp(v->name, "callerid")) {
24528             char cid_name[80] = { '\0' }, cid_num[80] = { '\0' };
24529 
24530             ast_callerid_split(v->value, cid_name, sizeof(cid_name), cid_num, sizeof(cid_num));
24531             ast_string_field_set(peer, cid_name, cid_name);
24532             ast_string_field_set(peer, cid_num, cid_num);
24533          } else if (!strcasecmp(v->name, "fullname")) {
24534             ast_string_field_set(peer, cid_name, v->value);
24535          } else if (!strcasecmp(v->name, "trunkname")) {
24536             /* This is actually for a trunk, so we don't want to override callerid */
24537             ast_string_field_set(peer, cid_name, "");
24538          } else if (!strcasecmp(v->name, "cid_number")) {
24539             ast_string_field_set(peer, cid_num, v->value);
24540          } else if (!strcasecmp(v->name, "context")) {
24541             ast_string_field_set(peer, context, v->value);
24542             ast_set_flag(&peer->flags[1], SIP_PAGE2_HAVEPEERCONTEXT);
24543          } else if (!strcasecmp(v->name, "subscribecontext")) {
24544             ast_string_field_set(peer, subscribecontext, v->value);
24545          } else if (!strcasecmp(v->name, "fromdomain")) {
24546             ast_string_field_set(peer, fromdomain, v->value);
24547          } else if (!strcasecmp(v->name, "usereqphone")) {
24548             ast_set2_flag(&peer->flags[0], ast_true(v->value), SIP_USEREQPHONE);
24549          } else if (!strcasecmp(v->name, "fromuser")) {
24550             ast_string_field_set(peer, fromuser, v->value);
24551          } else if (!strcasecmp(v->name, "outboundproxy")) {
24552             char *port, *next, *force, *proxyname;
24553             int forceopt = FALSE;
24554             /* Set peer channel variable */
24555             next = proxyname = ast_strdupa(v->value);
24556             if ((port = strchr(proxyname, ':'))) {
24557                *port++ = '\0';
24558                next = port;
24559             }
24560             if ((force = strchr(next, ','))) {
24561                *force++ = '\0';
24562                forceopt = strcmp(force, "force");
24563             }
24564             /* Allocate proxy object */
24565             peer->outboundproxy = proxy_allocate(proxyname, port, forceopt);
24566          } else if (!strcasecmp(v->name, "host")) {
24567             if (!strcasecmp(v->value, "dynamic")) {
24568                /* They'll register with us */
24569                if (!found || !peer->host_dynamic) {
24570                   /* Initialize stuff if this is a new peer, or if it used to
24571                    * not be dynamic before the reload. */
24572                   memset(&peer->addr.sin_addr, 0, 4);
24573                   peer->addr.sin_port = 0;
24574                }
24575                peer->host_dynamic = TRUE;
24576             } else {
24577                /* Non-dynamic.  Make sure we become that way if we're not */
24578                AST_SCHED_DEL_UNREF(sched, peer->expire,
24579                      unref_peer(peer, "removing register expire ref"));
24580                /* the port will either be set to a default value or a config specified value once all option parsing is complete */
24581                peer->addr.sin_port = 0;
24582                peer->host_dynamic = FALSE;
24583                srvlookup = v->value;
24584             }
24585          } else if (!strcasecmp(v->name, "defaultip")) {
24586             if (!ast_strlen_zero(v->value) && ast_get_ip(&peer->defaddr, v->value)) {
24587                unref_peer(peer, "unref_peer: from build_peer defaultip");
24588                return NULL;
24589             }
24590          } else if (!strcasecmp(v->name, "permit") || !strcasecmp(v->name, "deny")) {
24591             int ha_error = 0;
24592             if (!ast_strlen_zero(v->value)) {
24593                peer->ha = ast_append_ha(v->name, v->value, peer->ha, &ha_error);
24594             }
24595             if (ha_error) {
24596                ast_log(LOG_ERROR, "Bad ACL entry in configuration line %d : %s\n", v->lineno, v->value);
24597             }
24598          } else if (!strcasecmp(v->name, "contactpermit") || !strcasecmp(v->name, "contactdeny")) {
24599             int ha_error = 0;
24600             if (!ast_strlen_zero(v->value)) {
24601                peer->contactha = ast_append_ha(v->name + 7, v->value, peer->contactha, &ha_error);
24602             }
24603             if (ha_error) {
24604                ast_log(LOG_ERROR, "Bad ACL entry in configuration line %d : %s\n", v->lineno, v->value);
24605             }
24606          } else if (!strcasecmp(v->name, "port")) {
24607             peer->portinuri = 1;
24608             if (!(port = port_str2int(v->value, 0))) {
24609                if (realtime) {
24610                   /* If stored as integer, could be 0 for some DBs (notably MySQL) */
24611                   peer->portinuri = 0;
24612                } else {
24613                   ast_log(LOG_WARNING, "Invalid peer port configuration at line %d : %s\n", v->lineno, v->value);
24614                }
24615             }
24616          } else if (!strcasecmp(v->name, "callingpres")) {
24617             peer->callingpres = ast_parse_caller_presentation(v->value);
24618             if (peer->callingpres == -1) {
24619                peer->callingpres = atoi(v->value);
24620             }
24621          } else if (!strcasecmp(v->name, "username") || !strcmp(v->name, "defaultuser")) {   /* "username" is deprecated */
24622             ast_string_field_set(peer, username, v->value);
24623             if (!strcasecmp(v->name, "username")) {
24624                if (deprecation_warning) {
24625                   ast_log(LOG_NOTICE, "The 'username' field for sip peers has been deprecated in favor of the term 'defaultuser'\n");
24626                   deprecation_warning = 0;
24627                }
24628                peer->deprecated_username = 1;
24629             }
24630          } else if (!strcasecmp(v->name, "language")) {
24631             ast_string_field_set(peer, language, v->value);
24632          } else if (!strcasecmp(v->name, "regexten")) {
24633             ast_string_field_set(peer, regexten, v->value);
24634          } else if (!strcasecmp(v->name, "callbackextension")) {
24635             ast_copy_string(callback, v->value, sizeof(callback));
24636          } else if (!strcasecmp(v->name, "amaflags")) {
24637             format = ast_cdr_amaflags2int(v->value);
24638             if (format < 0) {
24639                ast_log(LOG_WARNING, "Invalid AMA Flags for peer: %s at line %d\n", v->value, v->lineno);
24640             } else {
24641                peer->amaflags = format;
24642             }
24643          } else if (!strcasecmp(v->name, "accountcode")) {
24644             ast_string_field_set(peer, accountcode, v->value);
24645          } else if (!strcasecmp(v->name, "mohinterpret")) {
24646             ast_string_field_set(peer, mohinterpret, v->value);
24647          } else if (!strcasecmp(v->name, "mohsuggest")) {
24648             ast_string_field_set(peer, mohsuggest, v->value);
24649          } else if (!strcasecmp(v->name, "parkinglot")) {
24650             ast_string_field_set(peer, parkinglot, v->value);
24651          } else if (!strcasecmp(v->name, "mailbox")) {
24652             add_peer_mailboxes(peer, v->value);
24653          } else if (!strcasecmp(v->name, "hasvoicemail")) {
24654             /* People expect that if 'hasvoicemail' is set, that the mailbox will
24655              * be also set, even if not explicitly specified. */
24656             if (ast_true(v->value) && AST_LIST_EMPTY(&peer->mailboxes)) {
24657                add_peer_mailboxes(peer, name);
24658             }
24659          } else if (!strcasecmp(v->name, "subscribemwi")) {
24660             ast_set2_flag(&peer->flags[1], ast_true(v->value), SIP_PAGE2_SUBSCRIBEMWIONLY);
24661          } else if (!strcasecmp(v->name, "vmexten")) {
24662             ast_string_field_set(peer, vmexten, v->value);
24663          } else if (!strcasecmp(v->name, "callgroup")) {
24664             peer->callgroup = ast_get_group(v->value);
24665          } else if (!strcasecmp(v->name, "allowtransfer")) {
24666             peer->allowtransfer = ast_true(v->value) ? TRANSFER_OPENFORALL : TRANSFER_CLOSED;
24667          } else if (!strcasecmp(v->name, "pickupgroup")) {
24668             peer->pickupgroup = ast_get_group(v->value);
24669          } else if (!strcasecmp(v->name, "allow")) {
24670             int error =  ast_parse_allow_disallow(&peer->prefs, &peer->capability, v->value, TRUE);
24671             if (error) {
24672                ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
24673             }
24674          } else if (!strcasecmp(v->name, "disallow")) {
24675             int error =  ast_parse_allow_disallow(&peer->prefs, &peer->capability, v->value, FALSE);
24676             if (error) {
24677                ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
24678             }
24679          } else if (!strcasecmp(v->name, "registertrying")) {
24680             ast_set2_flag(&peer->flags[1], ast_true(v->value), SIP_PAGE2_REGISTERTRYING);
24681          } else if (!strcasecmp(v->name, "autoframing")) {
24682             peer->autoframing = ast_true(v->value);
24683          } else if (!strcasecmp(v->name, "rtptimeout")) {
24684             if ((sscanf(v->value, "%30d", &peer->rtptimeout) != 1) || (peer->rtptimeout < 0)) {
24685                ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d.  Using default.\n", v->value, v->lineno);
24686                peer->rtptimeout = global_rtptimeout;
24687             }
24688          } else if (!strcasecmp(v->name, "rtpholdtimeout")) {
24689             if ((sscanf(v->value, "%30d", &peer->rtpholdtimeout) != 1) || (peer->rtpholdtimeout < 0)) {
24690                ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d.  Using default.\n", v->value, v->lineno);
24691                peer->rtpholdtimeout = global_rtpholdtimeout;
24692             }
24693          } else if (!strcasecmp(v->name, "rtpkeepalive")) {
24694             if ((sscanf(v->value, "%30d", &peer->rtpkeepalive) != 1) || (peer->rtpkeepalive < 0)) {
24695                ast_log(LOG_WARNING, "'%s' is not a valid RTP keepalive time at line %d.  Using default.\n", v->value, v->lineno);
24696                peer->rtpkeepalive = global_rtpkeepalive;
24697             }
24698          } else if (!strcasecmp(v->name, "timert1")) {
24699             if ((sscanf(v->value, "%30d", &peer->timer_t1) != 1) || (peer->timer_t1 < 0)) {
24700                ast_log(LOG_WARNING, "'%s' is not a valid T1 time at line %d.  Using default.\n", v->value, v->lineno);
24701                peer->timer_t1 = global_t1;
24702             }
24703             /* Note that Timer B is dependent upon T1 and MUST NOT be lower
24704              * than T1 * 64, according to RFC 3261, Section 17.1.1.2 */
24705             if (peer->timer_b < peer->timer_t1 * 64) {
24706                peer->timer_b = peer->timer_t1 * 64;
24707             }
24708          } else if (!strcasecmp(v->name, "timerb")) {
24709             if ((sscanf(v->value, "%30d", &peer->timer_b) != 1) || (peer->timer_b < 0)) {
24710                ast_log(LOG_WARNING, "'%s' is not a valid Timer B time at line %d.  Using default.\n", v->value, v->lineno);
24711                peer->timer_b = global_timer_b;
24712             }
24713             if (peer->timer_b < peer->timer_t1 * 64) {
24714                static int warning = 0;
24715                if (warning++ % 20 == 0) {
24716                   ast_log(LOG_WARNING, "Timer B has been set lower than recommended. (RFC 3261, 17.1.1.2)\n");
24717                }
24718             }
24719          } else if (!strcasecmp(v->name, "setvar")) {
24720             peer->chanvars = add_var(v->value, peer->chanvars);
24721          } else if (!strcasecmp(v->name, "qualifyfreq")) {
24722             int i;
24723             if (sscanf(v->value, "%30d", &i) == 1) {
24724                peer->qualifyfreq = i * 1000;
24725             } else {
24726                ast_log(LOG_WARNING, "Invalid qualifyfreq number '%s' at line %d of %s\n", v->value, v->lineno, config);
24727                peer->qualifyfreq = global_qualifyfreq;
24728             }
24729          } else if (!strcasecmp(v->name, "maxcallbitrate")) {
24730             peer->maxcallbitrate = atoi(v->value);
24731             if (peer->maxcallbitrate < 0) {
24732                peer->maxcallbitrate = default_maxcallbitrate;
24733             }
24734          } else if (!strcasecmp(v->name, "session-timers")) {
24735             int i = (int) str2stmode(v->value);
24736             if (i < 0) {
24737                ast_log(LOG_WARNING, "Invalid session-timers '%s' at line %d of %s\n", v->value, v->lineno, config);
24738                peer->stimer.st_mode_oper = global_st_mode;
24739             } else {
24740                peer->stimer.st_mode_oper = i;
24741             }
24742          } else if (!strcasecmp(v->name, "session-expires")) {
24743             if (sscanf(v->value, "%30d", &peer->stimer.st_max_se) != 1) {
24744                ast_log(LOG_WARNING, "Invalid session-expires '%s' at line %d of %s\n", v->value, v->lineno, config);
24745                peer->stimer.st_max_se = global_max_se;
24746             }
24747          } else if (!strcasecmp(v->name, "session-minse")) {
24748             if (sscanf(v->value, "%30d", &peer->stimer.st_min_se) != 1) {
24749                ast_log(LOG_WARNING, "Invalid session-minse '%s' at line %d of %s\n", v->value, v->lineno, config);
24750                peer->stimer.st_min_se = global_min_se;
24751             }
24752             if (peer->stimer.st_min_se < 90) {
24753                ast_log(LOG_WARNING, "session-minse '%s' at line %d of %s is not allowed to be < 90 secs\n", v->value, v->lineno, config);
24754                peer->stimer.st_min_se = global_min_se;
24755             }
24756          } else if (!strcasecmp(v->name, "session-refresher")) {
24757             int i = (int) str2strefresher(v->value);
24758             if (i < 0) {
24759                ast_log(LOG_WARNING, "Invalid session-refresher '%s' at line %d of %s\n", v->value, v->lineno, config);
24760                peer->stimer.st_ref = global_st_refresher;
24761             } else {
24762                peer->stimer.st_ref = i;
24763             }
24764          }
24765       }
24766 
24767       /* These apply to devstate lookups */
24768       if (realtime && !strcasecmp(v->name, "lastms")) {
24769          sscanf(v->value, "%30d", &peer->lastms);
24770       } else if (realtime && !strcasecmp(v->name, "ipaddr") && !ast_strlen_zero(v->value) ) {
24771          inet_aton(v->value, &(peer->addr.sin_addr));
24772       } else if (realtime && !strcasecmp(v->name, "fullcontact")) {
24773          if (alt_fullcontact && !alt) {
24774             /* Reset, because the alternate also has a fullcontact and we
24775              * do NOT want the field value to be doubled. It might be
24776              * tempting to skip this, but the first table might not have
24777              * fullcontact and since we're here, we know that the alternate
24778              * absolutely does. */
24779             alt_fullcontact = 0;
24780             ast_str_reset(fullcontact);
24781          }
24782          /* Reconstruct field, because realtime separates our value at the ';' */
24783          if (fullcontact->used > 0) {
24784             ast_str_append(&fullcontact, 0, ";%s", v->value);
24785          } else {
24786             ast_str_set(&fullcontact, 0, "%s", v->value);
24787          }
24788       } else if (!strcasecmp(v->name, "qualify")) {
24789          if (!strcasecmp(v->value, "no")) {
24790             peer->maxms = 0;
24791          } else if (!strcasecmp(v->value, "yes")) {
24792             peer->maxms = default_qualify ? default_qualify : DEFAULT_MAXMS;
24793          } else if (sscanf(v->value, "%30d", &peer->maxms) != 1) {
24794             ast_log(LOG_WARNING, "Qualification of peer '%s' should be 'yes', 'no', or a number of milliseconds at line %d of sip.conf\n", peer->name, v->lineno);
24795             peer->maxms = 0;
24796          }
24797          if (realtime && !ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) && peer->maxms > 0) {
24798             /* This would otherwise cause a network storm, where the
24799              * qualify response refreshes the peer from the database,
24800              * which in turn causes another qualify to be sent, ad
24801              * infinitum. */
24802             ast_log(LOG_WARNING, "Qualify is incompatible with dynamic uncached realtime.  Please either turn rtcachefriends on or turn qualify off on peer '%s'\n", peer->name);
24803             peer->maxms = 0;
24804          }
24805       } else if (!strcasecmp(v->name, "callcounter")) {
24806          peer->call_limit = ast_true(v->value) ? INT_MAX : 0;
24807       } else if (!strcasecmp(v->name, "call-limit")) {
24808          peer->call_limit = atoi(v->value);
24809          if (peer->call_limit < 0) {
24810             peer->call_limit = 0;
24811          }
24812       } else if (!strcasecmp(v->name, "busylevel")) {
24813          peer->busy_level = atoi(v->value);
24814          if (peer->busy_level < 0) {
24815             peer->busy_level = 0;
24816          }
24817       }
24818    }
24819 
24820    if (!devstate_only) {
24821       struct sip_mailbox *mailbox;
24822       AST_LIST_TRAVERSE_SAFE_BEGIN(&peer->mailboxes, mailbox, entry) {
24823          if (mailbox->delme) {
24824             AST_LIST_REMOVE_CURRENT(entry);
24825             destroy_mailbox(mailbox);
24826          }
24827       }
24828       AST_LIST_TRAVERSE_SAFE_END;
24829    }
24830 
24831    if (!peer->default_outbound_transport) {
24832       /* Set default set of transports */
24833       peer->transports = default_transports;
24834       /* Set default primary transport */
24835       peer->default_outbound_transport = default_primary_transport;
24836    }
24837 
24838    /* The default transport type set during build_peer should only replace the socket.type when...
24839     * 1. Registration is not present and the socket.type and default transport types are different.
24840     * 2. The socket.type is not an acceptable transport type after rebuilding peer.
24841     * 3. The socket.type is not set yet. */
24842    if (((peer->socket.type != peer->default_outbound_transport) && (peer->expire == -1)) ||
24843       !(peer->socket.type & peer->transports) || !(peer->socket.type)) {
24844 
24845       set_socket_transport(&peer->socket, peer->default_outbound_transport);
24846    }
24847 
24848    if (port && !realtime && peer->host_dynamic) {
24849       peer->defaddr.sin_port = htons(port);
24850    } else if (port) {
24851       peer->addr.sin_port = htons(port);
24852    }
24853 
24854    if (ast_str_strlen(fullcontact)) {
24855       ast_string_field_set(peer, fullcontact, ast_str_buffer(fullcontact));
24856       peer->rt_fromcontact = TRUE;
24857       /* We have a hostname in the fullcontact, but if we don't have an
24858        * address listed on the entry (or if it's 'dynamic'), then we need to
24859        * parse the entry to obtain the IP address, so a dynamic host can be
24860        * contacted immediately after reload (as opposed to waiting for it to
24861        * register once again). But if we have an address for this peer and NAT was
24862        * specified, use that address instead. */
24863       /* XXX May need to revisit the final argument; does the realtime DB store whether
24864        * the original contact was over TLS or not? XXX */
24865       if (!ast_test_flag(&peer->flags[0], SIP_NAT_ROUTE) || !peer->addr.sin_addr.s_addr) {
24866          __set_address_from_contact(fullcontact->str, &peer->addr, 0);
24867       }
24868    }
24869 
24870    if (srvlookup && peer->dnsmgr == NULL) {
24871       char transport[MAXHOSTNAMELEN];
24872       char _srvlookup[MAXHOSTNAMELEN];
24873       char *params;
24874 
24875       ast_copy_string(_srvlookup, srvlookup, sizeof(_srvlookup));
24876       if ((params = strchr(_srvlookup, ';'))) {
24877          *params++ = '\0';
24878       }
24879 
24880       snprintf(transport, sizeof(transport), "_%s._%s", get_srv_service(peer->socket.type), get_srv_protocol(peer->socket.type));
24881 
24882       if (ast_dnsmgr_lookup(_srvlookup, &peer->addr, &peer->dnsmgr, sip_cfg.srvlookup && !peer->portinuri ? transport : NULL)) {
24883          ast_log(LOG_ERROR, "srvlookup failed for host: %s, on peer %s, removing peer\n", _srvlookup, peer->name);
24884          unref_peer(peer, "getting rid of a peer pointer");
24885          return NULL;
24886       }
24887 
24888       ast_string_field_set(peer, tohost, srvlookup);
24889       if (global_dynamic_exclude_static) {
24890          int err = 0;
24891          global_contact_ha = ast_append_ha("deny", (char *)ast_inet_ntoa(peer->addr.sin_addr), global_contact_ha, &err);
24892          if (err) {
24893             ast_log(LOG_ERROR, "Bad ACL entry in configuration line %d : %s\n", v->lineno, v->value);
24894          }
24895       }
24896    }
24897 
24898    if (!peer->addr.sin_port) {
24899       peer->addr.sin_port = htons(((peer->socket.type & SIP_TRANSPORT_TLS) ? STANDARD_TLS_PORT : STANDARD_SIP_PORT));
24900    }
24901    if (!peer->defaddr.sin_port) {
24902       peer->defaddr.sin_port = htons(((peer->socket.type & SIP_TRANSPORT_TLS) ? STANDARD_TLS_PORT : STANDARD_SIP_PORT));
24903    }
24904    if (!peer->socket.port) {
24905       peer->socket.port = htons(((peer->socket.type & SIP_TRANSPORT_TLS) ? STANDARD_TLS_PORT : STANDARD_SIP_PORT));
24906    }
24907 
24908    if (!sip_cfg.ignore_regexpire && peer->host_dynamic && realtime) {
24909       time_t nowtime = time(NULL);
24910 
24911       if ((nowtime - regseconds) > 0) {
24912          destroy_association(peer);
24913          memset(&peer->addr, 0, sizeof(peer->addr));
24914          peer->lastms = -1;
24915          ast_debug(1, "Bah, we're expired (%d/%d/%d)!\n", (int)(nowtime - regseconds), (int)regseconds, (int)nowtime);
24916       }
24917    }
24918 
24919    /* Startup regular pokes */
24920    if (!devstate_only && realtime && peer->lastms > 0) {
24921       ref_peer(peer, "schedule qualify");
24922       sip_poke_peer(peer, 0);
24923    }
24924 
24925    ast_copy_flags(&peer->flags[0], &peerflags[0], mask[0].flags);
24926    ast_copy_flags(&peer->flags[1], &peerflags[1], mask[1].flags);
24927    if (ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)) {
24928       sip_cfg.allowsubscribe = TRUE;   /* No global ban any more */
24929    }
24930    if (peer->host_dynamic && !peer->is_realtime) {
24931       reg_source_db(peer);
24932    }
24933 
24934    /* If they didn't request that MWI is sent *only* on subscribe, go ahead and
24935     * subscribe to it now. */
24936    if (!devstate_only && !ast_test_flag(&peer->flags[1], SIP_PAGE2_SUBSCRIBEMWIONLY) &&
24937       !AST_LIST_EMPTY(&peer->mailboxes)) {
24938       add_peer_mwi_subs(peer);
24939       /* Send MWI from the event cache only.  This is so we can send initial
24940        * MWI if app_voicemail got loaded before chan_sip.  If it is the other
24941        * way, then we will get events when app_voicemail gets loaded. */
24942       sip_send_mwi_to_peer(peer, NULL, 1);
24943    }
24944 
24945    peer->the_mark = 0;
24946 
24947    ast_free_ha(oldha);
24948    if (!ast_strlen_zero(callback)) { /* build string from peer info */
24949       char *reg_string;
24950       if (asprintf(&reg_string, "%s?%s:%s@%s/%s", peer->name, peer->username, !ast_strlen_zero(peer->remotesecret) ? peer->remotesecret : peer->secret, peer->tohost, callback) < 0) {
24951          ast_log(LOG_WARNING, "asprintf() failed: %s\n", strerror(errno));
24952       } else if (reg_string) {
24953          sip_register(reg_string, 0); /* XXX TODO: count in registry_count */
24954          ast_free(reg_string);
24955       }
24956    }
24957    return peer;
24958 }
24959 
24960 static int peer_markall_func(void *device, void *arg, int flags)
24961 {
24962    struct sip_peer *peer = device;
24963    peer->the_mark = 1;
24964    return 0;
24965 }
24966 
24967 /*! \brief Re-read SIP.conf config file
24968 \note This function reloads all config data, except for
24969    active peers (with registrations). They will only
24970    change configuration data at restart, not at reload.
24971    SIP debug and recordhistory state will not change
24972  */
24973 static int reload_config(enum channelreloadreason reason)
24974 {
24975    struct ast_config *cfg, *ucfg;
24976    struct ast_variable *v;
24977    struct sip_peer *peer;
24978    char *cat, *stringp, *context, *oldregcontext;
24979    char newcontexts[AST_MAX_CONTEXT], oldcontexts[AST_MAX_CONTEXT];
24980    struct ast_flags dummy[2];
24981    struct ast_flags config_flags = { reason == CHANNEL_MODULE_LOAD ? 0 : ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) ? 0 : CONFIG_FLAG_FILEUNCHANGED };
24982    int auto_sip_domains = FALSE;
24983    struct sockaddr_in old_bindaddr = bindaddr;
24984    int registry_count = 0, peer_count = 0;
24985    time_t run_start, run_end;
24986    
24987    run_start = time(0);
24988    ast_unload_realtime("sipregs");     
24989    ast_unload_realtime("sippeers");
24990    cfg = ast_config_load(config, config_flags);
24991 
24992    /* We *must* have a config file otherwise stop immediately */
24993    if (!cfg) {
24994       ast_log(LOG_NOTICE, "Unable to load config %s\n", config);
24995       return -1;
24996    } else if (cfg == CONFIG_STATUS_FILEUNCHANGED) {
24997       ucfg = ast_config_load("users.conf", config_flags);
24998       if (ucfg == CONFIG_STATUS_FILEUNCHANGED) {
24999          return 1;
25000       } else if (ucfg == CONFIG_STATUS_FILEINVALID) {
25001          ast_log(LOG_ERROR, "Contents of users.conf are invalid and cannot be parsed\n");
25002          return 1;
25003       }
25004       /* Must reread both files, because one changed */
25005       ast_clear_flag(&config_flags, CONFIG_FLAG_FILEUNCHANGED);
25006       if ((cfg = ast_config_load(config, config_flags)) == CONFIG_STATUS_FILEINVALID) {
25007          ast_log(LOG_ERROR, "Contents of %s are invalid and cannot be parsed\n", config);
25008          ast_config_destroy(ucfg);
25009          return 1;
25010       }
25011    } else if (cfg == CONFIG_STATUS_FILEINVALID) {
25012       ast_log(LOG_ERROR, "Contents of %s are invalid and cannot be parsed\n", config);
25013       return 1;
25014    } else {
25015       ast_clear_flag(&config_flags, CONFIG_FLAG_FILEUNCHANGED);
25016       if ((ucfg = ast_config_load("users.conf", config_flags)) == CONFIG_STATUS_FILEINVALID) {
25017          ast_log(LOG_ERROR, "Contents of users.conf are invalid and cannot be parsed\n");
25018          ast_config_destroy(cfg);
25019          return 1;
25020       }
25021    }
25022 
25023    /* Initialize tcp sockets */
25024    memset(&sip_tcp_desc.local_address, 0, sizeof(sip_tcp_desc.local_address));
25025    memset(&sip_tls_desc.local_address, 0, sizeof(sip_tls_desc.local_address));
25026 
25027    ast_free_ha(global_contact_ha);
25028    global_contact_ha = NULL;
25029 
25030    default_tls_cfg.enabled = FALSE;    /* Default: Disable TLS */
25031 
25032    sip_tcp_desc.local_address.sin_port = htons(STANDARD_SIP_PORT);
25033    sip_tls_desc.local_address.sin_port = htons(STANDARD_TLS_PORT);
25034 
25035    if (reason != CHANNEL_MODULE_LOAD) {
25036       ast_debug(4, "--------------- SIP reload started\n");
25037 
25038       clear_realm_authentication(authl);
25039       clear_sip_domains();
25040       authl = NULL;
25041 
25042       /* First, destroy all outstanding registry calls */
25043       /* This is needed, since otherwise active registry entries will not be destroyed */
25044       ASTOBJ_CONTAINER_TRAVERSE(&regl, 1, do {  /* regl is locked */
25045 
25046             ASTOBJ_RDLOCK(iterator); /* now regl is locked, and the object is also locked */
25047             if (iterator->call) {
25048                ast_debug(3, "Destroying active SIP dialog for registry %s@%s\n", iterator->username, iterator->hostname);
25049                /* This will also remove references to the registry */
25050                dialog_unlink_all(iterator->call, TRUE, TRUE);
25051                iterator->call = dialog_unref(iterator->call, "remove iterator->call from registry traversal");
25052             }
25053             if (iterator->expire > -1) {
25054                AST_SCHED_DEL_UNREF(sched, iterator->expire, registry_unref(iterator, "reg ptr unref from reload config"));
25055             }
25056             if (iterator->timeout > -1) {
25057                AST_SCHED_DEL_UNREF(sched, iterator->timeout, registry_unref(iterator, "reg ptr unref from reload config"));
25058             }
25059             ASTOBJ_UNLOCK(iterator);
25060             
25061       } while(0));
25062 
25063       /* Then, actually destroy users and registry */
25064       ASTOBJ_CONTAINER_DESTROYALL(&regl, sip_registry_destroy);
25065       ast_debug(4, "--------------- Done destroying registry list\n");
25066       ao2_t_callback(peers, OBJ_NODATA, peer_markall_func, NULL, "callback to mark all peers");
25067    }
25068    
25069    /* Reset certificate handling for TLS sessions */
25070    if (reason != CHANNEL_MODULE_LOAD) {
25071       ast_free(default_tls_cfg.certfile);
25072       ast_free(default_tls_cfg.cipher);
25073       ast_free(default_tls_cfg.cafile);
25074       ast_free(default_tls_cfg.capath);
25075    }
25076    default_tls_cfg.certfile = ast_strdup(AST_CERTFILE); /*XXX Not sure if this is useful */
25077    default_tls_cfg.cipher = ast_strdup("");
25078    default_tls_cfg.cafile = ast_strdup("");
25079    default_tls_cfg.capath = ast_strdup("");
25080 
25081    
25082    /* Initialize copy of current global_regcontext for later use in removing stale contexts */
25083    ast_copy_string(oldcontexts, global_regcontext, sizeof(oldcontexts));
25084    oldregcontext = oldcontexts;
25085 
25086    /* Clear all flags before setting default values */
25087    /* Preserve debugging settings for console */
25088    sipdebug &= sip_debug_console;
25089    ast_clear_flag(&global_flags[0], AST_FLAGS_ALL);
25090    ast_clear_flag(&global_flags[1], AST_FLAGS_ALL);
25091 
25092    /* Reset IP addresses  */
25093    memset(&bindaddr, 0, sizeof(bindaddr));
25094    memset(&stunaddr, 0, sizeof(stunaddr));
25095    memset(&internip, 0, sizeof(internip));
25096 
25097    /* Free memory for local network address mask */
25098    ast_free_ha(localaddr);
25099    memset(&localaddr, 0, sizeof(localaddr));
25100    memset(&externip, 0, sizeof(externip));
25101    memset(&default_prefs, 0 , sizeof(default_prefs));
25102    memset(&sip_cfg.outboundproxy, 0, sizeof(struct sip_proxy));
25103    sip_cfg.outboundproxy.ip.sin_port = htons(STANDARD_SIP_PORT);
25104    sip_cfg.outboundproxy.ip.sin_family = AF_INET;  /*!< Type of address: IPv4 */
25105    sip_cfg.outboundproxy.force = FALSE;      /*!< Don't force proxy usage, use route: headers */
25106    default_transports = 0;          /*!< Reset default transport to zero here, default value later on */
25107    default_primary_transport = 0;         /*!< Reset default primary transport to zero here, default value later on */
25108    ourport_tcp = STANDARD_SIP_PORT;
25109    ourport_tls = STANDARD_TLS_PORT;
25110    bindaddr.sin_port = htons(STANDARD_SIP_PORT);
25111    sip_cfg.srvlookup = DEFAULT_SRVLOOKUP;
25112    global_tos_sip = DEFAULT_TOS_SIP;
25113    global_tos_audio = DEFAULT_TOS_AUDIO;
25114    global_tos_video = DEFAULT_TOS_VIDEO;
25115    global_tos_text = DEFAULT_TOS_TEXT;
25116    global_cos_sip = DEFAULT_COS_SIP;
25117    global_cos_audio = DEFAULT_COS_AUDIO;
25118    global_cos_video = DEFAULT_COS_VIDEO;
25119    global_cos_text = DEFAULT_COS_TEXT;
25120 
25121    externhost[0] = '\0';         /* External host name (for behind NAT DynDNS support) */
25122    externexpire = 0;       /* Expiration for DNS re-issuing */
25123    externrefresh = 10;
25124 
25125    /* Reset channel settings to default before re-configuring */
25126    sip_cfg.allow_external_domains = DEFAULT_ALLOW_EXT_DOM;           /* Allow external invites */
25127    global_regcontext[0] = '\0';
25128    sip_cfg.regextenonqualify = DEFAULT_REGEXTENONQUALIFY;
25129    sip_cfg.notifyringing = DEFAULT_NOTIFYRINGING;
25130    sip_cfg.notifycid = DEFAULT_NOTIFYCID;
25131    sip_cfg.notifyhold = FALSE;      /*!< Keep track of hold status for a peer */
25132    sip_cfg.directrtpsetup = FALSE;     /* Experimental feature, disabled by default */
25133    sip_cfg.alwaysauthreject = DEFAULT_ALWAYSAUTHREJECT;
25134    sip_cfg.allowsubscribe = FALSE;
25135    snprintf(global_useragent, sizeof(global_useragent), "%s %s", DEFAULT_USERAGENT, ast_get_version());
25136    snprintf(global_sdpsession, sizeof(global_sdpsession), "%s %s", DEFAULT_SDPSESSION, ast_get_version());
25137    snprintf(global_sdpowner, sizeof(global_sdpowner), "%s", DEFAULT_SDPOWNER);
25138    global_prematuremediafilter = TRUE;
25139    ast_copy_string(default_notifymime, DEFAULT_NOTIFYMIME, sizeof(default_notifymime));
25140    ast_copy_string(sip_cfg.realm, S_OR(ast_config_AST_SYSTEM_NAME, DEFAULT_REALM), sizeof(sip_cfg.realm));
25141    ast_copy_string(default_callerid, DEFAULT_CALLERID, sizeof(default_callerid));
25142    sip_cfg.compactheaders = DEFAULT_COMPACTHEADERS;
25143    global_reg_timeout = DEFAULT_REGISTRATION_TIMEOUT;
25144    global_regattempts_max = 0;
25145    sip_cfg.pedanticsipchecking = DEFAULT_PEDANTIC;
25146    sip_cfg.autocreatepeer = DEFAULT_AUTOCREATEPEER;
25147    global_autoframing = 0;
25148    sip_cfg.allowguest = DEFAULT_ALLOWGUEST;
25149    global_callcounter = DEFAULT_CALLCOUNTER;
25150    global_match_auth_username = FALSE;    /*!< Match auth username if available instead of From: Default off. */
25151    global_rtptimeout = 0;
25152    global_rtpholdtimeout = 0;
25153    global_rtpkeepalive = DEFAULT_RTPKEEPALIVE;
25154    sip_cfg.allowtransfer = TRANSFER_OPENFORALL; /* Merrily accept all transfers by default */
25155    sip_cfg.rtautoclear = 120;
25156    ast_set_flag(&global_flags[1], SIP_PAGE2_ALLOWSUBSCRIBE);   /* Default for all devices: TRUE */
25157    ast_set_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP);     /* Default for all devices: TRUE */
25158    sip_cfg.peer_rtupdate = TRUE;
25159    global_dynamic_exclude_static = 0;  /* Exclude static peers */
25160 
25161    /* Session-Timers */
25162    global_st_mode = SESSION_TIMER_MODE_ACCEPT;    
25163    global_st_refresher = SESSION_TIMER_REFRESHER_UAS;
25164    global_min_se  = DEFAULT_MIN_SE;
25165    global_max_se  = DEFAULT_MAX_SE;
25166 
25167    /* Peer poking settings */
25168    global_qualify_gap = DEFAULT_QUALIFY_GAP;
25169    global_qualify_peers = DEFAULT_QUALIFY_PEERS;
25170 
25171    /* Initialize some reasonable defaults at SIP reload (used both for channel and as default for devices */
25172    ast_copy_string(sip_cfg.default_context, DEFAULT_CONTEXT, sizeof(sip_cfg.default_context));
25173    sip_cfg.default_subscribecontext[0] = '\0';
25174    default_language[0] = '\0';
25175    default_fromdomain[0] = '\0';
25176    default_qualify = DEFAULT_QUALIFY;
25177    default_maxcallbitrate = DEFAULT_MAX_CALL_BITRATE;
25178    ast_copy_string(default_mohinterpret, DEFAULT_MOHINTERPRET, sizeof(default_mohinterpret));
25179    ast_copy_string(default_mohsuggest, DEFAULT_MOHSUGGEST, sizeof(default_mohsuggest));
25180    ast_copy_string(default_vmexten, DEFAULT_VMEXTEN, sizeof(default_vmexten));
25181    ast_set_flag(&global_flags[0], SIP_DTMF_RFC2833);        /*!< Default DTMF setting: RFC2833 */
25182    ast_set_flag(&global_flags[0], SIP_NAT_RFC3581);         /*!< NAT support if requested by device with rport */
25183    ast_set_flag(&global_flags[0], SIP_DIRECT_MEDIA);        /*!< Allow re-invites */
25184    ast_set_flag(&global_flags[1], SIP_PAGE2_FORWARD_LOOP_DETECTED); /*!< Set up call forward on 482 Loop Detected */
25185 
25186    /* Debugging settings, always default to off */
25187    dumphistory = FALSE;
25188    recordhistory = FALSE;
25189    sipdebug &= ~sip_debug_config;
25190 
25191    /* Misc settings for the channel */
25192    global_relaxdtmf = FALSE;
25193    sip_cfg.callevents = DEFAULT_CALLEVENTS;
25194    global_authfailureevents = FALSE;
25195    global_t1 = DEFAULT_TIMER_T1;
25196    global_timer_b = 64 * DEFAULT_TIMER_T1;
25197    global_t1min = DEFAULT_T1MIN;
25198    global_qualifyfreq = DEFAULT_QUALIFYFREQ;
25199    global_t38_maxdatagram = -1;
25200    global_shrinkcallerid = 1;
25201    authlimit = DEFAULT_AUTHLIMIT;
25202    authtimeout = DEFAULT_AUTHTIMEOUT;
25203 
25204    sip_cfg.matchexterniplocally = DEFAULT_MATCHEXTERNIPLOCALLY;
25205 
25206    /* Copy the default jb config over global_jbconf */
25207    memcpy(&global_jbconf, &default_jbconf, sizeof(struct ast_jb_conf));
25208 
25209    ast_clear_flag(&global_flags[1], SIP_PAGE2_FAX_DETECT);
25210    ast_clear_flag(&global_flags[1], SIP_PAGE2_VIDEOSUPPORT | SIP_PAGE2_VIDEOSUPPORT_ALWAYS);
25211    ast_clear_flag(&global_flags[1], SIP_PAGE2_TEXTSUPPORT);
25212    ast_clear_flag(&global_flags[1], SIP_PAGE2_IGNORESDPVERSION);
25213 
25214 
25215    /* Read the [general] config section of sip.conf (or from realtime config) */
25216    for (v = ast_variable_browse(cfg, "general"); v; v = v->next) {
25217       if (handle_common_options(&global_flags[0], &dummy[0], v))
25218          continue;
25219       if (handle_t38_options(&global_flags[0], &dummy[0], v, &global_t38_maxdatagram)) {
25220          continue;
25221       }
25222       /* handle jb conf */
25223       if (!ast_jb_read_conf(&global_jbconf, v->name, v->value))
25224          continue;
25225 
25226       if (!strcasecmp(v->name, "context")) {
25227          ast_copy_string(sip_cfg.default_context, v->value, sizeof(sip_cfg.default_context));
25228       } else if (!strcasecmp(v->name, "subscribecontext")) {
25229          ast_copy_string(sip_cfg.default_subscribecontext, v->value, sizeof(sip_cfg.default_subscribecontext));
25230       } else if (!strcasecmp(v->name, "callcounter")) {
25231          global_callcounter = ast_true(v->value) ? 1 : 0;
25232       } else if (!strcasecmp(v->name, "allowguest")) {
25233          sip_cfg.allowguest = ast_true(v->value) ? 1 : 0;
25234       } else if (!strcasecmp(v->name, "realm")) {
25235          ast_copy_string(sip_cfg.realm, v->value, sizeof(sip_cfg.realm));
25236       } else if (!strcasecmp(v->name, "useragent")) {
25237          ast_copy_string(global_useragent, v->value, sizeof(global_useragent));
25238          ast_debug(1, "Setting SIP channel User-Agent Name to %s\n", global_useragent);
25239       } else if (!strcasecmp(v->name, "sdpsession")) {
25240          ast_copy_string(global_sdpsession, v->value, sizeof(global_sdpsession));
25241       } else if (!strcasecmp(v->name, "sdpowner")) {
25242          /* Field cannot contain spaces */
25243          if (!strstr(v->value, " "))
25244             ast_copy_string(global_sdpowner, v->value, sizeof(global_sdpowner));
25245          else
25246             ast_log(LOG_WARNING, "'%s' must not contain spaces at line %d.  Using default.\n", v->value, v->lineno);
25247       } else if (!strcasecmp(v->name, "allowtransfer")) {
25248          sip_cfg.allowtransfer = ast_true(v->value) ? TRANSFER_OPENFORALL : TRANSFER_CLOSED;
25249       } else if (!strcasecmp(v->name, "rtcachefriends")) {
25250          ast_set2_flag(&global_flags[1], ast_true(v->value), SIP_PAGE2_RTCACHEFRIENDS);   
25251       } else if (!strcasecmp(v->name, "rtsavesysname")) {
25252          sip_cfg.rtsave_sysname = ast_true(v->value);
25253       } else if (!strcasecmp(v->name, "rtupdate")) {
25254          sip_cfg.peer_rtupdate = ast_true(v->value);
25255       } else if (!strcasecmp(v->name, "ignoreregexpire")) {
25256          sip_cfg.ignore_regexpire = ast_true(v->value);
25257       } else if (!strcasecmp(v->name, "timert1")) {
25258          /* Defaults to 500ms, but RFC 3261 states that it is recommended
25259           * for the value to be set higher, though a lower value is only
25260           * allowed on private networks unconnected to the Internet. */
25261          global_t1 = atoi(v->value);
25262          /* Note that timer B is dependent on the value of T1 */
25263          global_timer_b = global_t1 * 64;
25264       } else if (!strcasecmp(v->name, "t1min")) {
25265          global_t1min = atoi(v->value);
25266       } else if (!strcasecmp(v->name, "transport") && !ast_strlen_zero(v->value)) {
25267          char *val = ast_strdupa(v->value);
25268          char *trans;
25269 
25270          while ((trans = strsep(&val, ","))) {
25271             trans = ast_skip_blanks(trans);
25272 
25273             if (!strncasecmp(trans, "udp", 3)) 
25274                default_transports |= SIP_TRANSPORT_UDP;
25275             else if (!strncasecmp(trans, "tcp", 3))
25276                default_transports |= SIP_TRANSPORT_TCP;
25277             else if (!strncasecmp(trans, "tls", 3))
25278                default_transports |= SIP_TRANSPORT_TLS;
25279             else
25280                ast_log(LOG_NOTICE, "'%s' is not a valid transport type. if no other is specified, udp will be used.\n", trans);
25281             if (default_primary_transport == 0) {
25282                default_primary_transport = default_transports;
25283             }
25284          }
25285       } else if (!strcasecmp(v->name, "tcpenable")) {
25286          sip_tcp_desc.local_address.sin_family = ast_false(v->value) ? 0 : AF_INET;
25287          ast_debug(2, "Enabling TCP socket for listening\n");
25288       } else if (!strcasecmp(v->name, "tcpbindaddr")) {
25289          int family = sip_tcp_desc.local_address.sin_family;
25290          if (ast_parse_arg(v->value, PARSE_INADDR, &sip_tcp_desc.local_address))
25291             ast_log(LOG_WARNING, "Invalid %s '%s' at line %d of %s\n", v->name, v->value, v->lineno, config);
25292          sip_tcp_desc.local_address.sin_family = family;
25293          ast_debug(2, "Setting TCP socket address to %s\n", v->value);
25294       } else if (!strcasecmp(v->name, "tlsenable")) {
25295          default_tls_cfg.enabled = ast_true(v->value) ? TRUE : FALSE;
25296          sip_tls_desc.local_address.sin_family = AF_INET;
25297       } else if (!strcasecmp(v->name, "tlscertfile")) {
25298          ast_free(default_tls_cfg.certfile);
25299          default_tls_cfg.certfile = ast_strdup(v->value);
25300       } else if (!strcasecmp(v->name, "tlscipher")) {
25301          ast_free(default_tls_cfg.cipher);
25302          default_tls_cfg.cipher = ast_strdup(v->value);
25303       } else if (!strcasecmp(v->name, "tlscafile")) {
25304          ast_free(default_tls_cfg.cafile);
25305          default_tls_cfg.cafile = ast_strdup(v->value);
25306       } else if (!strcasecmp(v->name, "tlscapath")) {
25307          ast_free(default_tls_cfg.capath);
25308          default_tls_cfg.capath = ast_strdup(v->value);
25309       } else if (!strcasecmp(v->name, "tlsverifyclient")) {
25310          ast_set2_flag(&default_tls_cfg.flags, ast_true(v->value), AST_SSL_VERIFY_CLIENT);   
25311       } else if (!strcasecmp(v->name, "tlsdontverifyserver")) {
25312          ast_set2_flag(&default_tls_cfg.flags, ast_true(v->value), AST_SSL_DONT_VERIFY_SERVER); 
25313       } else if (!strcasecmp(v->name, "tlsbindaddr")) {
25314          if (ast_parse_arg(v->value, PARSE_INADDR, &sip_tls_desc.local_address))
25315             ast_log(LOG_WARNING, "Invalid %s '%s' at line %d of %s\n", v->name, v->value, v->lineno, config);
25316       } else if (!strcasecmp(v->name, "dynamic_exclude_static") || !strcasecmp(v->name, "dynamic_excludes_static")) {
25317          global_dynamic_exclude_static = ast_true(v->value);
25318       } else if (!strcasecmp(v->name, "contactpermit") || !strcasecmp(v->name, "contactdeny")) {
25319          int ha_error = 0;
25320          global_contact_ha = ast_append_ha(v->name + 7, v->value, global_contact_ha, &ha_error);
25321          if (ha_error) {
25322             ast_log(LOG_ERROR, "Bad ACL entry in configuration line %d : %s\n", v->lineno, v->value);
25323          }
25324       } else if (!strcasecmp(v->name, "rtautoclear")) {
25325          int i = atoi(v->value);
25326          if (i > 0)
25327             sip_cfg.rtautoclear = i;
25328          else
25329             i = 0;
25330          ast_set2_flag(&global_flags[1], i || ast_true(v->value), SIP_PAGE2_RTAUTOCLEAR);
25331       } else if (!strcasecmp(v->name, "usereqphone")) {
25332          ast_set2_flag(&global_flags[0], ast_true(v->value), SIP_USEREQPHONE);   
25333       } else if (!strcasecmp(v->name, "prematuremedia")) {
25334          global_prematuremediafilter = ast_true(v->value);
25335       } else if (!strcasecmp(v->name, "relaxdtmf")) {
25336          global_relaxdtmf = ast_true(v->value);
25337       } else if (!strcasecmp(v->name, "vmexten")) {
25338          ast_copy_string(default_vmexten, v->value, sizeof(default_vmexten));
25339       } else if (!strcasecmp(v->name, "rtptimeout")) {
25340          if ((sscanf(v->value, "%30d", &global_rtptimeout) != 1) || (global_rtptimeout < 0)) {
25341             ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d.  Using default.\n", v->value, v->lineno);
25342             global_rtptimeout = 0;
25343          }
25344       } else if (!strcasecmp(v->name, "rtpholdtimeout")) {
25345          if ((sscanf(v->value, "%30d", &global_rtpholdtimeout) != 1) || (global_rtpholdtimeout < 0)) {
25346             ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d.  Using default.\n", v->value, v->lineno);
25347             global_rtpholdtimeout = 0;
25348          }
25349       } else if (!strcasecmp(v->name, "rtpkeepalive")) {
25350          if ((sscanf(v->value, "%30d", &global_rtpkeepalive) != 1) || (global_rtpkeepalive < 0)) {
25351             ast_log(LOG_WARNING, "'%s' is not a valid RTP keepalive time at line %d.  Using default.\n", v->value, v->lineno);
25352             global_rtpkeepalive = DEFAULT_RTPKEEPALIVE;
25353          }
25354       } else if (!strcasecmp(v->name, "compactheaders")) {
25355          sip_cfg.compactheaders = ast_true(v->value);
25356       } else if (!strcasecmp(v->name, "notifymimetype")) {
25357          ast_copy_string(default_notifymime, v->value, sizeof(default_notifymime));
25358       } else if (!strcasecmp(v->name, "directrtpsetup")) {
25359          sip_cfg.directrtpsetup = ast_true(v->value);
25360       } else if (!strcasecmp(v->name, "notifyringing")) {
25361          sip_cfg.notifyringing = ast_true(v->value);
25362       } else if (!strcasecmp(v->name, "notifyhold")) {
25363          sip_cfg.notifyhold = ast_true(v->value);
25364       } else if (!strcasecmp(v->name, "notifycid")) {
25365          if (!strcasecmp(v->value, "ignore-context")) {
25366             sip_cfg.notifycid = IGNORE_CONTEXT;
25367          } else {
25368             sip_cfg.notifycid = ast_true(v->value);
25369          }
25370       } else if (!strcasecmp(v->name, "alwaysauthreject")) {
25371          sip_cfg.alwaysauthreject = ast_true(v->value);
25372       } else if (!strcasecmp(v->name, "mohinterpret")) {
25373          ast_copy_string(default_mohinterpret, v->value, sizeof(default_mohinterpret));
25374       } else if (!strcasecmp(v->name, "mohsuggest")) {
25375          ast_copy_string(default_mohsuggest, v->value, sizeof(default_mohsuggest));
25376       } else if (!strcasecmp(v->name, "language")) {
25377          ast_copy_string(default_language, v->value, sizeof(default_language));
25378       } else if (!strcasecmp(v->name, "regcontext")) {
25379          ast_copy_string(newcontexts, v->value, sizeof(newcontexts));
25380          stringp = newcontexts;
25381          /* Let's remove any contexts that are no longer defined in regcontext */
25382          cleanup_stale_contexts(stringp, oldregcontext);
25383          /* Create contexts if they don't exist already */
25384          while ((context = strsep(&stringp, "&"))) {
25385             ast_copy_string(used_context, context, sizeof(used_context));
25386             ast_context_find_or_create(NULL, NULL, context, "SIP");
25387          }
25388          ast_copy_string(global_regcontext, v->value, sizeof(global_regcontext));
25389       } else if (!strcasecmp(v->name, "regextenonqualify")) {
25390          sip_cfg.regextenonqualify = ast_true(v->value);
25391       } else if (!strcasecmp(v->name, "callerid")) {
25392          ast_copy_string(default_callerid, v->value, sizeof(default_callerid));
25393       } else if (!strcasecmp(v->name, "fromdomain")) {
25394          ast_copy_string(default_fromdomain, v->value, sizeof(default_fromdomain));
25395       } else if (!strcasecmp(v->name, "outboundproxy")) {
25396          int portnum;
25397          char *tok, *proxyname;
25398 
25399          if (ast_strlen_zero(v->value)) {
25400             ast_log(LOG_WARNING, "no value given for outbound proxy on line %d of sip.conf.", v->lineno);
25401             continue;
25402          }
25403 
25404          tok = ast_skip_blanks(strtok(ast_strdupa(v->value), ","));
25405 
25406          sip_parse_host(tok, v->lineno, &proxyname, &portnum, &sip_cfg.outboundproxy.transport);
25407 
25408          sip_cfg.outboundproxy.ip.sin_port = htons(portnum);
25409    
25410          if ((tok = strtok(NULL, ","))) {
25411             sip_cfg.outboundproxy.force = !strncasecmp(ast_skip_blanks(tok), "force", 5);
25412          } else {
25413             sip_cfg.outboundproxy.force = FALSE;
25414          }
25415 
25416          if (ast_strlen_zero(proxyname)) {
25417             ast_log(LOG_WARNING, "you must specify a name for the outboundproxy on line %d of sip.conf.", v->lineno);
25418             sip_cfg.outboundproxy.name[0] = '\0';
25419             continue;
25420          }
25421 
25422          ast_copy_string(sip_cfg.outboundproxy.name, proxyname, sizeof(sip_cfg.outboundproxy.name));
25423 
25424          proxy_update(&sip_cfg.outboundproxy);
25425       } else if (!strcasecmp(v->name, "autocreatepeer")) {
25426          sip_cfg.autocreatepeer = ast_true(v->value);
25427       } else if (!strcasecmp(v->name, "match_auth_username")) {
25428          global_match_auth_username = ast_true(v->value);
25429       } else if (!strcasecmp(v->name, "srvlookup")) {
25430          sip_cfg.srvlookup = ast_true(v->value);
25431       } else if (!strcasecmp(v->name, "pedantic")) {
25432          sip_cfg.pedanticsipchecking = ast_true(v->value);
25433       } else if (!strcasecmp(v->name, "maxexpirey") || !strcasecmp(v->name, "maxexpiry")) {
25434          max_expiry = atoi(v->value);
25435          if (max_expiry < 1)
25436             max_expiry = DEFAULT_MAX_EXPIRY;
25437       } else if (!strcasecmp(v->name, "minexpirey") || !strcasecmp(v->name, "minexpiry")) {
25438          min_expiry = atoi(v->value);
25439          if (min_expiry < 1)
25440             min_expiry = DEFAULT_MIN_EXPIRY;
25441       } else if (!strcasecmp(v->name, "defaultexpiry") || !strcasecmp(v->name, "defaultexpirey")) {
25442          default_expiry = atoi(v->value);
25443          if (default_expiry < 1)
25444             default_expiry = DEFAULT_DEFAULT_EXPIRY;
25445       } else if (!strcasecmp(v->name, "mwiexpiry") || !strcasecmp(v->name, "mwiexpirey")) {
25446          mwi_expiry = atoi(v->value);
25447          if (mwi_expiry < 1)
25448             mwi_expiry = DEFAULT_MWI_EXPIRY;
25449       } else if (!strcasecmp(v->name, "tcpauthtimeout")) {
25450          if (ast_parse_arg(v->value, PARSE_INT32|PARSE_DEFAULT|PARSE_IN_RANGE,
25451                  &authtimeout, DEFAULT_AUTHTIMEOUT, 1, INT_MAX)) {
25452             ast_log(LOG_WARNING, "Invalid %s '%s' at line %d of %s\n",
25453                v->name, v->value, v->lineno, config);
25454          }
25455       } else if (!strcasecmp(v->name, "tcpauthlimit")) {
25456          if (ast_parse_arg(v->value, PARSE_INT32|PARSE_DEFAULT|PARSE_IN_RANGE,
25457                  &authlimit, DEFAULT_AUTHLIMIT, 1, INT_MAX)) {
25458             ast_log(LOG_WARNING, "Invalid %s '%s' at line %d of %s\n",
25459                v->name, v->value, v->lineno, config);
25460          }
25461       } else if (!strcasecmp(v->name, "sipdebug")) {
25462          if (ast_true(v->value))
25463             sipdebug |= sip_debug_config;
25464       } else if (!strcasecmp(v->name, "dumphistory")) {
25465          dumphistory = ast_true(v->value);
25466       } else if (!strcasecmp(v->name, "recordhistory")) {
25467          recordhistory = ast_true(v->value);
25468       } else if (!strcasecmp(v->name, "registertimeout")) {
25469          global_reg_timeout = atoi(v->value);
25470          if (global_reg_timeout < 1)
25471             global_reg_timeout = DEFAULT_REGISTRATION_TIMEOUT;
25472       } else if (!strcasecmp(v->name, "registerattempts")) {
25473          global_regattempts_max = atoi(v->value);
25474       } else if (!strcasecmp(v->name, "stunaddr")) {
25475          stunaddr.sin_port = htons(3478);
25476          if (ast_parse_arg(v->value, PARSE_INADDR, &stunaddr))
25477             ast_log(LOG_WARNING, "Invalid STUN server address: %s\n", v->value);
25478          externexpire = time(NULL);
25479       } else if (!strcasecmp(v->name, "bindaddr") || !strcasecmp(v->name, "udpbindaddr")) {
25480          if (ast_parse_arg(v->value, PARSE_INADDR, &bindaddr))
25481             ast_log(LOG_WARNING, "Invalid address: %s\n", v->value);
25482       } else if (!strcasecmp(v->name, "localnet")) {
25483          struct ast_ha *na;
25484          int ha_error = 0;
25485 
25486          if (!(na = ast_append_ha("d", v->value, localaddr, &ha_error)))
25487             ast_log(LOG_WARNING, "Invalid localnet value: %s\n", v->value);
25488          else
25489             localaddr = na;
25490          if (ha_error)
25491             ast_log(LOG_ERROR, "Bad localnet configuration value line %d : %s\n", v->lineno, v->value);
25492       } else if (!strcasecmp(v->name, "externip")) {
25493          if (ast_parse_arg(v->value, PARSE_INADDR, &externip))
25494             ast_log(LOG_WARNING, "Invalid address for externip keyword: %s\n", v->value);
25495          externexpire = 0;
25496          /* If no port was specified use the value of bindport */
25497          if (!externip.sin_port)
25498             externip.sin_port = bindaddr.sin_port;
25499       } else if (!strcasecmp(v->name, "externhost")) {
25500          ast_copy_string(externhost, v->value, sizeof(externhost));
25501          if (ast_parse_arg(externhost, PARSE_INADDR, &externip))
25502             ast_log(LOG_WARNING, "Invalid address for externhost keyword: %s\n", externhost);
25503          externexpire = time(NULL);
25504          /* If no port was specified use the value of bindport */
25505          if (!externip.sin_port)
25506             externip.sin_port = bindaddr.sin_port;
25507       } else if (!strcasecmp(v->name, "externrefresh")) {
25508          if (sscanf(v->value, "%30d", &externrefresh) != 1) {
25509             ast_log(LOG_WARNING, "Invalid externrefresh value '%s', must be an integer >0 at line %d\n", v->value, v->lineno);
25510             externrefresh = 10;
25511          }
25512       } else if (!strcasecmp(v->name, "allow")) {
25513          int error =  ast_parse_allow_disallow(&default_prefs, &global_capability, v->value, TRUE);
25514          if (error)
25515             ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
25516       } else if (!strcasecmp(v->name, "disallow")) {
25517          int error =  ast_parse_allow_disallow(&default_prefs, &global_capability, v->value, FALSE);
25518          if (error)
25519             ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
25520       } else if (!strcasecmp(v->name, "autoframing")) {
25521          global_autoframing = ast_true(v->value);
25522       } else if (!strcasecmp(v->name, "allowexternaldomains")) {
25523          sip_cfg.allow_external_domains = ast_true(v->value);
25524       } else if (!strcasecmp(v->name, "autodomain")) {
25525          auto_sip_domains = ast_true(v->value);
25526       } else if (!strcasecmp(v->name, "domain")) {
25527          char *domain = ast_strdupa(v->value);
25528          char *cntx = strchr(domain, ',');
25529 
25530          if (cntx)
25531             *cntx++ = '\0';
25532 
25533          if (ast_strlen_zero(cntx))
25534             ast_debug(1, "No context specified at line %d for domain '%s'\n", v->lineno, domain);
25535          if (ast_strlen_zero(domain))
25536             ast_log(LOG_WARNING, "Empty domain specified at line %d\n", v->lineno);
25537          else
25538             add_sip_domain(ast_strip(domain), SIP_DOMAIN_CONFIG, cntx ? ast_strip(cntx) : "");
25539       } else if (!strcasecmp(v->name, "register")) {
25540          if (sip_register(v->value, v->lineno) == 0)
25541             registry_count++;
25542       } else if (!strcasecmp(v->name, "mwi")) {
25543          sip_subscribe_mwi(v->value, v->lineno);
25544       } else if (!strcasecmp(v->name, "tos_sip")) {
25545          if (ast_str2tos(v->value, &global_tos_sip))
25546             ast_log(LOG_WARNING, "Invalid tos_sip value at line %d, refer to QoS documentation\n", v->lineno);
25547       } else if (!strcasecmp(v->name, "tos_audio")) {
25548          if (ast_str2tos(v->value, &global_tos_audio))
25549             ast_log(LOG_WARNING, "Invalid tos_audio value at line %d, refer to QoS documentation\n", v->lineno);
25550       } else if (!strcasecmp(v->name, "tos_video")) {
25551          if (ast_str2tos(v->value, &global_tos_video))
25552             ast_log(LOG_WARNING, "Invalid tos_video value at line %d, refer to QoS documentation\n", v->lineno);
25553       } else if (!strcasecmp(v->name, "tos_text")) {
25554          if (ast_str2tos(v->value, &global_tos_text))
25555             ast_log(LOG_WARNING, "Invalid tos_text value at line %d, refer to QoS documentation\n", v->lineno);
25556       } else if (!strcasecmp(v->name, "cos_sip")) {
25557          if (ast_str2cos(v->value, &global_cos_sip))
25558             ast_log(LOG_WARNING, "Invalid cos_sip value at line %d, refer to QoS documentation\n", v->lineno);
25559       } else if (!strcasecmp(v->name, "cos_audio")) {
25560          if (ast_str2cos(v->value, &global_cos_audio))
25561             ast_log(LOG_WARNING, "Invalid cos_audio value at line %d, refer to QoS documentation\n", v->lineno);
25562       } else if (!strcasecmp(v->name, "cos_video")) {
25563          if (ast_str2cos(v->value, &global_cos_video))
25564             ast_log(LOG_WARNING, "Invalid cos_video value at line %d, refer to QoS documentation\n", v->lineno);
25565       } else if (!strcasecmp(v->name, "cos_text")) {
25566          if (ast_str2cos(v->value, &global_cos_text))
25567             ast_log(LOG_WARNING, "Invalid cos_text value at line %d, refer to QoS documentation\n", v->lineno);
25568       } else if (!strcasecmp(v->name, "bindport")) {
25569          int i;
25570          if (sscanf(v->value, "%5d", &i) == 1) {
25571             bindaddr.sin_port = htons(i);
25572          } else {
25573             ast_log(LOG_WARNING, "Invalid port number '%s' at line %d of %s\n", v->value, v->lineno, config);
25574          }
25575       } else if (!strcasecmp(v->name, "qualify")) {
25576          if (!strcasecmp(v->value, "no")) {
25577             default_qualify = 0;
25578          } else if (!strcasecmp(v->value, "yes")) {
25579             default_qualify = DEFAULT_MAXMS;
25580          } else if (sscanf(v->value, "%30d", &default_qualify) != 1) {
25581             ast_log(LOG_WARNING, "Qualification default should be 'yes', 'no', or a number of milliseconds at line %d of sip.conf\n", v->lineno);
25582             default_qualify = 0;
25583          }
25584       } else if (!strcasecmp(v->name, "qualifyfreq")) {
25585          int i;
25586          if (sscanf(v->value, "%30d", &i) == 1)
25587             global_qualifyfreq = i * 1000;
25588          else {
25589             ast_log(LOG_WARNING, "Invalid qualifyfreq number '%s' at line %d of %s\n", v->value, v->lineno, config);
25590             global_qualifyfreq = DEFAULT_QUALIFYFREQ;
25591          }
25592       } else if (!strcasecmp(v->name, "callevents")) {
25593          sip_cfg.callevents = ast_true(v->value);
25594       } else if (!strcasecmp(v->name, "authfailureevents")) {
25595          global_authfailureevents = ast_true(v->value);
25596       } else if (!strcasecmp(v->name, "maxcallbitrate")) {
25597          default_maxcallbitrate = atoi(v->value);
25598          if (default_maxcallbitrate < 0)
25599             default_maxcallbitrate = DEFAULT_MAX_CALL_BITRATE;
25600       } else if (!strcasecmp(v->name, "matchexterniplocally")) {
25601          sip_cfg.matchexterniplocally = ast_true(v->value);
25602       } else if (!strcasecmp(v->name, "session-timers")) {
25603          int i = (int) str2stmode(v->value); 
25604          if (i < 0) {
25605             ast_log(LOG_WARNING, "Invalid session-timers '%s' at line %d of %s\n", v->value, v->lineno, config);
25606             global_st_mode = SESSION_TIMER_MODE_ACCEPT;
25607          } else {
25608             global_st_mode = i;
25609          }
25610       } else if (!strcasecmp(v->name, "session-expires")) {
25611          if (sscanf(v->value, "%30d", &global_max_se) != 1) {
25612             ast_log(LOG_WARNING, "Invalid session-expires '%s' at line %d of %s\n", v->value, v->lineno, config);
25613             global_max_se = DEFAULT_MAX_SE;
25614          } 
25615       } else if (!strcasecmp(v->name, "session-minse")) {
25616          if (sscanf(v->value, "%30d", &global_min_se) != 1) {
25617             ast_log(LOG_WARNING, "Invalid session-minse '%s' at line %d of %s\n", v->value, v->lineno, config);
25618             global_min_se = DEFAULT_MIN_SE;
25619          } 
25620          if (global_min_se < 90) {
25621             ast_log(LOG_WARNING, "session-minse '%s' at line %d of %s is not allowed to be < 90 secs\n", v->value, v->lineno, config);
25622             global_min_se = DEFAULT_MIN_SE;
25623          } 
25624       } else if (!strcasecmp(v->name, "session-refresher")) {
25625          int i = (int) str2strefresher(v->value); 
25626          if (i < 0) {
25627             ast_log(LOG_WARNING, "Invalid session-refresher '%s' at line %d of %s\n", v->value, v->lineno, config);
25628             global_st_refresher = SESSION_TIMER_REFRESHER_UAS;
25629          } else {
25630             global_st_refresher = i;
25631          }
25632       } else if (!strcasecmp(v->name, "qualifygap")) {
25633          if (sscanf(v->value, "%30d", &global_qualify_gap) != 1) {
25634             ast_log(LOG_WARNING, "Invalid qualifygap '%s' at line %d of %s\n", v->value, v->lineno, config);
25635             global_qualify_gap = DEFAULT_QUALIFY_GAP;
25636          }
25637       } else if (!strcasecmp(v->name, "qualifypeers")) {
25638          if (sscanf(v->value, "%30d", &global_qualify_peers) != 1) {
25639             ast_log(LOG_WARNING, "Invalid pokepeers '%s' at line %d of %s\n", v->value, v->lineno, config);
25640             global_qualify_peers = DEFAULT_QUALIFY_PEERS;
25641          }
25642       } else if (!strcasecmp(v->name, "shrinkcallerid")) {
25643          if (ast_true(v->value)) {
25644             global_shrinkcallerid = 1;
25645          } else if (ast_false(v->value)) {
25646             global_shrinkcallerid = 0;
25647          } else {
25648             ast_log(LOG_WARNING, "shrinkcallerid value %s is not valid at line %d.\n", v->value, v->lineno);
25649          }
25650       }
25651    }
25652 
25653    if (!sip_cfg.allow_external_domains && AST_LIST_EMPTY(&domain_list)) {
25654       ast_log(LOG_WARNING, "To disallow external domains, you need to configure local SIP domains.\n");
25655       sip_cfg.allow_external_domains = 1;
25656    }
25657    /* If not configured, set default transports */
25658    if (default_transports == 0) {
25659       default_transports = default_primary_transport = SIP_TRANSPORT_UDP;
25660    }
25661    
25662    /* Build list of authentication to various SIP realms, i.e. service providers */
25663    for (v = ast_variable_browse(cfg, "authentication"); v ; v = v->next) {
25664       /* Format for authentication is auth = username:password@realm */
25665       if (!strcasecmp(v->name, "auth"))
25666          authl = add_realm_authentication(authl, v->value, v->lineno);
25667    }
25668 
25669    /* Set UDP address and open socket */
25670    bindaddr.sin_family = AF_INET;
25671    internip = bindaddr;
25672    if (ast_find_ourip(&internip.sin_addr, bindaddr)) {
25673       ast_log(LOG_WARNING, "Unable to get own IP address, SIP disabled\n");
25674       ast_config_destroy(cfg);
25675       return 0;
25676    }
25677 
25678    ast_mutex_lock(&netlock);
25679    if ((sipsock > -1) && (memcmp(&old_bindaddr, &bindaddr, sizeof(struct sockaddr_in)))) {
25680       close(sipsock);
25681       sipsock = -1;
25682    }
25683    if (sipsock < 0) {
25684       sipsock = socket(AF_INET, SOCK_DGRAM, 0);
25685       if (sipsock < 0) {
25686          ast_log(LOG_WARNING, "Unable to create SIP socket: %s\n", strerror(errno));
25687          ast_config_destroy(cfg);
25688          ast_mutex_unlock(&netlock);
25689          return -1;
25690       } else {
25691          /* Allow SIP clients on the same host to access us: */
25692          const int reuseFlag = 1;
25693 
25694          setsockopt(sipsock, SOL_SOCKET, SO_REUSEADDR,
25695                (const char*)&reuseFlag,
25696                sizeof reuseFlag);
25697 
25698          ast_enable_packet_fragmentation(sipsock);
25699 
25700          if (bind(sipsock, (struct sockaddr *)&bindaddr, sizeof(bindaddr)) < 0) {
25701             ast_log(LOG_WARNING, "Failed to bind to %s:%d: %s\n",
25702             ast_inet_ntoa(bindaddr.sin_addr), ntohs(bindaddr.sin_port),
25703             strerror(errno));
25704             close(sipsock);
25705             sipsock = -1;
25706          } else {
25707             ast_verb(2, "SIP Listening on %s:%d\n",
25708                   ast_inet_ntoa(bindaddr.sin_addr), ntohs(bindaddr.sin_port));
25709             ast_netsock_set_qos(sipsock, global_tos_sip, global_cos_sip, "SIP");
25710          }
25711       }
25712    } else {
25713       ast_netsock_set_qos(sipsock, global_tos_sip, global_cos_sip, "SIP");
25714    }
25715    if (stunaddr.sin_addr.s_addr != 0) {
25716       ast_debug(1, "stun to %s:%d\n",
25717          ast_inet_ntoa(stunaddr.sin_addr) , ntohs(stunaddr.sin_port));
25718       ast_stun_request(sipsock, &stunaddr,
25719          NULL, &externip);
25720       ast_debug(1, "STUN sees us at %s:%d\n", 
25721          ast_inet_ntoa(externip.sin_addr) , ntohs(externip.sin_port));
25722    }
25723    ast_mutex_unlock(&netlock);
25724 
25725    /* Start TCP server */
25726    ast_tcptls_server_start(&sip_tcp_desc);
25727    if (sip_tcp_desc.accept_fd == -1 &&  sip_tcp_desc.local_address.sin_family == AF_INET) {
25728       /* TCP server start failed. Tell the admin */
25729       ast_log(LOG_ERROR, "SIP TCP Server start failed. Not listening on TCP socket.\n");
25730       sip_tcp_desc.local_address.sin_family = 0;
25731    } else {
25732       ast_debug(2, "SIP TCP server started\n");
25733    }
25734 
25735    /* Start TLS server if needed */
25736    memcpy(sip_tls_desc.tls_cfg, &default_tls_cfg, sizeof(default_tls_cfg));
25737 
25738    if (ast_ssl_setup(sip_tls_desc.tls_cfg)) {
25739       ast_tcptls_server_start(&sip_tls_desc);
25740       if (default_tls_cfg.enabled && sip_tls_desc.accept_fd == -1) {
25741          ast_log(LOG_ERROR, "TLS Server start failed. Not listening on TLS socket.\n");
25742          sip_tls_desc.tls_cfg = NULL;
25743       }
25744    } else if (sip_tls_desc.tls_cfg->enabled) {
25745       sip_tls_desc.tls_cfg = NULL;
25746       ast_log(LOG_WARNING, "SIP TLS server did not load because of errors.\n");
25747    }
25748 
25749    if (ucfg) {
25750       struct ast_variable *gen;
25751       int genhassip, genregistersip;
25752       const char *hassip, *registersip;
25753       
25754       genhassip = ast_true(ast_variable_retrieve(ucfg, "general", "hassip"));
25755       genregistersip = ast_true(ast_variable_retrieve(ucfg, "general", "registersip"));
25756       gen = ast_variable_browse(ucfg, "general");
25757       cat = ast_category_browse(ucfg, NULL);
25758       while (cat) {
25759          if (strcasecmp(cat, "general")) {
25760             hassip = ast_variable_retrieve(ucfg, cat, "hassip");
25761             registersip = ast_variable_retrieve(ucfg, cat, "registersip");
25762             if (ast_true(hassip) || (!hassip && genhassip)) {
25763                peer = build_peer(cat, gen, ast_variable_browse(ucfg, cat), 0, 0);
25764                if (peer) {
25765                   /* user.conf entries are always of type friend */
25766                   peer->type = SIP_TYPE_USER | SIP_TYPE_PEER;
25767                   ao2_t_link(peers, peer, "link peer into peer table");
25768                   if ((peer->type & SIP_TYPE_PEER) && peer->addr.sin_addr.s_addr) {
25769                      ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
25770                   }
25771                   
25772                   unref_peer(peer, "unref_peer: from reload_config");
25773                   peer_count++;
25774                }
25775             }
25776             if (ast_true(registersip) || (!registersip && genregistersip)) {
25777                char tmp[256];
25778                const char *host = ast_variable_retrieve(ucfg, cat, "host");
25779                const char *username = ast_variable_retrieve(ucfg, cat, "username");
25780                const char *secret = ast_variable_retrieve(ucfg, cat, "secret");
25781                const char *contact = ast_variable_retrieve(ucfg, cat, "contact");
25782                const char *authuser = ast_variable_retrieve(ucfg, cat, "authuser");
25783                if (!host)
25784                   host = ast_variable_retrieve(ucfg, "general", "host");
25785                if (!username)
25786                   username = ast_variable_retrieve(ucfg, "general", "username");
25787                if (!secret)
25788                   secret = ast_variable_retrieve(ucfg, "general", "secret");
25789                if (!contact)
25790                   contact = "s";
25791                if (!ast_strlen_zero(username) && !ast_strlen_zero(host)) {
25792                   if (!ast_strlen_zero(secret)) {
25793                      if (!ast_strlen_zero(authuser)) {
25794                         snprintf(tmp, sizeof(tmp), "%s?%s:%s:%s@%s/%s", cat, username, secret, authuser, host, contact);
25795                      } else {
25796                         snprintf(tmp, sizeof(tmp), "%s?%s:%s@%s/%s", cat, username, secret, host, contact);
25797                      }
25798                   } else if (!ast_strlen_zero(authuser)) {
25799                      snprintf(tmp, sizeof(tmp), "%s?%s::%s@%s/%s", cat, username, authuser, host, contact);
25800                   } else {
25801                      snprintf(tmp, sizeof(tmp), "%s?%s@%s/%s", cat, username, host, contact);
25802                   }
25803                   if (sip_register(tmp, 0) == 0)
25804                      registry_count++;
25805                }
25806             }
25807          }
25808          cat = ast_category_browse(ucfg, cat);
25809       }
25810       ast_config_destroy(ucfg);
25811    }
25812 
25813    /* Load peers, users and friends */
25814    cat = NULL;
25815    while ( (cat = ast_category_browse(cfg, cat)) ) {
25816       const char *utype;
25817       if (!strcasecmp(cat, "general") || !strcasecmp(cat, "authentication"))
25818          continue;
25819       utype = ast_variable_retrieve(cfg, cat, "type");
25820       if (!utype) {
25821          ast_log(LOG_WARNING, "Section '%s' lacks type\n", cat);
25822          continue;
25823       } else {
25824          if (!strcasecmp(utype, "user")) {
25825             ;
25826          } else if (!strcasecmp(utype, "friend")) {
25827             ;
25828          } else if (!strcasecmp(utype, "peer")) {
25829             ;
25830          } else {
25831             ast_log(LOG_WARNING, "Unknown type '%s' for '%s' in %s\n", utype, cat, "sip.conf");
25832             continue;
25833          }
25834          peer = build_peer(cat, ast_variable_browse(cfg, cat), NULL, 0, 0);
25835          if (peer) {
25836             ao2_t_link(peers, peer, "link peer into peers table");
25837             if ((peer->type & SIP_TYPE_PEER) && peer->addr.sin_addr.s_addr) {
25838                ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
25839             }
25840             unref_peer(peer, "unref the result of the build_peer call. Now, the links from the tables are the only ones left.");
25841             peer_count++;
25842          }
25843       }
25844    }
25845 
25846    /* Add default domains - host name, IP address and IP:port
25847     * Only do this if user added any sip domain with "localdomains" 
25848     * In order to *not* break backwards compatibility 
25849     *    Some phones address us at IP only, some with additional port number 
25850     */
25851    if (auto_sip_domains) {
25852       char temp[MAXHOSTNAMELEN];
25853 
25854       /* First our default IP address */
25855       if (bindaddr.sin_addr.s_addr) {
25856          add_sip_domain(ast_inet_ntoa(bindaddr.sin_addr), SIP_DOMAIN_AUTO, NULL);
25857       } else if (internip.sin_addr.s_addr) {
25858       /* Our internal IP address, if configured */
25859          add_sip_domain(ast_inet_ntoa(internip.sin_addr), SIP_DOMAIN_AUTO, NULL);
25860       } else {
25861          ast_log(LOG_NOTICE, "Can't add wildcard IP address to domain list, please add IP address to domain manually.\n");
25862       }
25863 
25864       /* If TCP is running on a different IP than UDP, then add it too */
25865       if (sip_tcp_desc.local_address.sin_addr.s_addr && !inaddrcmp(&bindaddr, &sip_tcp_desc.local_address))
25866          add_sip_domain(ast_inet_ntoa(sip_tcp_desc.local_address.sin_addr), SIP_DOMAIN_AUTO, NULL);
25867 
25868       /* If TLS is running on a differen IP than UDP and TCP, then add that too */
25869       if (sip_tls_desc.local_address.sin_addr.s_addr && !inaddrcmp(&bindaddr, &sip_tls_desc.local_address) && inaddrcmp(&sip_tcp_desc.local_address, &sip_tls_desc.local_address))
25870          add_sip_domain(ast_inet_ntoa(sip_tls_desc.local_address.sin_addr), SIP_DOMAIN_AUTO, NULL);
25871 
25872       /* Our extern IP address, if configured */
25873       if (externip.sin_addr.s_addr)
25874          add_sip_domain(ast_inet_ntoa(externip.sin_addr), SIP_DOMAIN_AUTO, NULL);
25875 
25876       /* Extern host name (NAT traversal support) */
25877       if (!ast_strlen_zero(externhost))
25878          add_sip_domain(externhost, SIP_DOMAIN_AUTO, NULL);
25879       
25880       /* Our host name */
25881       if (!gethostname(temp, sizeof(temp)))
25882          add_sip_domain(temp, SIP_DOMAIN_AUTO, NULL);
25883    }
25884 
25885    /* Release configuration from memory */
25886    ast_config_destroy(cfg);
25887 
25888    /* Load the list of manual NOTIFY types to support */
25889    if (notify_types)
25890       ast_config_destroy(notify_types);
25891    if ((notify_types = ast_config_load(notify_config, config_flags)) == CONFIG_STATUS_FILEINVALID) {
25892       ast_log(LOG_ERROR, "Contents of %s are invalid and cannot be parsed.\n", notify_config);
25893       notify_types = NULL;
25894    }
25895 
25896    /* Done, tell the manager */
25897    manager_event(EVENT_FLAG_SYSTEM, "ChannelReload", "ChannelType: SIP\r\nReloadReason: %s\r\nRegistry_Count: %d\r\nPeer_Count: %d\r\n", channelreloadreason2txt(reason), registry_count, peer_count);
25898    run_end = time(0);
25899    ast_debug(4, "SIP reload_config done...Runtime= %d sec\n", (int)(run_end-run_start));
25900 
25901    return 0;
25902 }
25903 
25904 static struct ast_udptl *sip_get_udptl_peer(struct ast_channel *chan)
25905 {
25906    struct sip_pvt *p;
25907    struct ast_udptl *udptl = NULL;
25908    
25909    p = chan->tech_pvt;
25910    if (!p)
25911       return NULL;
25912    
25913    sip_pvt_lock(p);
25914    if (p->udptl && ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA))
25915       udptl = p->udptl;
25916    sip_pvt_unlock(p);
25917    return udptl;
25918 }
25919 
25920 static int sip_set_udptl_peer(struct ast_channel *chan, struct ast_udptl *udptl)
25921 {
25922    struct sip_pvt *p;
25923    
25924    p = chan->tech_pvt;
25925    if (!p)
25926       return -1;
25927    sip_pvt_lock(p);
25928    if (udptl)
25929       ast_udptl_get_peer(udptl, &p->udptlredirip);
25930    else
25931       memset(&p->udptlredirip, 0, sizeof(p->udptlredirip));
25932    if (!ast_test_flag(&p->flags[0], SIP_GOTREFER)) {
25933       if (!p->pendinginvite) {
25934          ast_debug(3, "Sending reinvite on SIP '%s' - It's UDPTL soon redirected to IP %s:%d\n", p->callid, ast_inet_ntoa(udptl ? p->udptlredirip.sin_addr : p->ourip.sin_addr), udptl ? ntohs(p->udptlredirip.sin_port) : 0);
25935          transmit_reinvite_with_sdp(p, TRUE, FALSE);
25936       } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
25937          ast_debug(3, "Deferring reinvite on SIP '%s' - It's UDPTL will be redirected to IP %s:%d\n", p->callid, ast_inet_ntoa(udptl ? p->udptlredirip.sin_addr : p->ourip.sin_addr), udptl ? ntohs(p->udptlredirip.sin_port) : 0);
25938          ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
25939       }
25940    }
25941    /* Reset lastrtprx timer */
25942    p->lastrtprx = p->lastrtptx = time(NULL);
25943    sip_pvt_unlock(p);
25944    return 0;
25945 }
25946 
25947 /*! \brief Returns null if we can't reinvite audio (part of RTP interface) */
25948 static enum ast_rtp_get_result sip_get_rtp_peer(struct ast_channel *chan, struct ast_rtp **rtp)
25949 {
25950    struct sip_pvt *p = NULL;
25951    enum ast_rtp_get_result res = AST_RTP_TRY_PARTIAL;
25952 
25953    if (!(p = chan->tech_pvt))
25954       return AST_RTP_GET_FAILED;
25955 
25956    sip_pvt_lock(p);
25957    if (!(p->rtp)) {
25958       sip_pvt_unlock(p);
25959       return AST_RTP_GET_FAILED;
25960    }
25961 
25962    *rtp = p->rtp;
25963 
25964    if (ast_rtp_getnat(*rtp) && !ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA_NAT))
25965       res = AST_RTP_TRY_PARTIAL;
25966    else if (ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA))
25967       res = AST_RTP_TRY_NATIVE;
25968    else if (ast_test_flag(&global_jbconf, AST_JB_FORCED))
25969       res = AST_RTP_GET_FAILED;
25970 
25971    sip_pvt_unlock(p);
25972 
25973    return res;
25974 }
25975 
25976 /*! \brief Returns null if we can't reinvite video (part of RTP interface) */
25977 static enum ast_rtp_get_result sip_get_vrtp_peer(struct ast_channel *chan, struct ast_rtp **rtp)
25978 {
25979    struct sip_pvt *p = NULL;
25980    enum ast_rtp_get_result res = AST_RTP_TRY_PARTIAL;
25981    
25982    if (!(p = chan->tech_pvt))
25983       return AST_RTP_GET_FAILED;
25984 
25985    sip_pvt_lock(p);
25986    if (!(p->vrtp)) {
25987       sip_pvt_unlock(p);
25988       return AST_RTP_GET_FAILED;
25989    }
25990 
25991    *rtp = p->vrtp;
25992 
25993    if (ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA))
25994       res = AST_RTP_TRY_NATIVE;
25995 
25996    sip_pvt_unlock(p);
25997 
25998    return res;
25999 }
26000 
26001 /*! \brief Returns null if we can't reinvite text (part of RTP interface) */
26002 static enum ast_rtp_get_result sip_get_trtp_peer(struct ast_channel *chan, struct ast_rtp **rtp)
26003 {
26004    struct sip_pvt *p = NULL;
26005    enum ast_rtp_get_result res = AST_RTP_TRY_PARTIAL;
26006    
26007    if (!(p = chan->tech_pvt))
26008       return AST_RTP_GET_FAILED;
26009 
26010    sip_pvt_lock(p);
26011    if (!(p->trtp)) {
26012       sip_pvt_unlock(p);
26013       return AST_RTP_GET_FAILED;
26014    }
26015 
26016    *rtp = p->trtp;
26017 
26018    if (ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA))
26019       res = AST_RTP_TRY_NATIVE;
26020 
26021    sip_pvt_unlock(p);
26022 
26023    return res;
26024 }
26025 
26026 /*! \brief Set the RTP peer for this call */
26027 static int sip_set_rtp_peer(struct ast_channel *chan, struct ast_rtp *rtp, struct ast_rtp *vrtp, struct ast_rtp *trtp, int codecs, int nat_active)
26028 {
26029    struct sip_pvt *p;
26030    int changed = 0;
26031 
26032    p = chan->tech_pvt;
26033    if (!p) 
26034       return -1;
26035 
26036    /* Disable early RTP bridge  */
26037    if (!ast_bridged_channel(chan) && !sip_cfg.directrtpsetup)  /* We are in early state */
26038       return 0;
26039 
26040    sip_pvt_lock(p);
26041    if (p->alreadygone) {
26042       /* If we're destroyed, don't bother */
26043       sip_pvt_unlock(p);
26044       return 0;
26045    }
26046 
26047    /* if this peer cannot handle reinvites of the media stream to devices
26048       that are known to be behind a NAT, then stop the process now
26049    */
26050         if (nat_active && !ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA_NAT)) {
26051                 sip_pvt_unlock(p);
26052                 return 0;
26053         }
26054 
26055    if (rtp) {
26056       changed |= ast_rtp_get_peer(rtp, &p->redirip);
26057    } else if (p->redirip.sin_addr.s_addr || ntohs(p->redirip.sin_port) != 0) {
26058       memset(&p->redirip, 0, sizeof(p->redirip));
26059       changed = 1;
26060    }
26061    if (vrtp) {
26062       changed |= ast_rtp_get_peer(vrtp, &p->vredirip);
26063    } else if (p->vredirip.sin_addr.s_addr || ntohs(p->vredirip.sin_port) != 0) {
26064       memset(&p->vredirip, 0, sizeof(p->vredirip));
26065       changed = 1;
26066    }
26067    if (trtp) {
26068       changed |= ast_rtp_get_peer(trtp, &p->tredirip);
26069    } else if (p->tredirip.sin_addr.s_addr || ntohs(p->tredirip.sin_port) != 0) {
26070       memset(&p->tredirip, 0, sizeof(p->tredirip));
26071       changed = 1;
26072    }
26073    if (codecs && (p->redircodecs != codecs)) {
26074       p->redircodecs = codecs;
26075       changed = 1;
26076    }
26077    if (changed && !ast_test_flag(&p->flags[0], SIP_GOTREFER) && !ast_test_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER)) {
26078       if (chan->_state != AST_STATE_UP) { /* We are in early state */
26079          if (p->do_history)
26080             append_history(p, "ExtInv", "Initial invite sent with remote bridge proposal.");
26081          ast_debug(1, "Early remote bridge setting SIP '%s' - Sending media to %s\n", p->callid, ast_inet_ntoa(rtp ? p->redirip.sin_addr : p->ourip.sin_addr));
26082       } else if (!p->pendinginvite) {     /* We are up, and have no outstanding invite */
26083          ast_debug(3, "Sending reinvite on SIP '%s' - It's audio soon redirected to IP %s\n", p->callid, ast_inet_ntoa(rtp ? p->redirip.sin_addr : p->ourip.sin_addr));
26084          transmit_reinvite_with_sdp(p, FALSE, FALSE);
26085       } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
26086          ast_debug(3, "Deferring reinvite on SIP '%s' - It's audio will be redirected to IP %s\n", p->callid, ast_inet_ntoa(rtp ? p->redirip.sin_addr : p->ourip.sin_addr));
26087          /* We have a pending Invite. Send re-invite when we're done with the invite */
26088          ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);   
26089       }
26090    }
26091    /* Reset lastrtprx timer */
26092    p->lastrtprx = p->lastrtptx = time(NULL);
26093    sip_pvt_unlock(p);
26094    return 0;
26095 }
26096 
26097 static char *app_dtmfmode = "SIPDtmfMode";
26098 static char *app_sipaddheader = "SIPAddHeader";
26099 static char *app_sipremoveheader = "SIPRemoveHeader";
26100 
26101 /*! \brief Set the DTMFmode for an outbound SIP call (application) */
26102 static int sip_dtmfmode(struct ast_channel *chan, void *data)
26103 {
26104    struct sip_pvt *p;
26105    char *mode = data;
26106 
26107    if (!data) {
26108       ast_log(LOG_WARNING, "This application requires the argument: info, inband, rfc2833\n");
26109       return 0;
26110    }
26111    ast_channel_lock(chan);
26112    if (!IS_SIP_TECH(chan->tech)) {
26113       ast_log(LOG_WARNING, "Call this application only on SIP incoming calls\n");
26114       ast_channel_unlock(chan);
26115       return 0;
26116    }
26117    p = chan->tech_pvt;
26118    if (!p) {
26119       ast_channel_unlock(chan);
26120       return 0;
26121    }
26122    sip_pvt_lock(p);
26123    if (!strcasecmp(mode, "info")) {
26124       ast_clear_flag(&p->flags[0], SIP_DTMF);
26125       ast_set_flag(&p->flags[0], SIP_DTMF_INFO);
26126       p->jointnoncodeccapability &= ~AST_RTP_DTMF;
26127    } else if (!strcasecmp(mode, "shortinfo")) {
26128       ast_clear_flag(&p->flags[0], SIP_DTMF);
26129       ast_set_flag(&p->flags[0], SIP_DTMF_SHORTINFO);
26130       p->jointnoncodeccapability &= ~AST_RTP_DTMF;
26131    } else if (!strcasecmp(mode, "rfc2833")) {
26132       ast_clear_flag(&p->flags[0], SIP_DTMF);
26133       ast_set_flag(&p->flags[0], SIP_DTMF_RFC2833);
26134       p->jointnoncodeccapability |= AST_RTP_DTMF;
26135    } else if (!strcasecmp(mode, "inband")) { 
26136       ast_clear_flag(&p->flags[0], SIP_DTMF);
26137       ast_set_flag(&p->flags[0], SIP_DTMF_INBAND);
26138       p->jointnoncodeccapability &= ~AST_RTP_DTMF;
26139    } else
26140       ast_log(LOG_WARNING, "I don't know about this dtmf mode: %s\n", mode);
26141    if (p->rtp)
26142       ast_rtp_setdtmf(p->rtp, ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
26143    if (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) {
26144       if (!p->dsp) {
26145          p->dsp = ast_dsp_new();
26146          ast_dsp_set_features(p->dsp, DSP_FEATURE_DIGIT_DETECT);
26147       }
26148    } else {
26149       if (p->dsp) {
26150          ast_dsp_free(p->dsp);
26151          p->dsp = NULL;
26152       }
26153    }
26154    sip_pvt_unlock(p);
26155    ast_channel_unlock(chan);
26156    return 0;
26157 }
26158 
26159 /*! \brief Add a SIP header to an outbound INVITE */
26160 static int sip_addheader(struct ast_channel *chan, void *data)
26161 {
26162    int no = 0;
26163    int ok = FALSE;
26164    char varbuf[30];
26165    char *inbuf = data, *subbuf;
26166    
26167    if (ast_strlen_zero(inbuf)) {
26168       ast_log(LOG_WARNING, "This application requires the argument: Header\n");
26169       return 0;
26170    }
26171    ast_channel_lock(chan);
26172 
26173    /* Check for headers */
26174    while (!ok && no <= 50) {
26175       no++;
26176       snprintf(varbuf, sizeof(varbuf), "__SIPADDHEADER%.2d", no);
26177 
26178       /* Compare without the leading underscores */
26179       if ((pbx_builtin_getvar_helper(chan, (const char *) varbuf + 2) == (const char *) NULL)) {
26180          ok = TRUE;
26181       }
26182    }
26183    if (ok) {
26184       size_t len = strlen(inbuf);
26185       subbuf = alloca(len + 1);
26186       ast_get_encoded_str(inbuf, subbuf, len + 1);
26187       pbx_builtin_setvar_helper(chan, varbuf, subbuf);
26188       if (sipdebug) {
26189          ast_debug(1, "SIP Header added \"%s\" as %s\n", inbuf, varbuf);
26190       }
26191    } else {
26192       ast_log(LOG_WARNING, "Too many SIP headers added, max 50\n");
26193    }
26194    ast_channel_unlock(chan);
26195    return 0;
26196 }
26197 
26198 /*! \brief Remove SIP headers added previously with SipAddHeader application */
26199 static int sip_removeheader(struct ast_channel *chan, void *data)
26200 {
26201    struct ast_var_t *newvariable;
26202    struct varshead *headp;
26203    int removeall = 0;
26204    char *inbuf = (char *) data;
26205 
26206    if (ast_strlen_zero(inbuf)) {
26207       removeall = 1;
26208    }
26209    ast_channel_lock(chan);
26210  
26211    headp=&chan->varshead;
26212    AST_LIST_TRAVERSE_SAFE_BEGIN (headp, newvariable, entries) {
26213       if (strncasecmp(ast_var_name(newvariable), "SIPADDHEADER", strlen("SIPADDHEADER")) == 0) {
26214          if (removeall || (!strncasecmp(ast_var_value(newvariable),inbuf,strlen(inbuf)))) {
26215             if (sipdebug)
26216                ast_log(LOG_DEBUG,"removing SIP Header \"%s\" as %s\n",
26217                   ast_var_value(newvariable),
26218                   ast_var_name(newvariable));
26219             AST_LIST_REMOVE_CURRENT(entries);
26220             ast_var_delete(newvariable);
26221          }
26222       }
26223    }
26224    AST_LIST_TRAVERSE_SAFE_END;
26225  
26226    ast_channel_unlock(chan);
26227    return 0;
26228 }
26229 
26230 /*! \brief Transfer call before connect with a 302 redirect
26231 \note Called by the transfer() dialplan application through the sip_transfer()
26232    pbx interface function if the call is in ringing state 
26233 \todo Fix this function so that we wait for reply to the REFER and
26234    react to errors, denials or other issues the other end might have.
26235  */
26236 static int sip_sipredirect(struct sip_pvt *p, const char *dest)
26237 {
26238    char *cdest;
26239    char *extension, *host, *port;
26240    char tmp[80];
26241 
26242    cdest = ast_strdupa(dest);
26243    
26244    extension = strsep(&cdest, "@");
26245    host = strsep(&cdest, ":");
26246    port = strsep(&cdest, ":");
26247    if (ast_strlen_zero(extension)) {
26248       ast_log(LOG_ERROR, "Missing mandatory argument: extension\n");
26249       return 0;
26250    }
26251 
26252    /* we'll issue the redirect message here */
26253    if (!host) {
26254       char *localtmp;
26255 
26256       ast_copy_string(tmp, get_header(&p->initreq, "To"), sizeof(tmp));
26257       if (ast_strlen_zero(tmp)) {
26258          ast_log(LOG_ERROR, "Cannot retrieve the 'To' header from the original SIP request!\n");
26259          return 0;
26260       }
26261       if ( ( (localtmp = strcasestr(tmp, "sip:")) || (localtmp = strcasestr(tmp, "sips:")) ) 
26262          && (localtmp = strchr(localtmp, '@'))) {
26263          char lhost[80], lport[80];
26264 
26265          memset(lhost, 0, sizeof(lhost));
26266          memset(lport, 0, sizeof(lport));
26267          localtmp++;
26268          /* This is okey because lhost and lport are as big as tmp */
26269          sscanf(localtmp, "%80[^<>:; ]:%80[^<>:; ]", lhost, lport);
26270          if (ast_strlen_zero(lhost)) {
26271             ast_log(LOG_ERROR, "Can't find the host address\n");
26272             return 0;
26273          }
26274          host = ast_strdupa(lhost);
26275          if (!ast_strlen_zero(lport)) {
26276             port = ast_strdupa(lport);
26277          }
26278       }
26279    }
26280 
26281    ast_string_field_build(p, our_contact, "Transfer <sip:%s@%s%s%s>", extension, host, port ? ":" : "", port ? port : "");
26282    transmit_response_reliable(p, "302 Moved Temporarily", &p->initreq);
26283 
26284    sip_scheddestroy(p, SIP_TRANS_TIMEOUT);   /* Make sure we stop send this reply. */
26285    sip_alreadygone(p);
26286    /* hangup here */
26287    return 0;
26288 }
26289 
26290 /*! \brief Return SIP UA's codec (part of the RTP interface) */
26291 static int sip_get_codec(struct ast_channel *chan)
26292 {
26293    struct sip_pvt *p = chan->tech_pvt;
26294    return p->jointcapability ? p->jointcapability : p->capability;   
26295 }
26296 
26297 /*! \brief Send a poke to all known peers */
26298 static void sip_poke_all_peers(void)
26299 {
26300    int ms = 0, num = 0;
26301    struct ao2_iterator i;
26302    struct sip_peer *peer;
26303 
26304    if (!speerobjs)   /* No peers, just give up */
26305       return;
26306 
26307    i = ao2_iterator_init(peers, 0);
26308    while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
26309       ao2_lock(peer);
26310       if (num == global_qualify_peers) {
26311          ms += global_qualify_gap;
26312          num = 0;
26313       } else {
26314          num++;
26315       }
26316       AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched, ms, sip_poke_peer_s, peer,
26317             unref_peer(_data, "removing poke peer ref"),
26318             unref_peer(peer, "removing poke peer ref"),
26319             ref_peer(peer, "adding poke peer ref"));
26320       ao2_unlock(peer);
26321       unref_peer(peer, "toss iterator peer ptr");
26322    }
26323    ao2_iterator_destroy(&i);
26324 }
26325 
26326 /*! \brief Send all known registrations */
26327 static void sip_send_all_registers(void)
26328 {
26329    int ms;
26330    int regspacing;
26331    if (!regobjs)
26332       return;
26333    regspacing = default_expiry * 1000/regobjs;
26334    if (regspacing > 100)
26335       regspacing = 100;
26336    ms = regspacing;
26337    ASTOBJ_CONTAINER_TRAVERSE(&regl, 1, do {
26338       ASTOBJ_WRLOCK(iterator);
26339       ms += regspacing;
26340       AST_SCHED_REPLACE_UNREF(iterator->expire, sched, ms, sip_reregister, iterator, 
26341                         registry_unref(_data, "REPLACE sched del decs the refcount"),
26342                         registry_unref(iterator, "REPLACE sched add failure decs the refcount"),
26343                         registry_addref(iterator, "REPLACE sched add incs the refcount"));
26344       ASTOBJ_UNLOCK(iterator);
26345    } while (0)
26346    );
26347 }
26348 
26349 /*! \brief Send all MWI subscriptions */
26350 static void sip_send_all_mwi_subscriptions(void)
26351 {
26352    ASTOBJ_CONTAINER_TRAVERSE(&submwil, 1, do {
26353       ASTOBJ_WRLOCK(iterator);
26354       AST_SCHED_DEL(sched, iterator->resub);
26355       if ((iterator->resub = ast_sched_add(sched, 1, sip_subscribe_mwi_do, ASTOBJ_REF(iterator))) < 0) {
26356          ASTOBJ_UNREF(iterator, sip_subscribe_mwi_destroy);
26357       }
26358       ASTOBJ_UNLOCK(iterator);
26359    } while (0));
26360 }
26361 
26362 /*! \brief Reload module */
26363 static int sip_do_reload(enum channelreloadreason reason)
26364 {
26365    time_t start_poke, end_poke;
26366    
26367    reload_config(reason);
26368    ast_sched_dump(sched);
26369 
26370    start_poke = time(0);
26371    /* Prune peers who still are supposed to be deleted */
26372    unlink_marked_peers_from_tables();
26373 
26374    ast_debug(4, "--------------- Done destroying pruned peers\n");
26375 
26376    /* Send qualify (OPTIONS) to all peers */
26377    sip_poke_all_peers();
26378 
26379    /* Register with all services */
26380    sip_send_all_registers();
26381 
26382    sip_send_all_mwi_subscriptions();
26383 
26384    end_poke = time(0);
26385    
26386    ast_debug(4, "do_reload finished. peer poke/prune reg contact time = %d sec.\n", (int)(end_poke-start_poke));
26387 
26388    ast_debug(4, "--------------- SIP reload done\n");
26389 
26390    return 0;
26391 }
26392 
26393 /*! \brief Force reload of module from cli */
26394 static char *sip_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
26395 {
26396    
26397    switch (cmd) {
26398    case CLI_INIT:
26399       e->command = "sip reload";
26400       e->usage =
26401          "Usage: sip reload\n"
26402          "       Reloads SIP configuration from sip.conf\n";
26403       return NULL;
26404    case CLI_GENERATE:
26405       return NULL;
26406    }
26407 
26408    ast_mutex_lock(&sip_reload_lock);
26409    if (sip_reloading) 
26410       ast_verbose("Previous SIP reload not yet done\n");
26411    else {
26412       sip_reloading = TRUE;
26413       sip_reloadreason = (a && a->fd) ? CHANNEL_CLI_RELOAD : CHANNEL_MODULE_RELOAD;
26414    }
26415    ast_mutex_unlock(&sip_reload_lock);
26416    restart_monitor();
26417 
26418    return CLI_SUCCESS;
26419 }
26420 
26421 /*! \brief  Part of Asterisk module interface */
26422 static int reload(void)
26423 {
26424    if (sip_reload(0, 0, NULL))
26425       return 0;
26426    return 1;
26427 }
26428 
26429 /*! \brief SIP Cli commands definition */
26430 static struct ast_cli_entry cli_sip[] = {
26431    AST_CLI_DEFINE(sip_show_channels, "List active SIP channels or subscriptions"),
26432    AST_CLI_DEFINE(sip_show_channelstats, "List statistics for active SIP channels"),
26433    AST_CLI_DEFINE(sip_show_domains, "List our local SIP domains"),
26434    AST_CLI_DEFINE(sip_show_inuse, "List all inuse/limits"),
26435    AST_CLI_DEFINE(sip_show_objects, "List all SIP object allocations"),
26436    AST_CLI_DEFINE(sip_show_peers, "List defined SIP peers"),
26437    AST_CLI_DEFINE(sip_show_registry, "List SIP registration status"),
26438    AST_CLI_DEFINE(sip_unregister, "Unregister (force expiration) a SIP peer from the registry"),
26439    AST_CLI_DEFINE(sip_show_settings, "Show SIP global settings"),
26440    AST_CLI_DEFINE(sip_show_mwi, "Show MWI subscriptions"),
26441    AST_CLI_DEFINE(sip_cli_notify, "Send a notify packet to a SIP peer"),
26442    AST_CLI_DEFINE(sip_show_channel, "Show detailed SIP channel info"),
26443    AST_CLI_DEFINE(sip_show_history, "Show SIP dialog history"),
26444    AST_CLI_DEFINE(sip_show_peer, "Show details on specific SIP peer"),
26445    AST_CLI_DEFINE(sip_show_users, "List defined SIP users"),
26446    AST_CLI_DEFINE(sip_show_user, "Show details on specific SIP user"),
26447    AST_CLI_DEFINE(sip_qualify_peer, "Send an OPTIONS packet to a peer"),
26448    AST_CLI_DEFINE(sip_show_sched, "Present a report on the status of the sched queue"),
26449    AST_CLI_DEFINE(sip_prune_realtime, "Prune cached Realtime users/peers"),
26450    AST_CLI_DEFINE(sip_do_debug, "Enable/Disable SIP debugging"),
26451    AST_CLI_DEFINE(sip_set_history, "Enable/Disable SIP history"),
26452    AST_CLI_DEFINE(sip_reload, "Reload SIP configuration"),
26453    AST_CLI_DEFINE(sip_show_tcp, "List TCP Connections")
26454 };
26455 
26456 /*! \brief PBX load module - initialization */
26457 static int load_module(void)
26458 {
26459    ast_verbose("SIP channel loading...\n");
26460    /* the fact that ao2_containers can't resize automatically is a major worry! */
26461    /* if the number of objects gets above MAX_XXX_BUCKETS, things will slow down */
26462    peers = ao2_t_container_alloc(HASH_PEER_SIZE, peer_hash_cb, peer_cmp_cb, "allocate peers");
26463    peers_by_ip = ao2_t_container_alloc(HASH_PEER_SIZE, peer_iphash_cb, peer_ipcmp_cb, "allocate peers_by_ip");
26464    dialogs = ao2_t_container_alloc(HASH_DIALOG_SIZE, dialog_hash_cb, dialog_cmp_cb, "allocate dialogs");
26465    threadt = ao2_t_container_alloc(HASH_DIALOG_SIZE, threadt_hash_cb, threadt_cmp_cb, "allocate threadt table");
26466    
26467    ASTOBJ_CONTAINER_INIT(&regl); /* Registry object list -- not searched for anything */
26468    ASTOBJ_CONTAINER_INIT(&submwil); /* MWI subscription object list */
26469 
26470    if (!(sched = sched_context_create())) {
26471       ast_log(LOG_ERROR, "Unable to create scheduler context\n");
26472       return AST_MODULE_LOAD_FAILURE;
26473    }
26474 
26475    if (!(io = io_context_create())) {
26476       ast_log(LOG_ERROR, "Unable to create I/O context\n");
26477       sched_context_destroy(sched);
26478       return AST_MODULE_LOAD_FAILURE;
26479    }
26480 
26481    sip_reloadreason = CHANNEL_MODULE_LOAD;
26482 
26483    if(reload_config(sip_reloadreason)) /* Load the configuration from sip.conf */
26484       return AST_MODULE_LOAD_DECLINE;
26485 
26486    /* Prepare the version that does not require DTMF BEGIN frames.
26487     * We need to use tricks such as memcpy and casts because the variable
26488     * has const fields.
26489     */
26490    memcpy(&sip_tech_info, &sip_tech, sizeof(sip_tech));
26491    memset((void *) &sip_tech_info.send_digit_begin, 0, sizeof(sip_tech_info.send_digit_begin));
26492 
26493    /* Make sure we can register our sip channel type */
26494    if (ast_channel_register(&sip_tech)) {
26495       ast_log(LOG_ERROR, "Unable to register channel type 'SIP'\n");
26496       io_context_destroy(io);
26497       sched_context_destroy(sched);
26498       return AST_MODULE_LOAD_FAILURE;
26499    }
26500 
26501    /* Register all CLI functions for SIP */
26502    ast_cli_register_multiple(cli_sip, ARRAY_LEN(cli_sip));
26503 
26504    /* Tell the RTP subdriver that we're here */
26505    ast_rtp_proto_register(&sip_rtp);
26506 
26507    /* Tell the UDPTL subdriver that we're here */
26508    ast_udptl_proto_register(&sip_udptl);
26509 
26510    /* Register dialplan applications */
26511    ast_register_application_xml(app_dtmfmode, sip_dtmfmode);
26512    ast_register_application_xml(app_sipaddheader, sip_addheader);
26513    ast_register_application_xml(app_sipremoveheader, sip_removeheader);
26514 
26515    /* Register dialplan functions */
26516    ast_custom_function_register(&sip_header_function);
26517    ast_custom_function_register(&sippeer_function);
26518    ast_custom_function_register(&sipchaninfo_function);
26519    ast_custom_function_register(&checksipdomain_function);
26520 
26521    /* Register manager commands */
26522    ast_manager_register2("SIPpeers", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_sip_show_peers,
26523          "List SIP peers (text format)", mandescr_show_peers);
26524    ast_manager_register2("SIPshowpeer", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_sip_show_peer,
26525          "Show SIP peer (text format)", mandescr_show_peer);
26526    ast_manager_register2("SIPqualifypeer", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_sip_qualify_peer,
26527          "Show SIP peer (text format)", mandescr_show_peer);   /*! \todo Fix this XXX This must be all wrong XXXX */
26528    ast_manager_register2("SIPshowregistry", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_show_registry,
26529          "Show SIP registrations (text format)", mandescr_show_registry);
26530    ast_manager_register2("SIPnotify", EVENT_FLAG_SYSTEM, manager_sipnotify,
26531          "Send a SIP notify", mandescr_sipnotify);
26532    sip_poke_all_peers();   
26533    sip_send_all_registers();
26534    sip_send_all_mwi_subscriptions();
26535 
26536    /* And start the monitor for the first time */
26537    restart_monitor();
26538 
26539    ast_realtime_require_field(ast_check_realtime("sipregs") ? "sipregs" : "sippeers",
26540       "name", RQ_CHAR, 10,
26541       "ipaddr", RQ_CHAR, 15,
26542       "port", RQ_UINTEGER2, 5,
26543       "regseconds", RQ_INTEGER4, 11,
26544       "defaultuser", RQ_CHAR, 10,
26545       "fullcontact", RQ_CHAR, 35,
26546       "regserver", RQ_CHAR, 20,
26547       "useragent", RQ_CHAR, 20,
26548       "lastms", RQ_INTEGER4, 11,
26549       SENTINEL);
26550 
26551    return AST_MODULE_LOAD_SUCCESS;
26552 }
26553 
26554 /*! \brief PBX unload module API */
26555 static int unload_module(void)
26556 {
26557    struct sip_pvt *p;
26558    struct sip_threadinfo *th;
26559    struct ast_context *con;
26560    struct ao2_iterator i;
26561 
26562    ast_sched_dump(sched);
26563    
26564    /* First, take us out of the channel type list */
26565    ast_channel_unregister(&sip_tech);
26566 
26567    /* Unregister dial plan functions */
26568    ast_custom_function_unregister(&sipchaninfo_function);
26569    ast_custom_function_unregister(&sippeer_function);
26570    ast_custom_function_unregister(&sip_header_function);
26571    ast_custom_function_unregister(&checksipdomain_function);
26572 
26573    /* Unregister dial plan applications */
26574    ast_unregister_application(app_dtmfmode);
26575    ast_unregister_application(app_sipaddheader);
26576    ast_unregister_application(app_sipremoveheader);
26577 
26578    /* Unregister CLI commands */
26579    ast_cli_unregister_multiple(cli_sip, ARRAY_LEN(cli_sip));
26580 
26581    /* Disconnect from the RTP subsystem */
26582    ast_rtp_proto_unregister(&sip_rtp);
26583 
26584    /* Disconnect from UDPTL */
26585    ast_udptl_proto_unregister(&sip_udptl);
26586 
26587    /* Unregister AMI actions */
26588    ast_manager_unregister("SIPpeers");
26589    ast_manager_unregister("SIPshowpeer");
26590    ast_manager_unregister("SIPqualifypeer");
26591    ast_manager_unregister("SIPshowregistry");
26592    ast_manager_unregister("SIPnotify");
26593    
26594    /* Kill TCP/TLS server threads */
26595    if (sip_tcp_desc.master)
26596       ast_tcptls_server_stop(&sip_tcp_desc);
26597    if (sip_tls_desc.master)
26598       ast_tcptls_server_stop(&sip_tls_desc);
26599 
26600    /* Kill all existing TCP/TLS threads */
26601    i = ao2_iterator_init(threadt, 0);
26602    while ((th = ao2_t_iterator_next(&i, "iterate through tcp threads for 'sip show tcp'"))) {
26603       pthread_t thread = th->threadid;
26604       th->stop = 1;
26605       pthread_kill(thread, SIGURG);
26606       pthread_join(thread, NULL);
26607       ao2_t_ref(th, -1, "decrement ref from iterator");
26608    }
26609    ao2_iterator_destroy(&i);
26610 
26611    /* Hangup all dialogs if they have an owner */
26612    i = ao2_iterator_init(dialogs, 0);
26613    while ((p = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
26614       if (p->owner)
26615          ast_softhangup(p->owner, AST_SOFTHANGUP_APPUNLOAD);
26616       ao2_t_ref(p, -1, "toss dialog ptr from iterator_next");
26617    }
26618    ao2_iterator_destroy(&i);
26619 
26620    ast_mutex_lock(&monlock);
26621    if (monitor_thread && (monitor_thread != AST_PTHREADT_STOP) && (monitor_thread != AST_PTHREADT_NULL)) {
26622       pthread_cancel(monitor_thread);
26623       pthread_kill(monitor_thread, SIGURG);
26624       pthread_join(monitor_thread, NULL);
26625    }
26626    monitor_thread = AST_PTHREADT_STOP;
26627    ast_mutex_unlock(&monlock);
26628 
26629    /* Destroy all the dialogs and free their memory */
26630    i = ao2_iterator_init(dialogs, 0);
26631    while ((p = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
26632       dialog_unlink_all(p, TRUE, TRUE);
26633       ao2_t_ref(p, -1, "throw away iterator result"); 
26634    }
26635    ao2_iterator_destroy(&i);
26636 
26637    /* Free memory for local network address mask */
26638    ast_free_ha(localaddr);
26639 
26640    clear_realm_authentication(authl);
26641 
26642 
26643    if (default_tls_cfg.certfile)
26644       ast_free(default_tls_cfg.certfile);
26645    if (default_tls_cfg.cipher)
26646       ast_free(default_tls_cfg.cipher);
26647    if (default_tls_cfg.cafile)
26648       ast_free(default_tls_cfg.cafile);
26649    if (default_tls_cfg.capath)
26650       ast_free(default_tls_cfg.capath);
26651 
26652    ASTOBJ_CONTAINER_DESTROYALL(&regl, sip_registry_destroy);
26653    ASTOBJ_CONTAINER_DESTROY(&regl);
26654    ASTOBJ_CONTAINER_DESTROYALL(&submwil, sip_subscribe_mwi_destroy);
26655    ASTOBJ_CONTAINER_DESTROY(&submwil);
26656 
26657    ao2_t_ref(peers, -1, "unref the peers table");
26658    ao2_t_ref(peers_by_ip, -1, "unref the peers_by_ip table");
26659    ao2_t_ref(dialogs, -1, "unref the dialogs table");
26660    ao2_t_ref(threadt, -1, "unref the thread table");
26661 
26662    clear_sip_domains();
26663    ast_free_ha(global_contact_ha);
26664    close(sipsock);
26665    sched_context_destroy(sched);
26666    con = ast_context_find(used_context);
26667    if (con)
26668       ast_context_destroy(con, "SIP");
26669    ast_unload_realtime("sipregs");
26670    ast_unload_realtime("sippeers");
26671 
26672    return 0;
26673 }
26674 
26675 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, "Session Initiation Protocol (SIP)",
26676       .load = load_module,
26677       .unload = unload_module,
26678       .reload = reload,
26679           );