Mon Sep 20 2010 00:21:29

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: 261315 $")
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 />
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 />
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 
00504 /* guard limit must be larger than guard secs */
00505 /* guard min must be < 1000, and should be >= 250 */
00506 #define EXPIRY_GUARD_SECS       15                /*!< How long before expiry do we reregister */
00507 #define EXPIRY_GUARD_LIMIT      30                /*!< Below here, we use EXPIRY_GUARD_PCT instead of 
00508                                                     EXPIRY_GUARD_SECS */
00509 #define EXPIRY_GUARD_MIN        500                /*!< This is the minimum guard time applied. If 
00510                                                    GUARD_PCT turns out to be lower than this, it 
00511                                                    will use this time instead.
00512                                                    This is in milliseconds. */
00513 #define EXPIRY_GUARD_PCT        0.20                /*!< Percentage of expires timeout to use when 
00514                                                     below EXPIRY_GUARD_LIMIT */
00515 #define DEFAULT_EXPIRY 900                          /*!< Expire slowly */
00516 
00517 static int min_expiry = DEFAULT_MIN_EXPIRY;        /*!< Minimum accepted registration time */
00518 static int max_expiry = DEFAULT_MAX_EXPIRY;        /*!< Maximum accepted registration time */
00519 static int default_expiry = DEFAULT_DEFAULT_EXPIRY;
00520 static int mwi_expiry = DEFAULT_MWI_EXPIRY;
00521 
00522 #define DEFAULT_QUALIFY_GAP   100
00523 #define DEFAULT_QUALIFY_PEERS 1
00524 
00525 
00526 #define CALLERID_UNKNOWN             "Anonymous"
00527 #define FROMDOMAIN_INVALID           "anonymous.invalid"
00528 
00529 #define DEFAULT_MAXMS                2000             /*!< Qualification: Must be faster than 2 seconds by default */
00530 #define DEFAULT_QUALIFYFREQ          60 * 1000        /*!< Qualification: How often to check for the host to be up */
00531 #define DEFAULT_FREQ_NOTOK           10 * 1000        /*!< Qualification: How often to check, if the host is down... */
00532 
00533 #define DEFAULT_RETRANS              1000             /*!< How frequently to retransmit Default: 2 * 500 ms in RFC 3261 */
00534 #define MAX_RETRANS                  6                /*!< Try only 6 times for retransmissions, a total of 7 transmissions */
00535 #define DEFAULT_TIMER_T1                 500              /*!< SIP timer T1 (according to RFC 3261) */
00536 #define SIP_TRANS_TIMEOUT            64 * DEFAULT_TIMER_T1 /*!< SIP request timeout (rfc 3261) 64*T1 
00537                                                       \todo Use known T1 for timeout (peerpoke)
00538                                                       */
00539 #define DEFAULT_TRANS_TIMEOUT        -1               /*!< Use default SIP transaction timeout */
00540 #define PROVIS_KEEPALIVE_TIMEOUT     60000            /*!< How long to wait before retransmitting a provisional response (rfc 3261 13.3.1.1) */
00541 #define MAX_AUTHTRIES                3                /*!< Try authentication three times, then fail */
00542 
00543 #define SIP_MAX_HEADERS              64               /*!< Max amount of SIP headers to read */
00544 #define SIP_MAX_LINES                64               /*!< Max amount of lines in SIP attachment (like SDP) */
00545 #define SIP_MIN_PACKET               4096             /*!< Initialize size of memory to allocate for packets */
00546 #define MAX_HISTORY_ENTRIES        50                /*!< Max entires in the history list for a sip_pvt */
00547 
00548 #define INITIAL_CSEQ                 101              /*!< Our initial sip sequence number */
00549 
00550 #define DEFAULT_MAX_SE               1800             /*!< Session-Timer Default Session-Expires period (RFC 4028) */
00551 #define DEFAULT_MIN_SE               90               /*!< Session-Timer Default Min-SE period (RFC 4028) */
00552 
00553 #define SDP_MAX_RTPMAP_CODECS        32               /*!< Maximum number of codecs allowed in received SDP */
00554 
00555 /*! \brief Global jitterbuffer configuration - by default, jb is disabled */
00556 static struct ast_jb_conf default_jbconf =
00557 {
00558    .flags = 0,
00559    .max_size = -1,
00560    .resync_threshold = -1,
00561    .impl = "",
00562    .target_extra = -1,
00563 };
00564 static struct ast_jb_conf global_jbconf;     /*!< Global jitterbuffer configuration */
00565 
00566 static const char config[] = "sip.conf";     /*!< Main configuration file */
00567 static const char notify_config[] = "sip_notify.conf";   /*!< Configuration file for sending Notify with CLI commands to reconfigure or reboot phones */
00568 
00569 #define RTP    1
00570 #define NO_RTP 0
00571 
00572 /*! \brief Authorization scheme for call transfers 
00573 
00574 \note Not a bitfield flag, since there are plans for other modes,
00575    like "only allow transfers for authenticated devices" */
00576 enum transfermodes {
00577    TRANSFER_OPENFORALL,            /*!< Allow all SIP transfers */
00578    TRANSFER_CLOSED,                /*!< Allow no SIP transfers */
00579 };
00580 
00581 
00582 /*! \brief The result of a lot of functions */
00583 enum sip_result {
00584    AST_SUCCESS = 0,     /*!< FALSE means success, funny enough */
00585    AST_FAILURE = -1,    /*!< Failure code */
00586 };
00587 
00588 /*! \brief States for the INVITE transaction, not the dialog 
00589    \note this is for the INVITE that sets up the dialog
00590 */
00591 enum invitestates {
00592    INV_NONE = 0,          /*!< No state at all, maybe not an INVITE dialog */
00593    INV_CALLING = 1,  /*!< Invite sent, no answer */
00594    INV_PROCEEDING = 2,  /*!< We got/sent 1xx message */
00595    INV_EARLY_MEDIA = 3,    /*!< We got 18x message with to-tag back */
00596    INV_COMPLETED = 4,   /*!< Got final response with error. Wait for ACK, then CONFIRMED */
00597    INV_CONFIRMED = 5,   /*!< Confirmed response - we've got an ack (Incoming calls only) */
00598    INV_TERMINATED = 6,  /*!< Transaction done - either successful (AST_STATE_UP) or failed, but done 
00599                  The only way out of this is a BYE from one side */
00600    INV_CANCELLED = 7,   /*!< Transaction cancelled by client or server in non-terminated state */
00601 };
00602 
00603 /*! \brief Readable descriptions of device states.
00604        \note Should be aligned to above table as index */
00605 static const struct invstate2stringtable {
00606    const enum invitestates state;
00607    const char *desc;
00608 } invitestate2string[] = {
00609    {INV_NONE,              "None"  },
00610    {INV_CALLING,           "Calling (Trying)"},
00611    {INV_PROCEEDING,        "Proceeding "},
00612    {INV_EARLY_MEDIA,       "Early media"},
00613    {INV_COMPLETED,         "Completed (done)"},
00614    {INV_CONFIRMED,         "Confirmed (up)"},
00615    {INV_TERMINATED,        "Done"},
00616    {INV_CANCELLED,         "Cancelled"}
00617 };
00618 
00619 /*! \brief When sending a SIP message, we can send with a few options, depending on
00620    type of SIP request. UNRELIABLE is moslty used for responses to repeated requests,
00621    where the original response would be sent RELIABLE in an INVITE transaction */
00622 enum xmittype {
00623    XMIT_CRITICAL = 2,              /*!< Transmit critical SIP message reliably, with re-transmits.
00624                                               If it fails, it's critical and will cause a teardown of the session */
00625    XMIT_RELIABLE = 1,              /*!< Transmit SIP message reliably, with re-transmits */
00626    XMIT_UNRELIABLE = 0,            /*!< Transmit SIP message without bothering with re-transmits */
00627 };
00628 
00629 /*! \brief Results from the parse_register() function */
00630 enum parse_register_result {
00631    PARSE_REGISTER_DENIED,
00632    PARSE_REGISTER_FAILED,
00633    PARSE_REGISTER_UPDATE,
00634    PARSE_REGISTER_QUERY,
00635 };
00636 
00637 /*! \brief Type of subscription, based on the packages we do support, see \ref subscription_types */
00638 enum subscriptiontype { 
00639    NONE = 0,
00640    XPIDF_XML,
00641    DIALOG_INFO_XML,
00642    CPIM_PIDF_XML,
00643    PIDF_XML,
00644    MWI_NOTIFICATION
00645 };
00646 
00647 /*! \brief Subscription types that we support. We support
00648    - dialoginfo updates (really device status, not dialog info as was the original intent of the standard)
00649    - SIMPLE presence used for device status
00650    - Voicemail notification subscriptions
00651 */
00652 static const struct cfsubscription_types {
00653    enum subscriptiontype type;
00654    const char * const event;
00655    const char * const mediatype;
00656    const char * const text;
00657 } subscription_types[] = {
00658    { NONE,        "-",        "unknown",               "unknown" },
00659    /* RFC 4235: SIP Dialog event package */
00660    { DIALOG_INFO_XML, "dialog",   "application/dialog-info+xml", "dialog-info+xml" },
00661    { CPIM_PIDF_XML,   "presence", "application/cpim-pidf+xml",   "cpim-pidf+xml" },  /* RFC 3863 */
00662    { PIDF_XML,        "presence", "application/pidf+xml",        "pidf+xml" },       /* RFC 3863 */
00663    { XPIDF_XML,       "presence", "application/xpidf+xml",       "xpidf+xml" },       /* Pre-RFC 3863 with MS additions */
00664    { MWI_NOTIFICATION,  "message-summary", "application/simple-message-summary", "mwi" } /* RFC 3842: Mailbox notification */
00665 };
00666 
00667 
00668 /*! \brief Authentication types - proxy or www authentication 
00669    \note Endpoints, like Asterisk, should always use WWW authentication to
00670    allow multiple authentications in the same call - to the proxy and
00671    to the end point.
00672 */
00673 enum sip_auth_type {
00674    PROXY_AUTH = 407,
00675    WWW_AUTH = 401,
00676 };
00677 
00678 /*! \brief Authentication result from check_auth* functions */
00679 enum check_auth_result {
00680    AUTH_DONT_KNOW = -100,  /*!< no result, need to check further */
00681       /* XXX maybe this is the same as AUTH_NOT_FOUND */
00682 
00683    AUTH_SUCCESSFUL = 0,
00684    AUTH_CHALLENGE_SENT = 1,
00685    AUTH_SECRET_FAILED = -1,
00686    AUTH_USERNAME_MISMATCH = -2,
00687    AUTH_NOT_FOUND = -3, /*!< returned by register_verify */
00688    AUTH_FAKE_AUTH = -4,
00689    AUTH_UNKNOWN_DOMAIN = -5,
00690    AUTH_PEER_NOT_DYNAMIC = -6,
00691    AUTH_ACL_FAILED = -7,
00692    AUTH_BAD_TRANSPORT = -8,
00693 };
00694 
00695 /*! \brief States for outbound registrations (with register= lines in sip.conf */
00696 enum sipregistrystate {
00697    REG_STATE_UNREGISTERED = 0,   /*!< We are not registered 
00698        *  \note Initial state. We should have a timeout scheduled for the initial
00699        * (or next) registration transmission, calling sip_reregister
00700        */
00701 
00702    REG_STATE_REGSENT,   /*!< Registration request sent 
00703        * \note sent initial request, waiting for an ack or a timeout to
00704        * retransmit the initial request.
00705       */
00706 
00707    REG_STATE_AUTHSENT,  /*!< We have tried to authenticate 
00708        * \note entered after transmit_register with auth info,
00709        * waiting for an ack.
00710        */
00711 
00712    REG_STATE_REGISTERED,   /*!< Registered and done */
00713 
00714    REG_STATE_REJECTED,  /*!< Registration rejected *
00715        * \note only used when the remote party has an expire larger than
00716        * our max-expire. This is a final state from which we do not
00717        * recover (not sure how correctly).
00718        */
00719 
00720    REG_STATE_TIMEOUT,   /*!< Registration timed out *
00721       * \note XXX unused */
00722 
00723    REG_STATE_NOAUTH, /*!< We have no accepted credentials
00724        * \note fatal - no chance to proceed */
00725 
00726    REG_STATE_FAILED, /*!< Registration failed after several tries
00727        * \note fatal - no chance to proceed */
00728 };
00729 
00730 /*! \brief Modes in which Asterisk can be configured to run SIP Session-Timers */
00731 enum st_mode {
00732         SESSION_TIMER_MODE_INVALID = 0, /*!< Invalid value */ 
00733         SESSION_TIMER_MODE_ACCEPT,      /*!< Honor inbound Session-Timer requests */
00734         SESSION_TIMER_MODE_ORIGINATE,   /*!< Originate outbound and honor inbound requests */
00735         SESSION_TIMER_MODE_REFUSE       /*!< Ignore inbound Session-Timers requests */
00736 };
00737 
00738 /*! \brief The entity playing the refresher role for Session-Timers */
00739 enum st_refresher {
00740         SESSION_TIMER_REFRESHER_AUTO,    /*!< Negotiated                      */
00741         SESSION_TIMER_REFRESHER_UAC,     /*!< Session is refreshed by the UAC */
00742         SESSION_TIMER_REFRESHER_UAS      /*!< Session is refreshed by the UAS */
00743 };
00744 
00745 /*! \brief Define some implemented SIP transports 
00746    \note Asterisk does not support SCTP or UDP/DTLS 
00747 */
00748 enum sip_transport {
00749    SIP_TRANSPORT_UDP = 1,     /*!< Unreliable transport for SIP, needs retransmissions */
00750    SIP_TRANSPORT_TCP = 1 << 1,   /*!< Reliable, but unsecure */
00751    SIP_TRANSPORT_TLS = 1 << 2,   /*!< TCP/TLS - reliable and secure transport for signalling */
00752 };
00753 
00754 /*! \brief definition of a sip proxy server
00755  *
00756  * For outbound proxies, a sip_peer will contain a reference to a 
00757  * dynamically allocated instance of a sip_proxy. A sip_pvt may also
00758  * contain a reference to a peer's outboundproxy, or it may contain
00759  * a reference to the sip_cfg.outboundproxy.
00760  */
00761 struct sip_proxy {
00762    char name[MAXHOSTNAMELEN];      /*!< DNS name of domain/host or IP */
00763    struct sockaddr_in ip;          /*!< Currently used IP address and port */
00764    time_t last_dnsupdate;          /*!< When this was resolved */
00765    enum sip_transport transport; 
00766    int force;                      /*!< If it's an outbound proxy, Force use of this outbound proxy for all outbound requests */
00767    /* Room for a SRV record chain based on the name */
00768 };
00769 
00770 /*! \brief argument for the 'show channels|subscriptions' callback. */
00771 struct __show_chan_arg { 
00772    int fd;
00773    int subscriptions;
00774    int numchans;   /* return value */
00775 };
00776 
00777 
00778 /*! \brief States whether a SIP message can create a dialog in Asterisk. */
00779 enum can_create_dialog {
00780    CAN_NOT_CREATE_DIALOG,
00781    CAN_CREATE_DIALOG,
00782    CAN_CREATE_DIALOG_UNSUPPORTED_METHOD,
00783 };
00784 
00785 /*! \brief SIP Request methods known by Asterisk 
00786 
00787    \note Do _NOT_ make any changes to this enum, or the array following it;
00788    if you think you are doing the right thing, you are probably
00789    not doing the right thing. If you think there are changes
00790    needed, get someone else to review them first _before_
00791    submitting a patch. If these two lists do not match properly
00792    bad things will happen.
00793 */
00794 
00795 enum sipmethod {
00796    SIP_UNKNOWN,      /*!< Unknown response */
00797    SIP_RESPONSE,     /*!< Not request, response to outbound request */
00798    SIP_REGISTER,     /*!< Registration to the mothership, tell us where you are located */
00799    SIP_OPTIONS,      /*!< Check capabilities of a device, used for "ping" too */
00800    SIP_NOTIFY,    /*!< Status update, Part of the event package standard, result of a SUBSCRIBE or a REFER */
00801    SIP_INVITE,    /*!< Set up a session */
00802    SIP_ACK,    /*!< End of a three-way handshake started with INVITE. */
00803    SIP_PRACK,     /*!< Reliable pre-call signalling. Not supported in Asterisk. */
00804    SIP_BYE,    /*!< End of a session */
00805    SIP_REFER,     /*!< Refer to another URI (transfer) */
00806    SIP_SUBSCRIBE,    /*!< Subscribe for updates (voicemail, session status, device status, presence) */
00807    SIP_MESSAGE,      /*!< Text messaging */
00808    SIP_UPDATE,    /*!< Update a dialog. We can send UPDATE; but not accept it */
00809    SIP_INFO,      /*!< Information updates during a session */
00810    SIP_CANCEL,    /*!< Cancel an INVITE */
00811    SIP_PUBLISH,      /*!< Not supported in Asterisk */
00812    SIP_PING,      /*!< Not supported at all, no standard but still implemented out there */
00813 };
00814 
00815 /*! \brief Settings for the 'notifycid' option, see sip.conf.sample for details. */
00816 enum notifycid_setting {
00817    DISABLED       = 0,
00818    ENABLED        = 1,
00819    IGNORE_CONTEXT = 2,
00820 };
00821 
00822 /*! \brief The core structure to setup dialogs. We parse incoming messages by using
00823    structure and then route the messages according to the type.
00824 
00825       \note Note that sip_methods[i].id == i must hold or the code breaks */
00826 static const struct  cfsip_methods { 
00827    enum sipmethod id;
00828    int need_rtp;     /*!< when this is the 'primary' use for a pvt structure, does it need RTP? */
00829    char * const text;
00830    enum can_create_dialog can_create;
00831 } sip_methods[] = {
00832    { SIP_UNKNOWN,  RTP,    "-UNKNOWN-",   CAN_CREATE_DIALOG },
00833    { SIP_RESPONSE,    NO_RTP, "SIP/2.0",  CAN_NOT_CREATE_DIALOG },
00834    { SIP_REGISTER,    NO_RTP, "REGISTER",    CAN_CREATE_DIALOG },
00835    { SIP_OPTIONS,  NO_RTP, "OPTIONS",  CAN_CREATE_DIALOG },
00836    { SIP_NOTIFY,   NO_RTP, "NOTIFY",   CAN_CREATE_DIALOG },
00837    { SIP_INVITE,   RTP,    "INVITE",   CAN_CREATE_DIALOG },
00838    { SIP_ACK,   NO_RTP, "ACK",   CAN_NOT_CREATE_DIALOG },
00839    { SIP_PRACK,    NO_RTP, "PRACK",    CAN_NOT_CREATE_DIALOG },
00840    { SIP_BYE,   NO_RTP, "BYE",   CAN_NOT_CREATE_DIALOG },
00841    { SIP_REFER,    NO_RTP, "REFER",    CAN_CREATE_DIALOG },
00842    { SIP_SUBSCRIBE, NO_RTP, "SUBSCRIBE",  CAN_CREATE_DIALOG },
00843    { SIP_MESSAGE,  NO_RTP, "MESSAGE",  CAN_CREATE_DIALOG },
00844    { SIP_UPDATE,   NO_RTP, "UPDATE",   CAN_NOT_CREATE_DIALOG },
00845    { SIP_INFO,  NO_RTP, "INFO",  CAN_NOT_CREATE_DIALOG },
00846    { SIP_CANCEL,   NO_RTP, "CANCEL",   CAN_NOT_CREATE_DIALOG },
00847    { SIP_PUBLISH,  NO_RTP, "PUBLISH",  CAN_CREATE_DIALOG_UNSUPPORTED_METHOD },
00848    { SIP_PING,  NO_RTP, "PING",  CAN_CREATE_DIALOG_UNSUPPORTED_METHOD }
00849 };
00850 
00851 static unsigned int chan_idx;
00852 
00853 /*!  Define SIP option tags, used in Require: and Supported: headers 
00854    We need to be aware of these properties in the phones to use 
00855    the replace: header. We should not do that without knowing
00856    that the other end supports it... 
00857    This is nothing we can configure, we learn by the dialog
00858    Supported: header on the REGISTER (peer) or the INVITE
00859    (other devices)
00860    We are not using many of these today, but will in the future.
00861    This is documented in RFC 3261
00862 */
00863 #define SUPPORTED    1
00864 #define NOT_SUPPORTED      0
00865 
00866 /* SIP options */
00867 #define SIP_OPT_REPLACES   (1 << 0)
00868 #define SIP_OPT_100REL     (1 << 1)
00869 #define SIP_OPT_TIMER      (1 << 2)
00870 #define SIP_OPT_EARLY_SESSION (1 << 3)
00871 #define SIP_OPT_JOIN    (1 << 4)
00872 #define SIP_OPT_PATH    (1 << 5)
00873 #define SIP_OPT_PREF    (1 << 6)
00874 #define SIP_OPT_PRECONDITION  (1 << 7)
00875 #define SIP_OPT_PRIVACY    (1 << 8)
00876 #define SIP_OPT_SDP_ANAT   (1 << 9)
00877 #define SIP_OPT_SEC_AGREE  (1 << 10)
00878 #define SIP_OPT_EVENTLIST  (1 << 11)
00879 #define SIP_OPT_GRUU    (1 << 12)
00880 #define SIP_OPT_TARGET_DIALOG (1 << 13)
00881 #define SIP_OPT_NOREFERSUB (1 << 14)
00882 #define SIP_OPT_HISTINFO   (1 << 15)
00883 #define SIP_OPT_RESPRIORITY   (1 << 16)
00884 #define SIP_OPT_FROMCHANGE (1 << 17)
00885 #define SIP_OPT_RECLISTINV (1 << 18)
00886 #define SIP_OPT_RECLISTSUB (1 << 19)
00887 #define SIP_OPT_OUTBOUND   (1 << 20)
00888 #define SIP_OPT_UNKNOWN    (1 << 21)
00889 
00890 
00891 /*! \brief List of well-known SIP options. If we get this in a require,
00892    we should check the list and answer accordingly. */
00893 static const struct cfsip_options {
00894    int id;        /*!< Bitmap ID */
00895    int supported;    /*!< Supported by Asterisk ? */
00896    char * const text;   /*!< Text id, as in standard */
00897 } sip_options[] = {  /* XXX used in 3 places */
00898    /* RFC3262: PRACK 100% reliability */
00899    { SIP_OPT_100REL, NOT_SUPPORTED, "100rel" }, 
00900    /* RFC3959: SIP Early session support */
00901    { SIP_OPT_EARLY_SESSION, NOT_SUPPORTED,   "early-session" },
00902    /* SIMPLE events:  RFC4662 */
00903    { SIP_OPT_EVENTLIST, NOT_SUPPORTED, "eventlist" },
00904    /* RFC 4916- Connected line ID updates */
00905    { SIP_OPT_FROMCHANGE,   NOT_SUPPORTED, "from-change" },
00906    /* GRUU: Globally Routable User Agent URI's */
00907    { SIP_OPT_GRUU,      NOT_SUPPORTED, "gruu" },
00908    /* RFC4244 History info */
00909    { SIP_OPT_HISTINFO,  NOT_SUPPORTED, "histinfo" },
00910    /* RFC3911: SIP Join header support */
00911    { SIP_OPT_JOIN,      NOT_SUPPORTED, "join" },
00912    /* Disable the REFER subscription, RFC 4488 */
00913    { SIP_OPT_NOREFERSUB,   NOT_SUPPORTED, "norefersub" },
00914    /* SIP outbound - the final NAT battle - draft-sip-outbound */
00915    { SIP_OPT_OUTBOUND,  NOT_SUPPORTED, "outbound" },
00916    /* RFC3327: Path support */
00917    { SIP_OPT_PATH,      NOT_SUPPORTED, "path" },
00918    /* RFC3840: Callee preferences */
00919    { SIP_OPT_PREF,      NOT_SUPPORTED, "pref" },
00920    /* RFC3312: Precondition support */
00921    { SIP_OPT_PRECONDITION, NOT_SUPPORTED, "precondition" },
00922    /* RFC3323: Privacy with proxies*/
00923    { SIP_OPT_PRIVACY,   NOT_SUPPORTED, "privacy" },
00924    /* RFC-ietf-sip-uri-list-conferencing-02.txt conference invite lists */
00925    { SIP_OPT_RECLISTINV,   NOT_SUPPORTED, "recipient-list-invite" },
00926    /* RFC-ietf-sip-uri-list-subscribe-02.txt - subscription lists */
00927    { SIP_OPT_RECLISTSUB,   NOT_SUPPORTED, "recipient-list-subscribe" },
00928    /* RFC3891: Replaces: header for transfer */
00929    { SIP_OPT_REPLACES,  SUPPORTED,  "replaces" },  
00930    /* One version of Polycom firmware has the wrong label */
00931    { SIP_OPT_REPLACES,  SUPPORTED,  "replace" },   
00932    /* RFC4412 Resource priorities */
00933    { SIP_OPT_RESPRIORITY,  NOT_SUPPORTED, "resource-priority" },
00934    /* RFC3329: Security agreement mechanism */
00935    { SIP_OPT_SEC_AGREE, NOT_SUPPORTED, "sec_agree" },
00936    /* RFC4092: Usage of the SDP ANAT Semantics in the SIP */
00937    { SIP_OPT_SDP_ANAT,  NOT_SUPPORTED, "sdp-anat" },
00938    /* RFC4028: SIP Session-Timers */
00939    { SIP_OPT_TIMER,  SUPPORTED,  "timer" },
00940    /* RFC4538: Target-dialog */
00941    { SIP_OPT_TARGET_DIALOG,NOT_SUPPORTED, "tdialog" },
00942 };
00943 
00944 
00945 /*! \brief SIP Methods we support 
00946    \todo This string should be set dynamically. We only support REFER and SUBSCRIBE if we have
00947    allowsubscribe and allowrefer on in sip.conf.
00948 */
00949 #define ALLOWED_METHODS "INVITE, ACK, CANCEL, OPTIONS, BYE, REFER, SUBSCRIBE, NOTIFY, INFO"
00950 
00951 /*! \brief SIP Extensions we support 
00952    \note This should be generated based on the previous array
00953       in combination with settings.
00954    \todo We should not have "timer" if it's disabled in the configuration file.
00955 */
00956 #define SUPPORTED_EXTENSIONS "replaces, timer" 
00957 
00958 /*! \brief Standard SIP unsecure port for UDP and TCP from RFC 3261. DO NOT CHANGE THIS */
00959 #define STANDARD_SIP_PORT  5060
00960 /*! \brief Standard SIP TLS port from RFC 3261. DO NOT CHANGE THIS */
00961 #define STANDARD_TLS_PORT  5061
00962 
00963 /*! \note in many SIP headers, absence of a port number implies port 5060,
00964  * and this is why we cannot change the above constant.
00965  * There is a limited number of places in asterisk where we could,
00966  * in principle, use a different "default" port number, but
00967  * we do not support this feature at the moment.
00968  * You can run Asterisk with SIP on a different port with a configuration
00969  * option. If you change this value, the signalling will be incorrect.
00970  */
00971 
00972 /*! \name DefaultValues Default values, set and reset in reload_config before reading configuration 
00973 
00974    These are default values in the source. There are other recommended values in the
00975    sip.conf.sample for new installations. These may differ to keep backwards compatibility,
00976    yet encouraging new behaviour on new installations 
00977  */
00978 /*@{*/ 
00979 #define DEFAULT_CONTEXT    "default"   /*!< The default context for [general] section as well as devices */
00980 #define DEFAULT_MOHINTERPRET    "default" /*!< The default music class */
00981 #define DEFAULT_MOHSUGGEST      ""
00982 #define DEFAULT_VMEXTEN    "asterisk"  /*!< Default voicemail extension */
00983 #define DEFAULT_CALLERID   "asterisk"  /*!< Default caller ID */
00984 #define DEFAULT_NOTIFYMIME    "application/simple-message-summary"
00985 #define DEFAULT_ALLOWGUEST TRUE
00986 #define DEFAULT_RTPKEEPALIVE  0     /*!< Default RTPkeepalive setting */
00987 #define DEFAULT_CALLCOUNTER   FALSE
00988 #define DEFAULT_SRVLOOKUP  TRUE     /*!< Recommended setting is ON */
00989 #define DEFAULT_COMPACTHEADERS   FALSE    /*!< Send compact (one-character) SIP headers. Default off */
00990 #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. */
00991 #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. */
00992 #define DEFAULT_TOS_VIDEO       0               /*!< Video packets should be marked as DSCP AF41, but the default is 0 to be compatible with previous versions. */
00993 #define DEFAULT_TOS_TEXT        0               /*!< Text packets should be marked as XXXX XXXX, but the default is 0 to be compatible with previous versions. */
00994 #define DEFAULT_COS_SIP         4      /*!< Level 2 class of service for SIP signalling */
00995 #define DEFAULT_COS_AUDIO       5      /*!< Level 2 class of service for audio media  */
00996 #define DEFAULT_COS_VIDEO       6      /*!< Level 2 class of service for video media */
00997 #define DEFAULT_COS_TEXT        5      /*!< Level 2 class of service for text media (T.140) */
00998 #define DEFAULT_ALLOW_EXT_DOM TRUE     /*!< Allow external domains */
00999 #define DEFAULT_REALM      "asterisk"  /*!< Realm for HTTP digest authentication */
01000 #define DEFAULT_NOTIFYRINGING TRUE     /*!< Notify devicestate system on ringing state */
01001 #define DEFAULT_NOTIFYCID     DISABLED /*!< Include CID with ringing notifications */
01002 #define DEFAULT_PEDANTIC   FALSE    /*!< Avoid following SIP standards for dialog matching */
01003 #define DEFAULT_AUTOCREATEPEER   FALSE    /*!< Don't create peers automagically */
01004 #define  DEFAULT_MATCHEXTERNIPLOCALLY FALSE  /*!< Match extern IP locally default setting */
01005 #define DEFAULT_QUALIFY    FALSE    /*!< Don't monitor devices */
01006 #define DEFAULT_CALLEVENTS FALSE    /*!< Extra manager SIP call events */
01007 #define DEFAULT_ALWAYSAUTHREJECT FALSE /*!< Don't reject authentication requests always */
01008 #define DEFAULT_REGEXTENONQUALIFY FALSE
01009 #define DEFAULT_T1MIN      100      /*!< 100 MS for minimal roundtrip time */
01010 #define DEFAULT_MAX_CALL_BITRATE (384)    /*!< Max bitrate for video */
01011 #ifndef DEFAULT_USERAGENT
01012 #define DEFAULT_USERAGENT "Asterisk PBX"  /*!< Default Useragent: header unless re-defined in sip.conf */
01013 #define DEFAULT_SDPSESSION "Asterisk PBX" /*!< Default SDP session name, (s=) header unless re-defined in sip.conf */
01014 #define DEFAULT_SDPOWNER "root"        /*!< Default SDP username field in (o=) header unless re-defined in sip.conf */
01015 #endif
01016 /*@}*/ 
01017 
01018 /*! \name DefaultSettings
01019    Default setttings are used as a channel setting and as a default when
01020    configuring devices 
01021 */
01022 /*@{*/ 
01023 static char default_language[MAX_LANGUAGE];
01024 static char default_callerid[AST_MAX_EXTENSION];
01025 static char default_fromdomain[AST_MAX_EXTENSION];
01026 static char default_notifymime[AST_MAX_EXTENSION];
01027 static int default_qualify;      /*!< Default Qualify= setting */
01028 static char default_vmexten[AST_MAX_EXTENSION];
01029 static char default_mohinterpret[MAX_MUSICCLASS];  /*!< Global setting for moh class to use when put on hold */
01030 static char default_mohsuggest[MAX_MUSICCLASS];    /*!< Global setting for moh class to suggest when putting 
01031                                                     *   a bridged channel on hold */
01032 static char default_parkinglot[AST_MAX_CONTEXT]; /*!< Parkinglot */
01033 static int default_maxcallbitrate;  /*!< Maximum bitrate for call */
01034 static struct ast_codec_pref default_prefs;     /*!< Default codec prefs */
01035 static unsigned int default_transports;         /*!< Default Transports (enum sip_transport) that are acceptable */
01036 static unsigned int default_primary_transport;     /*!< Default primary Transport (enum sip_transport) for outbound connections to devices */
01037 
01038 /*@}*/ 
01039 
01040 /*! \name GlobalSettings
01041    Global settings apply to the channel (often settings you can change in the general section
01042    of sip.conf
01043 */
01044 /*@{*/ 
01045 /*! \brief a place to store all global settings for the sip channel driver 
01046    These are settings that will be possibly to apply on a group level later on.
01047    \note Do not add settings that only apply to the channel itself and can't
01048          be applied to devices (trunks, services, phones)
01049 */
01050 struct sip_settings {
01051    int peer_rtupdate;      /*!< G: Update database with registration data for peer? */
01052    int rtsave_sysname;     /*!< G: Save system name at registration? */
01053    int ignore_regexpire;      /*!< G: Ignore expiration of peer  */
01054    int rtautoclear;     /*!< Realtime ?? */
01055    int directrtpsetup;     /*!< Enable support for Direct RTP setup (no re-invites) */
01056    int pedanticsipchecking;   /*!< Extra checking ?  Default off */
01057    int autocreatepeer;     /*!< Auto creation of peers at registration? Default off. */
01058    int srvlookup;       /*!< SRV Lookup on or off. Default is on */
01059    int allowguest;         /*!< allow unauthenticated peers to connect? */
01060    int alwaysauthreject;      /*!< Send 401 Unauthorized for all failing requests */
01061    int compactheaders;     /*!< send compact sip headers */
01062    int allow_external_domains;   /*!< Accept calls to external SIP domains? */
01063    int callevents;         /*!< Whether we send manager events or not */
01064    int regextenonqualify;     /*!< Whether to add/remove regexten when qualifying peers */
01065    int matchexterniplocally;  /*!< Match externip/externhost setting against localnet setting */
01066    int notifyringing;      /*!< Send notifications on ringing */
01067    int notifyhold;         /*!< Send notifications on hold */
01068    enum notifycid_setting notifycid; /*!< Send CID with ringing notifications */
01069    enum transfermodes allowtransfer;   /*!< SIP Refer restriction scheme */
01070    int allowsubscribe;          /*!< Flag for disabling ALL subscriptions, this is FALSE only if all peers are FALSE 
01071                    the global setting is in globals_flags[1] */
01072    char realm[MAXHOSTNAMELEN];      /*!< Default realm */
01073    struct sip_proxy outboundproxy;  /*!< Outbound proxy */
01074    char default_context[AST_MAX_CONTEXT];
01075    char default_subscribecontext[AST_MAX_CONTEXT];
01076 };
01077 
01078 static struct sip_settings sip_cfg;
01079 
01080 static int global_match_auth_username;    /*!< Match auth username if available instead of From: Default off. */
01081 
01082 static int global_relaxdtmf;     /*!< Relax DTMF */
01083 static int global_prematuremediafilter;   /*!< Enable/disable premature frames in a call (causing 183 early media) */
01084 static int global_relaxdtmf;        /*!< Relax DTMF */
01085 static int global_rtptimeout;    /*!< Time out call if no RTP */
01086 static int global_rtpholdtimeout;   /*!< Time out call if no RTP during hold */
01087 static int global_rtpkeepalive;     /*!< Send RTP keepalives */
01088 static int global_reg_timeout;
01089 static int global_regattempts_max;  /*!< Registration attempts before giving up */
01090 static int global_shrinkcallerid;   /*!< enable or disable shrinking of caller id  */
01091 static int global_callcounter;      /*!< Enable call counters for all devices. This is currently enabled by setting the peer
01092                   call-limit to INT_MAX. When we remove the call-limit from the code, we can make it
01093                   with just a boolean flag in the device structure */
01094 static unsigned int global_tos_sip;    /*!< IP type of service for SIP packets */
01095 static unsigned int global_tos_audio;     /*!< IP type of service for audio RTP packets */
01096 static unsigned int global_tos_video;     /*!< IP type of service for video RTP packets */
01097 static unsigned int global_tos_text;      /*!< IP type of service for text RTP packets */
01098 static unsigned int global_cos_sip;    /*!< 802.1p class of service for SIP packets */
01099 static unsigned int global_cos_audio;     /*!< 802.1p class of service for audio RTP packets */
01100 static unsigned int global_cos_video;     /*!< 802.1p class of service for video RTP packets */
01101 static unsigned int global_cos_text;      /*!< 802.1p class of service for text RTP packets */
01102 static int recordhistory;     /*!< Record SIP history. Off by default */
01103 static int dumphistory;       /*!< Dump history to verbose before destroying SIP dialog */
01104 static char global_regcontext[AST_MAX_CONTEXT];    /*!< Context for auto-extensions */
01105 static char global_useragent[AST_MAX_EXTENSION];   /*!< Useragent for the SIP channel */
01106 static char global_sdpsession[AST_MAX_EXTENSION];  /*!< SDP session name for the SIP channel */
01107 static char global_sdpowner[AST_MAX_EXTENSION]; /*!< SDP owner name for the SIP channel */
01108 static int global_authfailureevents;      /*!< Whether we send authentication failure manager events or not. Default no. */
01109 static int global_t1;         /*!< T1 time */
01110 static int global_t1min;      /*!< T1 roundtrip time minimum */
01111 static int global_timer_b;             /*!< Timer B - RFC 3261 Section 17.1.1.2 */
01112 static int global_autoframing;            /*!< Turn autoframing on or off. */
01113 static int global_qualifyfreq;         /*!< Qualify frequency */
01114 static int global_qualify_gap;              /*!< Time between our group of peer pokes */
01115 static int global_qualify_peers;          /*!< Number of peers to poke at a given time */
01116 
01117 
01118 /*! \brief Codecs that we support by default: */
01119 static int global_capability = AST_FORMAT_ULAW | AST_FORMAT_ALAW | AST_FORMAT_GSM | AST_FORMAT_H263;
01120 
01121 static enum st_mode global_st_mode;           /*!< Mode of operation for Session-Timers           */
01122 static enum st_refresher global_st_refresher; /*!< Session-Timer refresher                        */
01123 static int global_min_se;                     /*!< Lowest threshold for session refresh interval  */
01124 static int global_max_se;                     /*!< Highest threshold for session refresh interval */
01125 
01126 static int global_dynamic_exclude_static = 0;   /*!< Exclude static peers from contact registrations */
01127 /*@}*/
01128 
01129 /*! \brief Global list of addresses dynamic peers are not allowed to use */
01130 static struct ast_ha *global_contact_ha = NULL;
01131 
01132 /*! \name Object counters @{
01133  * \bug These counters are not handled in a thread-safe way ast_atomic_fetchadd_int()
01134  * should be used to modify these values. */
01135 static int speerobjs = 0;                /*!< Static peers */
01136 static int rpeerobjs = 0;                /*!< Realtime peers */
01137 static int apeerobjs = 0;                /*!< Autocreated peer objects */
01138 static int regobjs = 0;                  /*!< Registry objects */
01139 /* }@ */
01140 
01141 static struct ast_flags global_flags[2] = {{0}};        /*!< global SIP_ flags */
01142 static int global_t38_maxdatagram;        /*!< global T.38 FaxMaxDatagram override */
01143 
01144 static char used_context[AST_MAX_CONTEXT];      /*!< name of automatically created context for unloading */
01145 
01146 
01147 AST_MUTEX_DEFINE_STATIC(netlock);
01148 
01149 /*! \brief Protect the monitoring thread, so only one process can kill or start it, and not
01150    when it's doing something critical. */
01151 AST_MUTEX_DEFINE_STATIC(monlock);
01152 
01153 AST_MUTEX_DEFINE_STATIC(sip_reload_lock);
01154 
01155 /*! \brief This is the thread for the monitor which checks for input on the channels
01156    which are not currently in use.  */
01157 static pthread_t monitor_thread = AST_PTHREADT_NULL;
01158 
01159 static int sip_reloading = FALSE;                       /*!< Flag for avoiding multiple reloads at the same time */
01160 static enum channelreloadreason sip_reloadreason;       /*!< Reason for last reload/load of configuration */
01161 
01162 static struct sched_context *sched;     /*!< The scheduling context */
01163 static struct io_context *io;           /*!< The IO context */
01164 static int *sipsock_read_id;            /*!< ID of IO entry for sipsock FD */
01165 
01166 #define DEC_CALL_LIMIT  0
01167 #define INC_CALL_LIMIT  1
01168 #define DEC_CALL_RINGING 2
01169 #define INC_CALL_RINGING 3
01170 
01171 /*! \brief The SIP socket definition */
01172 struct sip_socket {
01173    enum sip_transport type;   /*!< UDP, TCP or TLS */
01174    int fd;           /*!< Filed descriptor, the actual socket */
01175    uint16_t port;
01176    struct ast_tcptls_session_instance *tcptls_session;   /* If tcp or tls, a socket manager */
01177 };
01178 
01179 /*! \brief sip_request: The data grabbed from the UDP socket
01180  *
01181  * \verbatim
01182  * Incoming messages: we first store the data from the socket in data[],
01183  * adding a trailing \0 to make string parsing routines happy.
01184  * Then call parse_request() and req.method = find_sip_method();
01185  * to initialize the other fields. The \r\n at the end of each line is   
01186  * replaced by \0, so that data[] is not a conforming SIP message anymore.
01187  * After this processing, rlPart1 is set to non-NULL to remember
01188  * that we can run get_header() on this kind of packet.
01189  *
01190  * parse_request() splits the first line as follows:
01191  * Requests have in the first line      method uri SIP/2.0
01192  *      rlPart1 = method; rlPart2 = uri;
01193  * Responses have in the first line     SIP/2.0 NNN description
01194  *      rlPart1 = SIP/2.0; rlPart2 = NNN + description;
01195  *
01196  * For outgoing packets, we initialize the fields with init_req() or init_resp()
01197  * (which fills the first line to "METHOD uri SIP/2.0" or "SIP/2.0 code text"),
01198  * and then fill the rest with add_header() and add_line().
01199  * The \r\n at the end of the line are still there, so the get_header()
01200  * and similar functions don't work on these packets. 
01201  * \endverbatim
01202  */
01203 struct sip_request {
01204    ptrdiff_t rlPart1;           /*!< Offset of the SIP Method Name or "SIP/2.0" protocol version */
01205    ptrdiff_t rlPart2;           /*!< Offset of the Request URI or Response Status */
01206    int len;                /*!< bytes used in data[], excluding trailing null terminator. Rarely used. */
01207    int headers;            /*!< # of SIP Headers */
01208    int method;             /*!< Method of this request */
01209    int lines;              /*!< Body Content */
01210    unsigned int sdp_start; /*!< the line number where the SDP begins */
01211    unsigned int sdp_count; /*!< the number of lines of SDP */
01212    char debug;    /*!< print extra debugging if non zero */
01213    char has_to_tag;  /*!< non-zero if packet has To: tag */
01214    char ignore;      /*!< if non-zero This is a re-transmit, ignore it */
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    /* XXX Do we need to unref socket.ser when the request goes away? */
01221    struct sip_socket socket;  /*!< The socket used for this request */
01222    AST_LIST_ENTRY(sip_request) next;
01223 };
01224 
01225 /* \brief given a sip_request and an offset, return the char * that resides there
01226  *
01227  * It used to be that rlPart1, rlPart2, and the header and line arrays were character
01228  * pointers. They are now offsets into the ast_str portion of the sip_request structure.
01229  * To avoid adding a bunch of redundant pointer arithmetic to the code, this macro is
01230  * provided to retrieve the string at a particular offset within the request's buffer
01231  */
01232 #define REQ_OFFSET_TO_STR(req,offset) (ast_str_buffer((req)->data) + ((req)->offset))
01233 
01234 /*! \brief structure used in transfers */
01235 struct sip_dual {
01236    struct ast_channel *chan1; /*!< First channel involved */
01237    struct ast_channel *chan2; /*!< Second channel involved */
01238    struct sip_request req;    /*!< Request that caused the transfer (REFER) */
01239    int seqno;        /*!< Sequence number */
01240 };
01241 
01242 struct sip_pkt;
01243 
01244 /*! \brief Parameters to the transmit_invite function */
01245 struct sip_invite_param {
01246    int addsipheaders;      /*!< Add extra SIP headers */
01247    const char *uri_options;   /*!< URI options to add to the URI */
01248    const char *vxml_url;      /*!< VXML url for Cisco phones */
01249    char *auth;       /*!< Authentication */
01250    char *authheader;    /*!< Auth header */
01251    enum sip_auth_type auth_type; /*!< Authentication type */
01252    const char *replaces;      /*!< Replaces header for call transfers */
01253    int transfer;        /*!< Flag - is this Invite part of a SIP transfer? (invite/replaces) */
01254 };
01255 
01256 /*! \brief Structure to save routing information for a SIP session */
01257 struct sip_route {
01258    struct sip_route *next;
01259    char hop[0];
01260 };
01261 
01262 /*! \brief Modes for SIP domain handling in the PBX */
01263 enum domain_mode {
01264    SIP_DOMAIN_AUTO,     /*!< This domain is auto-configured */
01265    SIP_DOMAIN_CONFIG,      /*!< This domain is from configuration */
01266 };
01267 
01268 /*! \brief Domain data structure. 
01269    \note In the future, we will connect this to a configuration tree specific
01270    for this domain
01271 */
01272 struct domain {
01273    char domain[MAXHOSTNAMELEN];     /*!< SIP domain we are responsible for */
01274    char context[AST_MAX_EXTENSION]; /*!< Incoming context for this domain */
01275    enum domain_mode mode;        /*!< How did we find this domain? */
01276    AST_LIST_ENTRY(domain) list;     /*!< List mechanics */
01277 };
01278 
01279 static AST_LIST_HEAD_STATIC(domain_list, domain);  /*!< The SIP domain list */
01280 
01281 
01282 /*! \brief sip_history: Structure for saving transactions within a SIP dialog */
01283 struct sip_history {
01284    AST_LIST_ENTRY(sip_history) list;
01285    char event[0]; /* actually more, depending on needs */
01286 };
01287 
01288 AST_LIST_HEAD_NOLOCK(sip_history_head, sip_history); /*!< history list, entry in sip_pvt */
01289 
01290 /*! \brief sip_auth: Credentials for authentication to other SIP services */
01291 struct sip_auth {
01292    char realm[AST_MAX_EXTENSION];  /*!< Realm in which these credentials are valid */
01293    char username[256];             /*!< Username */
01294    char secret[256];               /*!< Secret */
01295    char md5secret[256];            /*!< MD5Secret */
01296    struct sip_auth *next;          /*!< Next auth structure in list */
01297 };
01298 
01299 /*! \name SIPflags
01300    Various flags for the flags field in the pvt structure 
01301    Trying to sort these up (one or more of the following):
01302    D: Dialog
01303    P: Peer/user
01304    G: Global flag
01305    When flags are used by multiple structures, it is important that
01306    they have a common layout so it is easy to copy them.
01307 */
01308 /*@{*/ 
01309 #define SIP_OUTGOING    (1 << 0) /*!< D: Direction of the last transaction in this dialog */
01310 #define SIP_RINGING     (1 << 2) /*!< D: Have sent 180 ringing */
01311 #define SIP_PROGRESS_SENT  (1 << 3) /*!< D: Have sent 183 message progress */
01312 #define SIP_NEEDREINVITE   (1 << 4) /*!< D: Do we need to send another reinvite? */
01313 #define SIP_PENDINGBYE     (1 << 5) /*!< D: Need to send bye after we ack? */
01314 #define SIP_GOTREFER    (1 << 6) /*!< D: Got a refer? */
01315 #define SIP_CALL_LIMIT     (1 << 7) /*!< D: Call limit enforced for this call */
01316 #define SIP_INC_COUNT      (1 << 8) /*!< D: Did this dialog increment the counter of in-use calls? */
01317 #define SIP_INC_RINGING    (1 << 9) /*!< D: Did this connection increment the counter of in-use calls? */
01318 #define SIP_DEFER_BYE_ON_TRANSFER   (1 << 10)   /*!< D: Do not hangup at first ast_hangup */
01319 
01320 #define SIP_PROMISCREDIR   (1 << 11)   /*!< DP: Promiscuous redirection */
01321 #define SIP_TRUSTRPID      (1 << 12)   /*!< DP: Trust RPID headers? */
01322 #define SIP_USEREQPHONE    (1 << 13)   /*!< DP: Add user=phone to numeric URI. Default off */
01323 #define SIP_USECLIENTCODE  (1 << 14)   /*!< DP: Trust X-ClientCode info message */
01324 
01325 /* DTMF flags - see str2dtmfmode() and dtmfmode2str() */
01326 #define SIP_DTMF     (7 << 15)   /*!< DP: DTMF Support: five settings, uses three bits */
01327 #define SIP_DTMF_RFC2833   (0 << 15)   /*!< DP: DTMF Support: RTP DTMF - "rfc2833" */
01328 #define SIP_DTMF_INBAND    (1 << 15)   /*!< DP: DTMF Support: Inband audio, only for ULAW/ALAW - "inband" */
01329 #define SIP_DTMF_INFO      (2 << 15)   /*!< DP: DTMF Support: SIP Info messages - "info" */
01330 #define SIP_DTMF_AUTO      (3 << 15)   /*!< DP: DTMF Support: AUTO switch between rfc2833 and in-band DTMF */
01331 #define SIP_DTMF_SHORTINFO      (4 << 15)       /*!< DP: DTMF Support: SIP Info messages - "info" - short variant */
01332 
01333 /* NAT settings - see nat2str() */
01334 #define SIP_NAT         (3 << 18)   /*!< DP: four settings, uses two bits */
01335 #define SIP_NAT_NEVER      (0 << 18)   /*!< DP: No nat support */
01336 #define SIP_NAT_RFC3581    (1 << 18)   /*!< DP: NAT RFC3581 */
01337 #define SIP_NAT_ROUTE      (2 << 18)   /*!< DP: NAT Only ROUTE */
01338 #define SIP_NAT_ALWAYS     (3 << 18)   /*!< DP: NAT Both ROUTE and RFC3581 */
01339 
01340 /* re-INVITE related settings */
01341 #define SIP_REINVITE    (7 << 20)   /*!< DP: four settings, uses three bits */
01342 #define SIP_REINVITE_NONE  (0 << 20)   /*!< DP: no reinvite allowed */
01343 #define SIP_DIRECT_MEDIA   (1 << 20)   /*!< DP: allow peers to be reinvited to send media directly p2p */
01344 #define SIP_DIRECT_MEDIA_NAT  (2 << 20)   /*!< DP: allow media reinvite when new peer is behind NAT */
01345 #define SIP_REINVITE_UPDATE   (4 << 20)   /*!< DP: use UPDATE (RFC3311) when reinviting this peer */
01346 
01347 /* "insecure" settings - see insecure2str() */
01348 #define SIP_INSECURE    (3 << 23)   /*!< DP: three settings, uses two bits */
01349 #define SIP_INSECURE_NONE  (0 << 23)   /*!< DP: secure mode */
01350 #define SIP_INSECURE_PORT  (1 << 23)   /*!< DP: don't require matching port for incoming requests */
01351 #define SIP_INSECURE_INVITE   (1 << 24)   /*!< DP: don't require authentication for incoming INVITEs */
01352 
01353 /* Sending PROGRESS in-band settings */
01354 #define SIP_PROG_INBAND    (3 << 25)   /*!< DP: three settings, uses two bits */
01355 #define SIP_PROG_INBAND_NEVER (0 << 25)
01356 #define SIP_PROG_INBAND_NO (1 << 25)
01357 #define SIP_PROG_INBAND_YES   (2 << 25)
01358 
01359 #define SIP_SENDRPID    (1 << 29)   /*!< DP: Remote Party-ID Support */
01360 #define SIP_G726_NONSTANDARD  (1 << 31)   /*!< DP: Use non-standard packing for G726-32 data */
01361 
01362 /*! \brief Flags to copy from peer/user to dialog */
01363 #define SIP_FLAGS_TO_COPY \
01364    (SIP_PROMISCREDIR | SIP_TRUSTRPID | SIP_SENDRPID | SIP_DTMF | SIP_REINVITE | \
01365     SIP_PROG_INBAND | SIP_USECLIENTCODE | SIP_NAT | SIP_G726_NONSTANDARD | \
01366     SIP_USEREQPHONE | SIP_INSECURE)
01367 /*@}*/ 
01368 
01369 /*! \name SIPflags2
01370    a second page of flags (for flags[1] */
01371 /*@{*/ 
01372 /* realtime flags */
01373 #define SIP_PAGE2_RTCACHEFRIENDS (1 << 0) /*!< GP: Should we keep RT objects in memory for extended time? */
01374 #define SIP_PAGE2_RTAUTOCLEAR    (1 << 2) /*!< GP: Should we clean memory from peers after expiry? */
01375 #define SIP_PAGE2_HAVEPEERCONTEXT   (1 << 3) /*< Are we associated with a configured peer context? */
01376 /* Space for addition of other realtime flags in the future */
01377 #define SIP_PAGE2_STATECHANGEQUEUE  (1 << 9) /*!< D: Unsent state pending change exists */
01378 
01379 #define SIP_PAGE2_RPORT_PRESENT         (1 << 10)       /*!< Was rport received in the Via header? */
01380 #define SIP_PAGE2_VIDEOSUPPORT      (1 << 14)   /*!< DP: Video supported if offered? */
01381 #define SIP_PAGE2_TEXTSUPPORT    (1 << 15)   /*!< GDP: Global text enable */
01382 #define SIP_PAGE2_ALLOWSUBSCRIBE (1 << 16)   /*!< GP: Allow subscriptions from this peer? */
01383 #define SIP_PAGE2_ALLOWOVERLAP      (1 << 17)   /*!< DP: Allow overlap dialing ? */
01384 #define SIP_PAGE2_SUBSCRIBEMWIONLY  (1 << 18)   /*!< GP: Only issue MWI notification if subscribed to */
01385 #define SIP_PAGE2_IGNORESDPVERSION  (1 << 19)   /*!< GDP: Ignore the SDP session version number we receive and treat all sessions as new */
01386 
01387 #define SIP_PAGE2_T38SUPPORT             (3 << 20) /*!< GDP: T.38 Fax Support */
01388 #define SIP_PAGE2_T38SUPPORT_UDPTL          (1 << 20) /*!< GDP: T.38 Fax Support (no error correction) */
01389 #define SIP_PAGE2_T38SUPPORT_UDPTL_FEC         (2 << 20) /*!< GDP: T.38 Fax Support (FEC error correction) */
01390 #define SIP_PAGE2_T38SUPPORT_UDPTL_REDUNDANCY   (3 << 20)   /*!< GDP: T.38 Fax Support (redundancy error correction) */
01391 
01392 #define SIP_PAGE2_CALL_ONHOLD    (3 << 23)   /*!< D: Call hold states: */
01393 #define SIP_PAGE2_CALL_ONHOLD_ACTIVE    (1 << 23)       /*!< D: Active hold */
01394 #define SIP_PAGE2_CALL_ONHOLD_ONEDIR   (2 << 23)   /*!< D: One directional hold */
01395 #define SIP_PAGE2_CALL_ONHOLD_INACTIVE (3 << 23)   /*!< D: Inactive hold */
01396 
01397 #define SIP_PAGE2_RFC2833_COMPENSATE    (1 << 25)  /*!< DP: Compensate for buggy RFC2833 implementations */
01398 #define SIP_PAGE2_BUGGY_MWI      (1 << 26)   /*!< DP: Buggy CISCO MWI fix */
01399 #define SIP_PAGE2_DIALOG_ESTABLISHED    (1 << 27)       /*!< 29: Has a dialog been established? */
01400 #define SIP_PAGE2_FAX_DETECT     (3 << 28)   /*!< DP: Fax Detection support */
01401 #define SIP_PAGE2_FAX_DETECT_CNG (1 << 28)   /*!< DP: Fax Detection support - detect CNG in audio */
01402 #define SIP_PAGE2_FAX_DETECT_T38 (2 << 28)   /*!< DP: Fax Detection support - detect T.38 reinvite from peer */
01403 #define SIP_PAGE2_FAX_DETECT_BOTH   (3 << 28)   /*!< DP: Fax Detection support - detect both */
01404 #define SIP_PAGE2_REGISTERTRYING        (1 << 29)       /*!< DP: Send 100 Trying on REGISTER attempts */
01405 #define SIP_PAGE2_UDPTL_DESTINATION     (1 << 30)       /*!< DP: Use source IP of RTP as destination if NAT is enabled */
01406 #define SIP_PAGE2_VIDEOSUPPORT_ALWAYS  (1 << 31)       /*!< DP: Always set up video, even if endpoints don't support it */
01407 
01408 #define SIP_PAGE2_FLAGS_TO_COPY \
01409    (SIP_PAGE2_ALLOWSUBSCRIBE | SIP_PAGE2_ALLOWOVERLAP | SIP_PAGE2_IGNORESDPVERSION | \
01410    SIP_PAGE2_VIDEOSUPPORT | SIP_PAGE2_T38SUPPORT | SIP_PAGE2_RFC2833_COMPENSATE | \
01411    SIP_PAGE2_BUGGY_MWI | SIP_PAGE2_TEXTSUPPORT | SIP_PAGE2_FAX_DETECT | \
01412    SIP_PAGE2_UDPTL_DESTINATION | SIP_PAGE2_VIDEOSUPPORT_ALWAYS | \
01413    SIP_PAGE2_HAVEPEERCONTEXT)
01414 
01415 /*@}*/ 
01416 
01417 /*! \brief debugging state
01418  * We store separately the debugging requests from the config file
01419  * and requests from the CLI. Debugging is enabled if either is set
01420  * (which means that if sipdebug is set in the config file, we can
01421  * only turn it off by reloading the config).
01422  */
01423 enum sip_debug_e {
01424    sip_debug_none = 0,
01425    sip_debug_config = 1,
01426    sip_debug_console = 2,
01427 };
01428 
01429 static enum sip_debug_e sipdebug;
01430 
01431 /*! \brief extra debugging for 'text' related events.
01432  * At the moment this is set together with sip_debug_console.
01433  * \note It should either go away or be implemented properly.
01434  */
01435 static int sipdebug_text;
01436 
01437 /*! \brief T38 States for a call */
01438 enum t38state {
01439    T38_DISABLED = 0,                /*!< Not enabled */
01440    T38_LOCAL_REINVITE,              /*!< Offered from local - REINVITE */
01441    T38_PEER_REINVITE,               /*!< Offered from peer - REINVITE */
01442    T38_ENABLED                      /*!< Negotiated (enabled) */
01443 };
01444 
01445 /*! \brief T.38 channel settings (at some point we need to make this alloc'ed */
01446 struct t38properties {
01447    enum t38state state;    /*!< T.38 state */
01448    struct ast_control_t38_parameters our_parms;
01449    struct ast_control_t38_parameters their_parms;
01450 };
01451 
01452 /*! \brief Parameters to know status of transfer */
01453 enum referstatus {
01454    REFER_IDLE,                    /*!< No REFER is in progress */
01455    REFER_SENT,                    /*!< Sent REFER to transferee */
01456    REFER_RECEIVED,                /*!< Received REFER from transferrer */
01457    REFER_CONFIRMED,               /*!< Refer confirmed with a 100 TRYING (unused) */
01458    REFER_ACCEPTED,                /*!< Accepted by transferee */
01459    REFER_RINGING,                 /*!< Target Ringing */
01460    REFER_200OK,                   /*!< Answered by transfer target */
01461    REFER_FAILED,                  /*!< REFER declined - go on */
01462    REFER_NOAUTH                   /*!< We had no auth for REFER */
01463 };
01464 
01465 /*! \brief generic struct to map between strings and integers.
01466  * Fill it with x-s pairs, terminate with an entry with s = NULL;
01467  * Then you can call map_x_s(...) to map an integer to a string,
01468  * and map_s_x() for the string -> integer mapping.
01469  */
01470 struct _map_x_s {
01471    int x;
01472    const char *s;
01473 };              
01474 
01475 static const struct _map_x_s referstatusstrings[] = {
01476    { REFER_IDLE,     "<none>" },
01477    { REFER_SENT,     "Request sent" },
01478    { REFER_RECEIVED, "Request received" },
01479    { REFER_CONFIRMED,   "Confirmed" },
01480    { REFER_ACCEPTED, "Accepted" },
01481    { REFER_RINGING,  "Target ringing" },
01482    { REFER_200OK,    "Done" },
01483    { REFER_FAILED,      "Failed" },
01484    { REFER_NOAUTH,      "Failed - auth failure" },
01485    { -1,       NULL} /* terminator */
01486 };
01487 
01488 /*! \brief Structure to handle SIP transfers. Dynamically allocated when needed
01489    \note OEJ: Should be moved to string fields */
01490 struct sip_refer {
01491    char refer_to[AST_MAX_EXTENSION];      /*!< Place to store REFER-TO extension */
01492    char refer_to_domain[AST_MAX_EXTENSION];  /*!< Place to store REFER-TO domain */
01493    char refer_to_urioption[AST_MAX_EXTENSION];  /*!< Place to store REFER-TO uri options */
01494    char refer_to_context[AST_MAX_EXTENSION]; /*!< Place to store REFER-TO context */
01495    char referred_by[AST_MAX_EXTENSION];      /*!< Place to store REFERRED-BY extension */
01496    char referred_by_name[AST_MAX_EXTENSION]; /*!< Place to store REFERRED-BY extension */
01497    char refer_contact[AST_MAX_EXTENSION];    /*!< Place to store Contact info from a REFER extension */
01498    char replaces_callid[SIPBUFSIZE];         /*!< Replace info: callid */
01499    char replaces_callid_totag[SIPBUFSIZE/2];    /*!< Replace info: to-tag */
01500    char replaces_callid_fromtag[SIPBUFSIZE/2];     /*!< Replace info: from-tag */
01501    struct sip_pvt *refer_call;         /*!< Call we are referring. This is just a reference to a
01502                       * dialog owned by someone else, so we should not destroy
01503                       * it when the sip_refer object goes.
01504                       */
01505    int attendedtransfer;            /*!< Attended or blind transfer? */
01506    int localtransfer;            /*!< Transfer to local domain? */
01507    enum referstatus status;         /*!< REFER status */
01508 };
01509 
01510 
01511 /*! \brief Structure that encapsulates all attributes related to running 
01512  *   SIP Session-Timers feature on a per dialog basis.
01513  */
01514 struct sip_st_dlg {
01515    int st_active;                          /*!< Session-Timers on/off */ 
01516    int st_interval;                        /*!< Session-Timers negotiated session refresh interval */
01517    int st_schedid;                         /*!< Session-Timers ast_sched scheduler id */
01518    enum st_refresher st_ref;               /*!< Session-Timers session refresher */
01519    int st_expirys;                         /*!< Session-Timers number of expirys */
01520    int st_active_peer_ua;                  /*!< Session-Timers on/off in peer UA */
01521    int st_cached_min_se;                   /*!< Session-Timers cached Min-SE */
01522    int st_cached_max_se;                   /*!< Session-Timers cached Session-Expires */
01523    enum st_mode st_cached_mode;            /*!< Session-Timers cached M.O. */
01524    enum st_refresher st_cached_ref;        /*!< Session-Timers cached refresher */
01525    unsigned char quit_flag:1;              /*!< Stop trying to lock; just quit */
01526 };
01527 
01528 
01529 /*! \brief Structure that encapsulates all attributes related to configuration 
01530  *   of SIP Session-Timers feature on a per user/peer basis.
01531  */
01532 struct sip_st_cfg {
01533    enum st_mode st_mode_oper;      /*!< Mode of operation for Session-Timers           */
01534    enum st_refresher st_ref;       /*!< Session-Timer refresher                        */
01535    int st_min_se;                  /*!< Lowest threshold for session refresh interval  */
01536    int st_max_se;                  /*!< Highest threshold for session refresh interval */
01537 };
01538 
01539 struct offered_media {
01540    int offered;
01541    char text[128];
01542 };
01543 
01544 /*! \brief Structure used for each SIP dialog, ie. a call, a registration, a subscribe.
01545  * Created and initialized by sip_alloc(), the descriptor goes into the list of
01546  * descriptors (dialoglist).
01547  */
01548 struct sip_pvt {
01549    struct sip_pvt *next;         /*!< Next dialog in chain */
01550    enum invitestates invitestate;      /*!< Track state of SIP_INVITEs */
01551    int method;          /*!< SIP method that opened this dialog */
01552    AST_DECLARE_STRING_FIELDS(
01553       AST_STRING_FIELD(callid);  /*!< Global CallID */
01554       AST_STRING_FIELD(randdata);   /*!< Random data */
01555       AST_STRING_FIELD(accountcode);   /*!< Account code */
01556       AST_STRING_FIELD(realm);   /*!< Authorization realm */
01557       AST_STRING_FIELD(nonce);   /*!< Authorization nonce */
01558       AST_STRING_FIELD(opaque);  /*!< Opaque nonsense */
01559       AST_STRING_FIELD(qop);     /*!< Quality of Protection, since SIP wasn't complicated enough yet. */
01560       AST_STRING_FIELD(domain);  /*!< Authorization domain */
01561       AST_STRING_FIELD(from);    /*!< The From: header */
01562       AST_STRING_FIELD(useragent);  /*!< User agent in SIP request */
01563       AST_STRING_FIELD(exten);   /*!< Extension where to start */
01564       AST_STRING_FIELD(context); /*!< Context for this call */
01565       AST_STRING_FIELD(subscribecontext); /*!< Subscribecontext */
01566       AST_STRING_FIELD(subscribeuri); /*!< Subscribecontext */
01567       AST_STRING_FIELD(fromdomain); /*!< Domain to show in the from field */
01568       AST_STRING_FIELD(fromuser);   /*!< User to show in the user field */
01569       AST_STRING_FIELD(fromname);   /*!< Name to show in the user field */
01570       AST_STRING_FIELD(tohost);  /*!< Host we should put in the "to" field */
01571       AST_STRING_FIELD(todnid);  /*!< DNID of this call (overrides host) */
01572       AST_STRING_FIELD(language);   /*!< Default language for this call */
01573       AST_STRING_FIELD(mohinterpret);  /*!< MOH class to use when put on hold */
01574       AST_STRING_FIELD(mohsuggest); /*!< MOH class to suggest when putting a peer on hold */
01575       AST_STRING_FIELD(rdnis);   /*!< Referring DNIS */
01576       AST_STRING_FIELD(redircause); /*!< Referring cause */
01577       AST_STRING_FIELD(theirtag);   /*!< Their tag */
01578       AST_STRING_FIELD(username);   /*!< [user] name */
01579       AST_STRING_FIELD(peername);   /*!< [peer] name, not set if [user] */
01580       AST_STRING_FIELD(authname);   /*!< Who we use for authentication */
01581       AST_STRING_FIELD(uri);     /*!< Original requested URI */
01582       AST_STRING_FIELD(okcontacturi);  /*!< URI from the 200 OK on INVITE */
01583       AST_STRING_FIELD(peersecret); /*!< Password */
01584       AST_STRING_FIELD(peermd5secret);
01585       AST_STRING_FIELD(cid_num); /*!< Caller*ID number */
01586       AST_STRING_FIELD(cid_name);   /*!< Caller*ID name */
01587       AST_STRING_FIELD(fullcontact);   /*!< The Contact: that the UA registers with us */
01588          /* we only store the part in <brackets> in this field. */
01589       AST_STRING_FIELD(our_contact);   /*!< Our contact header */
01590       AST_STRING_FIELD(rpid);    /*!< Our RPID header */
01591       AST_STRING_FIELD(rpid_from);  /*!< Our RPID From header */
01592       AST_STRING_FIELD(url);     /*!< URL to be sent with next message to peer */
01593       AST_STRING_FIELD(parkinglot);    /*!< Parkinglot */
01594    );
01595    char via[128];                          /*!< Via: header */
01596    struct sip_socket socket;     /*!< The socket used for this dialog */
01597    unsigned int ocseq;        /*!< Current outgoing seqno */
01598    unsigned int icseq;        /*!< Current incoming seqno */
01599    ast_group_t callgroup;        /*!< Call group */
01600    ast_group_t pickupgroup;      /*!< Pickup group */
01601    int lastinvite;            /*!< Last Cseq of invite */
01602    struct ast_flags flags[2];    /*!< SIP_ flags */
01603 
01604    /* boolean or small integers that don't belong in flags */
01605    char do_history;        /*!< Set if we want to record history */
01606    char alreadygone;       /*!< already destroyed by our peer */
01607    char needdestroy;       /*!< need to be destroyed by the monitor thread */
01608    char outgoing_call;        /*!< this is an outgoing call */
01609    char answered_elsewhere;      /*!< This call is cancelled due to answer on another channel */
01610    char novideo;           /*!< Didn't get video in invite, don't offer */
01611    char notext;            /*!< Text not supported  (?) */
01612 
01613    int timer_t1;           /*!< SIP timer T1, ms rtt */
01614    int timer_b;                            /*!< SIP timer B, ms */
01615    unsigned int sipoptions;      /*!< Supported SIP options on the other end */
01616    unsigned int reqsipoptions;      /*!< Required SIP options on the other end */
01617    struct ast_codec_pref prefs;     /*!< codec prefs */
01618    int capability;            /*!< Special capability (codec) */
01619    int jointcapability;       /*!< Supported capability at both ends (codecs) */
01620    int peercapability;        /*!< Supported peer capability */
01621    int prefcodec;          /*!< Preferred codec (outbound only) */
01622    int noncodeccapability;       /*!< DTMF RFC2833 telephony-event */
01623    int jointnoncodeccapability;            /*!< Joint Non codec capability */
01624    int redircodecs;        /*!< Redirect codecs */
01625    int maxcallbitrate;        /*!< Maximum Call Bitrate for Video Calls */ 
01626    int t38_maxdatagram;       /*!< T.38 FaxMaxDatagram override */
01627    struct sip_proxy *outboundproxy; /*!< Outbound proxy for this dialog. Use ref_proxy to set this instead of setting it directly*/
01628    struct t38properties t38;     /*!< T38 settings */
01629    struct sockaddr_in udptlredirip; /*!< Where our T.38 UDPTL should be going if not to us */
01630    struct ast_udptl *udptl;      /*!< T.38 UDPTL session */
01631    int callingpres;        /*!< Calling presentation */
01632    int authtries;          /*!< Times we've tried to authenticate */
01633    int expiry;          /*!< How long we take to expire */
01634    long branch;            /*!< The branch identifier of this session */
01635    long invite_branch;        /*!< The branch used when we sent the initial INVITE */
01636    char tag[11];           /*!< Our tag for this session */
01637    int sessionid;          /*!< SDP Session ID */
01638    int sessionversion;        /*!< SDP Session Version */
01639    int64_t sessionversion_remote;      /*!< Remote UA's SDP Session Version */
01640    int session_modify;        /*!< Session modification request true/false  */
01641    unsigned int portinuri:1;     /*!< Non zero if a port has been specified, will also disable srv lookups */
01642    struct sockaddr_in sa;        /*!< Our peer */
01643    struct sockaddr_in redirip;      /*!< Where our RTP should be going if not to us */
01644    struct sockaddr_in vredirip;     /*!< Where our Video RTP should be going if not to us */
01645    struct sockaddr_in tredirip;     /*!< Where our Text RTP should be going if not to us */
01646    time_t lastrtprx;       /*!< Last RTP received */
01647    time_t lastrtptx;       /*!< Last RTP sent */
01648    int rtptimeout;            /*!< RTP timeout time */
01649    struct sockaddr_in recv;      /*!< Received as */
01650    struct sockaddr_in ourip;     /*!< Our IP (as seen from the outside) */
01651    struct ast_channel *owner;    /*!< Who owns us (if we have an owner) */
01652    struct sip_route *route;      /*!< Head of linked list of routing steps (fm Record-Route) */
01653    int route_persistant;         /*!< Is this the "real" route? */
01654    struct ast_variable *notify_headers;    /*!< Custom notify type */
01655    struct sip_auth *peerauth;    /*!< Realm authentication */
01656    int noncecount;            /*!< Nonce-count */
01657    unsigned int stalenonce:1; /*!< Marks the current nonce as responded too */
01658    char lastmsg[256];         /*!< Last Message sent/received */
01659    int amaflags;           /*!< AMA Flags */
01660    int pendinginvite;         /*!< Any pending INVITE or state NOTIFY (in subscribe pvt's) ? (seqno of this) */
01661    int glareinvite;        /*!< A invite received while a pending invite is already present is stored here.  Its seqno is the
01662                   value. Since this glare invite's seqno is not the same as the pending invite's, it must be 
01663                   held in order to properly process acknowledgements for our 491 response. */
01664    struct sip_request initreq;      /*!< Latest request that opened a new transaction
01665                      within this dialog.
01666                      NOT the request that opened the dialog */
01667 
01668    int initid;          /*!< Auto-congest ID if appropriate (scheduler) */
01669    int waitid;          /*!< Wait ID for scheduler after 491 or other delays */
01670    int autokillid;            /*!< Auto-kill ID (scheduler) */
01671    int t38id;                              /*!< T.38 Response ID */
01672    enum transfermodes allowtransfer;   /*!< REFER: restriction scheme */
01673    struct sip_refer *refer;      /*!< REFER: SIP transfer data structure */
01674    enum subscriptiontype subscribed;   /*!< SUBSCRIBE: Is this dialog a subscription?  */
01675    int stateid;            /*!< SUBSCRIBE: ID for devicestate subscriptions */
01676    int laststate;          /*!< SUBSCRIBE: Last known extension state */
01677    int dialogver;          /*!< SUBSCRIBE: Version for subscription dialog-info */
01678 
01679    struct ast_dsp *dsp;       /*!< A DSP for inband DTMF and fax CNG tone detection */
01680 
01681    struct sip_peer *relatedpeer;    /*!< If this dialog is related to a peer, which one 
01682                      Used in peerpoke, mwi subscriptions */
01683    struct sip_registry *registry;      /*!< If this is a REGISTER dialog, to which registry */
01684    struct ast_rtp *rtp;       /*!< RTP Session */
01685    struct ast_rtp *vrtp;         /*!< Video RTP session */
01686    struct ast_rtp *trtp;         /*!< Text RTP session */
01687    struct sip_pkt *packets;      /*!< Packets scheduled for re-transmission */
01688    struct sip_history_head *history;   /*!< History of this SIP dialog */
01689    size_t history_entries;       /*!< Number of entires in the history */
01690    struct ast_variable *chanvars;      /*!< Channel variables to set for inbound call */
01691    AST_LIST_HEAD_NOLOCK(request_queue, sip_request) request_queue; /*!< Requests that arrived but could not be processed immediately */
01692    int request_queue_sched_id;      /*!< Scheduler ID of any scheduled action to process queued requests */
01693    int provisional_keepalive_sched_id; /*!< Scheduler ID for provisional responses that need to be sent out to avoid cancellation */
01694    const char *last_provisional;   /*!< The last successfully transmitted provisonal response message */
01695    struct sip_invite_param *options;   /*!< Options for INVITE */
01696    int autoframing;        /*!< The number of Asters we group in a Pyroflax
01697                      before strolling to the Grokyzpå
01698                      (A bit unsure of this, please correct if
01699                      you know more) */
01700    struct sip_st_dlg *stimer;    /*!< SIP Session-Timers */              
01701   
01702    int red;             /*!< T.140 RTP Redundancy */
01703    int hangupcause;        /*!< Storage of hangupcause copied from our owner before we disconnect from the AST channel (only used at hangup) */
01704 
01705    struct sip_subscription_mwi *mwi;       /*!< If this is a subscription MWI dialog, to which subscription */
01706    /*! When receiving an SDP offer, it is important to take note of what media types were offered.
01707     * By doing this, even if we don't want to answer a particular media stream with something meaningful, we can
01708     * still put an m= line in our answer with the port set to 0.
01709     *
01710     * The reason for the length being 4 is that in this branch of Asterisk, the only media types supported are 
01711     * image, audio, text, and video. Therefore we need to keep track of which types of media were offered.
01712     *
01713     * Note that if we wanted to be 100% correct, we would keep a list of all media streams offered. That way we could respond
01714     * even to unknown media types, and we could respond to multiple streams of the same type. Such large-scale changes
01715     * are not a good idea for released branches, though, so we're compromising by just making sure that for the common cases:
01716     * audio and video, audio and T.38, and audio and text, we give the appropriate response to both media streams.
01717     *
01718     * The large-scale changes would be a good idea for implementing during an SDP rewrite.
01719     */
01720    struct offered_media offered_media[4];
01721 }; 
01722 
01723 
01724 /*! \brief
01725  * Here we implement the container for dialogs (sip_pvt), defining
01726  * generic wrapper functions to ease the transition from the current
01727  * implementation (a single linked list) to a different container.
01728  * In addition to a reference to the container, we need functions to lock/unlock
01729  * the container and individual items, and functions to add/remove
01730  * references to the individual items.
01731  */
01732 struct ao2_container *dialogs;
01733 
01734 #define sip_pvt_lock(x) ao2_lock(x)
01735 #define sip_pvt_trylock(x) ao2_trylock(x)
01736 #define sip_pvt_unlock(x) ao2_unlock(x)
01737 
01738 /*! \brief
01739  * when we create or delete references, make sure to use these
01740  * functions so we keep track of the refcounts.
01741  * To simplify the code, we allow a NULL to be passed to dialog_unref().
01742  */
01743 #ifdef REF_DEBUG
01744 #define dialog_ref(arg1,arg2) dialog_ref_debug((arg1),(arg2), __FILE__, __LINE__, __PRETTY_FUNCTION__)
01745 #define dialog_unref(arg1,arg2) dialog_unref_debug((arg1),(arg2), __FILE__, __LINE__, __PRETTY_FUNCTION__)
01746 
01747 static struct sip_pvt *dialog_ref_debug(struct sip_pvt *p, char *tag, char *file, int line, const char *func)
01748 {
01749    if (p)
01750       _ao2_ref_debug(p, 1, tag, file, line, func);
01751    else
01752       ast_log(LOG_ERROR, "Attempt to Ref a null pointer\n");
01753    return p;
01754 }
01755 
01756 static struct sip_pvt *dialog_unref_debug(struct sip_pvt *p, char *tag, char *file, int line, const char *func)
01757 {
01758    if (p)
01759       _ao2_ref_debug(p, -1, tag, file, line, func);
01760    return NULL;
01761 }
01762 #else
01763 static struct sip_pvt *dialog_ref(struct sip_pvt *p, char *tag)
01764 {
01765    if (p)
01766       ao2_ref(p, 1);
01767    else
01768       ast_log(LOG_ERROR, "Attempt to Ref a null pointer\n");
01769    return p;
01770 }
01771 
01772 static struct sip_pvt *dialog_unref(struct sip_pvt *p, char *tag)
01773 {
01774    if (p)
01775       ao2_ref(p, -1);
01776    return NULL;
01777 }
01778 #endif
01779 
01780 /*! \brief sip packet - raw format for outbound packets that are sent or scheduled for transmission
01781  * Packets are linked in a list, whose head is in the struct sip_pvt they belong to.
01782  * Each packet holds a reference to the parent struct sip_pvt.
01783  * This structure is allocated in __sip_reliable_xmit() and only for packets that
01784  * require retransmissions.
01785  */
01786 struct sip_pkt {
01787    struct sip_pkt *next;         /*!< Next packet in linked list */
01788    int retrans;            /*!< Retransmission number */
01789    int method;          /*!< SIP method for this packet */
01790    int seqno;           /*!< Sequence number */
01791    char is_resp;           /*!< 1 if this is a response packet (e.g. 200 OK), 0 if it is a request */
01792    char is_fatal;          /*!< non-zero if there is a fatal error */
01793    int response_code;      /*!< If this is a response, the response code */
01794    struct sip_pvt *owner;        /*!< Owner AST call */
01795    int retransid;          /*!< Retransmission ID */
01796    int timer_a;            /*!< SIP timer A, retransmission timer */
01797    int timer_t1;           /*!< SIP Timer T1, estimated RTT or 500 ms */
01798    int packetlen;          /*!< Length of packet */
01799    struct ast_str *data;
01800 }; 
01801 
01802 /*!
01803  * \brief A peer's mailbox
01804  *
01805  * We could use STRINGFIELDS here, but for only two strings, it seems like
01806  * too much effort ...
01807  */
01808 struct sip_mailbox {
01809    char *mailbox;
01810    char *context;
01811    /*! Associated MWI subscription */
01812    struct ast_event_sub *event_sub;
01813    AST_LIST_ENTRY(sip_mailbox) entry;
01814 };
01815 
01816 enum sip_peer_type {
01817    SIP_TYPE_PEER = (1 << 0),
01818    SIP_TYPE_USER = (1 << 1),
01819 };
01820 
01821 /*! \brief Structure for SIP peer data, we place calls to peers if registered  or fixed IP address (host) 
01822 */
01823 /* XXX field 'name' must be first otherwise sip_addrcmp() will fail, as will astobj2 hashing of the structure */
01824 struct sip_peer {
01825    char name[80];             /*!< the unique name of this object */
01826    AST_DECLARE_STRING_FIELDS(
01827       AST_STRING_FIELD(secret);     /*!< Password for inbound auth */
01828       AST_STRING_FIELD(md5secret);     /*!< Password in MD5 */
01829       AST_STRING_FIELD(remotesecret);     /*!< Remote secret (trunks, remote devices) */
01830       AST_STRING_FIELD(context);    /*!< Default context for incoming calls */
01831       AST_STRING_FIELD(subscribecontext); /*!< Default context for subscriptions */
01832       AST_STRING_FIELD(username);      /*!< Temporary username until registration */ 
01833       AST_STRING_FIELD(accountcode);      /*!< Account code */
01834       AST_STRING_FIELD(tohost);     /*!< If not dynamic, IP address */
01835       AST_STRING_FIELD(regexten);      /*!< Extension to register (if regcontext is used) */
01836       AST_STRING_FIELD(fromuser);      /*!< From: user when calling this peer */
01837       AST_STRING_FIELD(fromdomain);    /*!< From: domain when calling this peer */
01838       AST_STRING_FIELD(fullcontact);      /*!< Contact registered with us (not in sip.conf) */
01839       AST_STRING_FIELD(cid_num);    /*!< Caller ID num */
01840       AST_STRING_FIELD(cid_name);      /*!< Caller ID name */
01841       AST_STRING_FIELD(vmexten);       /*!< Dialplan extension for MWI notify message*/
01842       AST_STRING_FIELD(language);      /*!<  Default language for prompts */
01843       AST_STRING_FIELD(mohinterpret);     /*!<  Music on Hold class */
01844       AST_STRING_FIELD(mohsuggest);    /*!<  Music on Hold class */
01845       AST_STRING_FIELD(parkinglot);    /*!<  Parkinglot */
01846       AST_STRING_FIELD(useragent);     /*!<  User agent in SIP request (saved from registration) */
01847       );
01848    struct sip_socket socket;  /*!< Socket used for this peer */
01849    enum sip_transport default_outbound_transport;    /*!< Peer Registration may change the default outbound transport.
01850                                     If register expires, default should be reset. to this value */
01851    unsigned int transports:3;      /*!< Transports (enum sip_transport) that are acceptable for this peer */
01852    struct sip_auth *auth;     /*!< Realm authentication list */
01853    int amaflags;        /*!< AMA Flags (for billing) */
01854    int callingpres;     /*!< Calling id presentation */
01855    int inUse;        /*!< Number of calls in use */
01856    int inRinging;       /*!< Number of calls ringing */
01857    int onHold;                     /*!< Peer has someone on hold */
01858    int call_limit;         /*!< Limit of concurrent calls */
01859    int t38_maxdatagram;    /*!< T.38 FaxMaxDatagram override */
01860    int busy_level;         /*!< Level of active channels where we signal busy */
01861    enum transfermodes allowtransfer;   /*! SIP Refer restriction scheme */
01862    struct ast_codec_pref prefs;  /*!<  codec prefs */
01863    int lastmsgssent;
01864    unsigned int sipoptions;   /*!<  Supported SIP options */
01865    struct ast_flags flags[2]; /*!<  SIP_ flags */
01866 
01867    /*! Mailboxes that this peer cares about */
01868    AST_LIST_HEAD_NOLOCK(, sip_mailbox) mailboxes;
01869 
01870    /* things that don't belong in flags */
01871    char is_realtime;    /*!< this is a 'realtime' peer */
01872    char rt_fromcontact;    /*!< copy fromcontact from realtime */
01873    char host_dynamic;      /*!< Dynamic Peers register with Asterisk */
01874    char selfdestruct;      /*!< Automatic peers need to destruct themselves */
01875    char the_mark;       /*!< moved out of ASTOBJ into struct proper; That which bears the_mark should be deleted! */
01876 
01877    int expire;       /*!<  When to expire this peer registration */
01878    int capability;         /*!<  Codec capability */
01879    int rtptimeout;         /*!<  RTP timeout */
01880    int rtpholdtimeout;     /*!<  RTP Hold Timeout */
01881    int rtpkeepalive;    /*!<  Send RTP packets for keepalive */
01882    ast_group_t callgroup;     /*!<  Call group */
01883    ast_group_t pickupgroup;   /*!<  Pickup group */
01884    struct sip_proxy *outboundproxy; /*!< Outbound proxy for this peer */
01885    struct ast_dnsmgr_entry *dnsmgr;/*!<  DNS refresh manager for peer */
01886    struct sockaddr_in addr;   /*!<  IP address of peer */
01887    int maxcallbitrate;     /*!< Maximum Bitrate for a video call */
01888    unsigned int portinuri:1;  /*!< Whether the port should be included in the URI */
01889 
01890    /* Qualification */
01891    struct sip_pvt *call;      /*!<  Call pointer */
01892    int pokeexpire;         /*!<  When to expire poke (qualify= checking) */
01893    int lastms;       /*!<  How long last response took (in ms), or -1 for no response */
01894    int maxms;        /*!<  Max ms we will accept for the host to be up, 0 to not monitor */
01895    int qualifyfreq;     /*!<  Qualification: How often to check for the host to be up */
01896    struct timeval ps;      /*!<  Time for sending SIP OPTION in sip_pke_peer() */
01897    struct sockaddr_in defaddr;   /*!<  Default IP address, used until registration */
01898    struct ast_ha *ha;      /*!<  Access control list */
01899    struct ast_ha *contactha;       /*!<  Restrict what IPs are allowed in the Contact header (for registration) */
01900    struct ast_variable *chanvars;   /*!<  Variables to set for channel created by user */
01901    struct sip_pvt *mwipvt;    /*!<  Subscription for MWI */
01902    int autoframing;
01903    struct sip_st_cfg stimer;  /*!<  SIP Session-Timers */
01904    int timer_t1;        /*!<  The maximum T1 value for the peer */
01905    int timer_b;         /*!<  The maximum timer B (transaction timeouts) */
01906    int deprecated_username; /*!< If it's a realtime peer, are they using the deprecated "username" instead of "defaultuser" */
01907    
01908    /*XXX Seems like we suddenly have two flags with the same content. Why? To be continued... */
01909    enum sip_peer_type type; /*!< Distinguish between "user" and "peer" types. This is used solely for CLI and manager commands */
01910 };
01911 
01912 
01913 /*! 
01914  * \brief Registrations with other SIP proxies
01915  *
01916  * Created by sip_register(), the entry is linked in the 'regl' list,
01917  * and never deleted (other than at 'sip reload' or module unload times).
01918  * The entry always has a pending timeout, either waiting for an ACK to
01919  * the REGISTER message (in which case we have to retransmit the request),
01920  * or waiting for the next REGISTER message to be sent (either the initial one,
01921  * or once the previously completed registration one expires).
01922  * The registration can be in one of many states, though at the moment
01923  * the handling is a bit mixed.
01924  */
01925 struct sip_registry {
01926    ASTOBJ_COMPONENTS_FULL(struct sip_registry,1,1);
01927    AST_DECLARE_STRING_FIELDS(
01928       AST_STRING_FIELD(callid);  /*!< Global Call-ID */
01929       AST_STRING_FIELD(realm);   /*!< Authorization realm */
01930       AST_STRING_FIELD(nonce);   /*!< Authorization nonce */
01931       AST_STRING_FIELD(opaque);  /*!< Opaque nonsense */
01932       AST_STRING_FIELD(qop);     /*!< Quality of Protection, since SIP wasn't complicated enough yet. */
01933       AST_STRING_FIELD(domain);  /*!< Authorization domain */
01934       AST_STRING_FIELD(username);   /*!< Who we are registering as */
01935       AST_STRING_FIELD(authuser);   /*!< Who we *authenticate* as */
01936       AST_STRING_FIELD(hostname);   /*!< Domain or host we register to */
01937       AST_STRING_FIELD(secret);  /*!< Password in clear text */   
01938       AST_STRING_FIELD(md5secret);  /*!< Password in md5 */
01939       AST_STRING_FIELD(callback);   /*!< Contact extension */
01940       AST_STRING_FIELD(random);
01941       AST_STRING_FIELD(peername);   /*!< Peer registering to */
01942    );
01943    enum sip_transport transport; /*!< Transport for this registration UDP, TCP or TLS */
01944    int portno;       /*!<  Optional port override */
01945    int expire;       /*!< Sched ID of expiration */
01946    int configured_expiry;     /*!< Configured value to use for the Expires header */
01947    int expiry;       /*!< Negotiated value used for the Expires header */
01948    int regattempts;     /*!< Number of attempts (since the last success) */
01949    int timeout;         /*!< sched id of sip_reg_timeout */
01950    int refresh;         /*!< How often to refresh */
01951    struct sip_pvt *call;      /*!< create a sip_pvt structure for each outbound "registration dialog" in progress */
01952    enum sipregistrystate regstate;  /*!< Registration state (see above) */
01953    struct timeval regtime;    /*!< Last successful registration time */
01954    int callid_valid;    /*!< 0 means we haven't chosen callid for this registry yet. */
01955    unsigned int ocseq;     /*!< Sequence number we got to for REGISTERs for this registry */
01956    struct ast_dnsmgr_entry *dnsmgr; /*!<  DNS refresh manager for register */
01957    struct sockaddr_in us;     /*!< Who the server thinks we are */
01958    int noncecount;         /*!< Nonce-count */
01959    char lastmsg[256];      /*!< Last Message sent/received */
01960 };
01961 
01962 enum sip_tcptls_alert {
01963    /*! \brief There is new data to be sent out */
01964    TCPTLS_ALERT_DATA,
01965    /*! \brief A request to stop the tcp_handler thread */
01966    TCPTLS_ALERT_STOP,
01967 };
01968 
01969 struct tcptls_packet {
01970    AST_LIST_ENTRY(tcptls_packet) entry;
01971    struct ast_str *data;
01972    size_t len;
01973 };
01974 /*! \brief Definition of a thread that handles a socket */
01975 struct sip_threadinfo {
01976    int stop;
01977    int alert_pipe[2]; /*! Used to alert tcptls thread when packet is ready to be written */
01978    pthread_t threadid;
01979    struct ast_tcptls_session_instance *tcptls_session;
01980    enum sip_transport type;   /*!< We keep a copy of the type here so we can display it in the connection list */
01981    AST_LIST_HEAD_NOLOCK(, tcptls_packet) packet_q;
01982 };
01983 
01984 /*! \brief Definition of an MWI subscription to another server */
01985 struct sip_subscription_mwi {
01986    ASTOBJ_COMPONENTS_FULL(struct sip_subscription_mwi,1,1);
01987    AST_DECLARE_STRING_FIELDS(
01988       AST_STRING_FIELD(username);     /*!< Who we are sending the subscription as */
01989       AST_STRING_FIELD(authuser);     /*!< Who we *authenticate* as */
01990       AST_STRING_FIELD(hostname);     /*!< Domain or host we subscribe to */
01991       AST_STRING_FIELD(secret);       /*!< Password in clear text */
01992       AST_STRING_FIELD(mailbox);      /*!< Mailbox store to put MWI into */
01993       );
01994    enum sip_transport transport;    /*!< Transport to use */
01995    int portno;                      /*!< Optional port override */
01996    int resub;                       /*!< Sched ID of resubscription */
01997    unsigned int subscribed:1;       /*!< Whether we are currently subscribed or not */
01998    struct sip_pvt *call;            /*!< Outbound subscription dialog */
01999    struct ast_dnsmgr_entry *dnsmgr; /*!< DNS refresh manager for subscription */
02000    struct sockaddr_in us;           /*!< Who the server thinks we are */
02001 };
02002 
02003 /* --- Hash tables of various objects --------*/
02004 
02005 #ifdef LOW_MEMORY
02006 static int hash_peer_size = 17;
02007 static int hash_dialog_size = 17;
02008 static int hash_user_size = 17;
02009 #else
02010 static int hash_peer_size = 563; /*!< Size of peer hash table, prime number preferred! */
02011 static int hash_dialog_size = 563;
02012 static int hash_user_size = 563;
02013 #endif
02014 
02015 /*! \brief  The table of TCP threads */
02016 static struct ao2_container *threadt;
02017 
02018 /*! \brief  The peer list: Users, Peers and Friends */
02019 struct ao2_container *peers;
02020 struct ao2_container *peers_by_ip;
02021 
02022 /*! \brief  The register list: Other SIP proxies we register with and place calls to */
02023 static struct ast_register_list {
02024    ASTOBJ_CONTAINER_COMPONENTS(struct sip_registry);
02025    int recheck;
02026 } regl;
02027 
02028 /*! \brief  The MWI subscription list */
02029 static struct ast_subscription_mwi_list {
02030    ASTOBJ_CONTAINER_COMPONENTS(struct sip_subscription_mwi);
02031 } submwil;
02032 
02033 /*! \brief
02034  * \note The only member of the peer used here is the name field
02035  */
02036 static int peer_hash_cb(const void *obj, const int flags)
02037 {
02038    const struct sip_peer *peer = obj;
02039 
02040    return ast_str_case_hash(peer->name);
02041 }
02042 
02043 /*!
02044  * \note The only member of the peer used here is the name field
02045  */
02046 static int peer_cmp_cb(void *obj, void *arg, int flags)
02047 {
02048    struct sip_peer *peer = obj, *peer2 = arg;
02049 
02050    return !strcasecmp(peer->name, peer2->name) ? CMP_MATCH | CMP_STOP : 0;
02051 }
02052 
02053 /*!
02054  * \note the peer's ip address field is used to create key.
02055  */
02056 static int peer_iphash_cb(const void *obj, const int flags)
02057 {
02058    const struct sip_peer *peer = obj;
02059    int ret1 = peer->addr.sin_addr.s_addr;
02060    if (ret1 < 0)
02061       ret1 = -ret1;
02062 
02063    return ret1;
02064 }
02065 
02066 /*!
02067  * Match Peers by IP and Port number.
02068  *
02069  * This function has two modes.
02070  *  - If the peer arg does not have INSECURE_PORT set, then we will only return
02071  *    a match for a peer that matches both the IP and port.
02072  *  - If the peer arg does have the INSECURE_PORT flag set, then we will only
02073  *    return a match for a peer that matches the IP and has insecure=port
02074  *    in its configuration.
02075  *
02076  * This callback will be used twice when doing peer matching.  There is a first
02077  * pass for full IP+port matching, and a second pass in case there is a match
02078  * that meets the insecure=port criteria.
02079  *
02080  * \note Connections coming in over TCP or TLS should never be matched by port.
02081  *
02082  * \note the peer's addr struct provides to fields combined to make a key: the sin_addr.s_addr and sin_port fields.
02083  */
02084 static int peer_ipcmp_cb(void *obj, void *arg, int flags)
02085 {
02086    struct sip_peer *peer = obj, *peer2 = arg;
02087 
02088    if (peer->addr.sin_addr.s_addr != peer2->addr.sin_addr.s_addr) {
02089       /* IP doesn't match */
02090       return 0;
02091    }
02092 
02093    /* We matched the IP, check to see if we need to match by port as well. */
02094    if ((peer->transports & peer2->transports) & (SIP_TRANSPORT_TLS | SIP_TRANSPORT_TCP)) {
02095       /* peer matching on port is not possible with TCP/TLS */
02096       return CMP_MATCH | CMP_STOP;
02097    } else if (ast_test_flag(&peer2->flags[0], SIP_INSECURE_PORT)) {
02098       /* We are allowing match without port for peers configured that
02099        * way in this pass through the peers. */
02100       return ast_test_flag(&peer->flags[0], SIP_INSECURE_PORT) ?
02101             (CMP_MATCH | CMP_STOP) : 0;
02102    }
02103 
02104    /* Now only return a match if the port matches, as well. */
02105    return peer->addr.sin_port == peer2->addr.sin_port ? (CMP_MATCH | CMP_STOP) : 0;
02106 }
02107 
02108 
02109 static int threadt_hash_cb(const void *obj, const int flags)
02110 {
02111    const struct sip_threadinfo *th = obj;
02112 
02113    return (int) th->tcptls_session->remote_address.sin_addr.s_addr;
02114 }
02115 
02116 static int threadt_cmp_cb(void *obj, void *arg, int flags)
02117 {
02118    struct sip_threadinfo *th = obj, *th2 = arg;
02119 
02120    return (th->tcptls_session == th2->tcptls_session) ? CMP_MATCH | CMP_STOP : 0;
02121 }
02122 
02123 /*!
02124  * \note The only member of the dialog used here callid string
02125  */
02126 static int dialog_hash_cb(const void *obj, const int flags)
02127 {
02128    const struct sip_pvt *pvt = obj;
02129 
02130    return ast_str_case_hash(pvt->callid);
02131 }
02132 
02133 /*!
02134  * \note The only member of the dialog used here callid string
02135  */
02136 static int dialog_cmp_cb(void *obj, void *arg, int flags)
02137 {
02138    struct sip_pvt *pvt = obj, *pvt2 = arg;
02139    
02140    return !strcasecmp(pvt->callid, pvt2->callid) ? CMP_MATCH | CMP_STOP : 0;
02141 }
02142 
02143 static int temp_pvt_init(void *);
02144 static void temp_pvt_cleanup(void *);
02145 
02146 /*! \brief A per-thread temporary pvt structure */
02147 AST_THREADSTORAGE_CUSTOM(ts_temp_pvt, temp_pvt_init, temp_pvt_cleanup);
02148 
02149 #ifdef LOW_MEMORY
02150 static void ts_ast_rtp_destroy(void *);
02151 
02152 AST_THREADSTORAGE_CUSTOM(ts_audio_rtp, NULL, ts_ast_rtp_destroy);
02153 AST_THREADSTORAGE_CUSTOM(ts_video_rtp, NULL, ts_ast_rtp_destroy);
02154 AST_THREADSTORAGE_CUSTOM(ts_text_rtp, NULL, ts_ast_rtp_destroy);
02155 #endif
02156 
02157 /*! \brief Authentication list for realm authentication 
02158  * \todo Move the sip_auth list to AST_LIST */
02159 static struct sip_auth *authl = NULL;
02160 
02161 
02162 /* --- Sockets and networking --------------*/
02163 
02164 /*! \brief Main socket for UDP SIP communication.
02165  *
02166  * sipsock is shared between the SIP manager thread (which handles reload
02167  * requests), the udp io handler (sipsock_read()) and the user routines that
02168  * issue udp writes (using __sip_xmit()).
02169  * The socket is -1 only when opening fails (this is a permanent condition),
02170  * or when we are handling a reload() that changes its address (this is
02171  * a transient situation during which we might have a harmless race, see
02172  * below). Because the conditions for the race to be possible are extremely
02173  * rare, we don't want to pay the cost of locking on every I/O.
02174  * Rather, we remember that when the race may occur, communication is
02175  * bound to fail anyways, so we just live with this event and let
02176  * the protocol handle this above us.
02177  */
02178 static int sipsock  = -1;
02179 
02180 static struct sockaddr_in bindaddr; /*!< UDP: The address we bind to */
02181 
02182 /*! \brief our (internal) default address/port to put in SIP/SDP messages
02183  *  internip is initialized picking a suitable address from one of the
02184  * interfaces, and the same port number we bind to. It is used as the
02185  * default address/port in SIP messages, and as the default address
02186  * (but not port) in SDP messages.
02187  */
02188 static struct sockaddr_in internip;
02189 
02190 /*! \brief our external IP address/port for SIP sessions.
02191  * externip.sin_addr is only set when we know we might be behind
02192  * a NAT, and this is done using a variety of (mutually exclusive)
02193  * ways from the config file:
02194  *
02195  * + with "externip = host[:port]" we specify the address/port explicitly.
02196  *   The address is looked up only once when (re)loading the config file;
02197  * 
02198  * + with "externhost = host[:port]" we do a similar thing, but the
02199  *   hostname is stored in externhost, and the hostname->IP mapping
02200  *   is refreshed every 'externrefresh' seconds;
02201  * 
02202  * + with "stunaddr = host[:port]" we run queries every externrefresh seconds
02203  *   to the specified server, and store the result in externip.
02204  *
02205  * Other variables (externhost, externexpire, externrefresh) are used
02206  * to support the above functions.
02207  */
02208 static struct sockaddr_in externip;    /*!< External IP address if we are behind NAT */
02209 
02210 static char externhost[MAXHOSTNAMELEN];      /*!< External host name */
02211 static time_t externexpire;         /*!< Expiration counter for re-resolving external host name in dynamic DNS */
02212 static int externrefresh = 10;
02213 static struct sockaddr_in stunaddr;    /*!< stun server address */
02214 
02215 /*! \brief  List of local networks
02216  * We store "localnet" addresses from the config file into an access list,
02217  * marked as 'DENY', so the call to ast_apply_ha() will return
02218  * AST_SENSE_DENY for 'local' addresses, and AST_SENSE_ALLOW for 'non local'
02219  * (i.e. presumably public) addresses.
02220  */
02221 static struct ast_ha *localaddr;    /*!< List of local networks, on the same side of NAT as this Asterisk */
02222 
02223 static int ourport_tcp;          /*!< The port used for TCP connections */
02224 static int ourport_tls;          /*!< The port used for TCP/TLS connections */
02225 static struct sockaddr_in debugaddr;
02226 
02227 static struct ast_config *notify_types = NULL;     /*!< The list of manual NOTIFY types we know how to send */
02228 
02229 /*! some list management macros. */
02230  
02231 #define UNLINK(element, head, prev) do {  \
02232    if (prev)            \
02233       (prev)->next = (element)->next;  \
02234    else              \
02235       (head) = (element)->next;  \
02236    } while (0)
02237 
02238 enum t38_action_flag {
02239    SDP_T38_NONE = 0, /*!< Do not modify T38 information at all */
02240    SDP_T38_INITIATE, /*!< Remote side has requested T38 with us */
02241    SDP_T38_ACCEPT,   /*!< Remote side accepted our T38 request */
02242 };
02243 
02244 /*---------------------------- Forward declarations of functions in chan_sip.c */
02245 /* Note: This is added to help splitting up chan_sip.c into several files
02246    in coming releases. */
02247 
02248 /*--- PBX interface functions */
02249 static struct ast_channel *sip_request_call(const char *type, int format, void *data, int *cause);
02250 static int sip_devicestate(void *data);
02251 static int sip_sendtext(struct ast_channel *ast, const char *text);
02252 static int sip_call(struct ast_channel *ast, char *dest, int timeout);
02253 static int sip_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen);
02254 static int sip_hangup(struct ast_channel *ast);
02255 static int sip_answer(struct ast_channel *ast);
02256 static struct ast_frame *sip_read(struct ast_channel *ast);
02257 static int sip_write(struct ast_channel *ast, struct ast_frame *frame);
02258 static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen);
02259 static int sip_transfer(struct ast_channel *ast, const char *dest);
02260 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
02261 static int sip_senddigit_begin(struct ast_channel *ast, char digit);
02262 static int sip_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration);
02263 static int sip_queryoption(struct ast_channel *chan, int option, void *data, int *datalen);
02264 static const char *sip_get_callid(struct ast_channel *chan);
02265 
02266 static int handle_request_do(struct sip_request *req, struct sockaddr_in *sin);
02267 static int sip_standard_port(enum sip_transport type, int port);
02268 static int sip_prepare_socket(struct sip_pvt *p);
02269 static int sip_parse_host(char *line, int lineno, char **hostname, int *portnum, enum sip_transport *transport);
02270 
02271 /*--- Transmitting responses and requests */
02272 static int sipsock_read(int *id, int fd, short events, void *ignore);
02273 static int __sip_xmit(struct sip_pvt *p, struct ast_str *data, int len);
02274 static int __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, struct ast_str *data, int len, int fatal, int sipmethod);
02275 static int __transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
02276 static int retrans_pkt(const void *data);
02277 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);
02278 static int transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req);
02279 static int transmit_response_reliable(struct sip_pvt *p, const char *msg, const struct sip_request *req);
02280 static int transmit_response_with_date(struct sip_pvt *p, const char *msg, const struct sip_request *req);
02281 static int transmit_response_with_sdp(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable, int oldsdp);
02282 static int transmit_response_with_unsupported(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *unsupported);
02283 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);
02284 static int transmit_provisional_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, int with_sdp);
02285 static int transmit_response_with_allow(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
02286 static void transmit_fake_auth_response(struct sip_pvt *p, int sipmethod, struct sip_request *req, enum xmittype reliable);
02287 static int transmit_request(struct sip_pvt *p, int sipmethod, int inc, enum xmittype reliable, int newbranch);
02288 static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, int seqno, enum xmittype reliable, int newbranch);
02289 static int transmit_invite(struct sip_pvt *p, int sipmethod, int sdp, int init);
02290 static int transmit_reinvite_with_sdp(struct sip_pvt *p, int t38version, int oldsdp);
02291 static int transmit_info_with_digit(struct sip_pvt *p, const char digit, unsigned int duration);
02292 static int transmit_info_with_vidupdate(struct sip_pvt *p);
02293 static int transmit_message_with_text(struct sip_pvt *p, const char *text);
02294 static int transmit_refer(struct sip_pvt *p, const char *dest);
02295 static int transmit_notify_with_mwi(struct sip_pvt *p, int newmsgs, int oldmsgs, const char *vmexten);
02296 static int transmit_notify_with_sipfrag(struct sip_pvt *p, int cseq, char *message, int terminate);
02297 static int transmit_notify_custom(struct sip_pvt *p, struct ast_variable *vars);
02298 static int transmit_register(struct sip_registry *r, int sipmethod, const char *auth, const char *authheader);
02299 static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno);
02300 static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno);
02301 static void copy_request(struct sip_request *dst, const struct sip_request *src);
02302 static void receive_message(struct sip_pvt *p, struct sip_request *req);
02303 static void parse_moved_contact(struct sip_pvt *p, struct sip_request *req);
02304 static int sip_send_mwi_to_peer(struct sip_peer *peer, const struct ast_event *event, int cache_only);
02305 
02306 /*--- Dialog management */
02307 static struct sip_pvt *sip_alloc(ast_string_field callid, struct sockaddr_in *sin,
02308              int useglobal_nat, const int intended_method, struct sip_request *req);
02309 static int __sip_autodestruct(const void *data);
02310 static void sip_scheddestroy(struct sip_pvt *p, int ms);
02311 static int sip_cancel_destroy(struct sip_pvt *p);
02312 static struct sip_pvt *sip_destroy(struct sip_pvt *p);
02313 static void *dialog_unlink_all(struct sip_pvt *dialog, int lockowner, int lockdialoglist);
02314 static void *registry_unref(struct sip_registry *reg, char *tag);
02315 static void __sip_destroy(struct sip_pvt *p, int lockowner, int lockdialoglist);
02316 static int __sip_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod);
02317 static void __sip_pretend_ack(struct sip_pvt *p);
02318 static int __sip_semi_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod);
02319 static int auto_congest(const void *arg);
02320 static int update_call_counter(struct sip_pvt *fup, int event);
02321 static int hangup_sip2cause(int cause);
02322 static const char *hangup_cause2sip(int cause);
02323 static struct sip_pvt *find_call(struct sip_request *req, struct sockaddr_in *sin, const int intended_method);
02324 static void free_old_route(struct sip_route *route);
02325 static void list_route(struct sip_route *route);
02326 static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards);
02327 static enum check_auth_result register_verify(struct sip_pvt *p, struct sockaddr_in *sin,
02328                      struct sip_request *req, char *uri);
02329 static struct sip_pvt *get_sip_pvt_byid_locked(const char *callid, const char *totag, const char *fromtag);
02330 static void check_pendings(struct sip_pvt *p);
02331 static void *sip_park_thread(void *stuff);
02332 static int sip_park(struct ast_channel *chan1, struct ast_channel *chan2, struct sip_request *req, int seqno);
02333 static int sip_sipredirect(struct sip_pvt *p, const char *dest);
02334 
02335 /*--- Codec handling / SDP */
02336 static void try_suggested_sip_codec(struct sip_pvt *p);
02337 static const char *get_sdp_iterate(int* start, struct sip_request *req, const char *name);
02338 static char get_sdp_line(int *start, int stop, struct sip_request *req, const char **value);
02339 static int find_sdp(struct sip_request *req);
02340 static int process_sdp(struct sip_pvt *p, struct sip_request *req, int t38action);
02341 static int process_sdp_o(const char *o, struct sip_pvt *p);
02342 static int process_sdp_c(const char *c, struct ast_hostent *hp);
02343 static int process_sdp_a_sendonly(const char *a, int *sendonly);
02344 static int process_sdp_a_audio(const char *a, struct sip_pvt *p, struct ast_rtp *newaudiortp, int *last_rtpmap_codec);
02345 static int process_sdp_a_video(const char *a, struct sip_pvt *p, struct ast_rtp *newvideortp, int *last_rtpmap_codec);
02346 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);
02347 static int process_sdp_a_image(const char *a, struct sip_pvt *p);
02348 static void add_codec_to_sdp(const struct sip_pvt *p, int codec,
02349               struct ast_str **m_buf, struct ast_str **a_buf,
02350               int debug, int *min_packet_size);
02351 static void add_noncodec_to_sdp(const struct sip_pvt *p, int format,
02352             struct ast_str **m_buf, struct ast_str **a_buf,
02353             int debug);
02354 static enum sip_result add_sdp(struct sip_request *resp, struct sip_pvt *p, int oldsdp, int add_audio, int add_t38);
02355 static void do_setnat(struct sip_pvt *p, int natflags);
02356 static void stop_media_flows(struct sip_pvt *p);
02357 
02358 /*--- Authentication stuff */
02359 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod, char *digest, int digest_len);
02360 static int build_reply_digest(struct sip_pvt *p, int method, char *digest, int digest_len);
02361 static enum check_auth_result check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
02362                 const char *secret, const char *md5secret, int sipmethod,
02363                 char *uri, enum xmittype reliable, int ignore);
02364 static enum check_auth_result check_user_full(struct sip_pvt *p, struct sip_request *req,
02365                      int sipmethod, char *uri, enum xmittype reliable,
02366                      struct sockaddr_in *sin, struct sip_peer **authpeer);
02367 static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, char *uri, enum xmittype reliable, struct sockaddr_in *sin);
02368 
02369 /*--- Domain handling */
02370 static int check_sip_domain(const char *domain, char *context, size_t len); /* Check if domain is one of our local domains */
02371 static int add_sip_domain(const char *domain, const enum domain_mode mode, const char *context);
02372 static void clear_sip_domains(void);
02373 
02374 /*--- SIP realm authentication */
02375 static struct sip_auth *add_realm_authentication(struct sip_auth *authlist, const char *configuration, int lineno);
02376 static int clear_realm_authentication(struct sip_auth *authlist); /* Clear realm authentication list (at reload) */
02377 static struct sip_auth *find_realm_authentication(struct sip_auth *authlist, const char *realm);
02378 
02379 /*--- Misc functions */
02380 static void check_rtp_timeout(struct sip_pvt *dialog, time_t t);
02381 static int sip_do_reload(enum channelreloadreason reason);
02382 static int reload_config(enum channelreloadreason reason);
02383 static int expire_register(const void *data);
02384 static void *do_monitor(void *data);
02385 static int restart_monitor(void);
02386 static void peer_mailboxes_to_str(struct ast_str **mailbox_str, struct sip_peer *peer);
02387 static struct ast_variable *copy_vars(struct ast_variable *src);
02388 /* static int sip_addrcmp(char *name, struct sockaddr_in *sin);   Support for peer matching */
02389 static int sip_refer_allocate(struct sip_pvt *p);
02390 static void ast_quiet_chan(struct ast_channel *chan);
02391 static int attempt_transfer(struct sip_dual *transferer, struct sip_dual *target);
02392 static int do_magic_pickup(struct ast_channel *channel, const char *extension, const char *context);
02393 
02394 /*!
02395  * \brief generic function for determining if a correct transport is being 
02396  * used to contact a peer
02397  *
02398  * this is done as a macro so that the "tmpl" var can be passed either a 
02399  * sip_request or a sip_peer 
02400  */
02401 #define check_request_transport(peer, tmpl) ({ \
02402    int ret = 0; \
02403    if (peer->socket.type == tmpl->socket.type) \
02404       ; \
02405    else if (!(peer->transports & tmpl->socket.type)) {\
02406       ast_log(LOG_ERROR, \
02407          "'%s' is not a valid transport for '%s'. we only use '%s'! ending call.\n", \
02408          get_transport(tmpl->socket.type), peer->name, get_transport_list(peer->transports) \
02409          ); \
02410       ret = 1; \
02411    } else if (peer->socket.type & SIP_TRANSPORT_TLS) { \
02412       ast_log(LOG_WARNING, \
02413          "peer '%s' HAS NOT USED (OR SWITCHED TO) TLS in favor of '%s' (but this was allowed in sip.conf)!\n", \
02414          peer->name, get_transport(tmpl->socket.type) \
02415       ); \
02416    } else { \
02417       ast_debug(1, \
02418          "peer '%s' has contacted us over %s even though we prefer %s.\n", \
02419          peer->name, get_transport(tmpl->socket.type), get_transport(peer->socket.type) \
02420       ); \
02421    }\
02422    (ret); \
02423 })
02424 
02425 
02426 /*--- Device monitoring and Device/extension state/event handling */
02427 static int cb_extensionstate(char *context, char* exten, int state, void *data);
02428 static int sip_devicestate(void *data);
02429 static int sip_poke_noanswer(const void *data);
02430 static int sip_poke_peer(struct sip_peer *peer, int force);
02431 static void sip_poke_all_peers(void);
02432 static void sip_peer_hold(struct sip_pvt *p, int hold);
02433 static void mwi_event_cb(const struct ast_event *, void *);
02434 
02435 /*--- Applications, functions, CLI and manager command helpers */
02436 static const char *sip_nat_mode(const struct sip_pvt *p);
02437 static char *sip_show_inuse(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02438 static char *transfermode2str(enum transfermodes mode) attribute_const;
02439 static const char *nat2str(int nat) attribute_const;
02440 static int peer_status(struct sip_peer *peer, char *status, int statuslen);
02441 static char *sip_show_sched(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02442 static char * _sip_show_peers(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char *argv[]);
02443 static char *sip_show_peers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02444 static char *sip_show_objects(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02445 static void  print_group(int fd, ast_group_t group, int crlf);
02446 static const char *dtmfmode2str(int mode) attribute_const;
02447 static int str2dtmfmode(const char *str) attribute_unused;
02448 static const char *insecure2str(int mode) attribute_const;
02449 static void cleanup_stale_contexts(char *new, char *old);
02450 static void print_codec_to_cli(int fd, struct ast_codec_pref *pref);
02451 static const char *domain_mode_to_text(const enum domain_mode mode);
02452 static char *sip_show_domains(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02453 static char *_sip_show_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[]);
02454 static char *sip_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02455 static char *_sip_qualify_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[]);
02456 static char *sip_qualify_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02457 static char *sip_show_registry(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02458 static char *sip_unregister(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02459 static char *sip_show_settings(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02460 static char *sip_show_mwi(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02461 static const char *subscription_type2str(enum subscriptiontype subtype) attribute_pure;
02462 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
02463 static char *complete_sip_peer(const char *word, int state, int flags2);
02464 static char *complete_sip_registered_peer(const char *word, int state, int flags2);
02465 static char *complete_sip_show_history(const char *line, const char *word, int pos, int state);
02466 static char *complete_sip_show_peer(const char *line, const char *word, int pos, int state);
02467 static char *complete_sip_unregister(const char *line, const char *word, int pos, int state);
02468 static char *complete_sipnotify(const char *line, const char *word, int pos, int state);
02469 static char *sip_show_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02470 static char *sip_show_channelstats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02471 static char *sip_show_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02472 static char *sip_do_debug_ip(int fd, char *arg);
02473 static char *sip_do_debug_peer(int fd, char *arg);
02474 static char *sip_do_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02475 static char *sip_cli_notify(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02476 static char *sip_set_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02477 static int sip_dtmfmode(struct ast_channel *chan, void *data);
02478 static int sip_addheader(struct ast_channel *chan, void *data);
02479 static int sip_do_reload(enum channelreloadreason reason);
02480 static char *sip_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02481 static int acf_channel_read(struct ast_channel *chan, const char *funcname, char *preparse, char *buf, size_t buflen);
02482 
02483 /*--- Debugging 
02484    Functions for enabling debug per IP or fully, or enabling history logging for
02485    a SIP dialog
02486 */
02487 static void sip_dump_history(struct sip_pvt *dialog); /* Dump history to debuglog at end of dialog, before destroying data */
02488 static inline int sip_debug_test_addr(const struct sockaddr_in *addr);
02489 static inline int sip_debug_test_pvt(struct sip_pvt *p);
02490 
02491 
02492 /*! \brief Append to SIP dialog history 
02493    \return Always returns 0 */
02494 #define append_history(p, event, fmt , args... )   append_history_full(p, "%-15s " fmt, event, ## args)
02495 static void append_history_full(struct sip_pvt *p, const char *fmt, ...);
02496 static void sip_dump_history(struct sip_pvt *dialog);
02497 
02498 /*--- Device object handling */
02499 static struct sip_peer *temp_peer(const char *name);
02500 static struct sip_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime, int devstate_only);
02501 static int update_call_counter(struct sip_pvt *fup, int event);
02502 static void sip_destroy_peer(struct sip_peer *peer);
02503 static void sip_destroy_peer_fn(void *peer);
02504 static void set_peer_defaults(struct sip_peer *peer);
02505 static struct sip_peer *temp_peer(const char *name);
02506 static void register_peer_exten(struct sip_peer *peer, int onoff);
02507 static struct sip_peer *find_peer(const char *peer, struct sockaddr_in *sin, int realtime, int forcenamematch, int devstate_only, int transport);
02508 static int sip_poke_peer_s(const void *data);
02509 static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *p, struct sip_request *req);
02510 static void reg_source_db(struct sip_peer *peer);
02511 static void destroy_association(struct sip_peer *peer);
02512 static void set_insecure_flags(struct ast_flags *flags, const char *value, int lineno);
02513 static int handle_common_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v);
02514 static void set_socket_transport(struct sip_socket *socket, int transport);
02515 
02516 /* Realtime device support */
02517 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);
02518 static void update_peer(struct sip_peer *p, int expire);
02519 static struct ast_variable *get_insecure_variable_from_config(struct ast_config *config);
02520 static const char *get_name_from_variable(struct ast_variable *var, const char *newpeername);
02521 static struct sip_peer *realtime_peer(const char *peername, struct sockaddr_in *sin, int devstate_only);
02522 static char *sip_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02523 
02524 /*--- Internal UA client handling (outbound registrations) */
02525 static void ast_sip_ouraddrfor(struct in_addr *them, struct sockaddr_in *us, struct sip_pvt *p);
02526 static void sip_registry_destroy(struct sip_registry *reg);
02527 static int sip_register(const char *value, int lineno);
02528 static const char *regstate2str(enum sipregistrystate regstate) attribute_const;
02529 static int sip_reregister(const void *data);
02530 static int __sip_do_register(struct sip_registry *r);
02531 static int sip_reg_timeout(const void *data);
02532 static void sip_send_all_registers(void);
02533 static int sip_reinvite_retry(const void *data);
02534 
02535 /*--- Parsing SIP requests and responses */
02536 static void append_date(struct sip_request *req);  /* Append date to SIP packet */
02537 static int determine_firstline_parts(struct sip_request *req);
02538 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
02539 static const char *gettag(const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize);
02540 static int find_sip_method(const char *msg);
02541 static unsigned int parse_sip_options(struct sip_pvt *pvt, const char *supported);
02542 static int parse_request(struct sip_request *req);
02543 static const char *get_header(const struct sip_request *req, const char *name);
02544 static const char *referstatus2str(enum referstatus rstatus) attribute_pure;
02545 static int method_match(enum sipmethod id, const char *name);
02546 static void parse_copy(struct sip_request *dst, const struct sip_request *src);
02547 static char *get_in_brackets(char *tmp);
02548 static const char *find_alias(const char *name, const char *_default);
02549 static const char *__get_header(const struct sip_request *req, const char *name, int *start);
02550 static int lws2sws(char *msgbuf, int len);
02551 static void extract_uri(struct sip_pvt *p, struct sip_request *req);
02552 static char *remove_uri_parameters(char *uri);
02553 static int get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req);
02554 static int get_also_info(struct sip_pvt *p, struct sip_request *oreq);
02555 static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req);
02556 static int set_address_from_contact(struct sip_pvt *pvt);
02557 static void check_via(struct sip_pvt *p, struct sip_request *req);
02558 static char *get_calleridname(const char *input, char *output, size_t outputsize);
02559 static int get_rpid_num(const char *input, char *output, int maxlen);
02560 static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq);
02561 static int get_destination(struct sip_pvt *p, struct sip_request *oreq);
02562 static int get_msg_text(char *buf, int len, struct sip_request *req, int addnewline);
02563 static int transmit_state_notify(struct sip_pvt *p, int state, int full, int timeout);
02564 
02565 /*-- TCP connection handling ---*/
02566 static void *_sip_tcp_helper_thread(struct sip_pvt *pvt, struct ast_tcptls_session_instance *tcptls_session);
02567 static void *sip_tcp_worker_fn(void *);
02568 
02569 /*--- Constructing requests and responses */
02570 static void initialize_initreq(struct sip_pvt *p, struct sip_request *req);
02571 static int init_req(struct sip_request *req, int sipmethod, const char *recip);
02572 static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, int seqno, int newbranch);
02573 static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod);
02574 static int init_resp(struct sip_request *resp, const char *msg);
02575 static inline int resp_needs_contact(const char *msg, enum sipmethod method);
02576 static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req);
02577 static const struct sockaddr_in *sip_real_dst(const struct sip_pvt *p);
02578 static void build_via(struct sip_pvt *p);
02579 static int create_addr_from_peer(struct sip_pvt *r, struct sip_peer *peer);
02580 static int create_addr(struct sip_pvt *dialog, const char *opeer, struct sockaddr_in *sin, int newdialog);
02581 static char *generate_random_string(char *buf, size_t size);
02582 static void build_callid_pvt(struct sip_pvt *pvt);
02583 static void build_callid_registry(struct sip_registry *reg, struct in_addr ourip, const char *fromdomain);
02584 static void make_our_tag(char *tagbuf, size_t len);
02585 static int add_header(struct sip_request *req, const char *var, const char *value);
02586 static int add_header_contentLength(struct sip_request *req, int len);
02587 static int add_line(struct sip_request *req, const char *line);
02588 static int add_text(struct sip_request *req, const char *text);
02589 static int add_digit(struct sip_request *req, char digit, unsigned int duration, int mode);
02590 static int add_vidupdate(struct sip_request *req);
02591 static void add_route(struct sip_request *req, struct sip_route *route);
02592 static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field);
02593 static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field);
02594 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field);
02595 static void set_destination(struct sip_pvt *p, char *uri);
02596 static void append_date(struct sip_request *req);
02597 static void build_contact(struct sip_pvt *p);
02598 static void build_rpid(struct sip_pvt *p);
02599 
02600 /*------Request handling functions */
02601 static int handle_incoming(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int *recount, int *nounlock);
02602 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);
02603 static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, int *nounlock);
02604 static int handle_request_bye(struct sip_pvt *p, struct sip_request *req);
02605 static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, char *e);
02606 static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req);
02607 static int handle_request_message(struct sip_pvt *p, struct sip_request *req);
02608 static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e);
02609 static void handle_request_info(struct sip_pvt *p, struct sip_request *req);
02610 static int handle_request_options(struct sip_pvt *p, struct sip_request *req);
02611 static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, struct sockaddr_in *sin, int *nounlock);
02612 static int handle_request_notify(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e);
02613 static int local_attended_transfer(struct sip_pvt *transferer, struct sip_dual *current, struct sip_request *req, int seqno);
02614 
02615 /*------Response handling functions */
02616 static void handle_response_invite(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
02617 static void handle_response_notify(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
02618 static void handle_response_refer(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
02619 static void handle_response_subscribe(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
02620 static int handle_response_register(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
02621 static void handle_response(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
02622 
02623 /*----- RTP interface functions */
02624 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);
02625 static enum ast_rtp_get_result sip_get_rtp_peer(struct ast_channel *chan, struct ast_rtp **rtp);
02626 static enum ast_rtp_get_result sip_get_vrtp_peer(struct ast_channel *chan, struct ast_rtp **rtp);
02627 static enum ast_rtp_get_result sip_get_trtp_peer(struct ast_channel *chan, struct ast_rtp **rtp);
02628 static int sip_get_codec(struct ast_channel *chan);
02629 static struct ast_frame *sip_rtp_read(struct ast_channel *ast, struct sip_pvt *p, int *faxdetect);
02630 
02631 /*------ T38 Support --------- */
02632 static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans);
02633 static struct ast_udptl *sip_get_udptl_peer(struct ast_channel *chan);
02634 static int sip_set_udptl_peer(struct ast_channel *chan, struct ast_udptl *udptl);
02635 static void change_t38_state(struct sip_pvt *p, int state);
02636 
02637 /*------ Session-Timers functions --------- */
02638 static void proc_422_rsp(struct sip_pvt *p, struct sip_request *rsp);
02639 static int  proc_session_timer(const void *vp);
02640 static void stop_session_timer(struct sip_pvt *p);
02641 static void start_session_timer(struct sip_pvt *p);
02642 static void restart_session_timer(struct sip_pvt *p);
02643 static const char *strefresher2str(enum st_refresher r);
02644 static int parse_session_expires(const char *p_hdrval, int *const p_interval, enum st_refresher *const p_ref);
02645 static int parse_minse(const char *p_hdrval, int *const p_interval);
02646 static int st_get_se(struct sip_pvt *, int max);
02647 static enum st_refresher st_get_refresher(struct sip_pvt *);
02648 static enum st_mode st_get_mode(struct sip_pvt *);
02649 static struct sip_st_dlg* sip_st_alloc(struct sip_pvt *const p);
02650 
02651 /*!--- SIP MWI Subscription support */
02652 static int sip_subscribe_mwi(const char *value, int lineno);
02653 static void sip_subscribe_mwi_destroy(struct sip_subscription_mwi *mwi);
02654 static void sip_send_all_mwi_subscriptions(void);
02655 static int sip_subscribe_mwi_do(const void *data);
02656 static int __sip_subscribe_mwi_do(struct sip_subscription_mwi *mwi);
02657 
02658 /*! \brief Definition of this channel for PBX channel registration */
02659 static const struct ast_channel_tech sip_tech = {
02660    .type = "SIP",
02661    .description = "Session Initiation Protocol (SIP)",
02662    .capabilities = AST_FORMAT_AUDIO_MASK, /* all audio formats */
02663    .properties = AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER,
02664    .requester = sip_request_call,         /* called with chan unlocked */
02665    .devicestate = sip_devicestate,        /* called with chan unlocked (not chan-specific) */
02666    .call = sip_call,       /* called with chan locked */
02667    .send_html = sip_sendhtml,
02668    .hangup = sip_hangup,         /* called with chan locked */
02669    .answer = sip_answer,         /* called with chan locked */
02670    .read = sip_read,       /* called with chan locked */
02671    .write = sip_write,        /* called with chan locked */
02672    .write_video = sip_write,     /* called with chan locked */
02673    .write_text = sip_write,
02674    .indicate = sip_indicate,     /* called with chan locked */
02675    .transfer = sip_transfer,     /* called with chan locked */
02676    .fixup = sip_fixup,        /* called with chan locked */
02677    .send_digit_begin = sip_senddigit_begin,  /* called with chan unlocked */
02678    .send_digit_end = sip_senddigit_end,
02679    .bridge = ast_rtp_bridge,        /* XXX chan unlocked ? */
02680    .early_bridge = ast_rtp_early_bridge,
02681    .send_text = sip_sendtext,    /* called with chan locked */
02682    .func_channel_read = acf_channel_read,
02683    .queryoption = sip_queryoption,
02684    .get_pvt_uniqueid = sip_get_callid,
02685 };
02686 
02687 /*! \brief This version of the sip channel tech has no send_digit_begin
02688  * callback so that the core knows that the channel does not want
02689  * DTMF BEGIN frames.
02690  * The struct is initialized just before registering the channel driver,
02691  * and is for use with channels using SIP INFO DTMF.
02692  */
02693 static struct ast_channel_tech sip_tech_info;
02694 
02695 
02696 /*! \brief Working TLS connection configuration */
02697 static struct ast_tls_config sip_tls_cfg;
02698 
02699 /*! \brief Default TLS connection configuration */
02700 static struct ast_tls_config default_tls_cfg;
02701 
02702 /*! \brief The TCP server definition */
02703 static struct ast_tcptls_session_args sip_tcp_desc = {
02704    .accept_fd = -1,
02705    .master = AST_PTHREADT_NULL,
02706    .tls_cfg = NULL,
02707    .poll_timeout = -1,
02708    .name = "SIP TCP server",
02709    .accept_fn = ast_tcptls_server_root,
02710    .worker_fn = sip_tcp_worker_fn,
02711 };
02712 
02713 /*! \brief The TCP/TLS server definition */
02714 static struct ast_tcptls_session_args sip_tls_desc = {
02715    .accept_fd = -1,
02716    .master = AST_PTHREADT_NULL,
02717    .tls_cfg = &sip_tls_cfg,
02718    .poll_timeout = -1,
02719    .name = "SIP TLS server",
02720    .accept_fn = ast_tcptls_server_root,
02721    .worker_fn = sip_tcp_worker_fn,
02722 };
02723 
02724 /* wrapper macro to tell whether t points to one of the sip_tech descriptors */
02725 #define IS_SIP_TECH(t)  ((t) == &sip_tech || (t) == &sip_tech_info)
02726 
02727 /*! \brief map from an integer value to a string.
02728  * If no match is found, return errorstring
02729  */
02730 static const char *map_x_s(const struct _map_x_s *table, int x, const char *errorstring)
02731 {
02732    const struct _map_x_s *cur;
02733 
02734    for (cur = table; cur->s; cur++)
02735       if (cur->x == x)
02736          return cur->s;
02737    return errorstring;
02738 }
02739 
02740 /*! \brief map from a string to an integer value, case insensitive.
02741  * If no match is found, return errorvalue.
02742  */
02743 static int map_s_x(const struct _map_x_s *table, const char *s, int errorvalue)
02744 {
02745    const struct _map_x_s *cur;
02746 
02747    for (cur = table; cur->s; cur++)
02748       if (!strcasecmp(cur->s, s))
02749          return cur->x;
02750    return errorvalue;
02751 }
02752 
02753 
02754 /*! \brief Interface structure with callbacks used to connect to RTP module */
02755 static struct ast_rtp_protocol sip_rtp = {
02756    .type = "SIP",
02757    .get_rtp_info = sip_get_rtp_peer,
02758    .get_vrtp_info = sip_get_vrtp_peer,
02759    .get_trtp_info = sip_get_trtp_peer,
02760    .set_rtp_peer = sip_set_rtp_peer,
02761    .get_codec = sip_get_codec,
02762 };
02763 
02764 /*!
02765  * duplicate a list of channel variables, \return the copy.
02766  */
02767 static struct ast_variable *copy_vars(struct ast_variable *src)
02768 {
02769    struct ast_variable *res = NULL, *tmp, *v = NULL;
02770 
02771    for (v = src ; v ; v = v->next) {
02772       if ((tmp = ast_variable_new(v->name, v->value, v->file))) {
02773          tmp->next = res;
02774          res = tmp;
02775       }
02776    }
02777    return res;
02778 }
02779 
02780 static void tcptls_packet_destructor(void *obj)
02781 {
02782    struct tcptls_packet *packet = obj;
02783 
02784    ast_free(packet->data);
02785 }
02786 
02787 static void sip_tcptls_client_args_destructor(void *obj)
02788 {
02789    struct ast_tcptls_session_args *args = obj;
02790    if (args->tls_cfg) {
02791       ast_free(args->tls_cfg->certfile);
02792       ast_free(args->tls_cfg->cipher);
02793       ast_free(args->tls_cfg->cafile);
02794       ast_free(args->tls_cfg->capath);
02795    }
02796    ast_free(args->tls_cfg);
02797    ast_free((char *) args->name);
02798 }
02799 
02800 static void sip_threadinfo_destructor(void *obj)
02801 {
02802    struct sip_threadinfo *th = obj;
02803    struct tcptls_packet *packet;
02804    if (th->alert_pipe[1] > -1) {
02805       close(th->alert_pipe[0]);
02806    }
02807    if (th->alert_pipe[1] > -1) {
02808       close(th->alert_pipe[1]);
02809    }
02810    th->alert_pipe[0] = th->alert_pipe[1] = -1;
02811 
02812    while ((packet = AST_LIST_REMOVE_HEAD(&th->packet_q, entry))) {
02813       ao2_t_ref(packet, -1, "thread destruction, removing packet from frame queue");
02814    }
02815 
02816    if (th->tcptls_session) {
02817       ao2_t_ref(th->tcptls_session, -1, "remove tcptls_session for sip_threadinfo object");
02818    }
02819 }
02820 
02821 /*! \brief creates a sip_threadinfo object and links it into the threadt table. */
02822 static struct sip_threadinfo *sip_threadinfo_create(struct ast_tcptls_session_instance *tcptls_session, int transport)
02823 {
02824    struct sip_threadinfo *th;
02825 
02826    if (!tcptls_session || !(th = ao2_alloc(sizeof(*th), sip_threadinfo_destructor))) {
02827       return NULL;
02828    }
02829 
02830    th->alert_pipe[0] = th->alert_pipe[1] = -1;
02831 
02832    if (pipe(th->alert_pipe) == -1) {
02833       ao2_t_ref(th, -1, "Failed to open alert pipe on sip_threadinfo");
02834       ast_log(LOG_ERROR, "Could not create sip alert pipe in tcptls thread, error %s\n", strerror(errno));
02835       return NULL;
02836    }
02837    ao2_t_ref(tcptls_session, +1, "tcptls_session ref for sip_threadinfo object");
02838    th->tcptls_session = tcptls_session;
02839    th->type = transport ? transport : (tcptls_session->ssl ? SIP_TRANSPORT_TLS: SIP_TRANSPORT_TCP);
02840    ao2_t_link(threadt, th, "Adding new tcptls helper thread");
02841    ao2_t_ref(th, -1, "Decrementing threadinfo ref from alloc, only table ref remains");
02842    return th;
02843 }
02844 
02845 /*! \brief used to indicate to a tcptls thread that data is ready to be written */
02846 static int sip_tcptls_write(struct ast_tcptls_session_instance *tcptls_session, const void *buf, size_t len)
02847 {
02848    int res = len;
02849    struct sip_threadinfo *th = NULL;
02850    struct tcptls_packet *packet = NULL;
02851    struct sip_threadinfo tmp = {
02852       .tcptls_session = tcptls_session,
02853    };
02854    enum sip_tcptls_alert alert = TCPTLS_ALERT_DATA;
02855 
02856    if (!tcptls_session) {
02857       return XMIT_ERROR;
02858    }
02859 
02860    ast_mutex_lock(&tcptls_session->lock);
02861 
02862    if ((tcptls_session->fd == -1) ||
02863       !(th = ao2_t_find(threadt, &tmp, OBJ_POINTER, "ao2_find, getting sip_threadinfo in tcp helper thread")) ||
02864       !(packet = ao2_alloc(sizeof(*packet), tcptls_packet_destructor)) ||
02865       !(packet->data = ast_str_create(len))) {
02866       goto tcptls_write_setup_error;
02867    }
02868 
02869    /* goto tcptls_write_error should _NOT_ be used beyond this point */
02870    ast_str_set(&packet->data, 0, "%s", (char *) buf);
02871    packet->len = len;
02872 
02873    /* alert tcptls thread handler that there is a packet to be sent.
02874     * must lock the thread info object to guarantee control of the
02875     * packet queue */
02876    ao2_lock(th);
02877    if (write(th->alert_pipe[1], &alert, sizeof(alert)) == -1) {
02878       ast_log(LOG_ERROR, "write() to alert pipe failed: %s\n", strerror(errno));
02879       ao2_t_ref(packet, -1, "could not write to alert pipe, remove packet");
02880       packet = NULL;
02881       res = XMIT_ERROR;
02882    } else { /* it is safe to queue the frame after issuing the alert when we hold the threadinfo lock */
02883       AST_LIST_INSERT_TAIL(&th->packet_q, packet, entry);
02884    }
02885    ao2_unlock(th);
02886 
02887    ast_mutex_unlock(&tcptls_session->lock);
02888    ao2_t_ref(th, -1, "In sip_tcptls_write, unref threadinfo object after finding it");
02889    return res;
02890 
02891 tcptls_write_setup_error:
02892    if (th) {
02893       ao2_t_ref(th, -1, "In sip_tcptls_write, unref threadinfo obj, could not create packet");
02894    }
02895    if (packet) {
02896       ao2_t_ref(packet, -1, "could not allocate packet's data");
02897    }
02898    ast_mutex_unlock(&tcptls_session->lock);
02899 
02900    return XMIT_ERROR;
02901 }
02902 
02903 /*! \brief SIP TCP connection handler */
02904 static void *sip_tcp_worker_fn(void *data)
02905 {
02906    struct ast_tcptls_session_instance *tcptls_session = data;
02907 
02908    return _sip_tcp_helper_thread(NULL, tcptls_session);
02909 }
02910 
02911 /*! \brief SIP TCP thread management function 
02912    This function reads from the socket, parses the packet into a request
02913 */
02914 static void *_sip_tcp_helper_thread(struct sip_pvt *pvt, struct ast_tcptls_session_instance *tcptls_session) 
02915 {
02916    int res, cl;
02917    struct sip_request req = { 0, } , reqcpy = { 0, };
02918    struct sip_threadinfo *me = NULL;
02919    char buf[1024] = "";
02920    struct pollfd fds[2] = { { 0 }, { 0 }, };
02921    struct ast_tcptls_session_args *ca = NULL;
02922 
02923    /* If this is a server session, then the connection has already been setup,
02924     * simply create the threadinfo object so we can access this thread for writing.
02925     * 
02926     * if this is a client connection more work must be done.
02927     * 1. We own the parent session args for a client connection.  This pointer needs
02928     *    to be held on to so we can decrement it's ref count on thread destruction.
02929     * 2. The threadinfo object was created before this thread was launched, however
02930     *    it must be found within the threadt table.
02931     * 3. Last, the tcptls_session must be started.
02932     */
02933    if (!tcptls_session->client) {
02934       if (!(me = sip_threadinfo_create(tcptls_session, tcptls_session->ssl ? SIP_TRANSPORT_TLS : SIP_TRANSPORT_TCP))) {
02935          goto cleanup;
02936       }
02937       ao2_t_ref(me, +1, "Adding threadinfo ref for tcp_helper_thread");
02938    } else {
02939       struct sip_threadinfo tmp = {
02940          .tcptls_session = tcptls_session,
02941       };
02942 
02943       if ((!(ca = tcptls_session->parent)) ||
02944          (!(me = ao2_t_find(threadt, &tmp, OBJ_POINTER, "ao2_find, getting sip_threadinfo in tcp helper thread"))) ||
02945          (!(tcptls_session = ast_tcptls_client_start(tcptls_session)))) {
02946          goto cleanup;
02947       }
02948    }
02949 
02950    me->threadid = pthread_self();
02951    ast_debug(2, "Starting thread for %s server\n", tcptls_session->ssl ? "SSL" : "TCP");
02952 
02953    /* set up pollfd to watch for reads on both the socket and the alert_pipe */
02954    fds[0].fd = tcptls_session->fd;
02955    fds[1].fd = me->alert_pipe[0];
02956    fds[0].events = fds[1].events = POLLIN | POLLPRI;
02957 
02958    if (!(req.data = ast_str_create(SIP_MIN_PACKET)))
02959       goto cleanup;
02960    if (!(reqcpy.data = ast_str_create(SIP_MIN_PACKET)))
02961       goto cleanup;
02962 
02963    for (;;) {
02964       struct ast_str *str_save;
02965 
02966       res = ast_poll(fds, 2, -1); /* polls for both socket and alert_pipe */
02967 
02968       if (res < 0) {
02969          ast_debug(2, "SIP %s server :: ast_wait_for_input returned %d\n", tcptls_session->ssl ? "SSL": "TCP", res);
02970          goto cleanup;
02971       }
02972 
02973       /* handle the socket event, check for both reads from the socket fd,
02974        * and writes from alert_pipe fd */
02975       if (fds[0].revents) { /* there is data on the socket to be read */
02976 
02977          fds[0].revents = 0;
02978 
02979          /* clear request structure */
02980          str_save = req.data;
02981          memset(&req, 0, sizeof(req));
02982          req.data = str_save;
02983          ast_str_reset(req.data);
02984 
02985          str_save = reqcpy.data;
02986          memset(&reqcpy, 0, sizeof(reqcpy));
02987          reqcpy.data = str_save;
02988          ast_str_reset(reqcpy.data);
02989 
02990          memset(buf, 0, sizeof(buf));
02991 
02992          if (tcptls_session->ssl) {
02993             set_socket_transport(&req.socket, SIP_TRANSPORT_TLS);
02994             req.socket.port = htons(ourport_tls);
02995          } else {
02996             set_socket_transport(&req.socket, SIP_TRANSPORT_TCP);
02997             req.socket.port = htons(ourport_tcp);
02998          }
02999          req.socket.fd = tcptls_session->fd;
03000 
03001          /* Read in headers one line at a time */
03002          while (req.len < 4 || strncmp(REQ_OFFSET_TO_STR(&req, len - 4), "\r\n\r\n", 4)) {
03003             ast_mutex_lock(&tcptls_session->lock);
03004             if (!fgets(buf, sizeof(buf), tcptls_session->f)) {
03005                ast_mutex_unlock(&tcptls_session->lock);
03006                goto cleanup;
03007             }
03008             ast_mutex_unlock(&tcptls_session->lock);
03009             if (me->stop)
03010                 goto cleanup;
03011             ast_str_append(&req.data, 0, "%s", buf);
03012             req.len = req.data->used;
03013          }
03014          copy_request(&reqcpy, &req);
03015          parse_request(&reqcpy);
03016          /* In order to know how much to read, we need the content-length header */
03017          if (sscanf(get_header(&reqcpy, "Content-Length"), "%30d", &cl)) {
03018             while (cl > 0) {
03019                size_t bytes_read;
03020                ast_mutex_lock(&tcptls_session->lock);
03021                if (!(bytes_read = fread(buf, 1, MIN(sizeof(buf) - 1, cl), tcptls_session->f))) {
03022                   ast_mutex_unlock(&tcptls_session->lock);
03023                   goto cleanup;
03024                }
03025                buf[bytes_read] = '\0';
03026                ast_mutex_unlock(&tcptls_session->lock);
03027                if (me->stop)
03028                   goto cleanup;
03029                cl -= strlen(buf);
03030                ast_str_append(&req.data, 0, "%s", buf);
03031                req.len = req.data->used;
03032             }
03033          }
03034          /*! \todo XXX If there's no Content-Length or if the content-length and what
03035                we receive is not the same - we should generate an error */
03036 
03037          req.socket.tcptls_session = tcptls_session;
03038          handle_request_do(&req, &tcptls_session->remote_address);
03039       }
03040 
03041       if (fds[1].revents) { /* alert_pipe indicates there is data in the send queue to be sent */
03042          enum sip_tcptls_alert alert;
03043          struct tcptls_packet *packet;
03044 
03045          fds[1].revents = 0;
03046 
03047          if (read(me->alert_pipe[0], &alert, sizeof(alert)) == -1) {
03048             ast_log(LOG_ERROR, "read() failed: %s\n", strerror(errno));
03049             continue;
03050          }
03051 
03052          switch (alert) {
03053          case TCPTLS_ALERT_STOP:
03054             goto cleanup;
03055          case TCPTLS_ALERT_DATA:
03056             ao2_lock(me);
03057             if (!(packet = AST_LIST_REMOVE_HEAD(&me->packet_q, entry))) {
03058                ast_log(LOG_WARNING, "TCPTLS thread alert_pipe indicated packet should be sent, but frame_q is empty");
03059             } else if (ast_tcptls_server_write(tcptls_session, ast_str_buffer(packet->data), packet->len) == -1) {
03060                ast_log(LOG_WARNING, "Failure to write to tcp/tls socket\n");
03061             }
03062 
03063             if (packet) {
03064                ao2_t_ref(packet, -1, "tcptls packet sent, this is no longer needed");
03065             }
03066             ao2_unlock(me);
03067             break;
03068          default:
03069             ast_log(LOG_ERROR, "Unknown tcptls thread alert '%d'\n", alert);
03070          }
03071       }
03072    }
03073 
03074    ast_debug(2, "Shutting down thread for %s server\n", tcptls_session->ssl ? "SSL" : "TCP");
03075 
03076 cleanup:
03077    if (me) {
03078       ao2_t_unlink(threadt, me, "Removing tcptls helper thread, thread is closing");
03079       ao2_t_ref(me, -1, "Removing tcp_helper_threads threadinfo ref");
03080    }
03081    if (reqcpy.data) {
03082       ast_free(reqcpy.data);
03083    }
03084 
03085    if (req.data) {
03086       ast_free(req.data);
03087       req.data = NULL;
03088    }
03089 
03090    /* if client, we own the parent session arguments and must decrement ref */
03091    if (ca) {
03092       ao2_t_ref(ca, -1, "closing tcptls thread, getting rid of client tcptls_session arguments");
03093    }
03094 
03095    if (tcptls_session) {
03096       ast_mutex_lock(&tcptls_session->lock);
03097       if (tcptls_session->f) {
03098          fclose(tcptls_session->f);
03099          tcptls_session->f = NULL;
03100       }
03101       if (tcptls_session->fd != -1) {
03102          close(tcptls_session->fd);
03103          tcptls_session->fd = -1;
03104       }
03105       tcptls_session->parent = NULL;
03106       ast_mutex_unlock(&tcptls_session->lock);
03107 
03108       ao2_ref(tcptls_session, -1);
03109       tcptls_session = NULL;
03110    }
03111    return NULL;
03112 }
03113 
03114 
03115 /*!
03116  * helper functions to unreference various types of objects.
03117  * By handling them this way, we don't have to declare the
03118  * destructor on each call, which removes the chance of errors.
03119  */
03120 static void *unref_peer(struct sip_peer *peer, char *tag)
03121 {
03122    ao2_t_ref(peer, -1, tag);
03123    return NULL;
03124 }
03125 
03126 static struct sip_peer *ref_peer(struct sip_peer *peer, char *tag)
03127 {
03128    ao2_t_ref(peer, 1, tag);
03129    return peer;
03130 }
03131 
03132 /*! \brief maintain proper refcounts for a sip_pvt's outboundproxy
03133  *
03134  * This function sets pvt's outboundproxy pointer to the one referenced
03135  * by the proxy parameter. Because proxy may be a refcounted object, and
03136  * because pvt's old outboundproxy may also be a refcounted object, we need
03137  * to maintain the proper refcounts.
03138  *
03139  * \param pvt The sip_pvt for which we wish to set the outboundproxy
03140  * \param proxy The sip_proxy which we will point pvt towards.
03141  * \return Returns void
03142  */
03143 static void ref_proxy(struct sip_pvt *pvt, struct sip_proxy *proxy)
03144 {
03145    struct sip_proxy *old_obproxy = pvt->outboundproxy;
03146    /* The sip_cfg.outboundproxy is statically allocated, and so
03147     * we don't ever need to adjust refcounts for it
03148     */
03149    if (proxy && proxy != &sip_cfg.outboundproxy) {
03150       ao2_ref(proxy, +1);
03151    }
03152    pvt->outboundproxy = proxy;
03153    if (old_obproxy && old_obproxy != &sip_cfg.outboundproxy) {
03154       ao2_ref(old_obproxy, -1);
03155    }
03156 }
03157 
03158 /*!
03159  * \brief Unlink a dialog from the dialogs container, as well as any other places
03160  * that it may be currently stored.
03161  *
03162  * \note A reference to the dialog must be held before calling this function, and this
03163  * function does not release that reference.
03164  */
03165 static void *dialog_unlink_all(struct sip_pvt *dialog, int lockowner, int lockdialoglist)
03166 {
03167    struct sip_pkt *cp;
03168 
03169    dialog_ref(dialog, "Let's bump the count in the unlink so it doesn't accidentally become dead before we are done");
03170 
03171    ao2_t_unlink(dialogs, dialog, "unlinking dialog via ao2_unlink");
03172 
03173    /* Unlink us from the owner (channel) if we have one */
03174    if (dialog->owner) {
03175       if (lockowner)
03176          ast_channel_lock(dialog->owner);
03177       ast_debug(1, "Detaching from channel %s\n", dialog->owner->name);
03178       dialog->owner->tech_pvt = dialog_unref(dialog->owner->tech_pvt, "resetting channel dialog ptr in unlink_all");
03179       if (lockowner)
03180          ast_channel_unlock(dialog->owner);
03181    }
03182    if (dialog->registry) {
03183       if (dialog->registry->call == dialog)
03184          dialog->registry->call = dialog_unref(dialog->registry->call, "nulling out the registry's call dialog field in unlink_all");
03185       dialog->registry = registry_unref(dialog->registry, "delete dialog->registry");
03186    }
03187    if (dialog->stateid > -1) {
03188       ast_extension_state_del(dialog->stateid, NULL);
03189       dialog_unref(dialog, "removing extension_state, should unref the associated dialog ptr that was stored there.");
03190       dialog->stateid = -1; /* shouldn't we 'zero' this out? */
03191    }
03192    /* Remove link from peer to subscription of MWI */
03193    if (dialog->relatedpeer && dialog->relatedpeer->mwipvt == dialog)
03194       dialog->relatedpeer->mwipvt = dialog_unref(dialog->relatedpeer->mwipvt, "delete ->relatedpeer->mwipvt");
03195    if (dialog->relatedpeer && dialog->relatedpeer->call == dialog)
03196       dialog->relatedpeer->call = dialog_unref(dialog->relatedpeer->call, "unset the relatedpeer->call field in tandem with relatedpeer field itself");
03197 
03198    /* remove all current packets in this dialog */
03199    while((cp = dialog->packets)) {
03200       dialog->packets = dialog->packets->next;
03201       AST_SCHED_DEL(sched, cp->retransid);
03202       dialog_unref(cp->owner, "remove all current packets in this dialog, and the pointer to the dialog too as part of __sip_destroy");
03203       if (cp->data) {
03204          ast_free(cp->data);
03205       }
03206       ast_free(cp);
03207    }
03208 
03209    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"));
03210 
03211    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"));
03212    
03213    if (dialog->autokillid > -1)
03214       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"));
03215 
03216    if (dialog->request_queue_sched_id > -1) {
03217       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"));
03218    }
03219 
03220    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"));
03221 
03222    if (dialog->t38id > -1) {
03223       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"));
03224    }
03225 
03226    dialog_unref(dialog, "Let's unbump the count in the unlink so the poor pvt can disappear if it is time");
03227    return NULL;
03228 }
03229 
03230 static void *registry_unref(struct sip_registry *reg, char *tag)
03231 {
03232    ast_debug(3, "SIP Registry %s: refcount now %d\n", reg->hostname, reg->refcount - 1);
03233    ASTOBJ_UNREF(reg, sip_registry_destroy);
03234    return NULL;
03235 }
03236 
03237 /*! \brief Add object reference to SIP registry */
03238 static struct sip_registry *registry_addref(struct sip_registry *reg, char *tag)
03239 {
03240    ast_debug(3, "SIP Registry %s: refcount now %d\n", reg->hostname, reg->refcount + 1);
03241    return ASTOBJ_REF(reg); /* Add pointer to registry in packet */
03242 }
03243 
03244 /*! \brief Interface structure with callbacks used to connect to UDPTL module*/
03245 static struct ast_udptl_protocol sip_udptl = {
03246    type: "SIP",
03247    get_udptl_info: sip_get_udptl_peer,
03248    set_udptl_peer: sip_set_udptl_peer,
03249 };
03250 
03251 static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
03252    __attribute__((format(printf, 2, 3)));
03253 
03254 
03255 /*! \brief Convert transfer status to string */
03256 static const char *referstatus2str(enum referstatus rstatus)
03257 {
03258    return map_x_s(referstatusstrings, rstatus, "");
03259 }
03260 
03261 static inline void pvt_set_needdestroy(struct sip_pvt *pvt, const char *reason)
03262 {
03263    append_history(pvt, "NeedDestroy", "Setting needdestroy because %s", reason);
03264    pvt->needdestroy = 1;
03265 }
03266 
03267 /*! \brief Initialize the initital request packet in the pvt structure.
03268    This packet is used for creating replies and future requests in
03269    a dialog */
03270 static void initialize_initreq(struct sip_pvt *p, struct sip_request *req)
03271 {
03272    if (p->initreq.headers)
03273       ast_debug(1, "Initializing already initialized SIP dialog %s (presumably reinvite)\n", p->callid);
03274    else
03275       ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
03276    /* Use this as the basis */
03277    copy_request(&p->initreq, req);
03278    parse_request(&p->initreq);
03279    if (req->debug)
03280       ast_verbose("Initreq: %d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
03281 }
03282 
03283 /*! \brief Encapsulate setting of SIP_ALREADYGONE to be able to trace it with debugging */
03284 static void sip_alreadygone(struct sip_pvt *dialog)
03285 {
03286    ast_debug(3, "Setting SIP_ALREADYGONE on dialog %s\n", dialog->callid);
03287    dialog->alreadygone = 1;
03288 }
03289 
03290 /*! Resolve DNS srv name or host name in a sip_proxy structure */
03291 static int proxy_update(struct sip_proxy *proxy)
03292 {
03293    /* if it's actually an IP address and not a name,
03294            there's no need for a managed lookup */
03295    if (!inet_aton(proxy->name, &proxy->ip.sin_addr)) {
03296       /* Ok, not an IP address, then let's check if it's a domain or host */
03297       /* XXX Todo - if we have proxy port, don't do SRV */
03298       if (ast_get_ip_or_srv(&proxy->ip, proxy->name, sip_cfg.srvlookup ? "_sip._udp" : NULL) < 0) {
03299          ast_log(LOG_WARNING, "Unable to locate host '%s'\n", proxy->name);
03300          return FALSE;
03301       }
03302    }
03303    proxy->last_dnsupdate = time(NULL);
03304    return TRUE;
03305 }
03306 
03307 /*! \brief converts ascii port to int representation. If no
03308  *  pt buffer is provided or the pt has errors when being converted
03309  *  to an int value, the port provided as the standard is used.
03310  */
03311 static int port_str2int(const char *pt, unsigned int standard)
03312 {
03313    int port = standard;
03314    if (ast_strlen_zero(pt) || (sscanf(pt, "%30d", &port) != 1) || (port < 1) || (port > 65535)) {
03315       port = standard;
03316    }
03317 
03318    return port;
03319 }
03320 
03321 /*! \brief Allocate and initialize sip proxy */
03322 static struct sip_proxy *proxy_allocate(char *name, char *port, int force)
03323 {
03324    struct sip_proxy *proxy;
03325 
03326    if (ast_strlen_zero(name)) {
03327       return NULL;
03328    }
03329 
03330    proxy = ao2_alloc(sizeof(*proxy), NULL);
03331    if (!proxy)
03332       return NULL;
03333    proxy->force = force;
03334    ast_copy_string(proxy->name, name, sizeof(proxy->name));
03335    proxy->ip.sin_port = htons(port_str2int(port, STANDARD_SIP_PORT));
03336    proxy_update(proxy);
03337    return proxy;
03338 }
03339 
03340 /*! \brief Get default outbound proxy or global proxy */
03341 static struct sip_proxy *obproxy_get(struct sip_pvt *dialog, struct sip_peer *peer)
03342 {
03343    if (peer && peer->outboundproxy) {
03344       if (sipdebug)
03345          ast_debug(1, "OBPROXY: Applying peer OBproxy to this call\n");
03346       append_history(dialog, "OBproxy", "Using peer obproxy %s", peer->outboundproxy->name);
03347       return peer->outboundproxy;
03348    }
03349    if (sip_cfg.outboundproxy.name[0]) {
03350       if (sipdebug)
03351          ast_debug(1, "OBPROXY: Applying global OBproxy to this call\n");
03352       append_history(dialog, "OBproxy", "Using global obproxy %s", sip_cfg.outboundproxy.name);
03353       return &sip_cfg.outboundproxy;
03354    }
03355    if (sipdebug)
03356       ast_debug(1, "OBPROXY: Not applying OBproxy to this call\n");
03357    return NULL;
03358 }
03359 
03360 /*! \brief returns true if 'name' (with optional trailing whitespace)
03361  * matches the sip method 'id'.
03362  * Strictly speaking, SIP methods are case SENSITIVE, but we do
03363  * a case-insensitive comparison to be more tolerant.
03364  * following Jon Postel's rule: Be gentle in what you accept, strict with what you send
03365  */
03366 static int method_match(enum sipmethod id, const char *name)
03367 {
03368    int len = strlen(sip_methods[id].text);
03369    int l_name = name ? strlen(name) : 0;
03370    /* true if the string is long enough, and ends with whitespace, and matches */
03371    return (l_name >= len && name[len] < 33 &&
03372       !strncasecmp(sip_methods[id].text, name, len));
03373 }
03374 
03375 /*! \brief  find_sip_method: Find SIP method from header */
03376 static int find_sip_method(const char *msg)
03377 {
03378    int i, res = 0;
03379    
03380    if (ast_strlen_zero(msg))
03381       return 0;
03382    for (i = 1; i < ARRAY_LEN(sip_methods) && !res; i++) {
03383       if (method_match(i, msg))
03384          res = sip_methods[i].id;
03385    }
03386    return res;
03387 }
03388 
03389 /*! \brief Parse supported header in incoming packet */
03390 static unsigned int parse_sip_options(struct sip_pvt *pvt, const char *supported)
03391 {
03392    char *next, *sep;
03393    char *temp;
03394    unsigned int profile = 0;
03395    int i, found;
03396 
03397    if (ast_strlen_zero(supported) )
03398       return 0;
03399    temp = ast_strdupa(supported);
03400 
03401    if (sipdebug)
03402       ast_debug(3, "Begin: parsing SIP \"Supported: %s\"\n", supported);
03403 
03404    for (next = temp; next; next = sep) {
03405       found = FALSE;
03406       if ( (sep = strchr(next, ',')) != NULL)
03407          *sep++ = '\0';
03408       next = ast_skip_blanks(next);
03409       if (sipdebug)
03410          ast_debug(3, "Found SIP option: -%s-\n", next);
03411       for (i = 0; i < ARRAY_LEN(sip_options); i++) {
03412          if (!strcasecmp(next, sip_options[i].text)) {
03413             profile |= sip_options[i].id;
03414             found = TRUE;
03415             if (sipdebug)
03416                ast_debug(3, "Matched SIP option: %s\n", next);
03417             break;
03418          }
03419       }
03420 
03421       /* This function is used to parse both Suported: and Require: headers.
03422       Let the caller of this function know that an unknown option tag was 
03423       encountered, so that if the UAC requires it then the request can be 
03424       rejected with a 420 response. */
03425       if (!found)
03426          profile |= SIP_OPT_UNKNOWN;
03427 
03428       if (!found && sipdebug) {
03429          if (!strncasecmp(next, "x-", 2))
03430             ast_debug(3, "Found private SIP option, not supported: %s\n", next);
03431          else
03432             ast_debug(3, "Found no match for SIP option: %s (Please file bug report!)\n", next);
03433       }
03434    }
03435 
03436    if (pvt)
03437       pvt->sipoptions = profile;
03438    return profile;
03439 }
03440 
03441 /*! \brief See if we pass debug IP filter */
03442 static inline int sip_debug_test_addr(const struct sockaddr_in *addr) 
03443 {
03444    if (!sipdebug)
03445       return 0;
03446    if (debugaddr.sin_addr.s_addr) {
03447       if (((ntohs(debugaddr.sin_port) != 0)
03448          && (debugaddr.sin_port != addr->sin_port))
03449          || (debugaddr.sin_addr.s_addr != addr->sin_addr.s_addr))
03450          return 0;
03451    }
03452    return 1;
03453 }
03454 
03455 /*! \brief The real destination address for a write */
03456 static const struct sockaddr_in *sip_real_dst(const struct sip_pvt *p)
03457 {
03458    if (p->outboundproxy)
03459       return &p->outboundproxy->ip;
03460 
03461    return ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE ? &p->recv : &p->sa;
03462 }
03463 
03464 /*! \brief Display SIP nat mode */
03465 static const char *sip_nat_mode(const struct sip_pvt *p)
03466 {
03467    return ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE ? "NAT" : "no NAT";
03468 }
03469 
03470 /*! \brief Test PVT for debugging output */
03471 static inline int sip_debug_test_pvt(struct sip_pvt *p) 
03472 {
03473    if (!sipdebug)
03474       return 0;
03475    return sip_debug_test_addr(sip_real_dst(p));
03476 }
03477 
03478 /*! \brief Return int representing a bit field of transport types found in const char *transport */
03479 static int get_transport_str2enum(const char *transport)
03480 {
03481    int res = 0;
03482 
03483    if (ast_strlen_zero(transport)) {
03484       return res;
03485    }
03486 
03487    if (!strcasecmp(transport, "udp")) {
03488       res |= SIP_TRANSPORT_UDP;
03489    }
03490    if (!strcasecmp(transport, "tcp")) {
03491       res |= SIP_TRANSPORT_TCP;
03492    }
03493    if (!strcasecmp(transport, "tls")) {
03494       res |= SIP_TRANSPORT_TLS;
03495    }
03496 
03497    return res;
03498 }
03499 
03500 /*! \brief Return configuration of transports for a device */
03501 static inline const char *get_transport_list(unsigned int transports) {
03502    switch (transports) {
03503       case SIP_TRANSPORT_UDP:
03504          return "UDP";
03505       case SIP_TRANSPORT_TCP:
03506          return "TCP";
03507       case SIP_TRANSPORT_TLS:
03508          return "TLS";
03509       case SIP_TRANSPORT_UDP | SIP_TRANSPORT_TCP:
03510          return "TCP,UDP";
03511       case SIP_TRANSPORT_UDP | SIP_TRANSPORT_TLS:
03512          return "TLS,UDP";
03513       case SIP_TRANSPORT_TCP | SIP_TRANSPORT_TLS:
03514          return "TLS,TCP";
03515       default:
03516          return transports ? 
03517             "TLS,TCP,UDP" : "UNKNOWN"; 
03518    }
03519 }
03520 
03521 /*! \brief Return transport as string */
03522 static inline const char *get_transport(enum sip_transport t)
03523 {
03524    switch (t) {
03525    case SIP_TRANSPORT_UDP:
03526       return "UDP";
03527    case SIP_TRANSPORT_TCP:
03528       return "TCP";
03529    case SIP_TRANSPORT_TLS:
03530       return "TLS";
03531    }
03532 
03533    return "UNKNOWN";
03534 }
03535 
03536 /*! \brief Return transport of dialog.
03537    \note this is based on a false assumption. We don't always use the
03538    outbound proxy for all requests in a dialog. It depends on the
03539    "force" parameter. The FIRST request is always sent to the ob proxy.
03540    \todo Fix this function to work correctly
03541 */
03542 static inline const char *get_transport_pvt(struct sip_pvt *p)
03543 {
03544    if (p->outboundproxy && p->outboundproxy->transport) {
03545       set_socket_transport(&p->socket, p->outboundproxy->transport);
03546    }
03547 
03548    return get_transport(p->socket.type);
03549 }
03550 
03551 /*! \brief Transmit SIP message 
03552    Sends a SIP request or response on a given socket (in the pvt)
03553    Called by retrans_pkt, send_request, send_response and 
03554    __sip_reliable_xmit
03555 */
03556 static int __sip_xmit(struct sip_pvt *p, struct ast_str *data, int len)
03557 {
03558    int res = 0;
03559    const struct sockaddr_in *dst = sip_real_dst(p);
03560 
03561    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));
03562 
03563    if (sip_prepare_socket(p) < 0)
03564       return XMIT_ERROR;
03565 
03566    if (p->socket.type == SIP_TRANSPORT_UDP) {
03567       res = sendto(p->socket.fd, data->str, len, 0, (const struct sockaddr *)dst, sizeof(struct sockaddr_in));
03568    } else if (p->socket.tcptls_session) {
03569       res = sip_tcptls_write(p->socket.tcptls_session, data->str, len);
03570    } else {
03571       ast_debug(2, "Socket type is TCP but no tcptls_session is present to write to\n");
03572       return XMIT_ERROR;
03573    }
03574 
03575    if (res == -1) {
03576       switch (errno) {
03577       case EBADF:       /* Bad file descriptor - seems like this is generated when the host exist, but doesn't accept the UDP packet */
03578       case EHOSTUNREACH:   /* Host can't be reached */
03579       case ENETDOWN:       /* Inteface down */
03580       case ENETUNREACH: /* Network failure */
03581       case ECONNREFUSED:      /* ICMP port unreachable */ 
03582          res = XMIT_ERROR; /* Don't bother with trying to transmit again */
03583       }
03584    }
03585    if (res != len)
03586       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));
03587 
03588    return res;
03589 }
03590 
03591 /*! \brief Build a Via header for a request */
03592 static void build_via(struct sip_pvt *p)
03593 {
03594    /* Work around buggy UNIDEN UIP200 firmware */
03595    const char *rport = ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_RFC3581 ? ";rport" : "";
03596 
03597    /* z9hG4bK is a magic cookie.  See RFC 3261 section 8.1.1.7 */
03598    snprintf(p->via, sizeof(p->via), "SIP/2.0/%s %s:%d;branch=z9hG4bK%08x%s",
03599        get_transport_pvt(p),
03600        ast_inet_ntoa(p->ourip.sin_addr),
03601        ntohs(p->ourip.sin_port), (int) p->branch, rport);
03602 }
03603 
03604 /*! \brief NAT fix - decide which IP address to use for Asterisk server?
03605  *
03606  * Using the localaddr structure built up with localnet statements in sip.conf
03607  * apply it to their address to see if we need to substitute our
03608  * externip or can get away with our internal bindaddr
03609  * 'us' is always overwritten.
03610  */
03611 static void ast_sip_ouraddrfor(struct in_addr *them, struct sockaddr_in *us, struct sip_pvt *p)
03612 {
03613    struct sockaddr_in theirs;
03614    /* Set want_remap to non-zero if we want to remap 'us' to an externally
03615     * reachable IP address and port. This is done if:
03616     * 1. we have a localaddr list (containing 'internal' addresses marked
03617     *    as 'deny', so ast_apply_ha() will return AST_SENSE_DENY on them,
03618     *    and AST_SENSE_ALLOW on 'external' ones);
03619     * 2. either stunaddr or externip is set, so we know what to use as the
03620     *    externally visible address;
03621     * 3. the remote address, 'them', is external;
03622     * 4. the address returned by ast_ouraddrfor() is 'internal' (AST_SENSE_DENY
03623     *    when passed to ast_apply_ha() so it does need to be remapped.
03624     *    This fourth condition is checked later.
03625     */
03626    int want_remap;
03627 
03628    *us = internip;      /* starting guess for the internal address */
03629    /* now ask the system what would it use to talk to 'them' */
03630    ast_ouraddrfor(them, &us->sin_addr);
03631    theirs.sin_addr = *them;
03632 
03633    want_remap = localaddr &&
03634       (externip.sin_addr.s_addr || stunaddr.sin_addr.s_addr) &&
03635       ast_apply_ha(localaddr, &theirs) == AST_SENSE_ALLOW ;
03636 
03637    if (want_remap &&
03638        (!sip_cfg.matchexterniplocally || !ast_apply_ha(localaddr, us)) ) {
03639       /* if we used externhost or stun, see if it is time to refresh the info */
03640       if (externexpire && time(NULL) >= externexpire) {
03641          if (stunaddr.sin_addr.s_addr) {
03642             ast_stun_request(sipsock, &stunaddr, NULL, &externip);
03643          } else {
03644             if (ast_parse_arg(externhost, PARSE_INADDR, &externip))
03645                ast_log(LOG_NOTICE, "Warning: Re-lookup of '%s' failed!\n", externhost);
03646          }
03647          externexpire = time(NULL) + externrefresh;
03648       }
03649       if (externip.sin_addr.s_addr)
03650          *us = externip;
03651       else
03652          ast_log(LOG_WARNING, "stun failed\n");
03653       ast_debug(1, "Target address %s is not local, substituting externip\n", 
03654          ast_inet_ntoa(*(struct in_addr *)&them->s_addr));
03655    } else if (p) {
03656       /* no remapping, but we bind to a specific address, so use it. */
03657       switch (p->socket.type) {
03658       case SIP_TRANSPORT_TCP:
03659          if (sip_tcp_desc.local_address.sin_addr.s_addr) {
03660             *us = sip_tcp_desc.local_address;
03661          } else {
03662             us->sin_port = sip_tcp_desc.local_address.sin_port;
03663          }
03664          break;
03665       case SIP_TRANSPORT_TLS:
03666          if (sip_tls_desc.local_address.sin_addr.s_addr) {
03667             *us = sip_tls_desc.local_address;
03668          } else {
03669             us->sin_port = sip_tls_desc.local_address.sin_port;
03670          }
03671             break;
03672       case SIP_TRANSPORT_UDP:
03673          /* fall through on purpose */
03674       default:
03675          if (bindaddr.sin_addr.s_addr) {
03676             *us = bindaddr;
03677          }
03678       }
03679    } else if (bindaddr.sin_addr.s_addr) {
03680       *us = bindaddr;
03681    }
03682    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));
03683 }
03684 
03685 /*! \brief Append to SIP dialog history with arg list  */
03686 static __attribute__((format(printf, 2, 0))) void append_history_va(struct sip_pvt *p, const char *fmt, va_list ap)
03687 {
03688    char buf[80], *c = buf; /* max history length */
03689    struct sip_history *hist;
03690    int l;
03691 
03692    vsnprintf(buf, sizeof(buf), fmt, ap);
03693    strsep(&c, "\r\n"); /* Trim up everything after \r or \n */
03694    l = strlen(buf) + 1;
03695    if (!(hist = ast_calloc(1, sizeof(*hist) + l)))
03696       return;
03697    if (!p->history && !(p->history = ast_calloc(1, sizeof(*p->history)))) {
03698       ast_free(hist);
03699       return;
03700    }
03701    memcpy(hist->event, buf, l);
03702    if (p->history_entries == MAX_HISTORY_ENTRIES) {
03703       struct sip_history *oldest;
03704       oldest = AST_LIST_REMOVE_HEAD(p->history, list);
03705       p->history_entries--;
03706       ast_free(oldest);
03707    }
03708    AST_LIST_INSERT_TAIL(p->history, hist, list);
03709    p->history_entries++;
03710 }
03711 
03712 /*! \brief Append to SIP dialog history with arg list  */
03713 static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
03714 {
03715    va_list ap;
03716 
03717    if (!p)
03718       return;
03719 
03720    if (!p->do_history && !recordhistory && !dumphistory)
03721       return;
03722 
03723    va_start(ap, fmt);
03724    append_history_va(p, fmt, ap);
03725    va_end(ap);
03726 
03727    return;
03728 }
03729 
03730 /*! \brief Retransmit SIP message if no answer (Called from scheduler) */
03731 static int retrans_pkt(const void *data)
03732 {
03733    struct sip_pkt *pkt = (struct sip_pkt *)data, *prev, *cur = NULL;
03734    int reschedule = DEFAULT_RETRANS;
03735    int xmitres = 0;
03736    
03737    /* Lock channel PVT */
03738    sip_pvt_lock(pkt->owner);
03739 
03740    if (pkt->retrans < MAX_RETRANS) {
03741       pkt->retrans++;
03742       if (!pkt->timer_t1) {   /* Re-schedule using timer_a and timer_t1 */
03743          if (sipdebug)
03744             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);
03745       } else {
03746          int siptimer_a;
03747 
03748          if (sipdebug)
03749             ast_debug(4, "SIP TIMER: Rescheduling retransmission #%d (%d) %s - %d\n", pkt->retransid, pkt->retrans, sip_methods[pkt->method].text, pkt->method);
03750          if (!pkt->timer_a)
03751             pkt->timer_a = 2 ;
03752          else
03753             pkt->timer_a = 2 * pkt->timer_a;
03754  
03755          /* For non-invites, a maximum of 4 secs */
03756          siptimer_a = pkt->timer_t1 * pkt->timer_a;   /* Double each time */
03757          if (pkt->method != SIP_INVITE && siptimer_a > 4000)
03758             siptimer_a = 4000;
03759       
03760          /* Reschedule re-transmit */
03761          reschedule = siptimer_a;
03762          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);
03763       } 
03764 
03765       if (sip_debug_test_pvt(pkt->owner)) {
03766          const struct sockaddr_in *dst = sip_real_dst(pkt->owner);
03767          ast_verbose("Retransmitting #%d (%s) to %s:%d:\n%s\n---\n",
03768             pkt->retrans, sip_nat_mode(pkt->owner),
03769             ast_inet_ntoa(dst->sin_addr),
03770             ntohs(dst->sin_port), pkt->data->str);
03771       }
03772 
03773       append_history(pkt->owner, "ReTx", "%d %s", reschedule, pkt->data->str);
03774       xmitres = __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
03775       sip_pvt_unlock(pkt->owner);
03776       if (xmitres == XMIT_ERROR)
03777          ast_log(LOG_WARNING, "Network error on retransmit in dialog %s\n", pkt->owner->callid);
03778       else 
03779          return  reschedule;
03780    } 
03781    /* Too many retries */
03782    if (pkt->owner && pkt->method != SIP_OPTIONS && xmitres == 0) {
03783       if (pkt->is_fatal || sipdebug)   /* Tell us if it's critical or if we're debugging */
03784          ast_log(LOG_WARNING, "Maximum retries exceeded on transmission %s for seqno %d (%s %s) -- See doc/sip-retransmit.txt.\n",
03785             pkt->owner->callid, pkt->seqno,
03786             pkt->is_fatal ? "Critical" : "Non-critical", pkt->is_resp ? "Response" : "Request");
03787    } else if (pkt->method == SIP_OPTIONS && sipdebug) {
03788          ast_log(LOG_WARNING, "Cancelling retransmit of OPTIONs (call id %s)  -- See doc/sip-retransmit.txt.\n", pkt->owner->callid);
03789 
03790    } 
03791    if (xmitres == XMIT_ERROR) {
03792       ast_log(LOG_WARNING, "Transmit error :: Cancelling transmission on Call ID %s\n", pkt->owner->callid);
03793       append_history(pkt->owner, "XmitErr", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
03794    } else 
03795       append_history(pkt->owner, "MaxRetries", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
03796       
03797    pkt->retransid = -1;
03798 
03799    if (pkt->is_fatal) {
03800       while(pkt->owner->owner && ast_channel_trylock(pkt->owner->owner)) {
03801          sip_pvt_unlock(pkt->owner);   /* SIP_PVT, not channel */
03802          usleep(1);
03803          sip_pvt_lock(pkt->owner);
03804       }
03805 
03806       if (pkt->owner->owner && !pkt->owner->owner->hangupcause) 
03807          pkt->owner->owner->hangupcause = AST_CAUSE_NO_USER_RESPONSE;
03808       
03809       if (pkt->owner->owner) {
03810          sip_alreadygone(pkt->owner);
03811          ast_log(LOG_WARNING, "Hanging up call %s - no reply to our critical packet (see doc/sip-retransmit.txt).\n", pkt->owner->callid);
03812          ast_queue_hangup_with_cause(pkt->owner->owner, AST_CAUSE_PROTOCOL_ERROR);
03813          ast_channel_unlock(pkt->owner->owner);
03814       } else {
03815          /* If no channel owner, destroy now */
03816 
03817          /* Let the peerpoke system expire packets when the timer expires for poke_noanswer */
03818          if (pkt->method != SIP_OPTIONS && pkt->method != SIP_REGISTER) {
03819             pvt_set_needdestroy(pkt->owner, "no response to critical packet");
03820             sip_alreadygone(pkt->owner);
03821             append_history(pkt->owner, "DialogKill", "Killing this failed dialog immediately");
03822          }
03823       }
03824    }
03825 
03826    if (pkt->method == SIP_BYE) {
03827       /* We're not getting answers on SIP BYE's.  Tear down the call anyway. */
03828       if (pkt->owner->owner) 
03829          ast_channel_unlock(pkt->owner->owner);
03830       append_history(pkt->owner, "ByeFailure", "Remote peer doesn't respond to bye. Destroying call anyway.");
03831       pvt_set_needdestroy(pkt->owner, "no response to BYE");
03832    }
03833 
03834    /* Remove the packet */
03835    for (prev = NULL, cur = pkt->owner->packets; cur; prev = cur, cur = cur->next) {
03836       if (cur == pkt) {
03837          UNLINK(cur, pkt->owner->packets, prev);
03838          sip_pvt_unlock(pkt->owner);
03839          if (pkt->owner)
03840             pkt->owner = dialog_unref(pkt->owner,"pkt is being freed, its dialog ref is dead now");
03841          if (pkt->data)
03842             ast_free(pkt->data);
03843          pkt->data = NULL;
03844          ast_free(pkt);
03845          return 0;
03846       }
03847    }
03848    /* error case */
03849    ast_log(LOG_WARNING, "Weird, couldn't find packet owner!\n");
03850    sip_pvt_unlock(pkt->owner);
03851    return 0;
03852 }
03853 
03854 /*! \brief Transmit packet with retransmits 
03855    \return 0 on success, -1 on failure to allocate packet 
03856 */
03857 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)
03858 {
03859    struct sip_pkt *pkt = NULL;
03860    int siptimer_a = DEFAULT_RETRANS;
03861    int xmitres = 0;
03862    int respid;
03863 
03864    if (sipmethod == SIP_INVITE) {
03865       /* Note this is a pending invite */
03866       p->pendinginvite = seqno;
03867    }
03868 
03869    /* If the transport is something reliable (TCP or TLS) then don't really send this reliably */
03870    /* I removed the code from retrans_pkt that does the same thing so it doesn't get loaded into the scheduler */
03871    /*! \todo According to the RFC some packets need to be retransmitted even if its TCP, so this needs to get revisited */
03872    if (!(p->socket.type & SIP_TRANSPORT_UDP)) {
03873       xmitres = __sip_xmit(p, data, len); /* Send packet */
03874       if (xmitres == XMIT_ERROR) {  /* Serious network trouble, no need to try again */
03875          append_history(p, "XmitErr", "%s", fatal ? "(Critical)" : "(Non-critical)");
03876          return AST_FAILURE;
03877       } else {
03878          return AST_SUCCESS;
03879       }
03880    }
03881 
03882    if (!(pkt = ast_calloc(1, sizeof(*pkt) + len + 1)))
03883       return AST_FAILURE;
03884    /* copy data, add a terminator and save length */
03885    if (!(pkt->data = ast_str_create(len))) {
03886       ast_free(pkt);
03887       return AST_FAILURE;
03888    }
03889    ast_str_set(&pkt->data, 0, "%s%s", data->str, "\0");
03890    pkt->packetlen = len;
03891    /* copy other parameters from the caller */
03892    pkt->method = sipmethod;
03893    pkt->seqno = seqno;
03894    pkt->is_resp = resp;
03895    pkt->is_fatal = fatal;
03896    pkt->owner = dialog_ref(p, "__sip_reliable_xmit: setting pkt->owner");
03897    pkt->next = p->packets;
03898    p->packets = pkt; /* Add it to the queue */
03899    if (resp) {
03900       /* Parse out the response code */
03901       if (sscanf(ast_str_buffer(pkt->data), "SIP/2.0 %30u", &respid) == 1) {
03902          pkt->response_code = respid;
03903       }
03904    }
03905    pkt->timer_t1 = p->timer_t1;  /* Set SIP timer T1 */
03906    pkt->retransid = -1;
03907    if (pkt->timer_t1)
03908       siptimer_a = pkt->timer_t1 * 2;
03909 
03910    /* Schedule retransmission */
03911    AST_SCHED_REPLACE_VARIABLE(pkt->retransid, sched, siptimer_a, retrans_pkt, pkt, 1);
03912    if (sipdebug)
03913       ast_debug(4, "*** SIP TIMER: Initializing retransmit timer on packet: Id  #%d\n", pkt->retransid);
03914 
03915    xmitres = __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);   /* Send packet */
03916 
03917    if (xmitres == XMIT_ERROR) {  /* Serious network trouble, no need to try again */
03918       append_history(pkt->owner, "XmitErr", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
03919       ast_log(LOG_ERROR, "Serious Network Trouble; __sip_xmit returns error for pkt data\n");
03920       AST_SCHED_DEL(sched, pkt->retransid);
03921       p->packets = pkt->next;
03922       pkt->owner = dialog_unref(pkt->owner,"pkt is being freed, its dialog ref is dead now");
03923       ast_free(pkt->data);
03924       ast_free(pkt);
03925       return AST_FAILURE;
03926    } else {
03927       return AST_SUCCESS;
03928    }
03929 }
03930 
03931 /*! \brief Kill a SIP dialog (called only by the scheduler)
03932  * The scheduler has a reference to this dialog when p->autokillid != -1,
03933  * and we are called using that reference. So if the event is not
03934  * rescheduled, we need to call dialog_unref().
03935  */
03936 static int __sip_autodestruct(const void *data)
03937 {
03938    struct sip_pvt *p = (struct sip_pvt *)data;
03939 
03940    /* If this is a subscription, tell the phone that we got a timeout */
03941    if (p->subscribed) {
03942       transmit_state_notify(p, AST_EXTENSION_DEACTIVATED, 1, TRUE);  /* Send last notification */
03943       p->subscribed = NONE;
03944       append_history(p, "Subscribestatus", "timeout");
03945       ast_debug(3, "Re-scheduled destruction of SIP subscription %s\n", p->callid ? p->callid : "<unknown>");
03946       return 10000;  /* Reschedule this destruction so that we know that it's gone */
03947    }
03948 
03949    /* If there are packets still waiting for delivery, delay the destruction */
03950    if (p->packets) {
03951       if (!p->needdestroy) {
03952          char method_str[31];
03953          ast_debug(3, "Re-scheduled destruction of SIP call %s\n", p->callid ? p->callid : "<unknown>");
03954          append_history(p, "ReliableXmit", "timeout");
03955          if (sscanf(p->lastmsg, "Tx: %30s", method_str) == 1 || sscanf(p->lastmsg, "Rx: %30s", method_str) == 1) {
03956             if (method_match(SIP_CANCEL, method_str) || method_match(SIP_BYE, method_str)) {
03957                pvt_set_needdestroy(p, "autodestruct");
03958             }
03959          }
03960          return 10000;
03961       } else {
03962          /* They've had their chance to respond. Time to bail */
03963          __sip_pretend_ack(p);
03964       }
03965    }
03966 
03967    if (p->subscribed == MWI_NOTIFICATION)
03968       if (p->relatedpeer)
03969          p->relatedpeer = unref_peer(p->relatedpeer, "__sip_autodestruct: unref peer p->relatedpeer");   /* Remove link to peer. If it's realtime, make sure it's gone from memory) */
03970 
03971    /* Reset schedule ID */
03972    p->autokillid = -1;
03973 
03974    if (p->owner) {
03975       ast_log(LOG_WARNING, "Autodestruct on dialog '%s' with owner in place (Method: %s)\n", p->callid, sip_methods[p->method].text);
03976       ast_queue_hangup_with_cause(p->owner, AST_CAUSE_PROTOCOL_ERROR);
03977    } else if (p->refer && !p->alreadygone) {
03978       ast_debug(3, "Finally hanging up channel after transfer: %s\n", p->callid);
03979       transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
03980       append_history(p, "ReferBYE", "Sending BYE on transferer call leg %s", p->callid);
03981       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
03982    } else {
03983       append_history(p, "AutoDestroy", "%s", p->callid);
03984       ast_debug(3, "Auto destroying SIP dialog '%s'\n", p->callid);
03985       dialog_unlink_all(p, TRUE, TRUE); /* once it's unlinked and unrefd everywhere, it'll be freed automagically */
03986       /* dialog_unref(p, "unref dialog-- no other matching conditions"); -- unlink all now should finish off the dialog's references and free it. */
03987       /* sip_destroy(p); */      /* Go ahead and destroy dialog. All attempts to recover is done */
03988       /* sip_destroy also absorbs the reference */
03989    }
03990    dialog_unref(p, "The ref to a dialog passed to this sched callback is going out of scope; unref it.");
03991    return 0;
03992 }
03993 
03994 /*! \brief Schedule destruction of SIP dialog */
03995 static void sip_scheddestroy(struct sip_pvt *p, int ms)
03996 {
03997    if (ms < 0) {
03998       if (p->timer_t1 == 0) {
03999          p->timer_t1 = global_t1;   /* Set timer T1 if not set (RFC 3261) */
04000          p->timer_b = global_timer_b;  /* Set timer B if not set (RFC 3261) */
04001       }
04002       ms = p->timer_t1 * 64;
04003    }
04004    if (sip_debug_test_pvt(p))
04005       ast_verbose("Scheduling destruction of SIP dialog '%s' in %d ms (Method: %s)\n", p->callid, ms, sip_methods[p->method].text);
04006    if (sip_cancel_destroy(p))
04007       ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
04008 
04009    if (p->do_history)
04010       append_history(p, "SchedDestroy", "%d ms", ms);
04011    p->autokillid = ast_sched_add(sched, ms, __sip_autodestruct, dialog_ref(p, "setting ref as passing into ast_sched_add for __sip_autodestruct"));
04012 
04013    if (p->stimer && p->stimer->st_active == TRUE && p->stimer->st_schedid > 0)
04014       stop_session_timer(p);
04015 }
04016 
04017 /*! \brief Cancel destruction of SIP dialog.
04018  * Be careful as this also absorbs the reference - if you call it
04019  * from within the scheduler, this might be the last reference.
04020  */
04021 static int sip_cancel_destroy(struct sip_pvt *p)
04022 {
04023    int res = 0;
04024    if (p->autokillid > -1) {
04025       int res3;
04026 
04027       if (!(res3 = ast_sched_del(sched, p->autokillid))) {
04028          append_history(p, "CancelDestroy", "");
04029          p->autokillid = -1;
04030          dialog_unref(p, "dialog unrefd because autokillid is de-sched'd");
04031       }
04032    }
04033    return res;
04034 }
04035 
04036 /*! \brief Acknowledges receipt of a packet and stops retransmission 
04037  * called with p locked*/
04038 static int __sip_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod)
04039 {
04040    struct sip_pkt *cur, *prev = NULL;
04041    const char *msg = "Not Found";   /* used only for debugging */
04042    int res = FALSE;
04043 
04044    /* If we have an outbound proxy for this dialog, then delete it now since
04045      the rest of the requests in this dialog needs to follow the routing.
04046      If obforcing is set, we will keep the outbound proxy during the whole
04047      dialog, regardless of what the SIP rfc says
04048    */
04049    if (p->outboundproxy && !p->outboundproxy->force){
04050       ref_proxy(p, NULL);
04051    }
04052 
04053    for (cur = p->packets; cur; prev = cur, cur = cur->next) {
04054       if (cur->seqno != seqno || cur->is_resp != resp)
04055          continue;
04056       if (cur->is_resp || cur->method == sipmethod) {
04057          res = TRUE;
04058          msg = "Found";
04059          if (!resp && (seqno == p->pendinginvite)) {
04060             ast_debug(1, "Acked pending invite %d\n", p->pendinginvite);
04061             p->pendinginvite = 0;
04062          }
04063          if (cur->retransid > -1) {
04064             if (sipdebug)
04065                ast_debug(4, "** SIP TIMER: Cancelling retransmit of packet (reply received) Retransid #%d\n", cur->retransid);
04066          }
04067          /* This odd section is designed to thwart a 
04068           * race condition in the packet scheduler. There are
04069           * two conditions under which deleting the packet from the
04070           * scheduler can fail.
04071           *
04072           * 1. The packet has been removed from the scheduler because retransmission
04073           * is being attempted. The problem is that if the packet is currently attempting
04074           * retransmission and we are at this point in the code, then that MUST mean
04075           * that retrans_pkt is waiting on p's lock. Therefore we will relinquish the
04076           * lock temporarily to allow retransmission.
04077           *
04078           * 2. The packet has reached its maximum number of retransmissions and has
04079           * been permanently removed from the packet scheduler. If this is the case, then
04080           * the packet's retransid will be set to -1. The atomicity of the setting and checking
04081           * of the retransid to -1 is ensured since in both cases p's lock is held.
04082           */
04083          while (cur->retransid > -1 && ast_sched_del(sched, cur->retransid)) {
04084             sip_pvt_unlock(p);
04085             usleep(1);
04086             sip_pvt_lock(p);
04087          }
04088          UNLINK(cur, p->packets, prev);
04089          dialog_unref(cur->owner, "unref pkt cur->owner dialog from sip ack before freeing pkt");
04090          if (cur->data)
04091             ast_free(cur->data);
04092          ast_free(cur);
04093          break;
04094       }
04095    }
04096    ast_debug(1, "Stopping retransmission on '%s' of %s %d: Match %s\n",
04097       p->callid, resp ? "Response" : "Request", seqno, msg);
04098    return res;
04099 }
04100 
04101 /*! \brief Pretend to ack all packets
04102  * called with p locked */
04103 static void __sip_pretend_ack(struct sip_pvt *p)
04104 {
04105    struct sip_pkt *cur = NULL;
04106 
04107    while (p->packets) {
04108       int method;
04109       if (cur == p->packets) {
04110          ast_log(LOG_WARNING, "Have a packet that doesn't want to give up! %s\n", sip_methods[cur->method].text);
04111          return;
04112       }
04113       cur = p->packets;
04114       method = (cur->method) ? cur->method : find_sip_method(cur->data->str);
04115       __sip_ack(p, cur->seqno, cur->is_resp, method);
04116    }
04117 }
04118 
04119 /*! \brief Acks receipt of packet, keep it around (used for provisional responses) */
04120 static int __sip_semi_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod)
04121 {
04122    struct sip_pkt *cur;
04123    int res = FALSE;
04124 
04125    for (cur = p->packets; cur; cur = cur->next) {
04126       if (cur->seqno == seqno && cur->is_resp == resp &&
04127          (cur->is_resp || method_match(sipmethod, cur->data->str))) {
04128          /* this is our baby */
04129          if (cur->retransid > -1) {
04130             if (sipdebug)
04131                ast_debug(4, "*** SIP TIMER: Cancelling retransmission #%d - %s (got response)\n", cur->retransid, sip_methods[sipmethod].text);
04132          }
04133          AST_SCHED_DEL(sched, cur->retransid);
04134          res = TRUE;
04135          break;
04136       }
04137    }
04138    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");
04139    return res;
04140 }
04141 
04142 
04143 /*! \brief Copy SIP request, parse it */
04144 static void parse_copy(struct sip_request *dst, const struct sip_request *src)
04145 {
04146    copy_request(dst, src);
04147    parse_request(dst);
04148 }
04149 
04150 /*! \brief add a blank line if no body */
04151 static void add_blank(struct sip_request *req)
04152 {
04153    if (!req->lines) {
04154       /* Add extra empty return. add_header() reserves 4 bytes so cannot be truncated */
04155       ast_str_append(&req->data, 0, "\r\n");
04156       req->len = ast_str_strlen(req->data);
04157    }
04158 }
04159 
04160 static int send_provisional_keepalive_full(struct sip_pvt *pvt, int with_sdp)
04161 {
04162    const char *msg = NULL;
04163 
04164    if (!pvt->last_provisional || !strncasecmp(pvt->last_provisional, "100", 3)) {
04165       msg = "183 Session Progress";
04166    }
04167 
04168    if (pvt->invitestate < INV_COMPLETED) {
04169       if (with_sdp) {
04170          transmit_response_with_sdp(pvt, S_OR(msg, pvt->last_provisional), &pvt->initreq, XMIT_UNRELIABLE, FALSE);
04171       } else {
04172          transmit_response(pvt, S_OR(msg, pvt->last_provisional), &pvt->initreq);
04173       }
04174       return PROVIS_KEEPALIVE_TIMEOUT;
04175    }
04176 
04177    return 0;
04178 }
04179 
04180 static int send_provisional_keepalive(const void *data) {
04181    struct sip_pvt *pvt = (struct sip_pvt *) data;
04182 
04183    return send_provisional_keepalive_full(pvt, 0);
04184 }
04185 
04186 static int send_provisional_keepalive_with_sdp(const void *data) {
04187    struct sip_pvt *pvt = (void *)data;
04188 
04189    return send_provisional_keepalive_full(pvt, 1);
04190 }
04191 
04192 static void update_provisional_keepalive(struct sip_pvt *pvt, int with_sdp)
04193 {
04194    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"));
04195 
04196    pvt->provisional_keepalive_sched_id = ast_sched_add(sched, PROVIS_KEEPALIVE_TIMEOUT,
04197       with_sdp ? send_provisional_keepalive_with_sdp : send_provisional_keepalive, dialog_ref(pvt, "Increment refcount to pass dialog pointer to sched callback"));
04198 }
04199 
04200 /*! \brief Transmit response on SIP request*/
04201 static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno)
04202 {
04203    int res;
04204 
04205    add_blank(req);
04206    if (sip_debug_test_pvt(p)) {
04207       const struct sockaddr_in *dst = sip_real_dst(p);
04208 
04209       ast_verbose("\n<--- %sTransmitting (%s) to %s:%d --->\n%s\n<------------>\n",
04210          reliable ? "Reliably " : "", sip_nat_mode(p),
04211          ast_inet_ntoa(dst->sin_addr),
04212          ntohs(dst->sin_port), req->data->str);
04213    }
04214    if (p->do_history) {
04215       struct sip_request tmp = { .rlPart1 = 0, };
04216       parse_copy(&tmp, req);
04217       append_history(p, reliable ? "TxRespRel" : "TxResp", "%s / %s - %s", tmp.data->str, get_header(&tmp, "CSeq"), 
04218          (tmp.method == SIP_RESPONSE || tmp.method == SIP_UNKNOWN) ? REQ_OFFSET_TO_STR(&tmp, rlPart2) : sip_methods[tmp.method].text);
04219       ast_free(tmp.data);
04220    }
04221 
04222    /* If we are sending a final response to an INVITE, stop retransmitting provisional responses */
04223    if (p->initreq.method == SIP_INVITE && reliable == XMIT_CRITICAL) {
04224       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"));
04225    }
04226 
04227    res = (reliable) ?
04228        __sip_reliable_xmit(p, seqno, 1, req->data, req->len, (reliable == XMIT_CRITICAL), req->method) :
04229       __sip_xmit(p, req->data, req->len);
04230    ast_free(req->data);
04231    req->data = NULL;
04232    if (res > 0)
04233       return 0;
04234    return res;
04235 }
04236 
04237 /*! \brief Send SIP Request to the other part of the dialogue */
04238 static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno)
04239 {
04240    int res;
04241 
04242    /* If we have an outbound proxy, reset peer address 
04243       Only do this once.
04244    */
04245    if (p->outboundproxy) {
04246       p->sa = p->outboundproxy->ip;
04247    }
04248 
04249    add_blank(req);
04250    if (sip_debug_test_pvt(p)) {
04251       if (ast_test_flag(&p->flags[0], SIP_NAT_ROUTE))
04252          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);
04253       else
04254          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);
04255    }
04256    if (p->do_history) {
04257       struct sip_request tmp = { .rlPart1 = 0, };
04258       parse_copy(&tmp, req);
04259       append_history(p, reliable ? "TxReqRel" : "TxReq", "%s / %s - %s", tmp.data->str, get_header(&tmp, "CSeq"), sip_methods[tmp.method].text);
04260       ast_free(tmp.data);
04261    }
04262    res = (reliable) ?
04263       __sip_reliable_xmit(p, seqno, 0, req->data, req->len, (reliable == XMIT_CRITICAL), req->method) :
04264       __sip_xmit(p, req->data, req->len);
04265    if (req->data) {
04266       ast_free(req->data);
04267       req->data = NULL;
04268    }
04269    return res;
04270 }
04271 
04272 /*! \brief Query an option on a SIP dialog */
04273 static int sip_queryoption(struct ast_channel *chan, int option, void *data, int *datalen)
04274 {
04275    int res = -1;
04276    enum ast_t38_state state = T38_STATE_UNAVAILABLE;
04277    struct sip_pvt *p = (struct sip_pvt *) chan->tech_pvt;
04278 
04279    switch (option) {
04280    case AST_OPTION_T38_STATE:
04281       /* Make sure we got an ast_t38_state enum passed in */
04282       if (*datalen != sizeof(enum ast_t38_state)) {
04283          ast_log(LOG_ERROR, "Invalid datalen for AST_OPTION_T38_STATE option. Expected %d, got %d\n", (int)sizeof(enum ast_t38_state), *datalen);
04284          return -1;
04285       }
04286 
04287       sip_pvt_lock(p);
04288 
04289       /* 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 */
04290       if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT)) {
04291          switch (p->t38.state) {
04292          case T38_LOCAL_REINVITE:
04293          case T38_PEER_REINVITE:
04294             state = T38_STATE_NEGOTIATING;
04295             break;
04296          case T38_ENABLED:
04297             state = T38_STATE_NEGOTIATED;
04298             break;
04299          default:
04300             state = T38_STATE_UNKNOWN;
04301          }
04302       }
04303 
04304       sip_pvt_unlock(p);
04305 
04306       *((enum ast_t38_state *) data) = state;
04307       res = 0;
04308 
04309       break;
04310    default:
04311       break;
04312    }
04313 
04314    return res;
04315 }
04316 
04317 /*! \brief Locate closing quote in a string, skipping escaped quotes.
04318  * optionally with a limit on the search.
04319  * start must be past the first quote.
04320  */
04321 static const char *find_closing_quote(const char *start, const char *lim)
04322 {
04323    char last_char = '\0';
04324    const char *s;
04325    for (s = start; *s && s != lim; last_char = *s++) {
04326       if (*s == '"' && last_char != '\\')
04327          break;
04328    }
04329    return s;
04330 }
04331 
04332 /*! \brief Pick out text in brackets from character string
04333    \return pointer to terminated stripped string
04334    \param tmp input string that will be modified
04335    Examples:
04336 \verbatim
04337    "foo" <bar> valid input, returns bar
04338    foo      returns the whole string
04339    < "foo ... >   returns the string between brackets
04340    < "foo...   bogus (missing closing bracket), returns the whole string
04341          XXX maybe should still skip the opening bracket
04342 \endverbatim
04343  */
04344 static char *get_in_brackets(char *tmp)
04345 {
04346    const char *parse = tmp;
04347    char *first_bracket;
04348 
04349    /*
04350     * Skip any quoted text until we find the part in brackets.
04351    * On any error give up and return the full string.
04352    */
04353    while ( (first_bracket = strchr(parse, '<')) ) {
04354       char *first_quote = strchr(parse, '"');
04355 
04356       if (!first_quote || first_quote > first_bracket)
04357          break; /* no need to look at quoted part */
04358       /* the bracket is within quotes, so ignore it */
04359       parse = find_closing_quote(first_quote + 1, NULL);
04360       if (!*parse) { /* not found, return full string ? */
04361          /* XXX or be robust and return in-bracket part ? */
04362          ast_log(LOG_WARNING, "No closing quote found in '%s'\n", tmp);
04363          break;
04364       }
04365       parse++;
04366    }
04367    if (first_bracket) {
04368       char *second_bracket = strchr(first_bracket + 1, '>');
04369       if (second_bracket) {
04370          *second_bracket = '\0';
04371          tmp = first_bracket + 1;
04372       } else {
04373          ast_log(LOG_WARNING, "No closing bracket found in '%s'\n", tmp);
04374       }
04375    }
04376    
04377    return tmp;
04378 }
04379 
04380 /*! \brief * parses a URI in its components.
04381  *
04382  * \note 
04383  * - If scheme is specified, drop it from the top.
04384  * - If a component is not requested, do not split around it.
04385  * - Multiple scheme's can be specified ',' delimited. ex: "sip:,sips:"
04386  *
04387  * This means that if we don't have domain, we cannot split
04388  * name:pass and domain:port.
04389  * It is safe to call with ret_name, pass, domain, port
04390  * pointing all to the same place.
04391  * Init pointers to empty string so we never get NULL dereferencing.
04392  * Overwrites the string.
04393  * return 0 on success, other values on error.
04394  * \verbatim 
04395  * general form we are expecting is sip[s]:username[:password][;parameter]@host[:port][;...] 
04396  * \endverbatim
04397  * 
04398  */
04399 static int parse_uri(char *uri, const char *scheme,
04400    char **ret_name, char **pass, char **domain, char **port, char **options, char **transport)
04401 {
04402    char *name = NULL;
04403    int error = 0;
04404 
04405    /* init field as required */
04406    if (pass)
04407       *pass = "";
04408    if (port)
04409       *port = "";
04410    if (scheme) {
04411       int l;
04412       char *scheme2 = ast_strdupa(scheme);
04413       char *cur = strsep(&scheme2, ",");
04414       for (; !ast_strlen_zero(cur); cur = strsep(&scheme2, ",")) {
04415          l = strlen(cur);
04416          if (!strncasecmp(uri, cur, l)) {
04417             uri += l;
04418             break;
04419          }
04420       }
04421       if (ast_strlen_zero(cur)) {
04422          ast_debug(1, "No supported scheme found in '%s' using the scheme[s] %s\n", uri, scheme);
04423          error = -1;
04424       }
04425    }
04426    if (transport) {
04427       char *t, *type = "";
04428       *transport = "";
04429       if ((t = strstr(uri, "transport="))) {
04430          strsep(&t, "=");
04431          if ((type = strsep(&t, ";"))) {
04432             *transport = type;
04433          }
04434       }
04435    }
04436 
04437    if (!domain) {
04438       /* if we don't want to split around domain, keep everything as a name,
04439        * so we need to do nothing here, except remember why.
04440        */
04441    } else {
04442       /* store the result in a temp. variable to avoid it being
04443        * overwritten if arguments point to the same place.
04444        */
04445       char *c, *dom = "";
04446 
04447       if ((c = strchr(uri, '@')) == NULL) {
04448          /* domain-only URI, according to the SIP RFC. */
04449          dom = uri;
04450          name = "";
04451       } else {
04452          *c++ = '\0';
04453          dom = c;
04454          name = uri;
04455       }
04456 
04457       /* Remove options in domain and name */
04458       dom = strsep(&dom, ";");
04459       name = strsep(&name, ";");
04460 
04461       if (port && (c = strchr(dom, ':'))) { /* Remove :port */
04462          *c++ = '\0';
04463          *port = c;
04464       }
04465       if (pass && (c = strchr(name, ':'))) { /* user:password */
04466          *c++ = '\0';
04467          *pass = c;
04468       }
04469       *domain = dom;
04470    }
04471    if (ret_name)  /* same as for domain, store the result only at the end */
04472       *ret_name = name;
04473    if (options)
04474       *options = uri ? uri : "";
04475 
04476    return error;
04477 }
04478 
04479 /*! \brief Send message with Access-URL header, if this is an HTML URL only! */
04480 static int sip_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen)
04481 {
04482    struct sip_pvt *p = chan->tech_pvt;
04483 
04484    if (subclass != AST_HTML_URL)
04485       return -1;
04486 
04487    ast_string_field_build(p, url, "<%s>;mode=active", data);
04488 
04489    if (sip_debug_test_pvt(p))
04490       ast_debug(1, "Send URL %s, state = %d!\n", data, chan->_state);
04491 
04492    switch (chan->_state) {
04493    case AST_STATE_RING:
04494       transmit_response(p, "100 Trying", &p->initreq);
04495       break;
04496    case AST_STATE_RINGING:
04497       transmit_response(p, "180 Ringing", &p->initreq);
04498       break;
04499    case AST_STATE_UP:
04500       if (!p->pendinginvite) {      /* We are up, and have no outstanding invite */
04501          transmit_reinvite_with_sdp(p, FALSE, FALSE);
04502       } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
04503          ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);   
04504       }  
04505       break;
04506    default:
04507       ast_log(LOG_WARNING, "Don't know how to send URI when state is %d!\n", chan->_state);
04508    }
04509 
04510    return 0;
04511 }
04512 
04513 /*! \brief Deliver SIP call ID for the call */
04514 static const char *sip_get_callid(struct ast_channel *chan)
04515 {
04516    return chan->tech_pvt ? ((struct sip_pvt *) chan->tech_pvt)->callid : "";
04517 }
04518 
04519 /*! \brief Send SIP MESSAGE text within a call
04520    Called from PBX core sendtext() application */
04521 static int sip_sendtext(struct ast_channel *ast, const char *text)
04522 {
04523    struct sip_pvt *p = ast->tech_pvt;
04524    int debug = sip_debug_test_pvt(p);
04525 
04526    if (debug)
04527       ast_verbose("Sending text %s on %s\n", text, ast->name);
04528    if (!p)
04529       return -1;
04530    /* NOT ast_strlen_zero, because a zero-length message is specifically
04531     * allowed by RFC 3428 (See section 10, Examples) */
04532    if (!text)
04533       return 0;
04534    if (debug)
04535       ast_verbose("Really sending text %s on %s\n", text, ast->name);
04536    transmit_message_with_text(p, text);
04537    return 0;   
04538 }
04539 
04540 /*! \brief Update peer object in realtime storage 
04541    If the Asterisk system name is set in asterisk.conf, we will use
04542    that name and store that in the "regserver" field in the sippeers
04543    table to facilitate multi-server setups.
04544 */
04545 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)
04546 {
04547    char port[10];
04548    char ipaddr[INET_ADDRSTRLEN];
04549    char regseconds[20];
04550    char *tablename = NULL;
04551    char str_lastms[20];
04552 
04553    const char *sysname = ast_config_AST_SYSTEM_NAME;
04554    char *syslabel = NULL;
04555 
04556    time_t nowtime = time(NULL) + expirey;
04557    const char *fc = fullcontact ? "fullcontact" : NULL;
04558 
04559    int realtimeregs = ast_check_realtime("sipregs");
04560 
04561    tablename = realtimeregs ? "sipregs" : "sippeers";
04562    
04563 
04564    snprintf(str_lastms, sizeof(str_lastms), "%d", lastms);
04565    snprintf(regseconds, sizeof(regseconds), "%d", (int)nowtime);  /* Expiration time */
04566    ast_copy_string(ipaddr, ast_inet_ntoa(sin->sin_addr), sizeof(ipaddr));
04567    snprintf(port, sizeof(port), "%d", ntohs(sin->sin_port));
04568    
04569    if (ast_strlen_zero(sysname)) /* No system name, disable this */
04570       sysname = NULL;
04571    else if (sip_cfg.rtsave_sysname)
04572       syslabel = "regserver";
04573 
04574    if (fc) {
04575       ast_update_realtime(tablename, "name", peername, "ipaddr", ipaddr,
04576          "port", port, "regseconds", regseconds,
04577          deprecated_username ? "username" : "defaultuser", defaultuser,
04578          "useragent", useragent, "lastms", str_lastms,
04579          fc, fullcontact, syslabel, sysname, SENTINEL); /* note fc and syslabel _can_ be NULL */
04580    } else {
04581       ast_update_realtime(tablename, "name", peername, "ipaddr", ipaddr,
04582          "port", port, "regseconds", regseconds,
04583          "useragent", useragent, "lastms", str_lastms,
04584          deprecated_username ? "username" : "defaultuser", defaultuser,
04585          syslabel, sysname, SENTINEL); /* note syslabel _can_ be NULL */
04586    }
04587 }
04588 
04589 /*! \brief Automatically add peer extension to dial plan */
04590 static void register_peer_exten(struct sip_peer *peer, int onoff)
04591 {
04592    char multi[256];
04593    char *stringp, *ext, *context;
04594    struct pbx_find_info q = { .stacklen = 0 };
04595 
04596    /* XXX note that global_regcontext is both a global 'enable' flag and
04597     * the name of the global regexten context, if not specified
04598     * individually.
04599     */
04600    if (ast_strlen_zero(global_regcontext))
04601       return;
04602 
04603    ast_copy_string(multi, S_OR(peer->regexten, peer->name), sizeof(multi));
04604    stringp = multi;
04605    while ((ext = strsep(&stringp, "&"))) {
04606       if ((context = strchr(ext, '@'))) {
04607          *context++ = '\0';   /* split ext@context */
04608          if (!ast_context_find(context)) {
04609             ast_log(LOG_WARNING, "Context %s must exist in regcontext= in sip.conf!\n", context);
04610             continue;
04611          }
04612       } else {
04613          context = global_regcontext;
04614       }
04615       if (onoff) {
04616          if (!ast_exists_extension(NULL, context, ext, 1, NULL)) {
04617             ast_add_extension(context, 1, ext, 1, NULL, NULL, "Noop",
04618                 ast_strdup(peer->name), ast_free_ptr, "SIP");
04619          }
04620       } else if (pbx_find_extension(NULL, NULL, &q, context, ext, 1, NULL, "", E_MATCH)) {
04621          ast_context_remove_extension(context, ext, 1, NULL);
04622       }
04623    }
04624 }
04625 
04626 /*! Destroy mailbox subscriptions */
04627 static void destroy_mailbox(struct sip_mailbox *mailbox)
04628 {
04629    if (mailbox->mailbox)
04630       ast_free(mailbox->mailbox);
04631    if (mailbox->context)
04632       ast_free(mailbox->context);
04633    if (mailbox->event_sub)
04634       ast_event_unsubscribe(mailbox->event_sub);
04635    ast_free(mailbox);
04636 }
04637 
04638 /*! Destroy all peer-related mailbox subscriptions */
04639 static void clear_peer_mailboxes(struct sip_peer *peer)
04640 {
04641    struct sip_mailbox *mailbox;
04642 
04643    while ((mailbox = AST_LIST_REMOVE_HEAD(&peer->mailboxes, entry)))
04644       destroy_mailbox(mailbox);
04645 }
04646 
04647 static void sip_destroy_peer_fn(void *peer)
04648 {
04649    sip_destroy_peer(peer);
04650 }
04651 
04652 /*! \brief Destroy peer object from memory */
04653 static void sip_destroy_peer(struct sip_peer *peer)
04654 {
04655    ast_debug(3, "Destroying SIP peer %s\n", peer->name);
04656    if (peer->outboundproxy)
04657       ao2_ref(peer->outboundproxy, -1);
04658    peer->outboundproxy = NULL;
04659 
04660    /* Delete it, it needs to disappear */
04661    if (peer->call) {
04662       dialog_unlink_all(peer->call, TRUE, TRUE);
04663       peer->call = dialog_unref(peer->call, "peer->call is being unset");
04664    }
04665    
04666 
04667    if (peer->mwipvt) {  /* We have an active subscription, delete it */
04668       dialog_unlink_all(peer->mwipvt, TRUE, TRUE);
04669       peer->mwipvt = dialog_unref(peer->mwipvt, "unreffing peer->mwipvt");
04670    }
04671    
04672    if (peer->chanvars) {
04673       ast_variables_destroy(peer->chanvars);
04674       peer->chanvars = NULL;
04675    }
04676    
04677    register_peer_exten(peer, FALSE);
04678    ast_free_ha(peer->ha);
04679    if (peer->selfdestruct)
04680       ast_atomic_fetchadd_int(&apeerobjs, -1);
04681    else if (peer->is_realtime) {
04682       ast_atomic_fetchadd_int(&rpeerobjs, -1);
04683       ast_debug(3, "-REALTIME- peer Destroyed. Name: %s. Realtime Peer objects: %d\n", peer->name, rpeerobjs);
04684    } else
04685       ast_atomic_fetchadd_int(&speerobjs, -1);
04686    clear_realm_authentication(peer->auth);
04687    peer->auth = NULL;
04688    if (peer->dnsmgr)
04689       ast_dnsmgr_release(peer->dnsmgr);
04690    clear_peer_mailboxes(peer);
04691 
04692    if (peer->socket.tcptls_session) {
04693       ao2_ref(peer->socket.tcptls_session, -1);
04694       peer->socket.tcptls_session = NULL;
04695    }
04696 
04697    ast_string_field_free_memory(peer);
04698 }
04699 
04700 /*! \brief Update peer data in database (if used) */
04701 static void update_peer(struct sip_peer *p, int expire)
04702 {
04703    int rtcachefriends = ast_test_flag(&p->flags[1], SIP_PAGE2_RTCACHEFRIENDS);
04704    if (sip_cfg.peer_rtupdate &&
04705        (p->is_realtime || rtcachefriends)) {
04706       realtime_update_peer(p->name, &p->addr, p->username, rtcachefriends ? p->fullcontact : NULL, p->useragent, expire, p->deprecated_username, p->lastms);
04707    }
04708 }
04709 
04710 static struct ast_variable *get_insecure_variable_from_config(struct ast_config *cfg)
04711 {
04712    struct ast_variable *var = NULL;
04713    struct ast_flags flags = {0};
04714    char *cat = NULL;
04715    const char *insecure;
04716    while ((cat = ast_category_browse(cfg, cat))) {
04717       insecure = ast_variable_retrieve(cfg, cat, "insecure");
04718       set_insecure_flags(&flags, insecure, -1);
04719       if (ast_test_flag(&flags, SIP_INSECURE_PORT)) {
04720          var = ast_category_root(cfg, cat);
04721          break;
04722       }
04723    }
04724    return var;
04725 }
04726 
04727 static const char *get_name_from_variable(struct ast_variable *var, const char *newpeername)
04728 {
04729    struct ast_variable *tmp;
04730    for (tmp = var; tmp; tmp = tmp->next) {
04731       if (!newpeername && !strcasecmp(tmp->name, "name"))
04732          newpeername = tmp->value;
04733    }
04734    return newpeername;
04735 }
04736 
04737 /*! \brief  realtime_peer: Get peer from realtime storage
04738  * Checks the "sippeers" realtime family from extconfig.conf 
04739  * Checks the "sipregs" realtime family from extconfig.conf if it's configured.
04740  * This returns a pointer to a peer and because we use build_peer, we can rest
04741  * assured that the refcount is bumped.
04742 */
04743 static struct sip_peer *realtime_peer(const char *newpeername, struct sockaddr_in *sin, int devstate_only)
04744 {
04745    struct sip_peer *peer;
04746    struct ast_variable *var = NULL;
04747    struct ast_variable *varregs = NULL;
04748    struct ast_variable *tmp;
04749    struct ast_config *peerlist = NULL;
04750    char ipaddr[INET_ADDRSTRLEN];
04751    char portstring[6]; /*up to 5 digits plus null terminator*/
04752    char *cat = NULL;
04753    unsigned short portnum;
04754    int realtimeregs = ast_check_realtime("sipregs");
04755 
04756    /* First check on peer name */
04757    if (newpeername) {
04758       if (realtimeregs)
04759          varregs = ast_load_realtime("sipregs", "name", newpeername, SENTINEL);
04760 
04761       var = ast_load_realtime("sippeers", "name", newpeername, "host", "dynamic", SENTINEL);
04762       if (!var && sin)
04763          var = ast_load_realtime("sippeers", "name", newpeername, "host", ast_inet_ntoa(sin->sin_addr), SENTINEL);
04764       if (!var) {
04765          var = ast_load_realtime("sippeers", "name", newpeername, SENTINEL);
04766          /*!\note
04767           * If this one loaded something, then we need to ensure that the host
04768           * field matched.  The only reason why we can't have this as a criteria
04769           * is because we only have the IP address and the host field might be
04770           * set as a name (and the reverse PTR might not match).
04771           */
04772          if (var && sin) {
04773             for (tmp = var; tmp; tmp = tmp->next) {
04774                if (!strcasecmp(tmp->name, "host")) {
04775                   struct hostent *hp;
04776                   struct ast_hostent ahp;
04777                   if (!(hp = ast_gethostbyname(tmp->value, &ahp)) || (memcmp(hp->h_addr, &sin->sin_addr, sizeof(hp->h_addr)))) {
04778                      /* No match */
04779                      ast_variables_destroy(var);
04780                      var = NULL;
04781                   }
04782                   break;
04783                }
04784             }
04785          }
04786       }
04787    }
04788 
04789    if (!var && sin) {   /* Then check on IP address for dynamic peers */
04790       ast_copy_string(ipaddr, ast_inet_ntoa(sin->sin_addr), sizeof(ipaddr));
04791       portnum = ntohs(sin->sin_port);
04792       sprintf(portstring, "%u", portnum);
04793       var = ast_load_realtime("sippeers", "host", ipaddr, "port", portstring, SENTINEL);  /* First check for fixed IP hosts */
04794       if (var) {
04795          if (realtimeregs) {
04796             newpeername = get_name_from_variable(var, newpeername);
04797             varregs = ast_load_realtime("sipregs", "name", newpeername, SENTINEL);
04798          }
04799       } else {
04800          if (realtimeregs)
04801             varregs = ast_load_realtime("sipregs", "ipaddr", ipaddr, "port", portstring, SENTINEL); /* Then check for registered hosts */
04802          else
04803             var = ast_load_realtime("sippeers", "ipaddr", ipaddr, "port", portstring, SENTINEL); /* Then check for registered hosts */
04804          if (varregs) {
04805             newpeername = get_name_from_variable(varregs, newpeername);
04806             var = ast_load_realtime("sippeers", "name", newpeername, SENTINEL);
04807          }
04808       }
04809       if (!var) { /*We couldn't match on ipaddress and port, so we need to check if port is insecure*/
04810          peerlist = ast_load_realtime_multientry("sippeers", "host", ipaddr, SENTINEL);
04811          if (peerlist) {
04812             var = get_insecure_variable_from_config(peerlist);
04813             if(var) {
04814                if (realtimeregs) {
04815                   newpeername = get_name_from_variable(var, newpeername);
04816                   varregs = ast_load_realtime("sipregs", "name", newpeername, SENTINEL);
04817                }
04818             } else { /*var wasn't found in the list of "hosts", so try "ipaddr"*/
04819                peerlist = NULL;
04820                cat = NULL;
04821                peerlist = ast_load_realtime_multientry("sippeers", "ipaddr", ipaddr, SENTINEL);
04822                if(peerlist) {
04823                   var = get_insecure_variable_from_config(peerlist);
04824                   if(var) {
04825                      if (realtimeregs) {
04826                         newpeername = get_name_from_variable(var, newpeername);
04827                         varregs = ast_load_realtime("sipregs", "name", newpeername, SENTINEL);
04828                      }
04829                   }
04830                }
04831             }
04832          } else {
04833             if (realtimeregs) {
04834                peerlist = ast_load_realtime_multientry("sipregs", "ipaddr", ipaddr, SENTINEL);
04835                if (peerlist) {
04836                   varregs = get_insecure_variable_from_config(peerlist);
04837                   if (varregs) {
04838                      newpeername = get_name_from_variable(varregs, newpeername);
04839                      var = ast_load_realtime("sippeers", "name", newpeername, SENTINEL);
04840                   }
04841                }
04842             } else {
04843                peerlist = ast_load_realtime_multientry("sippeers", "ipaddr", ipaddr, SENTINEL);
04844                if (peerlist) {
04845                   var = get_insecure_variable_from_config(peerlist);
04846                   if (var) {
04847                      newpeername = get_name_from_variable(var, newpeername);
04848                      varregs = ast_load_realtime("sipregs", "name", newpeername, SENTINEL);
04849                   }
04850                }
04851             }
04852          }
04853       }
04854    }
04855 
04856    if (!var) {
04857       if (peerlist)
04858          ast_config_destroy(peerlist);
04859       return NULL;
04860    }
04861 
04862    for (tmp = var; tmp; tmp = tmp->next) {
04863       /* If this is type=user, then skip this object. */
04864       if (!strcasecmp(tmp->name, "type") &&
04865           !strcasecmp(tmp->value, "user")) {
04866          if(peerlist)
04867             ast_config_destroy(peerlist);
04868          else {
04869             ast_variables_destroy(var);
04870             ast_variables_destroy(varregs);
04871          }
04872          return NULL;
04873       } else if (!newpeername && !strcasecmp(tmp->name, "name")) {
04874          newpeername = tmp->value;
04875       }
04876    }
04877    
04878    if (!newpeername) {  /* Did not find peer in realtime */
04879       ast_log(LOG_WARNING, "Cannot Determine peer name ip=%s\n", ipaddr);
04880       if(peerlist)
04881          ast_config_destroy(peerlist);
04882       else
04883          ast_variables_destroy(var);
04884       return NULL;
04885    }
04886 
04887 
04888    /* Peer found in realtime, now build it in memory */
04889    peer = build_peer(newpeername, var, varregs, TRUE, devstate_only);
04890    if (!peer) {
04891       if(peerlist)
04892          ast_config_destroy(peerlist);
04893       else {
04894          ast_variables_destroy(var);
04895          ast_variables_destroy(varregs);
04896       }
04897       return NULL;
04898    }
04899 
04900    ast_debug(3, "-REALTIME- loading peer from database to memory. Name: %s. Peer objects: %d\n", peer->name, rpeerobjs);
04901 
04902    if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) && !devstate_only) {
04903       /* Cache peer */
04904       ast_copy_flags(&peer->flags[1], &global_flags[1], SIP_PAGE2_RTAUTOCLEAR|SIP_PAGE2_RTCACHEFRIENDS);
04905       if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTAUTOCLEAR)) {
04906          AST_SCHED_REPLACE_UNREF(peer->expire, sched, sip_cfg.rtautoclear * 1000, expire_register, peer,
04907                unref_peer(_data, "remove registration ref"),
04908                unref_peer(peer, "remove registration ref"),
04909                ref_peer(peer, "add registration ref"));
04910       }
04911       ao2_t_link(peers, peer, "link peer into peers table");
04912       if (peer->addr.sin_addr.s_addr) {
04913          ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
04914       }
04915    }
04916    peer->is_realtime = 1;
04917    if (peerlist)
04918       ast_config_destroy(peerlist);
04919    else {
04920       ast_variables_destroy(var);
04921       ast_variables_destroy(varregs);
04922    }
04923 
04924    return peer;
04925 }
04926 
04927 /* Function to assist finding peers by name only */
04928 static int find_by_name(void *obj, void *arg, void *data, int flags)
04929 {
04930    struct sip_peer *search = obj, *match = arg;
04931    int *which_objects = data;
04932 
04933    /* Usernames in SIP uri's are case sensitive. Domains are not */
04934    if (strcmp(search->name, match->name)) {
04935       return 0;
04936    }
04937 
04938    switch (*which_objects) {
04939    case FINDUSERS:
04940       if (!(search->type & SIP_TYPE_USER)) {
04941          return 0;
04942       }
04943       break;
04944    case FINDPEERS:
04945       if (!(search->type & SIP_TYPE_PEER)) {
04946          return 0;
04947       }
04948       break;
04949    case FINDALLDEVICES:
04950       break;
04951    }
04952 
04953    return CMP_MATCH | CMP_STOP;
04954 }
04955 
04956 /*! 
04957  * \brief Locate device by name or ip address 
04958  *
04959  * \param which_objects Define which objects should be matched when doing a lookup
04960  *        by name.  Valid options are FINDUSERS, FINDPEERS, or FINDALLDEVICES.
04961  *        Note that this option is not used at all when doing a lookup by IP.
04962  *
04963  * This is used on find matching device on name or ip/port.
04964  * If the device was declared as type=peer, we don't match on peer name on incoming INVITEs.
04965  *
04966  * \note Avoid using this function in new functions if there is a way to avoid it,
04967  * since it might cause a database lookup.
04968  */
04969 static struct sip_peer *find_peer(const char *peer, struct sockaddr_in *sin, int realtime, int which_objects, int devstate_only, int transport)
04970 {
04971    struct sip_peer *p = NULL;
04972    struct sip_peer tmp_peer;
04973 
04974    if (peer) {
04975       ast_copy_string(tmp_peer.name, peer, sizeof(tmp_peer.name));
04976       p = ao2_t_callback_data(peers, OBJ_POINTER, find_by_name, &tmp_peer, &which_objects, "ao2_find in peers table");
04977    } else if (sin) { /* search by addr? */
04978       tmp_peer.addr.sin_addr.s_addr = sin->sin_addr.s_addr;
04979       tmp_peer.addr.sin_port = sin->sin_port;
04980       tmp_peer.flags[0].flags = 0;
04981       tmp_peer.transports = transport;
04982       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); */
04983       if (!p) {
04984          ast_set_flag(&tmp_peer.flags[0], SIP_INSECURE_PORT);
04985          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); */
04986          if (p) {
04987             return p;
04988          }
04989       }
04990    }
04991 
04992    if (!p && (realtime || devstate_only)) {
04993       p = realtime_peer(peer, sin, devstate_only);
04994    }
04995 
04996    return p;
04997 }
04998 
04999 /*! \brief Set nat mode on the various data sockets */
05000 static void do_setnat(struct sip_pvt *p, int natflags)
05001 {
05002    const char *mode = natflags ? "On" : "Off";
05003 
05004    if (p->rtp) {
05005       ast_debug(1, "Setting NAT on RTP to %s\n", mode);
05006       ast_rtp_setnat(p->rtp, natflags);
05007    }
05008    if (p->vrtp) {
05009       ast_debug(1, "Setting NAT on VRTP to %s\n", mode);
05010       ast_rtp_setnat(p->vrtp, natflags);
05011    }
05012    if (p->udptl) {
05013       ast_debug(1, "Setting NAT on UDPTL to %s\n", mode);
05014       ast_udptl_setnat(p->udptl, natflags);
05015    }
05016    if (p->trtp) {
05017       ast_debug(1, "Setting NAT on TRTP to %s\n", mode);
05018       ast_rtp_setnat(p->trtp, natflags);
05019    }
05020 }
05021 
05022 /*! \brief Change the T38 state on a SIP dialog */
05023 static void change_t38_state(struct sip_pvt *p, int state)
05024 {
05025    int old = p->t38.state;
05026    struct ast_channel *chan = p->owner;
05027    struct ast_control_t38_parameters parameters = { .request_response = 0 };
05028 
05029    /* Don't bother changing if we are already in the state wanted */
05030    if (old == state)
05031       return;
05032 
05033    p->t38.state = state;
05034    ast_debug(2, "T38 state changed to %d on channel %s\n", p->t38.state, chan ? chan->name : "<none>");
05035 
05036    /* If no channel was provided we can't send off a control frame */
05037    if (!chan)
05038       return;
05039 
05040    /* Given the state requested and old state determine what control frame we want to queue up */
05041    switch (state) {
05042    case T38_PEER_REINVITE:
05043       parameters = p->t38.their_parms;
05044       parameters.max_ifp = ast_udptl_get_far_max_ifp(p->udptl);
05045       parameters.request_response = AST_T38_REQUEST_NEGOTIATE;
05046       ast_udptl_set_tag(p->udptl, "SIP/%s", p->username);
05047       break;
05048    case T38_ENABLED:
05049       parameters = p->t38.their_parms;
05050       parameters.max_ifp = ast_udptl_get_far_max_ifp(p->udptl);
05051       parameters.request_response = AST_T38_NEGOTIATED;
05052       ast_udptl_set_tag(p->udptl, "SIP/%s", p->username);
05053       break;
05054    case T38_DISABLED:
05055       if (old == T38_ENABLED) {
05056          parameters.request_response = AST_T38_TERMINATED;
05057       } else if (old == T38_LOCAL_REINVITE) {
05058          parameters.request_response = AST_T38_REFUSED;
05059       }
05060       break;
05061    case T38_LOCAL_REINVITE:
05062       /* wait until we get a peer response before responding to local reinvite */
05063       break;
05064    }
05065 
05066    /* Woot we got a message, create a control frame and send it on! */
05067    if (parameters.request_response)
05068       ast_queue_control_data(chan, AST_CONTROL_T38_PARAMETERS, &parameters, sizeof(parameters));
05069 }
05070 
05071 /*! \brief Set the global T38 capabilities on a SIP dialog structure */
05072 static void set_t38_capabilities(struct sip_pvt *p)
05073 {
05074    if (p->udptl) {
05075       if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) == SIP_PAGE2_T38SUPPORT_UDPTL_REDUNDANCY) {
05076                         ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_REDUNDANCY);
05077       } else if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) == SIP_PAGE2_T38SUPPORT_UDPTL_FEC) {
05078          ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_FEC);
05079       } else if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) == SIP_PAGE2_T38SUPPORT_UDPTL) {
05080          ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_NONE);
05081       }
05082    }
05083 }
05084 
05085 static void copy_socket_data(struct sip_socket *to_sock, const struct sip_socket *from_sock)
05086 {
05087    if (to_sock->tcptls_session) {
05088       ao2_ref(to_sock->tcptls_session, -1);
05089       to_sock->tcptls_session = NULL;
05090    }
05091 
05092    if (from_sock->tcptls_session) {
05093       ao2_ref(from_sock->tcptls_session, +1);
05094    }
05095 
05096    *to_sock = *from_sock;
05097 }
05098 
05099 /*! \brief Create address structure from peer reference.
05100  * This function copies data from peer to the dialog, so we don't have to look up the peer
05101  * again from memory or database during the life time of the dialog.
05102  *
05103  * \return -1 on error, 0 on success.
05104  *
05105  */
05106 static int create_addr_from_peer(struct sip_pvt *dialog, struct sip_peer *peer)
05107 {
05108 
05109    /* this checks that the dialog is contacting the peer on a valid
05110     * transport type based on the peers transport configuration,
05111     * otherwise, this function bails out */
05112    if (dialog->socket.type && check_request_transport(peer, dialog))
05113       return -1;
05114    copy_socket_data(&dialog->socket, &peer->socket);
05115 
05116    if ((peer->addr.sin_addr.s_addr || peer->defaddr.sin_addr.s_addr) &&
05117        (!peer->maxms || ((peer->lastms >= 0)  && (peer->lastms <= peer->maxms)))) {
05118       dialog->sa = (peer->addr.sin_addr.s_addr) ? peer->addr : peer->defaddr;
05119       dialog->recv = dialog->sa;
05120    } else 
05121       return -1;
05122 
05123    ast_copy_flags(&dialog->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
05124    ast_copy_flags(&dialog->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
05125    dialog->capability = peer->capability;
05126    if (!ast_test_flag(&dialog->flags[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS) &&
05127          (!ast_test_flag(&dialog->flags[1], SIP_PAGE2_VIDEOSUPPORT) ||
05128             !(dialog->capability & AST_FORMAT_VIDEO_MASK)) &&
05129          dialog->vrtp) {
05130       ast_rtp_destroy(dialog->vrtp);
05131       dialog->vrtp = NULL;
05132    }
05133    if (!ast_test_flag(&dialog->flags[1], SIP_PAGE2_TEXTSUPPORT) && dialog->trtp) {
05134       ast_rtp_destroy(dialog->trtp);
05135       dialog->trtp = NULL;
05136    }
05137    dialog->prefs = peer->prefs;
05138    if (ast_test_flag(&dialog->flags[1], SIP_PAGE2_T38SUPPORT)) {
05139       if (!dialog->udptl) {
05140          /* t38pt_udptl was enabled in the peer and not in [general] */
05141          dialog->udptl = ast_udptl_new_with_bindaddr(sched, io, 0, bindaddr.sin_addr);
05142       }
05143       dialog->t38_maxdatagram = peer->t38_maxdatagram;
05144       set_t38_capabilities(dialog);
05145    } else if (dialog->udptl) {
05146       ast_udptl_destroy(dialog->udptl);
05147       dialog->udptl = NULL;
05148    }
05149    do_setnat(dialog, ast_test_flag(&dialog->flags[0], SIP_NAT) & SIP_NAT_ROUTE);
05150 
05151    if (dialog->rtp) { /* Audio */
05152       ast_rtp_setdtmf(dialog->rtp, ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
05153       ast_rtp_setdtmfcompensate(dialog->rtp, ast_test_flag(&dialog->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
05154       ast_rtp_set_rtptimeout(dialog->rtp, peer->rtptimeout);
05155       ast_rtp_set_rtpholdtimeout(dialog->rtp, peer->rtpholdtimeout);
05156       ast_rtp_set_rtpkeepalive(dialog->rtp, peer->rtpkeepalive);
05157       /* Set Frame packetization */
05158       ast_rtp_codec_setpref(dialog->rtp, &dialog->prefs);
05159       dialog->autoframing = peer->autoframing;
05160    }
05161    if (dialog->vrtp) { /* Video */
05162       ast_rtp_setdtmf(dialog->vrtp, 0);
05163       ast_rtp_setdtmfcompensate(dialog->vrtp, 0);
05164       ast_rtp_set_rtptimeout(dialog->vrtp, peer->rtptimeout);
05165       ast_rtp_set_rtpholdtimeout(dialog->vrtp, peer->rtpholdtimeout);
05166       ast_rtp_set_rtpkeepalive(dialog->vrtp, peer->rtpkeepalive);
05167    }
05168    if (dialog->trtp) { /* Realtime text */
05169       ast_rtp_setdtmf(dialog->trtp, 0);
05170       ast_rtp_setdtmfcompensate(dialog->trtp, 0);
05171       ast_rtp_set_rtptimeout(dialog->trtp, peer->rtptimeout);
05172       ast_rtp_set_rtpholdtimeout(dialog->trtp, peer->rtpholdtimeout);
05173       ast_rtp_set_rtpkeepalive(dialog->trtp, peer->rtpkeepalive);
05174    }
05175 
05176    ast_string_field_set(dialog, peername, peer->name);
05177    ast_string_field_set(dialog, authname, peer->username);
05178    ast_string_field_set(dialog, username, peer->username);
05179    ast_string_field_set(dialog, peersecret, peer->secret);
05180    ast_string_field_set(dialog, peermd5secret, peer->md5secret);
05181    ast_string_field_set(dialog, mohsuggest, peer->mohsuggest);
05182    ast_string_field_set(dialog, mohinterpret, peer->mohinterpret);
05183    ast_string_field_set(dialog, tohost, peer->tohost);
05184    ast_string_field_set(dialog, fullcontact, peer->fullcontact);
05185    ast_string_field_set(dialog, context, peer->context);
05186    ast_string_field_set(dialog, parkinglot, peer->parkinglot);
05187    ref_proxy(dialog, obproxy_get(dialog, peer));
05188    dialog->callgroup = peer->callgroup;
05189    dialog->pickupgroup = peer->pickupgroup;
05190    dialog->allowtransfer = peer->allowtransfer;
05191    dialog->jointnoncodeccapability = dialog->noncodeccapability;
05192    dialog->rtptimeout = peer->rtptimeout;
05193    dialog->peerauth = peer->auth;
05194    dialog->maxcallbitrate = peer->maxcallbitrate;
05195    if (ast_strlen_zero(dialog->tohost))
05196       ast_string_field_set(dialog, tohost, ast_inet_ntoa(dialog->sa.sin_addr));
05197    if (!ast_strlen_zero(peer->fromdomain)) {
05198       ast_string_field_set(dialog, fromdomain, peer->fromdomain);
05199       if (!dialog->initreq.headers) {
05200          char *c;
05201          char *tmpcall = ast_strdupa(dialog->callid);
05202          /* this sure looks to me like we are going to change the callid on this dialog!! */
05203          c = strchr(tmpcall, '@');
05204          if (c) {
05205             *c = '\0';
05206             ao2_t_unlink(dialogs, dialog, "About to change the callid -- remove the old name");
05207             ast_string_field_build(dialog, callid, "%s@%s", tmpcall, peer->fromdomain);
05208             ao2_t_link(dialogs, dialog, "New dialog callid -- inserted back into table");
05209          }
05210       }
05211    }
05212    if (!ast_strlen_zero(peer->fromuser)) 
05213       ast_string_field_set(dialog, fromuser, peer->fromuser);
05214    if (!ast_strlen_zero(peer->language))
05215       ast_string_field_set(dialog, language, peer->language);
05216    /* Set timer T1 to RTT for this peer (if known by qualify=) */
05217    /* Minimum is settable or default to 100 ms */
05218    /* If there is a maxms and lastms from a qualify use that over a manual T1
05219       value. Otherwise, use the peer's T1 value. */
05220    if (peer->maxms && peer->lastms)
05221       dialog->timer_t1 = peer->lastms < global_t1min ? global_t1min : peer->lastms;
05222    else
05223       dialog->timer_t1 = peer->timer_t1;
05224 
05225    /* Set timer B to control transaction timeouts, the peer setting is the default and overrides
05226       the known timer */
05227    if (peer->timer_b)
05228       dialog->timer_b = peer->timer_b;
05229    else
05230       dialog->timer_b = 64 * dialog->timer_t1;
05231 
05232    if ((ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
05233        (ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
05234       dialog->noncodeccapability |= AST_RTP_DTMF;
05235    else
05236       dialog->noncodeccapability &= ~AST_RTP_DTMF;
05237    if (peer->call_limit)
05238       ast_set_flag(&dialog->flags[0], SIP_CALL_LIMIT);
05239    if (!dialog->portinuri)
05240       dialog->portinuri = peer->portinuri;
05241    
05242    dialog->chanvars = copy_vars(peer->chanvars);
05243 
05244    return 0;
05245 }
05246 
05247 /*! \brief create address structure from device name
05248  *      Or, if peer not found, find it in the global DNS 
05249  *      returns TRUE (-1) on failure, FALSE on success */
05250 static int create_addr(struct sip_pvt *dialog, const char *opeer, struct sockaddr_in *sin, int newdialog)
05251 {
05252    struct hostent *hp;
05253    struct ast_hostent ahp;
05254    struct sip_peer *peer;
05255    char *port;
05256    int portno = 0;
05257    char host[MAXHOSTNAMELEN], *hostn;
05258    char peername[256];
05259    int srv_ret = 0;
05260 
05261    ast_copy_string(peername, opeer, sizeof(peername));
05262    port = strchr(peername, ':');
05263    if (port) {
05264       *port++ = '\0';
05265       dialog->portinuri = 1;
05266    }
05267    dialog->sa.sin_family = AF_INET;
05268    dialog->timer_t1 = global_t1; /* Default SIP retransmission timer T1 (RFC 3261) */
05269    dialog->timer_b = global_timer_b; /* Default SIP transaction timer B (RFC 3261) */
05270    peer = find_peer(peername, NULL, TRUE, FINDPEERS, FALSE, 0);
05271 
05272    if (peer) {
05273       int res;
05274       if (newdialog) {
05275          set_socket_transport(&dialog->socket, 0);
05276       }
05277       res = create_addr_from_peer(dialog, peer);
05278       if (!ast_strlen_zero(port)) {
05279          if ((portno = atoi(port))) {
05280             dialog->sa.sin_port = dialog->recv.sin_port = htons(portno);
05281          }
05282       }
05283       unref_peer(peer, "create_addr: unref peer from find_peer hashtab lookup");
05284       return res;
05285    }
05286 
05287    do_setnat(dialog, ast_test_flag(&dialog->flags[0], SIP_NAT) & SIP_NAT_ROUTE);
05288 
05289    ast_string_field_set(dialog, tohost, peername);
05290 
05291    /* Get the outbound proxy information */
05292    ref_proxy(dialog, obproxy_get(dialog, NULL));
05293 
05294    if (sin) {
05295       /* This address should be updated using dnsmgr */
05296       memcpy(&dialog->sa.sin_addr, &sin->sin_addr, sizeof(dialog->sa.sin_addr));
05297       if (!sin->sin_port) {
05298          portno = port_str2int(port, (dialog->socket.type == SIP_TRANSPORT_TLS) ? STANDARD_TLS_PORT : STANDARD_SIP_PORT);
05299       } else {
05300          portno = ntohs(sin->sin_port);
05301       }
05302    } else {
05303 
05304       /* Let's see if we can find the host in DNS. First try DNS SRV records,
05305          then hostname lookup */
05306       /*! \todo Fix this function. When we ask for SRV, we should check all transports 
05307            In the future, we should first check NAPTR to find out transport preference
05308        */
05309       hostn = peername;
05310       /* Section 4.2 of RFC 3263 specifies that if a port number is specified, then
05311        * an A record lookup should be used instead of SRV.
05312        */
05313       if (!port && sip_cfg.srvlookup) {
05314          char service[MAXHOSTNAMELEN];
05315          int tportno;
05316    
05317          snprintf(service, sizeof(service), "_sip._%s.%s", get_transport(dialog->socket.type), peername);
05318          srv_ret = ast_get_srv(NULL, host, sizeof(host), &tportno, service);
05319          if (srv_ret > 0) {
05320             hostn = host;
05321             portno = tportno;
05322          }
05323       }
05324       if (!portno)
05325          portno = port_str2int(port, (dialog->socket.type == SIP_TRANSPORT_TLS) ? STANDARD_TLS_PORT : STANDARD_SIP_PORT);
05326       hp = ast_gethostbyname(hostn, &ahp);
05327       if (!hp) {
05328          ast_log(LOG_WARNING, "No such host: %s\n", peername);
05329          return -1;
05330       }
05331       memcpy(&dialog->sa.sin_addr, hp->h_addr, sizeof(dialog->sa.sin_addr));
05332    }
05333 
05334    if (!dialog->socket.type)
05335       set_socket_transport(&dialog->socket, SIP_TRANSPORT_UDP);
05336    if (!dialog->socket.port)
05337       dialog->socket.port = bindaddr.sin_port;
05338    dialog->sa.sin_port = htons(portno);
05339    dialog->recv = dialog->sa;
05340    return 0;
05341 }
05342 
05343 /*! \brief Scheduled congestion on a call.
05344  * Only called by the scheduler, must return the reference when done.
05345  */
05346 static int auto_congest(const void *arg)
05347 {
05348    struct sip_pvt *p = (struct sip_pvt *)arg;
05349 
05350    sip_pvt_lock(p);
05351    p->initid = -1;   /* event gone, will not be rescheduled */
05352    if (p->owner) {
05353       /* XXX fails on possible deadlock */
05354       if (!ast_channel_trylock(p->owner)) {
05355          append_history(p, "Cong", "Auto-congesting (timer)");
05356          ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
05357          ast_channel_unlock(p->owner);
05358       }
05359 
05360       /* Give the channel a chance to act before we proceed with destruction */
05361       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
05362    }
05363    sip_pvt_unlock(p);
05364    dialog_unref(p, "unreffing arg passed into auto_congest callback (p->initid)");
05365    return 0;
05366 }
05367 
05368 
05369 /*! \brief Initiate SIP call from PBX 
05370  *      used from the dial() application      */
05371 static int sip_call(struct ast_channel *ast, char *dest, int timeout)
05372 {
05373    int res;
05374    struct sip_pvt *p = ast->tech_pvt;  /* chan is locked, so the reference cannot go away */
05375    struct varshead *headp;
05376    struct ast_var_t *current;
05377    const char *referer = NULL;   /* SIP referrer */
05378 
05379    if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
05380       ast_log(LOG_WARNING, "sip_call called on %s, neither down nor reserved\n", ast->name);
05381       return -1;
05382    }
05383 
05384    /* Check whether there is vxml_url, distinctive ring variables */
05385    headp=&ast->varshead;
05386    AST_LIST_TRAVERSE(headp, current, entries) {
05387       /* Check whether there is a VXML_URL variable */
05388       if (!p->options->vxml_url && !strcasecmp(ast_var_name(current), "VXML_URL")) {
05389          p->options->vxml_url = ast_var_value(current);
05390       } else if (!p->options->uri_options && !strcasecmp(ast_var_name(current), "SIP_URI_OPTIONS")) {
05391          p->options->uri_options = ast_var_value(current);
05392       } else if (!p->options->addsipheaders && !strncasecmp(ast_var_name(current), "SIPADDHEADER", strlen("SIPADDHEADER"))) {
05393          /* Check whether there is a variable with a name starting with SIPADDHEADER */
05394          p->options->addsipheaders = 1;
05395       } else if (!strcasecmp(ast_var_name(current), "SIPFROMDOMAIN")) {
05396          ast_string_field_set(p, fromdomain, ast_var_value(current));
05397       } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER")) {
05398          /* This is a transfered call */
05399          p->options->transfer = 1;
05400       } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER_REFERER")) {
05401          /* This is the referrer */
05402          referer = ast_var_value(current);
05403       } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER_REPLACES")) {
05404          /* We're replacing a call. */
05405          p->options->replaces = ast_var_value(current);
05406       }
05407    }
05408 
05409    res = 0;
05410    ast_set_flag(&p->flags[0], SIP_OUTGOING);
05411 
05412    /* T.38 re-INVITE FAX detection should never be done for outgoing calls,
05413     * so ensure it is disabled.
05414     */
05415    ast_clear_flag(&p->flags[1], SIP_PAGE2_FAX_DETECT_T38);
05416 
05417    if (p->options->transfer) {
05418       char buf[SIPBUFSIZE/2];
05419 
05420       if (referer) {
05421          if (sipdebug)
05422             ast_debug(3, "Call for %s transfered by %s\n", p->username, referer);
05423          snprintf(buf, sizeof(buf)-1, "-> %s (via %s)", p->cid_name, referer);
05424       } else 
05425          snprintf(buf, sizeof(buf)-1, "-> %s", p->cid_name);
05426       ast_string_field_set(p, cid_name, buf);
05427    } 
05428    ast_debug(1, "Outgoing Call for %s\n", p->username);
05429 
05430    res = update_call_counter(p, INC_CALL_RINGING);
05431 
05432    if (res == -1) {
05433       ast->hangupcause = AST_CAUSE_USER_BUSY;
05434       return res;
05435    }
05436    p->callingpres = ast->cid.cid_pres;
05437    p->jointcapability = ast_translate_available_formats(p->capability, p->prefcodec);
05438    p->jointnoncodeccapability = p->noncodeccapability;
05439 
05440    /* If there are no audio formats left to offer, punt */
05441    if (!(p->jointcapability & AST_FORMAT_AUDIO_MASK)) {
05442       ast_log(LOG_WARNING, "No audio format found to offer. Cancelling call to %s\n", p->username);
05443       res = -1;
05444    } else {
05445       int xmitres;
05446 
05447       xmitres = transmit_invite(p, SIP_INVITE, 1, 2);
05448       if (xmitres == XMIT_ERROR)
05449          return -1;
05450       p->invitestate = INV_CALLING;
05451    
05452       /* Initialize auto-congest time */
05453       AST_SCHED_REPLACE_UNREF(p->initid, sched, p->timer_b, auto_congest, p, 
05454                         dialog_unref(_data, "dialog ptr dec when SCHED_REPLACE del op succeeded"), 
05455                         dialog_unref(p, "dialog ptr dec when SCHED_REPLACE add failed"),
05456                         dialog_ref(p, "dialog ptr inc when SCHED_REPLACE add succeeded") );
05457    }
05458    return res;
05459 }
05460 
05461 /*! \brief Destroy registry object
05462    Objects created with the register= statement in static configuration */
05463 static void sip_registry_destroy(struct sip_registry *reg)
05464 {
05465    /* Really delete */
05466    ast_debug(3, "Destroying registry entry for %s@%s\n", reg->username, reg->hostname);
05467 
05468    if (reg->call) {
05469       /* Clear registry before destroying to ensure
05470          we don't get reentered trying to grab the registry lock */
05471       reg->call->registry = registry_unref(reg->call->registry, "destroy reg->call->registry");
05472       ast_debug(3, "Destroying active SIP dialog for registry %s@%s\n", reg->username, reg->hostname);
05473       dialog_unlink_all(reg->call, TRUE, TRUE);
05474       reg->call = dialog_unref(reg->call, "unref reg->call");
05475       /* reg->call = sip_destroy(reg->call); */
05476    }
05477    AST_SCHED_DEL(sched, reg->expire);  
05478    AST_SCHED_DEL(sched, reg->timeout);
05479    
05480    ast_string_field_free_memory(reg);
05481    ast_atomic_fetchadd_int(&regobjs, -1);
05482    ast_dnsmgr_release(reg->dnsmgr);
05483    ast_free(reg);
05484 }
05485 
05486 /*! \brief Destroy MWI subscription object */
05487 static void sip_subscribe_mwi_destroy(struct sip_subscription_mwi *mwi)
05488 {
05489    if (mwi->call) {
05490       mwi->call->mwi = NULL;
05491       sip_destroy(mwi->call);
05492    }
05493    
05494    AST_SCHED_DEL(sched, mwi->resub);
05495    ast_string_field_free_memory(mwi);
05496    ast_dnsmgr_release(mwi->dnsmgr);
05497    ast_free(mwi);
05498 }
05499 
05500 /*! \brief Execute destruction of SIP dialog structure, release memory */
05501 static void __sip_destroy(struct sip_pvt *p, int lockowner, int lockdialoglist)
05502 {
05503    struct sip_request *req;
05504 
05505    if (p->stimer) {
05506       ast_free(p->stimer);
05507       p->stimer = NULL;
05508    }
05509 
05510    if (sip_debug_test_pvt(p))
05511       ast_verbose("Really destroying SIP dialog '%s' Method: %s\n", p->callid, sip_methods[p->method].text);
05512 
05513    if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
05514       update_call_counter(p, DEC_CALL_LIMIT);
05515       ast_debug(2, "This call did not properly clean up call limits. Call ID %s\n", p->callid);
05516    }
05517 
05518    /* Unlink us from the owner if we have one */
05519    if (p->owner) {
05520       if (lockowner)
05521          ast_channel_lock(p->owner);
05522       if (option_debug)
05523          ast_log(LOG_DEBUG, "Detaching from %s\n", p->owner->name);
05524       p->owner->tech_pvt = NULL;
05525       /* Make sure that the channel knows its backend is going away */
05526       p->owner->_softhangup |= AST_SOFTHANGUP_DEV;
05527       if (lockowner)
05528          ast_channel_unlock(p->owner);
05529       /* Give the channel a chance to react before deallocation */
05530       usleep(1);
05531    }
05532 
05533    /* Remove link from peer to subscription of MWI */
05534    if (p->relatedpeer && p->relatedpeer->mwipvt)
05535       p->relatedpeer->mwipvt = dialog_unref(p->relatedpeer->mwipvt, "delete ->relatedpeer->mwipvt");
05536    if (p->relatedpeer && p->relatedpeer->call == p)
05537       p->relatedpeer->call = dialog_unref(p->relatedpeer->call, "unset the relatedpeer->call field in tandem with relatedpeer field itself");
05538    
05539    if (p->relatedpeer)
05540       p->relatedpeer = unref_peer(p->relatedpeer,"unsetting a dialog relatedpeer field in sip_destroy");
05541    
05542    if (p->registry) {
05543       if (p->registry->call == p)
05544          p->registry->call = dialog_unref(p->registry->call, "nulling out the registry's call dialog field in unlink_all");
05545       p->registry = registry_unref(p->registry, "delete p->registry");
05546    }
05547    
05548    if (p->mwi) {
05549       p->mwi->call = NULL;
05550    }
05551 
05552    if (dumphistory)
05553       sip_dump_history(p);
05554 
05555    if (p->options)
05556       ast_free(p->options);
05557 
05558    if (p->notify_headers) {
05559       ast_variables_destroy(p->notify_headers);
05560       p->notify_headers = NULL;
05561    }
05562    if (p->rtp) {
05563       ast_rtp_destroy(p->rtp);
05564    }
05565    if (p->vrtp) {
05566       ast_rtp_destroy(p->vrtp);
05567    }
05568    if (p->trtp) {
05569       while (ast_rtp_get_bridged(p->trtp))
05570          usleep(1);
05571       ast_rtp_destroy(p->trtp);
05572    }
05573    if (p->udptl)
05574       ast_udptl_destroy(p->udptl);
05575    if (p->refer)
05576       ast_free(p->refer);
05577    if (p->route) {
05578       free_old_route(p->route);
05579       p->route = NULL;
05580    }
05581    if (p->initreq.data)
05582       ast_free(p->initreq.data);
05583 
05584    /* Destroy Session-Timers if allocated */
05585    if (p->stimer) {
05586       p->stimer->quit_flag = 1;
05587       if (p->stimer->st_active == TRUE && p->stimer->st_schedid > -1) {
05588          AST_SCHED_DEL_UNREF(sched, p->stimer->st_schedid,
05589                dialog_unref(p, "removing session timer ref"));
05590       }
05591       ast_free(p->stimer);
05592       p->stimer = NULL;
05593    }
05594 
05595    /* Clear history */
05596    if (p->history) {
05597       struct sip_history *hist;
05598       while ( (hist = AST_LIST_REMOVE_HEAD(p->history, list)) ) {
05599          ast_free(hist);
05600          p->history_entries--;
05601       }
05602       ast_free(p->history);
05603       p->history = NULL;
05604    }
05605 
05606    while ((req = AST_LIST_REMOVE_HEAD(&p->request_queue, next))) {
05607       ast_free(req);
05608    }
05609 
05610    if (p->chanvars) {
05611       ast_variables_destroy(p->chanvars);
05612       p->chanvars = NULL;
05613    }
05614 
05615    ast_string_field_free_memory(p);
05616 
05617    if (p->socket.tcptls_session) {
05618       ao2_ref(p->socket.tcptls_session, -1);
05619       p->socket.tcptls_session = NULL;
05620    }
05621 }
05622 
05623 /*! \brief  update_call_counter: Handle call_limit for SIP devices
05624  * Setting a call-limit will cause calls above the limit not to be accepted.
05625  *
05626  * Remember that for a type=friend, there's one limit for the user and
05627  * another for the peer, not a combined call limit.
05628  * This will cause unexpected behaviour in subscriptions, since a "friend"
05629  * is *two* devices in Asterisk, not one.
05630  *
05631  * Thought: For realtime, we should probably update storage with inuse counter... 
05632  *
05633  * \return 0 if call is ok (no call limit, below threshold)
05634  * -1 on rejection of call
05635  *    
05636  */
05637 static int update_call_counter(struct sip_pvt *fup, int event)
05638 {
05639    char name[256];
05640    int *inuse = NULL, *call_limit = NULL, *inringing = NULL;
05641    int outgoing = fup->outgoing_call;
05642    struct sip_peer *p = NULL;
05643 
05644    ast_debug(3, "Updating call counter for %s call\n", outgoing ? "outgoing" : "incoming");
05645 
05646 
05647    /* Test if we need to check call limits, in order to avoid 
05648       realtime lookups if we do not need it */
05649    if (!ast_test_flag(&fup->flags[0], SIP_CALL_LIMIT) && !ast_test_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD))
05650       return 0;
05651 
05652    ast_copy_string(name, fup->username, sizeof(name));
05653 
05654    /* Check the list of devices */
05655    if ((p = find_peer(ast_strlen_zero(fup->peername) ? name : fup->peername, NULL, TRUE, FINDALLDEVICES, FALSE, 0))) { 
05656       inuse = &p->inUse;
05657       call_limit = &p->call_limit;
05658       inringing = &p->inRinging;
05659       ast_copy_string(name, fup->peername, sizeof(name));
05660    }
05661    if (!p) {
05662       ast_debug(2, "%s is not a local device, no call limit\n", name);
05663       return 0;
05664    }
05665 
05666    switch(event) {
05667    /* incoming and outgoing affects the inUse counter */
05668    case DEC_CALL_LIMIT:
05669       /* Decrement inuse count if applicable */
05670       if (inuse) {
05671          sip_pvt_lock(fup);
05672          ao2_lock(p);
05673          if (*inuse > 0) {
05674             if (ast_test_flag(&fup->flags[0], SIP_INC_COUNT)) {
05675                (*inuse)--;
05676                ast_clear_flag(&fup->flags[0], SIP_INC_COUNT);
05677             }
05678          } else {
05679             *inuse = 0;
05680          }
05681          ao2_unlock(p);
05682          sip_pvt_unlock(fup);
05683       }
05684 
05685       /* Decrement ringing count if applicable */
05686       if (inringing) {
05687          sip_pvt_lock(fup);
05688          ao2_lock(p);
05689          if (*inringing > 0) {
05690             if (ast_test_flag(&fup->flags[0], SIP_INC_RINGING)) {
05691                (*inringing)--;
05692                ast_clear_flag(&fup->flags[0], SIP_INC_RINGING);
05693             }
05694          } else {
05695             *inringing = 0;
05696          }
05697          ao2_unlock(p);
05698          sip_pvt_unlock(fup);
05699       }
05700 
05701       /* Decrement onhold count if applicable */
05702       sip_pvt_lock(fup);
05703       ao2_lock(p);
05704       if (ast_test_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD) && sip_cfg.notifyhold) {
05705          ast_clear_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD);
05706          ao2_unlock(p);
05707          sip_pvt_unlock(fup);
05708          sip_peer_hold(fup, FALSE);
05709       } else {
05710          ao2_unlock(p);
05711          sip_pvt_unlock(fup);
05712       }
05713       if (sipdebug)
05714          ast_debug(2, "Call %s %s '%s' removed from call limit %d\n", outgoing ? "to" : "from", "peer", name, *call_limit);
05715       break;
05716 
05717    case INC_CALL_RINGING:
05718    case INC_CALL_LIMIT:
05719       /* If call limit is active and we have reached the limit, reject the call */
05720       if (*call_limit > 0 ) {
05721          if (*inuse >= *call_limit) {
05722             ast_log(LOG_NOTICE, "Call %s %s '%s' rejected due to usage limit of %d\n", outgoing ? "to" : "from", "peer", name, *call_limit);
05723             unref_peer(p, "update_call_counter: unref peer p, call limit exceeded");
05724             return -1; 
05725          }
05726       }
05727       if (inringing && (event == INC_CALL_RINGING)) {
05728          sip_pvt_lock(fup);
05729          ao2_lock(p);
05730          if (!ast_test_flag(&fup->flags[0], SIP_INC_RINGING)) {
05731             (*inringing)++;
05732             ast_set_flag(&fup->flags[0], SIP_INC_RINGING);
05733          }
05734          ao2_unlock(p);
05735          sip_pvt_unlock(fup);
05736       }
05737       if (inuse) {
05738          sip_pvt_lock(fup);
05739          ao2_lock(p);
05740          if (!ast_test_flag(&fup->flags[0], SIP_INC_COUNT)) {
05741             (*inuse)++;
05742             ast_set_flag(&fup->flags[0], SIP_INC_COUNT);
05743          }
05744          ao2_unlock(p);
05745          sip_pvt_unlock(fup);
05746       }
05747       if (sipdebug) {
05748          ast_debug(2, "Call %s %s '%s' is %d out of %d\n", outgoing ? "to" : "from", "peer", name, *inuse, *call_limit);
05749       }
05750       break;
05751 
05752    case DEC_CALL_RINGING:
05753       if (inringing) {
05754          sip_pvt_lock(fup);
05755          ao2_lock(p);
05756          if (ast_test_flag(&fup->flags[0], SIP_INC_RINGING)) {
05757             if (*inringing > 0) {
05758                (*inringing)--;
05759             }
05760             ast_clear_flag(&fup->flags[0], SIP_INC_RINGING);
05761          }
05762          ao2_unlock(p);
05763          sip_pvt_unlock(fup);
05764       }
05765       break;
05766 
05767    default:
05768       ast_log(LOG_ERROR, "update_call_counter(%s, %d) called with no event!\n", name, event);
05769    }
05770 
05771    if (p) {
05772       ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", p->name);
05773       unref_peer(p, "update_call_counter: unref_peer from call counter");
05774    } 
05775    return 0;
05776 }
05777 
05778 
05779 static void sip_destroy_fn(void *p)
05780 {
05781    sip_destroy(p);
05782 }
05783 
05784 /*! \brief Destroy SIP call structure.
05785  * Make it return NULL so the caller can do things like
05786  * foo = sip_destroy(foo);
05787  * and reduce the chance of bugs due to dangling pointers.
05788  */
05789 static struct sip_pvt * sip_destroy(struct sip_pvt *p)
05790 {
05791    ast_debug(3, "Destroying SIP dialog %s\n", p->callid);
05792    __sip_destroy(p, TRUE, TRUE);
05793    return NULL;
05794 }
05795 
05796 /*! \brief Convert SIP hangup causes to Asterisk hangup causes */
05797 static int hangup_sip2cause(int cause)
05798 {
05799    /* Possible values taken from causes.h */
05800 
05801    switch(cause) {
05802       case 401:   /* Unauthorized */
05803          return AST_CAUSE_CALL_REJECTED;
05804       case 403:   /* Not found */
05805          return AST_CAUSE_CALL_REJECTED;
05806       case 404:   /* Not found */
05807          return AST_CAUSE_UNALLOCATED;
05808       case 405:   /* Method not allowed */
05809          return AST_CAUSE_INTERWORKING;
05810       case 407:   /* Proxy authentication required */
05811          return AST_CAUSE_CALL_REJECTED;
05812       case 408:   /* No reaction */
05813          return AST_CAUSE_NO_USER_RESPONSE;
05814       case 409:   /* Conflict */
05815          return AST_CAUSE_NORMAL_TEMPORARY_FAILURE;
05816       case 410:   /* Gone */
05817          return AST_CAUSE_NUMBER_CHANGED;
05818       case 411:   /* Length required */
05819          return AST_CAUSE_INTERWORKING;
05820       case 413:   /* Request entity too large */
05821          return AST_CAUSE_INTERWORKING;
05822       case 414:   /* Request URI too large */
05823          return AST_CAUSE_INTERWORKING;
05824       case 415:   /* Unsupported media type */
05825          return AST_CAUSE_INTERWORKING;
05826       case 420:   /* Bad extension */
05827          return AST_CAUSE_NO_ROUTE_DESTINATION;
05828       case 480:   /* No answer */
05829          return AST_CAUSE_NO_ANSWER;
05830       case 481:   /* No answer */
05831          return AST_CAUSE_INTERWORKING;
05832       case 482:   /* Loop detected */
05833          return AST_CAUSE_INTERWORKING;
05834       case 483:   /* Too many hops */
05835          return AST_CAUSE_NO_ANSWER;
05836       case 484:   /* Address incomplete */
05837          return AST_CAUSE_INVALID_NUMBER_FORMAT;
05838       case 485:   /* Ambiguous */
05839          return AST_CAUSE_UNALLOCATED;
05840       case 486:   /* Busy everywhere */
05841          return AST_CAUSE_BUSY;
05842       case 487:   /* Request terminated */
05843          return AST_CAUSE_INTERWORKING;
05844       case 488:   /* No codecs approved */
05845          return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
05846       case 491:   /* Request pending */
05847          return AST_CAUSE_INTERWORKING;
05848       case 493:   /* Undecipherable */
05849          return AST_CAUSE_INTERWORKING;
05850       case 500:   /* Server internal failure */
05851          return AST_CAUSE_FAILURE;
05852       case 501:   /* Call rejected */
05853          return AST_CAUSE_FACILITY_REJECTED;
05854       case 502:   
05855          return AST_CAUSE_DESTINATION_OUT_OF_ORDER;
05856       case 503:   /* Service unavailable */
05857          return AST_CAUSE_CONGESTION;
05858       case 504:   /* Gateway timeout */
05859          return AST_CAUSE_RECOVERY_ON_TIMER_EXPIRE;
05860       case 505:   /* SIP version not supported */
05861          return AST_CAUSE_INTERWORKING;
05862       case 600:   /* Busy everywhere */
05863          return AST_CAUSE_USER_BUSY;
05864       case 603:   /* Decline */
05865          return AST_CAUSE_CALL_REJECTED;
05866       case 604:   /* Does not exist anywhere */
05867          return AST_CAUSE_UNALLOCATED;
05868       case 606:   /* Not acceptable */
05869          return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
05870       default:
05871          return AST_CAUSE_NORMAL;
05872    }
05873    /* Never reached */
05874    return 0;
05875 }
05876 
05877 /*! \brief Convert Asterisk hangup causes to SIP codes 
05878 \verbatim
05879  Possible values from causes.h
05880         AST_CAUSE_NOTDEFINED    AST_CAUSE_NORMAL        AST_CAUSE_BUSY
05881         AST_CAUSE_FAILURE       AST_CAUSE_CONGESTION    AST_CAUSE_UNALLOCATED
05882 
05883    In addition to these, a lot of PRI codes is defined in causes.h 
05884    ...should we take care of them too ?
05885    
05886    Quote RFC 3398
05887 
05888    ISUP Cause value                        SIP response
05889    ----------------                        ------------
05890    1  unallocated number                   404 Not Found
05891    2  no route to network                  404 Not found
05892    3  no route to destination              404 Not found
05893    16 normal call clearing                 --- (*)
05894    17 user busy                            486 Busy here
05895    18 no user responding                   408 Request Timeout
05896    19 no answer from the user              480 Temporarily unavailable
05897    20 subscriber absent                    480 Temporarily unavailable
05898    21 call rejected                        403 Forbidden (+)
05899    22 number changed (w/o diagnostic)      410 Gone
05900    22 number changed (w/ diagnostic)       301 Moved Permanently
05901    23 redirection to new destination       410 Gone
05902    26 non-selected user clearing           404 Not Found (=)
05903    27 destination out of order             502 Bad Gateway
05904    28 address incomplete                   484 Address incomplete
05905    29 facility rejected                    501 Not implemented
05906    31 normal unspecified                   480 Temporarily unavailable
05907 \endverbatim
05908 */
05909 static const char *hangup_cause2sip(int cause)
05910 {
05911    switch (cause) {
05912       case AST_CAUSE_UNALLOCATED:      /* 1 */
05913       case AST_CAUSE_NO_ROUTE_DESTINATION:   /* 3 IAX2: Can't find extension in context */
05914       case AST_CAUSE_NO_ROUTE_TRANSIT_NET:   /* 2 */
05915          return "404 Not Found";
05916       case AST_CAUSE_CONGESTION:    /* 34 */
05917       case AST_CAUSE_SWITCH_CONGESTION:   /* 42 */
05918          return "503 Service Unavailable";
05919       case AST_CAUSE_NO_USER_RESPONSE: /* 18 */
05920          return "408 Request Timeout";
05921       case AST_CAUSE_NO_ANSWER:     /* 19 */
05922       case AST_CAUSE_UNREGISTERED:        /* 20 */
05923          return "480 Temporarily unavailable";
05924       case AST_CAUSE_CALL_REJECTED:    /* 21 */
05925          return "403 Forbidden";
05926       case AST_CAUSE_NUMBER_CHANGED:      /* 22 */
05927          return "410 Gone";
05928       case AST_CAUSE_NORMAL_UNSPECIFIED:  /* 31 */
05929          return "480 Temporarily unavailable";
05930       case AST_CAUSE_INVALID_NUMBER_FORMAT:
05931          return "484 Address incomplete";
05932       case AST_CAUSE_USER_BUSY:
05933          return "486 Busy here";
05934       case AST_CAUSE_FAILURE:
05935          return "500 Server internal failure";
05936       case AST_CAUSE_FACILITY_REJECTED:   /* 29 */
05937          return "501 Not Implemented";
05938       case AST_CAUSE_CHAN_NOT_IMPLEMENTED:
05939          return "503 Service Unavailable";
05940       /* Used in chan_iax2 */
05941       case AST_CAUSE_DESTINATION_OUT_OF_ORDER:
05942          return "502 Bad Gateway";
05943       case AST_CAUSE_BEARERCAPABILITY_NOTAVAIL: /* Can't find codec to connect to host */
05944          return "488 Not Acceptable Here";
05945          
05946       case AST_CAUSE_NOTDEFINED:
05947       default:
05948          ast_debug(1, "AST hangup cause %d (no match found in SIP)\n", cause);
05949          return NULL;
05950    }
05951 
05952    /* Never reached */
05953    return 0;
05954 }
05955 
05956 
05957 /*! \brief  sip_hangup: Hangup SIP call
05958  * Part of PBX interface, called from ast_hangup */
05959 static int sip_hangup(struct ast_channel *ast)
05960 {
05961    struct sip_pvt *p = ast->tech_pvt;
05962    int needcancel = FALSE;
05963    int needdestroy = 0;
05964    struct ast_channel *oldowner = ast;
05965 
05966    if (!p) {
05967       ast_debug(1, "Asked to hangup channel that was not connected\n");
05968       return 0;
05969    }
05970    if (ast_test_flag(ast, AST_FLAG_ANSWERED_ELSEWHERE) || ast->hangupcause == AST_CAUSE_ANSWERED_ELSEWHERE) {
05971       ast_debug(1, "This call was answered elsewhere");
05972       if (ast->hangupcause == AST_CAUSE_ANSWERED_ELSEWHERE) {
05973          ast_debug(1, "####### It's the cause code, buddy. The cause code!!!\n");
05974       }
05975       append_history(p, "Cancel", "Call answered elsewhere");
05976       p->answered_elsewhere = TRUE;
05977    }
05978 
05979    /* Store hangupcause locally in PVT so we still have it before disconnect */
05980    if (p->owner)
05981       p->hangupcause = p->owner->hangupcause;
05982 
05983    if (ast_test_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER)) {
05984       if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
05985          if (sipdebug)
05986             ast_debug(1, "update_call_counter(%s) - decrement call limit counter on hangup\n", p->username);
05987          update_call_counter(p, DEC_CALL_LIMIT);
05988       }
05989       ast_debug(4, "SIP Transfer: Not hanging up right now... Rescheduling hangup for %s.\n", p->callid);
05990       if (p->autokillid > -1 && sip_cancel_destroy(p))
05991          ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
05992       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
05993       ast_clear_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER); /* Really hang up next time */
05994       p->needdestroy = 0;
05995       p->owner->tech_pvt = dialog_unref(p->owner->tech_pvt, "unref p->owner->tech_pvt");
05996       sip_pvt_lock(p);
05997       p->owner = NULL;  /* Owner will be gone after we return, so take it away */
05998       sip_pvt_unlock(p);
05999       return 0;
06000    }
06001 
06002    if (ast_test_flag(ast, AST_FLAG_ZOMBIE)) {
06003       if (p->refer)
06004          ast_debug(1, "SIP Transfer: Hanging up Zombie channel %s after transfer ... Call-ID: %s\n", ast->name, p->callid);
06005       else
06006          ast_debug(1, "Hanging up zombie call. Be scared.\n");
06007    } else
06008       ast_debug(1, "Hangup call %s, SIP callid %s\n", ast->name, p->callid);
06009 
06010    sip_pvt_lock(p);
06011    if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
06012       if (sipdebug)
06013          ast_debug(1, "update_call_counter(%s) - decrement call limit counter on hangup\n", p->username);
06014       update_call_counter(p, DEC_CALL_LIMIT);
06015    }
06016 
06017    /* Determine how to disconnect */
06018    if (p->owner != ast) {
06019       ast_log(LOG_WARNING, "Huh?  We aren't the owner? Can't hangup call.\n");
06020       sip_pvt_unlock(p);
06021       return 0;
06022    }
06023    /* If the call is not UP, we need to send CANCEL instead of BYE */
06024    /* In case of re-invites, the call might be UP even though we have an incomplete invite transaction */
06025    if (p->invitestate < INV_COMPLETED && p->owner->_state != AST_STATE_UP) {
06026       needcancel = TRUE;
06027       ast_debug(4, "Hanging up channel in state %s (not UP)\n", ast_state2str(ast->_state));
06028    }
06029 
06030    stop_media_flows(p); /* Immediately stop RTP, VRTP and UDPTL as applicable */
06031 
06032    append_history(p, needcancel ? "Cancel" : "Hangup", "Cause %s", p->owner ? ast_cause2str(p->hangupcause) : "Unknown");
06033 
06034    /* Disconnect */
06035    if (p->dsp)
06036       ast_dsp_free(p->dsp);
06037 
06038    p->owner = NULL;
06039    ast->tech_pvt = dialog_unref(ast->tech_pvt, "unref ast->tech_pvt");
06040 
06041    ast_module_unref(ast_module_info->self);
06042    /* Do not destroy this pvt until we have timeout or
06043       get an answer to the BYE or INVITE/CANCEL 
06044       If we get no answer during retransmit period, drop the call anyway.
06045       (Sorry, mother-in-law, you can't deny a hangup by sending
06046       603 declined to BYE...)
06047    */
06048    if (p->alreadygone)
06049       needdestroy = 1;  /* Set destroy flag at end of this function */
06050    else if (p->invitestate != INV_CALLING)
06051       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
06052 
06053    /* Start the process if it's not already started */
06054    if (!p->alreadygone && p->initreq.data && !ast_strlen_zero(p->initreq.data->str)) {
06055       if (needcancel) { /* Outgoing call, not up */
06056          if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06057             /* stop retransmitting an INVITE that has not received a response */
06058             /* if we can't send right now, mark it pending */
06059             if (p->invitestate == INV_CALLING) {
06060                /* We can't send anything in CALLING state */
06061                ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
06062                __sip_pretend_ack(p);
06063                /* 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. */
06064                sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
06065                append_history(p, "DELAY", "Not sending cancel, waiting for timeout");
06066             } else {
06067                struct sip_pkt *cur;
06068 
06069                for (cur = p->packets; cur; cur = cur->next) {
06070                   __sip_semi_ack(p, cur->seqno, cur->is_resp, cur->method ? cur->method : find_sip_method(cur->data->str));
06071                }
06072                p->invitestate = INV_CANCELLED;
06073                /* Send a new request: CANCEL */
06074                transmit_request(p, SIP_CANCEL, p->lastinvite, XMIT_RELIABLE, FALSE);
06075                /* Actually don't destroy us yet, wait for the 487 on our original 
06076                   INVITE, but do set an autodestruct just in case we never get it. */
06077                needdestroy = 0;
06078                sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
06079             }
06080          } else { /* Incoming call, not up */
06081             const char *res;
06082             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"));
06083             if (p->hangupcause && (res = hangup_cause2sip(p->hangupcause)))
06084                transmit_response_reliable(p, res, &p->initreq);
06085             else 
06086                transmit_response_reliable(p, "603 Declined", &p->initreq);
06087             p->invitestate = INV_TERMINATED;
06088          }
06089       } else { /* Call is in UP state, send BYE */
06090          if (p->stimer->st_active == TRUE) {
06091             stop_session_timer(p);
06092          }
06093 
06094          if (!p->pendinginvite) {
06095             struct ast_channel *bridge = ast_bridged_channel(oldowner);
06096             char *audioqos = "";
06097             char *videoqos = "";
06098             char *textqos = "";
06099 
06100             /* We need to get the lock on bridge because ast_rtp_set_vars will attempt
06101              * to lock the bridge. This may get hairy...
06102              */
06103             while (bridge && ast_channel_trylock(bridge)) {
06104                sip_pvt_unlock(p);
06105                do {
06106                   /* Use oldowner since p->owner is already NULL */
06107                   CHANNEL_DEADLOCK_AVOIDANCE(oldowner);
06108                } while (sip_pvt_trylock(p));
06109                bridge = ast_bridged_channel(oldowner);
06110             }
06111 
06112             if (p->rtp)
06113                ast_rtp_set_vars(oldowner, p->rtp);
06114 
06115             if (bridge) {
06116                struct sip_pvt *q = bridge->tech_pvt;
06117 
06118                if (IS_SIP_TECH(bridge->tech) && q && q->rtp)
06119                   ast_rtp_set_vars(bridge, q->rtp);
06120                ast_channel_unlock(bridge);
06121             }
06122 
06123             if (p->vrtp)
06124                videoqos = ast_rtp_get_quality(p->vrtp, NULL, RTPQOS_SUMMARY);
06125             if (p->trtp)
06126                textqos = ast_rtp_get_quality(p->trtp, NULL, RTPQOS_SUMMARY);
06127             /* Send a hangup */
06128             if (oldowner->_state == AST_STATE_UP) {
06129                transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
06130             }
06131 
06132             /* Get RTCP quality before end of call */
06133             if (p->do_history) {
06134                if (p->rtp)
06135                   append_history(p, "RTCPaudio", "Quality:%s", audioqos);
06136                if (p->vrtp)
06137                   append_history(p, "RTCPvideo", "Quality:%s", videoqos);
06138                if (p->trtp)
06139                   append_history(p, "RTCPtext", "Quality:%s", textqos);
06140             }
06141             if (p->rtp && oldowner)
06142                pbx_builtin_setvar_helper(oldowner, "RTPAUDIOQOS", audioqos);
06143             if (p->vrtp && oldowner)
06144                pbx_builtin_setvar_helper(oldowner, "RTPVIDEOQOS", videoqos);
06145             if (p->trtp && oldowner)
06146                pbx_builtin_setvar_helper(oldowner, "RTPTEXTQOS", textqos);
06147          } else {
06148             /* Note we will need a BYE when this all settles out
06149                but we can't send one while we have "INVITE" outstanding. */
06150             ast_set_flag(&p->flags[0], SIP_PENDINGBYE);  
06151             ast_clear_flag(&p->flags[0], SIP_NEEDREINVITE); 
06152             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"));
06153             if (sip_cancel_destroy(p))
06154                ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
06155          }
06156       }
06157    }
06158    if (needdestroy) {
06159       pvt_set_needdestroy(p, "hangup");
06160    }
06161    sip_pvt_unlock(p);
06162    return 0;
06163 }
06164 
06165 /*! \brief Try setting codec suggested by the SIP_CODEC channel variable */
06166 static void try_suggested_sip_codec(struct sip_pvt *p)
06167 {
06168    int fmt;
06169    const char *codec;
06170 
06171    codec = pbx_builtin_getvar_helper(p->owner, "SIP_CODEC");
06172    if (!codec) 
06173       return;
06174 
06175    fmt = ast_getformatbyname(codec);
06176    if (fmt) {
06177       ast_log(LOG_NOTICE, "Changing codec to '%s' for this call because of ${SIP_CODEC} variable\n", codec);
06178       if (p->jointcapability & fmt) {
06179          p->jointcapability &= fmt;
06180          p->capability &= fmt;
06181       } else
06182          ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because it is not shared by both ends.\n");
06183    } else
06184       ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because of unrecognized/not configured codec (check allow/disallow in sip.conf): %s\n", codec);
06185    return;  
06186 }
06187 
06188 /*! \brief  sip_answer: Answer SIP call , send 200 OK on Invite 
06189  * Part of PBX interface */
06190 static int sip_answer(struct ast_channel *ast)
06191 {
06192    int res = 0;
06193    struct sip_pvt *p = ast->tech_pvt;
06194 
06195    sip_pvt_lock(p);
06196    if (ast->_state != AST_STATE_UP) {
06197       try_suggested_sip_codec(p);   
06198 
06199       ast_setstate(ast, AST_STATE_UP);
06200       ast_debug(1, "SIP answering channel: %s\n", ast->name);
06201       ast_rtp_new_source(p->rtp);
06202       res = transmit_response_with_sdp(p, "200 OK", &p->initreq, XMIT_CRITICAL, FALSE);
06203       ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
06204    }
06205    sip_pvt_unlock(p);
06206    return res;
06207 }
06208 
06209 /*! \brief Send frame to media channel (rtp) */
06210 static int sip_write(struct ast_channel *ast, struct ast_frame *frame)
06211 {
06212    struct sip_pvt *p = ast->tech_pvt;
06213    int res = 0;
06214 
06215    switch (frame->frametype) {
06216    case AST_FRAME_VOICE:
06217       if (!(frame->subclass & ast->nativeformats)) {
06218          char s1[512], s2[512], s3[512];
06219          ast_log(LOG_WARNING, "Asked to transmit frame type %d, while native formats is %s(%d) read/write = %s(%d)/%s(%d)\n",
06220             frame->subclass, 
06221             ast_getformatname_multiple(s1, sizeof(s1) - 1, ast->nativeformats & AST_FORMAT_AUDIO_MASK),
06222             ast->nativeformats & AST_FORMAT_AUDIO_MASK,
06223             ast_getformatname_multiple(s2, sizeof(s2) - 1, ast->readformat),
06224             ast->readformat,
06225             ast_getformatname_multiple(s3, sizeof(s3) - 1, ast->writeformat),
06226             ast->writeformat);
06227          return 0;
06228       }
06229       if (p) {
06230          sip_pvt_lock(p);
06231          if (p->rtp) {
06232             /* If channel is not up, activate early media session */
06233             if ((ast->_state != AST_STATE_UP) &&
06234                 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
06235                 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06236                ast_rtp_new_source(p->rtp);
06237                if (!global_prematuremediafilter) {
06238                   p->invitestate = INV_EARLY_MEDIA;
06239                   transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
06240                   ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
06241                }
06242             } else if (p->t38.state == T38_ENABLED) {
06243                /* drop frame, can't sent VOICE frames while in T.38 mode */
06244             } else {
06245                p->lastrtptx = time(NULL);
06246                res = ast_rtp_write(p->rtp, frame);
06247             }
06248          }
06249          sip_pvt_unlock(p);
06250       }
06251       break;
06252    case AST_FRAME_VIDEO:
06253       if (p) {
06254          sip_pvt_lock(p);
06255          if (p->vrtp) {
06256             /* Activate video early media */
06257             if ((ast->_state != AST_STATE_UP) &&
06258                 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
06259                 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06260                p->invitestate = INV_EARLY_MEDIA;
06261                transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
06262                ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
06263             }
06264             p->lastrtptx = time(NULL);
06265             res = ast_rtp_write(p->vrtp, frame);
06266          }
06267          sip_pvt_unlock(p);
06268       }
06269       break;
06270    case AST_FRAME_TEXT:
06271       if (p) {
06272          sip_pvt_lock(p);
06273          if (p->red) {
06274             red_buffer_t140(p->trtp, frame);
06275          } else {
06276             if (p->trtp) {
06277                /* Activate text early media */
06278                if ((ast->_state != AST_STATE_UP) &&
06279                    !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
06280                    !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06281                   p->invitestate = INV_EARLY_MEDIA;
06282                   transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
06283                   ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
06284                }
06285                p->lastrtptx = time(NULL);
06286                res = ast_rtp_write(p->trtp, frame);
06287             }
06288          }
06289          sip_pvt_unlock(p);
06290       }
06291       break;
06292    case AST_FRAME_IMAGE:
06293       return 0;
06294       break;
06295    case AST_FRAME_MODEM:
06296       if (p) {
06297          sip_pvt_lock(p);
06298          /* UDPTL requires two-way communication, so early media is not needed here.
06299             we simply forget the frames if we get modem frames before the bridge is up.
06300             Fax will re-transmit.
06301          */
06302          if ((ast->_state == AST_STATE_UP) &&
06303              p->udptl &&
06304              (p->t38.state == T38_ENABLED)) {
06305             res = ast_udptl_write(p->udptl, frame);
06306          }
06307          sip_pvt_unlock(p);
06308       }
06309       break;
06310    default: 
06311       ast_log(LOG_WARNING, "Can't send %d type frames with SIP write\n", frame->frametype);
06312       return 0;
06313    }
06314 
06315    return res;
06316 }
06317 
06318 /*! \brief  sip_fixup: Fix up a channel:  If a channel is consumed, this is called.
06319         Basically update any ->owner links */
06320 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
06321 {
06322    int ret = -1;
06323    struct sip_pvt *p;
06324 
06325    if (newchan && ast_test_flag(newchan, AST_FLAG_ZOMBIE))
06326       ast_debug(1, "New channel is zombie\n");
06327    if (oldchan && ast_test_flag(oldchan, AST_FLAG_ZOMBIE))
06328       ast_debug(1, "Old channel is zombie\n");
06329 
06330    if (!newchan || !newchan->tech_pvt) {
06331       if (!newchan)
06332          ast_log(LOG_WARNING, "No new channel! Fixup of %s failed.\n", oldchan->name);
06333       else
06334          ast_log(LOG_WARNING, "No SIP tech_pvt! Fixup of %s failed.\n", oldchan->name);
06335       return -1;
06336    }
06337    p = newchan->tech_pvt;
06338 
06339    sip_pvt_lock(p);
06340    append_history(p, "Masq", "Old channel: %s\n", oldchan->name);
06341    append_history(p, "Masq (cont)", "...new owner: %s\n", newchan->name);
06342    if (p->owner != oldchan)
06343       ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, p->owner);
06344    else {
06345       p->owner = newchan;
06346       /* Re-invite RTP back to Asterisk. Needed if channel is masqueraded out of a native
06347          RTP bridge (i.e., RTP not going through Asterisk): RTP bridge code might not be
06348          able to do this if the masquerade happens before the bridge breaks (e.g., AMI
06349          redirect of both channels). Note that a channel can not be masqueraded *into*
06350          a native bridge. So there is no danger that this breaks a native bridge that
06351          should stay up. */
06352       sip_set_rtp_peer(newchan, NULL, NULL, 0, 0, 0);
06353       ret = 0;
06354    }
06355    ast_debug(3, "SIP Fixup: New owner for dialogue %s: %s (Old parent: %s)\n", p->callid, p->owner->name, oldchan->name);
06356 
06357    sip_pvt_unlock(p);
06358    return ret;
06359 }
06360 
06361 static int sip_senddigit_begin(struct ast_channel *ast, char digit)
06362 {
06363    struct sip_pvt *p = ast->tech_pvt;
06364    int res = 0;
06365 
06366    sip_pvt_lock(p);
06367    switch (ast_test_flag(&p->flags[0], SIP_DTMF)) {
06368    case SIP_DTMF_INBAND:
06369       res = -1; /* Tell Asterisk to generate inband indications */
06370       break;
06371    case SIP_DTMF_RFC2833:
06372       if (p->rtp)
06373          ast_rtp_senddigit_begin(p->rtp, digit);
06374       break;
06375    default:
06376       break;
06377    }
06378    sip_pvt_unlock(p);
06379 
06380    return res;
06381 }
06382 
06383 /*! \brief Send DTMF character on SIP channel
06384    within one call, we're able to transmit in many methods simultaneously */
06385 static int sip_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration)
06386 {
06387    struct sip_pvt *p = ast->tech_pvt;
06388    int res = 0;
06389 
06390    sip_pvt_lock(p);
06391    switch (ast_test_flag(&p->flags[0], SIP_DTMF)) {
06392    case SIP_DTMF_INFO:
06393    case SIP_DTMF_SHORTINFO:
06394       transmit_info_with_digit(p, digit, duration);
06395       break;
06396    case SIP_DTMF_RFC2833:
06397       if (p->rtp)
06398          ast_rtp_senddigit_end(p->rtp, digit);
06399       break;
06400    case SIP_DTMF_INBAND:
06401       res = -1; /* Tell Asterisk to stop inband indications */
06402       break;
06403    }
06404    sip_pvt_unlock(p);
06405 
06406    return res;
06407 }
06408 
06409 /*! \brief Transfer SIP call */
06410 static int sip_transfer(struct ast_channel *ast, const char *dest)
06411 {
06412    struct sip_pvt *p = ast->tech_pvt;
06413    int res;
06414 
06415    if (dest == NULL) /* functions below do not take a NULL */
06416       dest = "";
06417    sip_pvt_lock(p);
06418    if (ast->_state == AST_STATE_RING)
06419       res = sip_sipredirect(p, dest);
06420    else
06421       res = transmit_refer(p, dest);
06422    sip_pvt_unlock(p);
06423    return res;
06424 }
06425 
06426 /*! \brief Helper function which updates T.38 capability information and triggers a reinvite */
06427 static int interpret_t38_parameters(struct sip_pvt *p, const struct ast_control_t38_parameters *parameters)
06428 {
06429    int res = 0;
06430 
06431    if (!ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT)) {
06432       return -1;
06433    }
06434    switch (parameters->request_response) {
06435    case AST_T38_NEGOTIATED:
06436    case AST_T38_REQUEST_NEGOTIATE:         /* Request T38 */
06437       /* Negotiation can not take place without a valid max_ifp value. */
06438       if (!parameters->max_ifp) {
06439          change_t38_state(p, T38_DISABLED);
06440          if (p->t38.state == T38_PEER_REINVITE) {
06441             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"));
06442             transmit_response_reliable(p, "488 Not acceptable here", &p->initreq);
06443          }
06444          break;
06445       } else if (p->t38.state == T38_PEER_REINVITE) {
06446          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"));
06447          p->t38.our_parms = *parameters;
06448          /* modify our parameters to conform to the peer's parameters,
06449           * based on the rules in the ITU T.38 recommendation
06450           */
06451          if (!p->t38.their_parms.fill_bit_removal) {
06452             p->t38.our_parms.fill_bit_removal = FALSE;
06453          }
06454          if (!p->t38.their_parms.transcoding_mmr) {
06455             p->t38.our_parms.transcoding_mmr = FALSE;
06456          }
06457          if (!p->t38.their_parms.transcoding_jbig) {
06458             p->t38.our_parms.transcoding_jbig = FALSE;
06459          }
06460          p->t38.our_parms.version = MIN(p->t38.our_parms.version, p->t38.their_parms.version);
06461          p->t38.our_parms.rate_management = p->t38.their_parms.rate_management;
06462          ast_udptl_set_local_max_ifp(p->udptl, p->t38.our_parms.max_ifp);
06463          change_t38_state(p, T38_ENABLED);
06464          transmit_response_with_t38_sdp(p, "200 OK", &p->initreq, XMIT_CRITICAL);
06465       } else if (p->t38.state != T38_ENABLED) {
06466          p->t38.our_parms = *parameters;
06467          ast_udptl_set_local_max_ifp(p->udptl, p->t38.our_parms.max_ifp);
06468          change_t38_state(p, T38_LOCAL_REINVITE);
06469          if (!p->pendinginvite) {
06470             transmit_reinvite_with_sdp(p, TRUE, FALSE);
06471          } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
06472             ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
06473          }
06474       }
06475       break;
06476    case AST_T38_TERMINATED:
06477    case AST_T38_REFUSED:
06478    case AST_T38_REQUEST_TERMINATE:         /* Shutdown T38 */
06479       if (p->t38.state == T38_PEER_REINVITE) {
06480          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"));
06481          change_t38_state(p, T38_DISABLED);
06482          transmit_response_reliable(p, "488 Not acceptable here", &p->initreq);
06483       } else if (p->t38.state == T38_ENABLED)
06484          transmit_reinvite_with_sdp(p, FALSE, FALSE);
06485       break;
06486    case AST_T38_REQUEST_PARMS: {    /* Application wants remote's parameters re-sent */
06487       struct ast_control_t38_parameters parameters = p->t38.their_parms;
06488 
06489       if (p->t38.state == T38_PEER_REINVITE) {
06490          AST_SCHED_DEL(sched, p->t38id);
06491          parameters.max_ifp = ast_udptl_get_far_max_ifp(p->udptl);
06492          parameters.request_response = AST_T38_REQUEST_NEGOTIATE;
06493          ast_queue_control_data(p->owner, AST_CONTROL_T38_PARAMETERS, &parameters, sizeof(parameters));
06494          /* we need to return a positive value here, so that applications that
06495           * send this request can determine conclusively whether it was accepted or not...
06496           * older versions of chan_sip would just silently accept it and return zero.
06497           */
06498          res = AST_T38_REQUEST_PARMS;
06499       }
06500       break;
06501    }
06502    default:
06503       res = -1;
06504       break;
06505    }
06506 
06507    return res;
06508 }
06509 
06510 /*! \brief Play indication to user 
06511  * With SIP a lot of indications is sent as messages, letting the device play
06512    the indication - busy signal, congestion etc 
06513    \return -1 to force ast_indicate to send indication in audio, 0 if SIP can handle the indication by sending a message
06514 */
06515 static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen)
06516 {
06517    struct sip_pvt *p = ast->tech_pvt;
06518    int res = 0;
06519 
06520    sip_pvt_lock(p);
06521    switch(condition) {
06522    case AST_CONTROL_RINGING:
06523       if (ast->_state == AST_STATE_RING) {
06524          p->invitestate = INV_EARLY_MEDIA;
06525          if (!ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) ||
06526              (ast_test_flag(&p->flags[0], SIP_PROG_INBAND) == SIP_PROG_INBAND_NEVER)) {            
06527             /* Send 180 ringing if out-of-band seems reasonable */
06528             transmit_provisional_response(p, "180 Ringing", &p->initreq, 0);
06529             ast_set_flag(&p->flags[0], SIP_RINGING);
06530             if (ast_test_flag(&p->flags[0], SIP_PROG_INBAND) != SIP_PROG_INBAND_YES)
06531                break;
06532          } else {
06533             /* Well, if it's not reasonable, just send in-band */
06534          }
06535       }
06536       res = -1;
06537       break;
06538    case AST_CONTROL_BUSY:
06539       if (ast->_state != AST_STATE_UP) {
06540          transmit_response_reliable(p, "486 Busy Here", &p->initreq);
06541          p->invitestate = INV_COMPLETED;
06542          sip_alreadygone(p);
06543          ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
06544          break;
06545       }
06546       res = -1;
06547       break;
06548    case AST_CONTROL_CONGESTION:
06549       if (ast->_state != AST_STATE_UP) {
06550          transmit_response_reliable(p, "503 Service Unavailable", &p->initreq);
06551          p->invitestate = INV_COMPLETED;
06552          sip_alreadygone(p);
06553          ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
06554          break;
06555       }
06556       res = -1;
06557       break;
06558    case AST_CONTROL_PROCEEDING:
06559       if ((ast->_state != AST_STATE_UP) &&
06560           !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
06561           !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06562          transmit_response(p, "100 Trying", &p->initreq);
06563          p->invitestate = INV_PROCEEDING;  
06564          break;
06565       }
06566       res = -1;
06567       break;
06568    case AST_CONTROL_PROGRESS:
06569       if ((ast->_state != AST_STATE_UP) &&
06570           !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
06571           !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06572          p->invitestate = INV_EARLY_MEDIA;
06573          transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
06574          ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
06575          break;
06576       }
06577       res = -1;
06578       break;
06579    case AST_CONTROL_HOLD:
06580       ast_rtp_new_source(p->rtp);
06581       ast_moh_start(ast, data, p->mohinterpret);
06582       break;
06583    case AST_CONTROL_UNHOLD:
06584       ast_rtp_new_source(p->rtp);
06585       ast_moh_stop(ast);
06586       break;
06587    case AST_CONTROL_VIDUPDATE:   /* Request a video frame update */
06588       if (p->vrtp && !p->novideo) {
06589          transmit_info_with_vidupdate(p);
06590          /* ast_rtcp_send_h261fur(p->vrtp); */
06591       } else
06592          res = -1;
06593       break;
06594    case AST_CONTROL_T38_PARAMETERS:
06595       if (datalen != sizeof(struct ast_control_t38_parameters)) {
06596          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);
06597          res = -1;
06598       } else {
06599          const struct ast_control_t38_parameters *parameters = data;
06600          res = interpret_t38_parameters(p, parameters);
06601       }
06602       break;
06603    case AST_CONTROL_SRCUPDATE:
06604       ast_rtp_new_source(p->rtp);
06605       break;
06606    case AST_CONTROL_SRCCHANGE:
06607       ast_rtp_change_source(p->rtp);
06608       break;
06609    case -1:
06610       res = -1;
06611       break;
06612    default:
06613       ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", condition);
06614       res = -1;
06615       break;
06616    }
06617    sip_pvt_unlock(p);
06618    return res;
06619 }
06620 
06621 
06622 /*! \brief Initiate a call in the SIP channel
06623    called from sip_request_call (calls from the pbx ) for outbound channels
06624    and from handle_request_invite for inbound channels
06625    
06626 */
06627 static struct ast_channel *sip_new(struct sip_pvt *i, int state, const char *title)
06628 {
06629    struct ast_channel *tmp;
06630    struct ast_variable *v = NULL;
06631    int fmt;
06632    int what;
06633    int video;
06634    int text;
06635    int needvideo = 0;
06636    int needtext = 0;
06637    char buf[SIPBUFSIZE];
06638    char *decoded_exten;
06639 
06640    {
06641       const char *my_name; /* pick a good name */
06642    
06643       if (title) {
06644          my_name = title;
06645       } else {
06646          char *port = NULL;
06647          my_name = ast_strdupa(i->fromdomain);
06648          if ((port = strchr(i->fromdomain, ':'))) {
06649             *port = '\0';
06650          }
06651       }
06652 
06653       sip_pvt_unlock(i);
06654       /* Don't hold a sip pvt lock while we allocate a channel */
06655       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));
06656 
06657    }
06658    if (!tmp) {
06659       ast_log(LOG_WARNING, "Unable to allocate AST channel structure for SIP channel\n");
06660       sip_pvt_lock(i);
06661       return NULL;
06662    }
06663    sip_pvt_lock(i);
06664 
06665    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;
06666 
06667    /* Select our native format based on codec preference until we receive
06668       something from another device to the contrary. */
06669    if (i->jointcapability) {  /* The joint capabilities of us and peer */
06670       what = i->jointcapability;
06671       video = i->jointcapability & AST_FORMAT_VIDEO_MASK;
06672       text = i->jointcapability & AST_FORMAT_TEXT_MASK;
06673    } else if (i->capability) {      /* Our configured capability for this peer */
06674       what = i->capability;
06675       video = i->capability & AST_FORMAT_VIDEO_MASK;
06676       text = i->capability & AST_FORMAT_TEXT_MASK;
06677    } else {
06678       what = global_capability;  /* Global codec support */
06679       video = global_capability & AST_FORMAT_VIDEO_MASK;
06680       text = global_capability & AST_FORMAT_TEXT_MASK;
06681    }
06682 
06683    /* Set the native formats for audio  and merge in video */
06684    tmp->nativeformats = ast_codec_choose(&i->prefs, what, 1) | video | text;
06685    ast_debug(3, "*** Our native formats are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, tmp->nativeformats));
06686    ast_debug(3, "*** Joint capabilities are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, i->jointcapability));
06687    ast_debug(3, "*** Our capabilities are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, i->capability));
06688    ast_debug(3, "*** AST_CODEC_CHOOSE formats are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, ast_codec_choose(&i->prefs, what, 1)));
06689    if (i->prefcodec)
06690       ast_debug(3, "*** Our preferred formats from the incoming channel are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, i->prefcodec));
06691 
06692    /* XXX Why are we choosing a codec from the native formats?? */
06693    fmt = ast_best_codec(tmp->nativeformats);
06694 
06695    /* If we have a prefcodec setting, we have an inbound channel that set a 
06696       preferred format for this call. Otherwise, we check the jointcapability
06697       We also check for vrtp. If it's not there, we are not allowed do any video anyway.
06698     */
06699    if (i->vrtp) {
06700       if (ast_test_flag(&i->flags[1], SIP_PAGE2_VIDEOSUPPORT))
06701          needvideo = AST_FORMAT_VIDEO_MASK;
06702       else if (i->prefcodec)
06703          needvideo = i->prefcodec & AST_FORMAT_VIDEO_MASK;  /* Outbound call */
06704       else
06705          needvideo = i->jointcapability & AST_FORMAT_VIDEO_MASK;  /* Inbound call */
06706    }
06707 
06708    if (i->trtp) {
06709       if (i->prefcodec)
06710          needtext = i->prefcodec & AST_FORMAT_TEXT_MASK; /* Outbound call */
06711       else
06712          needtext = i->jointcapability & AST_FORMAT_TEXT_MASK; /* Inbound call */
06713    }
06714 
06715    if (needvideo) 
06716       ast_debug(3, "This channel can handle video! HOLLYWOOD next!\n");
06717    else
06718       ast_debug(3, "This channel will not be able to handle video.\n");
06719 
06720    if ((ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) || (ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_AUTO) ||
06721        (ast_test_flag(&i->flags[1], SIP_PAGE2_FAX_DETECT))) {
06722       int features = 0;
06723 
06724       if ((ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) || (ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_AUTO)) {
06725          features |= DSP_FEATURE_DIGIT_DETECT;
06726       }
06727 
06728       if (ast_test_flag(&i->flags[1], SIP_PAGE2_FAX_DETECT)) {
06729          features |= DSP_FEATURE_FAX_DETECT;
06730       }
06731 
06732       i->dsp = ast_dsp_new();
06733       ast_dsp_set_features(i->dsp, features);
06734       if (global_relaxdtmf)
06735          ast_dsp_set_digitmode(i->dsp, DSP_DIGITMODE_DTMF | DSP_DIGITMODE_RELAXDTMF);
06736          }
06737 
06738    /* Set file descriptors for audio, video, realtime text and UDPTL as needed */
06739    if (i->rtp) {
06740       ast_channel_set_fd(tmp, 0, ast_rtp_fd(i->rtp));
06741       ast_channel_set_fd(tmp, 1, ast_rtcp_fd(i->rtp));
06742    }
06743    if (needvideo && i->vrtp) {
06744       ast_channel_set_fd(tmp, 2, ast_rtp_fd(i->vrtp));
06745       ast_channel_set_fd(tmp, 3, ast_rtcp_fd(i->vrtp));
06746    }
06747    if (needtext && i->trtp) 
06748       ast_channel_set_fd(tmp, 4, ast_rtp_fd(i->trtp));
06749    if (i->udptl)
06750       ast_channel_set_fd(tmp, 5, ast_udptl_fd(i->udptl));
06751 
06752    if (state == AST_STATE_RING)
06753       tmp->rings = 1;
06754    tmp->adsicpe = AST_ADSI_UNAVAILABLE;
06755    tmp->writeformat = fmt;
06756    tmp->rawwriteformat = fmt;
06757    tmp->readformat = fmt;
06758    tmp->rawreadformat = fmt;
06759    tmp->tech_pvt = dialog_ref(i, "sip_new: set chan->tech_pvt to i");
06760 
06761    tmp->callgroup = i->callgroup;
06762    tmp->pickupgroup = i->pickupgroup;
06763    tmp->cid.cid_pres = i->callingpres;
06764    if (!ast_strlen_zero(i->parkinglot))
06765       ast_string_field_set(tmp, parkinglot, i->parkinglot);
06766    if (!ast_strlen_zero(i->accountcode))
06767       ast_string_field_set(tmp, accountcode, i->accountcode);
06768    if (i->amaflags)
06769       tmp->amaflags = i->amaflags;
06770    if (!ast_strlen_zero(i->language))
06771       ast_string_field_set(tmp, language, i->language);
06772    i->owner = tmp;
06773    ast_module_ref(ast_module_info->self);
06774    ast_copy_string(tmp->context, i->context, sizeof(tmp->context));
06775    /*Since it is valid to have extensions in the dialplan that have unescaped characters in them
06776     * we should decode the uri before storing it in the channel, but leave it encoded in the sip_pvt
06777     * structure so that there aren't issues when forming URI's
06778     */
06779    decoded_exten = ast_strdupa(i->exten);
06780    ast_uri_decode(decoded_exten);
06781    ast_copy_string(tmp->exten, decoded_exten, sizeof(tmp->exten));
06782 
06783    /* Don't use ast_set_callerid() here because it will
06784     * generate an unnecessary NewCallerID event  */
06785    tmp->cid.cid_ani = ast_strdup(i->cid_num);
06786    if (!ast_strlen_zero(i->rdnis))
06787       tmp->cid.cid_rdnis = ast_strdup(i->rdnis);
06788    
06789    if (!ast_strlen_zero(i->exten) && strcmp(i->exten, "s"))
06790       tmp->cid.cid_dnid = ast_strdup(i->exten);
06791 
06792    tmp->priority = 1;
06793    if (!ast_strlen_zero(i->uri))
06794       pbx_builtin_setvar_helper(tmp, "SIPURI", i->uri);
06795    if (!ast_strlen_zero(i->domain))
06796       pbx_builtin_setvar_helper(tmp, "SIPDOMAIN", i->domain);
06797    if (!ast_strlen_zero(i->callid))
06798       pbx_builtin_setvar_helper(tmp, "SIPCALLID", i->callid);
06799    if (i->rtp)
06800       ast_jb_configure(tmp, &global_jbconf);
06801 
06802    /* Set channel variables for this call from configuration */
06803    for (v = i->chanvars ; v ; v = v->next) {
06804       char valuebuf[1024];
06805       pbx_builtin_setvar_helper(tmp, v->name, ast_get_encoded_str(v->value, valuebuf, sizeof(valuebuf)));
06806    }
06807 
06808    if (state != AST_STATE_DOWN && ast_pbx_start(tmp)) {
06809       ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
06810       tmp->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
06811       ast_hangup(tmp);
06812       tmp = NULL;
06813    }
06814 
06815    if (i->do_history)
06816       append_history(i, "NewChan", "Channel %s - from %s", tmp->name, i->callid);
06817 
06818    /* Inform manager user about new channel and their SIP call ID */
06819    if (sip_cfg.callevents)
06820       manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
06821          "Channel: %s\r\nUniqueid: %s\r\nChanneltype: %s\r\nSIPcallid: %s\r\nSIPfullcontact: %s\r\n",
06822          tmp->name, tmp->uniqueid, "SIP", i->callid, i->fullcontact);
06823 
06824    return tmp;
06825 }
06826 
06827 /*! \brief Reads one line of SIP message body */
06828 static char *get_body_by_line(const char *line, const char *name, int nameLen, char delimiter)
06829 {
06830    if (!strncasecmp(line, name, nameLen) && line[nameLen] == delimiter)
06831       return ast_skip_blanks(line + nameLen + 1);
06832 
06833    return "";
06834 }
06835 
06836 /*! \brief Lookup 'name' in the SDP starting
06837  * at the 'start' line. Returns the matching line, and 'start'
06838  * is updated with the next line number.
06839  */
06840 static const char *get_sdp_iterate(int *start, struct sip_request *req, const char *name)
06841 {
06842    int len = strlen(name);
06843 
06844    while (*start < (req->sdp_start + req->sdp_count)) {
06845       const char *r = get_body_by_line(REQ_OFFSET_TO_STR(req, line[(*start)++]), name, len, '=');
06846       if (r[0] != '\0')
06847          return r;
06848    }
06849 
06850    /* if the line was not found, ensure that *start points past the SDP */
06851    (*start)++;
06852 
06853    return "";
06854 }
06855 
06856 /*! \brief Fetches the next valid SDP line between the 'start' line
06857  * (inclusive) and the 'stop' line (exclusive). Returns the type
06858  * ('a', 'c', ...) and matching line in reference 'start' is updated
06859  * with the next line number.
06860  */
06861 static char get_sdp_line(int *start, int stop, struct sip_request *req, const char **value)
06862 {
06863    char type = '\0';
06864    const char *line = NULL;
06865 
06866    if (stop > (req->sdp_start + req->sdp_count)) {
06867       stop = req->sdp_start + req->sdp_count;
06868    }
06869 
06870    while (*start < stop) {
06871       line = REQ_OFFSET_TO_STR(req, line[(*start)++]);
06872       if (line[1] == '=') {
06873          type = line[0];
06874          *value = ast_skip_blanks(line + 2);
06875          break;
06876       }
06877    }
06878 
06879    return type;
06880 }
06881 
06882 /*! \brief Get a specific line from the message body */
06883 static char *get_body(struct sip_request *req, char *name, char delimiter) 
06884 {
06885    int x;
06886    int len = strlen(name);
06887    char *r;
06888 
06889    for (x = 0; x < req->lines; x++) {
06890       r = get_body_by_line(REQ_OFFSET_TO_STR(req, line[x]), name, len, delimiter);
06891       if (r[0] != '\0')
06892          return r;
06893    }
06894 
06895    return "";
06896 }
06897 
06898 /*! \brief Find compressed SIP alias */
06899 static const char *find_alias(const char *name, const char *_default)
06900 {
06901    /*! \brief Structure for conversion between compressed SIP and "normal" SIP */
06902    static const struct cfalias {
06903       char * const fullname;
06904       char * const shortname;
06905    } aliases[] = {
06906       { "Content-Type",  "c" },
06907       { "Content-Encoding",    "e" },
06908       { "From",       "f" },
06909       { "Call-ID",       "i" },
06910       { "Contact",       "m" },
06911       { "Content-Length",   "l" },
06912       { "Subject",       "s" },
06913       { "To",         "t" },
06914       { "Supported",     "k" },
06915       { "Refer-To",      "r" },
06916       { "Referred-By",   "b" },
06917       { "Allow-Events",  "u" },
06918       { "Event",      "o" },
06919       { "Via",     "v" },
06920       { "Accept-Contact",      "a" },
06921       { "Reject-Contact",      "j" },
06922       { "Request-Disposition", "d" },
06923       { "Session-Expires",     "x" },
06924       { "Identity",            "y" },
06925       { "Identity-Info",       "n" },
06926    };
06927    int x;
06928 
06929    for (x = 0; x < ARRAY_LEN(aliases); x++) {
06930       if (!strcasecmp(aliases[x].fullname, name))
06931          return aliases[x].shortname;
06932    }
06933 
06934    return _default;
06935 }
06936 
06937 static const char *__get_header(const struct sip_request *req, const char *name, int *start)
06938 {
06939    int pass;
06940 
06941    /*
06942     * Technically you can place arbitrary whitespace both before and after the ':' in
06943     * a header, although RFC3261 clearly says you shouldn't before, and place just
06944     * one afterwards.  If you shouldn't do it, what absolute idiot decided it was 
06945     * a good idea to say you can do it, and if you can do it, why in the hell would.
06946     * you say you shouldn't.
06947     * Anyways, pedanticsipchecking controls whether we allow spaces before ':',
06948     * and we always allow spaces after that for compatibility.
06949     */
06950    for (pass = 0; name && pass < 2;pass++) {
06951       int x, len = strlen(name);
06952       for (x = *start; x < req->headers; x++) {
06953          char *header = REQ_OFFSET_TO_STR(req, header[x]);
06954          if (!strncasecmp(header, name, len)) {
06955             char *r = header + len; /* skip name */
06956             if (sip_cfg.pedanticsipchecking)
06957                r = ast_skip_blanks(r);
06958 
06959             if (*r == ':') {
06960                *start = x+1;
06961                return ast_skip_blanks(r+1);
06962             }
06963          }
06964       }
06965       if (pass == 0) /* Try aliases */
06966          name = find_alias(name, NULL);
06967    }
06968 
06969    /* Don't return NULL, so get_header is always a valid pointer */
06970    return "";
06971 }
06972 
06973 /*! \brief Get header from SIP request 
06974    \return Always return something, so don't check for NULL because it won't happen :-)
06975 */
06976 static const char *get_header(const struct sip_request *req, const char *name)
06977 {
06978    int start = 0;
06979    return __get_header(req, name, &start);
06980 }
06981 
06982 /*! \brief Read RTP from network */
06983 static struct ast_frame *sip_rtp_read(struct ast_channel *ast, struct sip_pvt *p, int *faxdetect)
06984 {
06985    /* Retrieve audio/etc from channel.  Assumes p->lock is already held. */
06986    struct ast_frame *f;
06987    
06988    if (!p->rtp) {
06989       /* We have no RTP allocated for this channel */
06990       return &ast_null_frame;
06991    }
06992 
06993    switch(ast->fdno) {
06994    case 0:
06995       f = ast_rtp_read(p->rtp);  /* RTP Audio */
06996       break;
06997    case 1:
06998       f = ast_rtcp_read(p->rtp); /* RTCP Control Channel */
06999       break;
07000    case 2:
07001       f = ast_rtp_read(p->vrtp); /* RTP Video */
07002       break;
07003    case 3:
07004       f = ast_rtcp_read(p->vrtp);   /* RTCP Control Channel for video */
07005       break;
07006    case 4:
07007       f = ast_rtp_read(p->trtp); /* RTP Text */
07008       if (sipdebug_text) {
07009          int i;
07010          unsigned char* arr = f->data.ptr;
07011          for (i=0; i < f->datalen; i++)
07012             ast_verbose("%c", (arr[i] > ' ' && arr[i] < '}') ? arr[i] : '.');
07013          ast_verbose(" -> ");
07014          for (i=0; i < f->datalen; i++)
07015             ast_verbose("%02X ", arr[i]);
07016          ast_verbose("\n");
07017       }
07018       break;
07019    case 5:
07020       f = ast_udptl_read(p->udptl); /* UDPTL for T.38 */
07021       break;
07022    default:
07023       f = &ast_null_frame;
07024    }
07025    /* Don't forward RFC2833 if we're not supposed to */
07026    if (f && (f->frametype == AST_FRAME_DTMF_BEGIN || f->frametype == AST_FRAME_DTMF_END) &&
07027        (ast_test_flag(&p->flags[0], SIP_DTMF) != SIP_DTMF_RFC2833)) {
07028       ast_debug(1, "Ignoring DTMF (%c) RTP frame because dtmfmode is not RFC2833\n", f->subclass);
07029       return &ast_null_frame;
07030    }
07031 
07032    /* We already hold the channel lock */
07033    if (!p->owner || (f && f->frametype != AST_FRAME_VOICE))
07034       return f;
07035 
07036    if (f && f->subclass != (p->owner->nativeformats & AST_FORMAT_AUDIO_MASK)) {
07037       if (!(f->subclass & p->jointcapability)) {
07038          ast_debug(1, "Bogus frame of format '%s' received from '%s'!\n",
07039             ast_getformatname(f->subclass), p->owner->name);
07040          return &ast_null_frame;
07041       }
07042       ast_debug(1, "Oooh, format changed to %d %s\n",
07043          f->subclass, ast_getformatname(f->subclass));
07044       p->owner->nativeformats = (p->owner->nativeformats & (AST_FORMAT_VIDEO_MASK | AST_FORMAT_TEXT_MASK)) | f->subclass;
07045       ast_set_read_format(p->owner, p->owner->readformat);
07046       ast_set_write_format(p->owner, p->owner->writeformat);
07047    }
07048 
07049    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) {
07050       f = ast_dsp_process(p->owner, p->dsp, f);
07051                 if (f && f->frametype == AST_FRAME_DTMF) {
07052          if (f->subclass == 'f') {
07053                                 if (option_debug)
07054                                         ast_log(LOG_DEBUG, "Fax CNG detected on %s\n", ast->name);
07055                                 *faxdetect = 1;
07056             /* If we only needed this DSP for fax detection purposes we can just drop it now */
07057             if (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) {
07058                ast_dsp_set_features(p->dsp, DSP_FEATURE_DIGIT_DETECT);
07059             } else {
07060                ast_dsp_free(p->dsp);
07061                p->dsp = NULL;
07062             }
07063          } else {
07064             ast_debug(1, "* Detected inband DTMF '%c'\n", f->subclass);
07065          }
07066       }
07067    }
07068    
07069    return f;
07070 }
07071 
07072 /*! \brief Read SIP RTP from channel */
07073 static struct ast_frame *sip_read(struct ast_channel *ast)
07074 {
07075    struct ast_frame *fr;
07076    struct sip_pvt *p = ast->tech_pvt;
07077    int faxdetected = FALSE;
07078 
07079    sip_pvt_lock(p);
07080    fr = sip_rtp_read(ast, p, &faxdetected);
07081    p->lastrtprx = time(NULL);
07082 
07083    /* If we detect a CNG tone and fax detection is enabled then send us off to the fax extension */
07084    if (faxdetected && ast_test_flag(&p->flags[1], SIP_PAGE2_FAX_DETECT_CNG)) {
07085       ast_channel_lock(ast);
07086       if (strcmp(ast->exten, "fax")) {
07087          const char *target_context = S_OR(ast->macrocontext, ast->context);
07088          ast_channel_unlock(ast);
07089          if (ast_exists_extension(ast, target_context, "fax", 1, ast->cid.cid_num)) {
07090             ast_verbose(VERBOSE_PREFIX_2 "Redirecting '%s' to fax extension due to CNG detection\n", ast->name);
07091             pbx_builtin_setvar_helper(ast, "FAXEXTEN", ast->exten);
07092             if (ast_async_goto(ast, target_context, "fax", 1)) {
07093                ast_log(LOG_NOTICE, "Failed to async goto '%s' into fax of '%s'\n", ast->name, target_context);
07094             }
07095             fr = &ast_null_frame;
07096          } else {
07097             ast_log(LOG_NOTICE, "FAX CNG detected but no fax extension\n");
07098                         }
07099       } else {
07100          ast_channel_unlock(ast);
07101                 }
07102         }
07103 
07104    /* Only allow audio through if they sent progress with SDP, or if the channel is actually answered */
07105    if (fr && fr->frametype == AST_FRAME_VOICE && p->invitestate != INV_EARLY_MEDIA && ast->_state != AST_STATE_UP) {
07106       fr = &ast_null_frame;
07107    }
07108 
07109    sip_pvt_unlock(p);
07110 
07111    return fr;
07112 }
07113 
07114 
07115 /*! \brief Generate 32 byte random string for callid's etc */
07116 static char *generate_random_string(char *buf, size_t size)
07117 {
07118    long val[4];
07119    int x;
07120 
07121    for (x=0; x<4; x++)
07122       val[x] = ast_random();
07123    snprintf(buf, size, "%08lx%08lx%08lx%08lx", val[0], val[1], val[2], val[3]);
07124 
07125    return buf;
07126 }
07127 
07128 /*! \brief Build SIP Call-ID value for a non-REGISTER transaction */
07129 static void build_callid_pvt(struct sip_pvt *pvt)
07130 {
07131    char buf[33];
07132 
07133    const char *host = S_OR(pvt->fromdomain, ast_inet_ntoa(pvt->ourip.sin_addr));
07134    
07135    ast_string_field_build(pvt, callid, "%s@%s", generate_random_string(buf, sizeof(buf)), host);
07136 
07137 }
07138 
07139 /*! \brief Build SIP Call-ID value for a REGISTER transaction */
07140 static void build_callid_registry(struct sip_registry *reg, struct in_addr ourip, const char *fromdomain)
07141 {
07142    char buf[33];
07143 
07144    const char *host = S_OR(fromdomain, ast_inet_ntoa(ourip));
07145 
07146    ast_string_field_build(reg, callid, "%s@%s", generate_random_string(buf, sizeof(buf)), host);
07147 }
07148 
07149 /*! \brief Make our SIP dialog tag */
07150 static void make_our_tag(char *tagbuf, size_t len)
07151 {
07152    snprintf(tagbuf, len, "as%08lx", ast_random());
07153 }
07154 
07155 /*! \brief Allocate Session-Timers struct w/in dialog */
07156 static struct sip_st_dlg* sip_st_alloc(struct sip_pvt *const p)
07157 {
07158    struct sip_st_dlg *stp;
07159 
07160    if (p->stimer) {
07161       ast_log(LOG_ERROR, "Session-Timer struct already allocated\n");
07162       return p->stimer;
07163    }
07164 
07165    if (!(stp = ast_calloc(1, sizeof(struct sip_st_dlg))))
07166       return NULL;
07167 
07168    p->stimer = stp;
07169 
07170    stp->st_schedid = -1;           /* Session-Timers ast_sched scheduler id */
07171 
07172    return p->stimer;
07173 }
07174 
07175 /*! \brief Allocate sip_pvt structure, set defaults and link in the container.
07176  * Returns a reference to the object so whoever uses it later must
07177  * remember to release the reference.
07178  */
07179 static struct sip_pvt *sip_alloc(ast_string_field callid, struct sockaddr_in *sin,
07180              int useglobal_nat, const int intended_method, struct sip_request *req)
07181 {
07182    struct sip_pvt *p;
07183 
07184    if (!(p = ao2_t_alloc(sizeof(*p), sip_destroy_fn, "allocate a dialog(pvt) struct")))
07185       return NULL;
07186 
07187    if (ast_string_field_init(p, 512)) {
07188       ao2_t_ref(p, -1, "failed to string_field_init, drop p");
07189       return NULL;
07190    }
07191 
07192    if (req) {
07193       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 */
07194    } else {
07195       set_socket_transport(&p->socket, SIP_TRANSPORT_UDP);
07196    }
07197 
07198    p->socket.fd = -1;
07199    p->method = intended_method;
07200    p->initid = -1;
07201    p->waitid = -1;
07202    p->autokillid = -1;
07203    p->request_queue_sched_id = -1;
07204    p->provisional_keepalive_sched_id = -1;
07205    p->t38id = -1;
07206    p->subscribed = NONE;
07207    p->stateid = -1;
07208    p->sessionversion_remote = -1;
07209    p->session_modify = TRUE;
07210    p->stimer = NULL;
07211    p->prefs = default_prefs;     /* Set default codecs for this call */
07212 
07213    if (intended_method != SIP_OPTIONS) {  /* Peerpoke has it's own system */
07214       p->timer_t1 = global_t1;   /* Default SIP retransmission timer T1 (RFC 3261) */
07215       p->timer_b = global_timer_b;  /* Default SIP transaction timer B (RFC 3261) */
07216    }
07217 
07218    if (!sin)
07219       p->ourip = internip;
07220    else {
07221       p->sa = *sin;
07222       ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
07223    }
07224 
07225    /* Copy global flags to this PVT at setup. */
07226    ast_copy_flags(&p->flags[0], &global_flags[0], SIP_FLAGS_TO_COPY);
07227    ast_copy_flags(&p->flags[1], &global_flags[1], SIP_PAGE2_FLAGS_TO_COPY);
07228 
07229    p->do_history = recordhistory;
07230 
07231    p->branch = ast_random();  
07232    make_our_tag(p->tag, sizeof(p->tag));
07233    p->ocseq = INITIAL_CSEQ;
07234 
07235    if (sip_methods[intended_method].need_rtp) {
07236       p->rtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
07237       /* If the global videosupport flag is on, we always create a RTP interface for video */
07238       if (ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT))
07239          p->vrtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
07240       if (ast_test_flag(&p->flags[1], SIP_PAGE2_TEXTSUPPORT))
07241          p->trtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
07242       if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT))
07243          p->udptl = ast_udptl_new_with_bindaddr(sched, io, 0, bindaddr.sin_addr);
07244       if (!p->rtp|| (ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT) && !p->vrtp) 
07245             || (ast_test_flag(&p->flags[1], SIP_PAGE2_TEXTSUPPORT) && !p->trtp)) {
07246          ast_log(LOG_WARNING, "Unable to create RTP audio %s%ssession: %s\n",
07247             ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT) ? "and video " : "",
07248             ast_test_flag(&p->flags[1], SIP_PAGE2_TEXTSUPPORT) ? "and text " : "", strerror(errno));
07249          if (p->chanvars) {
07250             ast_variables_destroy(p->chanvars);
07251             p->chanvars = NULL;
07252          }
07253          ao2_t_ref(p, -1, "failed to create RTP audio session, drop p");
07254          return NULL;
07255          p->t38_maxdatagram = global_t38_maxdatagram;
07256       }
07257       ast_rtp_setqos(p->rtp, global_tos_audio, global_cos_audio, "SIP RTP");
07258       ast_rtp_setdtmf(p->rtp, ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
07259       ast_rtp_setdtmfcompensate(p->rtp, ast_test_flag(&p->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
07260       ast_rtp_set_rtptimeout(p->rtp, global_rtptimeout);
07261       ast_rtp_set_rtpholdtimeout(p->rtp, global_rtpholdtimeout);
07262       ast_rtp_set_rtpkeepalive(p->rtp, global_rtpkeepalive);
07263       if (p->vrtp) {
07264          ast_rtp_setqos(p->vrtp, global_tos_video, global_cos_video, "SIP VRTP");
07265          ast_rtp_setdtmf(p->vrtp, 0);
07266          ast_rtp_setdtmfcompensate(p->vrtp, 0);
07267          ast_rtp_set_rtptimeout(p->vrtp, global_rtptimeout);
07268          ast_rtp_set_rtpholdtimeout(p->vrtp, global_rtpholdtimeout);
07269          ast_rtp_set_rtpkeepalive(p->vrtp, global_rtpkeepalive);
07270       }
07271       if (p->trtp) {
07272          ast_rtp_setqos(p->trtp, global_tos_text, global_cos_text, "SIP TRTP");
07273          ast_rtp_setdtmf(p->trtp, 0);
07274          ast_rtp_setdtmfcompensate(p->trtp, 0);
07275       }
07276       if (p->udptl)
07277          ast_udptl_setqos(p->udptl, global_tos_audio, global_cos_audio);
07278       p->maxcallbitrate = default_maxcallbitrate;
07279       p->autoframing = global_autoframing;
07280       ast_rtp_codec_setpref(p->rtp, &p->prefs);
07281    }
07282 
07283    if (useglobal_nat && sin) {
07284       /* Setup NAT structure according to global settings if we have an address */
07285       ast_copy_flags(&p->flags[0], &global_flags[0], SIP_NAT);
07286       p->recv = *sin;
07287       do_setnat(p, ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE);
07288    }
07289 
07290    if (p->method != SIP_REGISTER)
07291       ast_string_field_set(p, fromdomain, default_fromdomain);
07292    build_via(p);
07293    if (!callid)
07294       build_callid_pvt(p);
07295    else
07296       ast_string_field_set(p, callid, callid);
07297    /* Assign default music on hold class */
07298    ast_string_field_set(p, mohinterpret, default_mohinterpret);
07299    ast_string_field_set(p, mohsuggest, default_mohsuggest);
07300    p->capability = global_capability;
07301    p->allowtransfer = sip_cfg.allowtransfer;
07302    if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
07303        (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
07304       p->noncodeccapability |= AST_RTP_DTMF;
07305    if (p->udptl) {
07306       p->t38_maxdatagram = global_t38_maxdatagram;
07307       set_t38_capabilities(p);
07308    }
07309    ast_string_field_set(p, context, sip_cfg.default_context);
07310    ast_string_field_set(p, parkinglot, default_parkinglot);
07311 
07312    AST_LIST_HEAD_INIT_NOLOCK(&p->request_queue);
07313 
07314    /* Add to active dialog list */
07315 
07316    ao2_t_link(dialogs, p, "link pvt into dialogs table");
07317    
07318    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");
07319    return p;
07320 }
07321 
07322 /*! \brief argument to the helper function to identify a call */
07323 struct find_call_cb_arg {
07324    enum sipmethod method;
07325    const char *callid;
07326    const char *fromtag;
07327    const char *totag;
07328    const char *tag;
07329 };
07330 
07331 /*!
07332  * code to determine whether this is the pvt that we are looking for.
07333  * Return FALSE if not found, true otherwise. p is unlocked.
07334  */
07335 static int find_call_cb(void *__pvt, void *__arg, int flags)
07336 {
07337    struct sip_pvt *p = __pvt;
07338    struct find_call_cb_arg *arg = __arg;
07339    /* In pedantic, we do not want packets with bad syntax to be connected to a PVT */
07340    int found = FALSE;
07341    
07342    if (!ast_strlen_zero(p->callid)) { /* XXX double check, do we allow match on empty p->callid ? */
07343       if (arg->method == SIP_REGISTER)
07344          found = (!strcmp(p->callid, arg->callid));
07345       else {
07346          found = !strcmp(p->callid, arg->callid);
07347          if (sip_cfg.pedanticsipchecking && found) {
07348             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);
07349          } 
07350       }
07351       
07352       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);
07353       
07354       /* If we get a new request within an existing to-tag - check the to tag as well */
07355       if (sip_cfg.pedanticsipchecking && found && arg->method != SIP_RESPONSE) { /* SIP Request */
07356          if (p->tag[0] == '\0' && arg->totag[0]) {
07357             /* We have no to tag, but they have. Wrong dialog */
07358             found = FALSE;
07359          } else if (arg->totag[0]) { /* Both have tags, compare them */
07360             if (strcmp(arg->totag, p->tag)) {
07361                found = FALSE; /* This is not our packet */
07362             }
07363          }
07364          if (!found)
07365             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);
07366       }
07367    }
07368    return found;
07369 }
07370 
07371 /*! \brief find or create a dialog structure for an incoming SIP message.
07372  * Connect incoming SIP message to current dialog or create new dialog structure
07373  * Returns a reference to the sip_pvt object, remember to give it back once done.
07374  *     Called by handle_incoming(), sipsock_read
07375  */
07376 static struct sip_pvt *find_call(struct sip_request *req, struct sockaddr_in *sin, const int intended_method)
07377 {
07378    struct sip_pvt *p = NULL;
07379    char *tag = "";   /* note, tag is never NULL */
07380    char totag[128];
07381    char fromtag[128];
07382    struct find_call_cb_arg arg;
07383    const char *callid = get_header(req, "Call-ID");
07384    const char *from = get_header(req, "From");
07385    const char *to = get_header(req, "To");
07386    const char *cseq = get_header(req, "Cseq");
07387    struct sip_pvt *sip_pvt_ptr;
07388 
07389    /* Call-ID, to, from and Cseq are required by RFC 3261. (Max-forwards and via too - ignored now) */
07390    /* get_header always returns non-NULL so we must use ast_strlen_zero() */
07391    if (ast_strlen_zero(callid) || ast_strlen_zero(to) ||
07392          ast_strlen_zero(from) || ast_strlen_zero(cseq))
07393       return NULL;   /* Invalid packet */
07394 
07395    arg.method = req->method;
07396    arg.callid = callid;
07397    arg.fromtag = fromtag;
07398    arg.totag = totag;
07399    arg.tag = ""; /* make sure tag is never NULL */
07400 
07401    if (sip_cfg.pedanticsipchecking) {
07402       /* In principle Call-ID's uniquely identify a call, but with a forking SIP proxy
07403          we need more to identify a branch - so we have to check branch, from
07404          and to tags to identify a call leg.
07405          For Asterisk to behave correctly, you need to turn on pedanticsipchecking
07406          in sip.conf
07407          */
07408       if (gettag(req, "To", totag, sizeof(totag)))
07409          req->has_to_tag = 1; /* Used in handle_request/response */
07410       gettag(req, "From", fromtag, sizeof(fromtag));
07411 
07412       tag = (req->method == SIP_RESPONSE) ? totag : fromtag;
07413 
07414       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);
07415 
07416       /* All messages must always have From: tag */
07417       if (ast_strlen_zero(fromtag)) {
07418          ast_debug(5, "%s request has no from tag, dropping callid: %s from: %s\n", sip_methods[req->method].text , callid, from );
07419          return NULL;
07420       }
07421       /* reject requests that must always have a To: tag */
07422       if (ast_strlen_zero(totag) && (req->method == SIP_ACK || req->method == SIP_BYE || req->method == SIP_INFO )) {
07423          ast_debug(5, "%s must have a to tag. dropping callid: %s from: %s\n", sip_methods[req->method].text , callid, from );
07424          return NULL;
07425       }
07426    }
07427 
07428 restartsearch:
07429    if (!sip_cfg.pedanticsipchecking) {
07430       struct sip_pvt tmp_dialog = {
07431          .callid = callid,
07432       };       
07433       sip_pvt_ptr = ao2_t_find(dialogs, &tmp_dialog, OBJ_POINTER, "ao2_find in dialogs");
07434       if (sip_pvt_ptr) {  /* well, if we don't find it-- what IS in there? */
07435          /* Found the call */
07436          sip_pvt_lock(sip_pvt_ptr);
07437          return sip_pvt_ptr;
07438       }
07439    } else { /* in pedantic mode! -- do the fancy linear search */
07440       ao2_lock(dialogs);
07441       p = ao2_t_callback(dialogs, 0 /* single, data */, find_call_cb, &arg, "pedantic linear search for dialog");
07442       if (p) {
07443          if (sip_pvt_trylock(p)) {
07444             ao2_unlock(dialogs);
07445             usleep(1);
07446             goto restartsearch;
07447          }
07448          ao2_unlock(dialogs);
07449          return p;
07450       }
07451       ao2_unlock(dialogs);
07452    }
07453  
07454    /* See if the method is capable of creating a dialog */
07455    if (sip_methods[intended_method].can_create == CAN_CREATE_DIALOG) {
07456       if (intended_method == SIP_REFER) {
07457          /* We do support REFER, but not outside of a dialog yet */
07458          transmit_response_using_temp(callid, sin, 1, intended_method, req, "603 Declined (no dialog)");
07459       } else if (intended_method == SIP_NOTIFY) {
07460          /* We do not support out-of-dialog NOTIFY either,
07461             like voicemail notification, so cancel that early */
07462          transmit_response_using_temp(callid, sin, 1, intended_method, req, "489 Bad event");
07463       } else {
07464          /* Ok, time to create a new SIP dialog object, a pvt */
07465          if ((p = sip_alloc(callid, sin, 1, intended_method, req)))  {
07466             /* Ok, we've created a dialog, let's go and process it */
07467             sip_pvt_lock(p);
07468          } else {
07469             /* We have a memory or file/socket error (can't allocate RTP sockets or something) so we're not
07470                getting a dialog from sip_alloc. 
07471    
07472                Without a dialog we can't retransmit and handle ACKs and all that, but at least
07473                send an error message.
07474    
07475                Sorry, we apologize for the inconvienience
07476             */
07477             transmit_response_using_temp(callid, sin, 1, intended_method, req, "500 Server internal error");
07478             ast_debug(4, "Failed allocating SIP dialog, sending 500 Server internal error and giving up\n");
07479          }
07480       }
07481       return p; /* can be NULL */
07482    } else if( sip_methods[intended_method].can_create == CAN_CREATE_DIALOG_UNSUPPORTED_METHOD) {
07483       /* A method we do not support, let's take it on the volley */
07484       transmit_response_using_temp(callid, sin, 1, intended_method, req, "501 Method Not Implemented");
07485       ast_debug(2, "Got a request with unsupported SIP method.\n");
07486    } else if (intended_method != SIP_RESPONSE && intended_method != SIP_ACK) {
07487       /* This is a request outside of a dialog that we don't know about */
07488       transmit_response_using_temp(callid, sin, 1, intended_method, req, "481 Call leg/transaction does not exist");
07489       ast_debug(2, "That's odd...  Got a request in unknown dialog. Callid %s\n", callid ? callid : "<unknown>");
07490    }
07491    /* We do not respond to responses for dialogs that we don't know about, we just drop
07492       the session quickly */
07493    if (intended_method == SIP_RESPONSE)
07494       ast_debug(2, "That's odd...  Got a response on a call we dont know about. Callid %s\n", callid ? callid : "<unknown>");
07495 
07496    return NULL;
07497 }
07498 
07499 /*! \brief Parse register=> line in sip.conf and add to registry */
07500 static int sip_register(const char *value, int lineno)
07501 {
07502    struct sip_registry *reg;
07503    int portnum = 0;
07504    enum sip_transport transport = SIP_TRANSPORT_UDP;
07505    char buf[256] = "";
07506    char *userpart = NULL, *hostpart = NULL;
07507    /* register => [peer?][transport://]user[@domain][:secret[:authuser]]@host[:port][/extension][~expiry] */
07508    AST_DECLARE_APP_ARGS(pre1,
07509       AST_APP_ARG(peer);
07510       AST_APP_ARG(userpart);
07511    );
07512    AST_DECLARE_APP_ARGS(pre2,
07513       AST_APP_ARG(transport);
07514       AST_APP_ARG(blank);
07515       AST_APP_ARG(userpart);
07516    );
07517    AST_DECLARE_APP_ARGS(user1,
07518       AST_APP_ARG(userpart);
07519       AST_APP_ARG(secret);
07520       AST_APP_ARG(authuser);
07521    );
07522    AST_DECLARE_APP_ARGS(host1,
07523       AST_APP_ARG(hostpart);
07524       AST_APP_ARG(expiry);
07525    );
07526    AST_DECLARE_APP_ARGS(host2,
07527       AST_APP_ARG(hostpart);
07528       AST_APP_ARG(extension);
07529    );
07530    AST_DECLARE_APP_ARGS(host3,
07531       AST_APP_ARG(host);
07532       AST_APP_ARG(port);
07533    );
07534 
07535    if (!value)
07536       return -1;
07537    ast_copy_string(buf, value, sizeof(buf));
07538 
07539    /*! register => [peer?][transport://]user[@domain][:secret[:authuser]]@host[:port][/extension][~expiry]
07540     * becomes
07541     *   userpart => [peer?][transport://]user[@domain][:secret[:authuser]]
07542     *   hostpart => host[:port][/extension][~expiry]
07543     */
07544    if ((hostpart = strrchr(buf, '@'))) {
07545       *hostpart++ = '\0';
07546       userpart = buf;
07547    }
07548 
07549    if (ast_strlen_zero(userpart) || ast_strlen_zero(hostpart)) {
07550       ast_log(LOG_WARNING, "Format for registration is [peer?][transport://]user[@domain][:secret[:authuser]]@host[:port][/extension][~expiry] at line %d\n", lineno);
07551       return -1;
07552    }
07553 
07554    /*!
07555     * pre1.peer => peer
07556     * pre1.userpart => [transport://]user[@domain][:secret[:authuser]]
07557     * hostpart => host[:port][/extension][~expiry]
07558     */
07559    AST_NONSTANDARD_RAW_ARGS(pre1, userpart, '?');
07560    if (ast_strlen_zero(pre1.userpart)) {
07561       pre1.userpart = pre1.peer;
07562       pre1.peer = NULL;
07563    }
07564 
07565    /*!
07566     * pre1.peer => peer
07567     * pre2.transport = transport
07568     * pre2.userpart => user[@domain][:secret[:authuser]]
07569     * hostpart => host[:port][/extension][~expiry]
07570     */
07571    AST_NONSTANDARD_RAW_ARGS(pre2, pre1.userpart, '/');
07572    if (ast_strlen_zero(pre2.userpart)) {
07573       pre2.userpart = pre2.transport;
07574       pre2.transport = NULL;
07575    } else {
07576       pre2.transport[strlen(pre2.transport) - 1] = '\0'; /* Remove trailing : */
07577    }
07578 
07579    if (!ast_strlen_zero(pre2.blank)) {
07580       ast_log(LOG_WARNING, "Format for registration is [peer?][transport://]user[@domain][:secret[:authuser]]@host[:port][/extension][~expiry] at line %d\n", lineno);
07581       return -1;
07582    }
07583 
07584    /*!
07585     * pre1.peer => peer
07586     * pre2.transport = transport
07587     * user1.userpart => user[@domain]
07588     * user1.secret => secret
07589     * user1.authuser => authuser
07590     * hostpart => host[:port][/extension][~expiry]
07591     */
07592    AST_NONSTANDARD_RAW_ARGS(user1, pre2.userpart, ':');
07593 
07594    /*!
07595     * pre1.peer => peer
07596     * pre2.transport = transport
07597     * user1.userpart => user[@domain]
07598     * user1.secret => secret
07599     * user1.authuser => authuser
07600     * host1.hostpart => host[:port][/extension]
07601     * host1.expiry => [expiry]
07602     */
07603    AST_NONSTANDARD_RAW_ARGS(host1, hostpart, '~');
07604 
07605    /*!
07606     * pre1.peer => peer
07607     * pre2.transport = transport
07608     * user1.userpart => user[@domain]
07609     * user1.secret => secret
07610     * user1.authuser => authuser
07611     * host2.hostpart => host[:port]
07612     * host2.extension => [extension]
07613     * host1.expiry => [expiry]
07614     */
07615    AST_NONSTANDARD_RAW_ARGS(host2, host1.hostpart, '/');
07616 
07617    /*!
07618     * pre1.peer => peer
07619     * pre2.transport = transport
07620     * user1.userpart => user[@domain]
07621     * user1.secret => secret
07622     * user1.authuser => authuser
07623     * host3.host => host
07624     * host3.port => port
07625     * host2.extension => extension
07626     * host1.expiry => expiry
07627     */
07628    AST_NONSTANDARD_RAW_ARGS(host3, host2.hostpart, ':');
07629 
07630    if (host3.port) {
07631       if (!(portnum = port_str2int(host3.port, 0))) {
07632          ast_log(LOG_NOTICE, "'%s' is not a valid port number on line %d of sip.conf. using default.\n", host3.port, lineno);
07633       }
07634    }
07635 
07636    /* set transport type */
07637    if (!pre2.transport) {
07638       transport = SIP_TRANSPORT_UDP;
07639    } else if (!strncasecmp(pre2.transport, "tcp", 3)) {
07640       transport = SIP_TRANSPORT_TCP;
07641    } else if (!strncasecmp(pre2.transport, "tls", 3)) {
07642       transport = SIP_TRANSPORT_TLS;
07643    } else if (!strncasecmp(pre2.transport, "udp", 3)) {
07644       transport = SIP_TRANSPORT_UDP;
07645    } else {
07646       transport = SIP_TRANSPORT_UDP;
07647       ast_log(LOG_NOTICE, "'%.3s' is not a valid transport type on line %d of sip.conf. defaulting to udp.\n", pre2.transport, lineno);
07648    }
07649 
07650    /* if no portnum specified, set default for transport */
07651    if (!portnum) {
07652       if (transport == SIP_TRANSPORT_TLS) {
07653          portnum = STANDARD_TLS_PORT;
07654       } else {
07655          portnum = STANDARD_SIP_PORT;
07656       }
07657    }
07658 
07659    if (!(reg = ast_calloc(1, sizeof(*reg)))) {
07660       ast_log(LOG_ERROR, "Out of memory. Can't allocate SIP registry entry\n");
07661       return -1;
07662    }
07663 
07664    if (ast_string_field_init(reg, 256)) {
07665       ast_log(LOG_ERROR, "Out of memory. Can't allocate SIP registry strings\n");
07666       ast_free(reg);
07667       return -1;
07668    }
07669 
07670    ast_atomic_fetchadd_int(&regobjs, 1);
07671    ASTOBJ_INIT(reg);
07672    ast_string_field_set(reg, callback, ast_strip_quoted(S_OR(host2.extension, "s"), "\"", "\""));
07673    ast_string_field_set(reg, username, ast_strip_quoted(S_OR(user1.userpart, ""), "\"", "\""));
07674    ast_string_field_set(reg, hostname, ast_strip_quoted(S_OR(host3.host, ""), "\"", "\""));
07675    ast_string_field_set(reg, authuser, ast_strip_quoted(S_OR(user1.authuser, ""), "\"", "\""));
07676    ast_string_field_set(reg, secret, ast_strip_quoted(S_OR(user1.secret, ""), "\"", "\""));
07677    ast_string_field_set(reg, peername, ast_strip_quoted(S_OR(pre1.peer, ""), "\"", "\""));
07678 
07679    reg->transport = transport;
07680    reg->timeout = reg->expire = -1;
07681    reg->refresh = reg->expiry = reg->configured_expiry = (host1.expiry ? atoi(ast_strip_quoted(host1.expiry, "\"", "\"")) : default_expiry);
07682    reg->portno = portnum;
07683    reg->callid_valid = FALSE;
07684    reg->ocseq = INITIAL_CSEQ;
07685    ASTOBJ_CONTAINER_LINK(&regl, reg); /* Add the new registry entry to the list */
07686    registry_unref(reg, "unref the reg pointer");   /* release the reference given by ASTOBJ_INIT. The container has another reference */
07687    return 0;
07688 }
07689 
07690 /*! \brief Parse mwi=> line in sip.conf and add to list */
07691 static int sip_subscribe_mwi(const char *value, int lineno)
07692 {
07693    struct sip_subscription_mwi *mwi;
07694    int portnum = 0;
07695    enum sip_transport transport = SIP_TRANSPORT_UDP;
07696    char buf[256] = "";
07697    char *username = NULL, *hostname = NULL, *secret = NULL, *authuser = NULL, *porta = NULL, *mailbox = NULL;
07698    
07699    if (!value) {
07700       return -1;
07701    }
07702    
07703    ast_copy_string(buf, value, sizeof(buf));
07704 
07705    sip_parse_host(buf, lineno, &username, &portnum, &transport);
07706    
07707    if ((hostname = strrchr(username, '@'))) {
07708       *hostname++ = '\0';
07709    }
07710    
07711    if ((secret = strchr(username, ':'))) {
07712       *secret++ = '\0';
07713       if ((authuser = strchr(secret, ':'))) {
07714          *authuser++ = '\0';
07715       }
07716    }
07717    
07718    if ((mailbox = strchr(hostname, '/'))) {
07719       *mailbox++ = '\0';
07720    }
07721 
07722    if (ast_strlen_zero(username) || ast_strlen_zero(hostname) || ast_strlen_zero(mailbox)) {
07723       ast_log(LOG_WARNING, "Format for MWI subscription is user[:secret[:authuser]]@host[:port][/mailbox] at line %d\n", lineno);
07724       return -1;
07725    }
07726    
07727    if ((porta = strchr(hostname, ':'))) {
07728       *porta++ = '\0';
07729       if (!(portnum = atoi(porta))) {
07730          ast_log(LOG_WARNING, "%s is not a valid port number at line %d\n", porta, lineno);
07731          return -1;
07732       }
07733    }
07734    
07735    if (!(mwi = ast_calloc(1, sizeof(*mwi)))) {
07736       return -1;
07737    }
07738    
07739    if (ast_string_field_init(mwi, 256)) {
07740       ast_free(mwi);
07741       return -1;
07742    }
07743    
07744    ASTOBJ_INIT(mwi);
07745    ast_string_field_set(mwi, username, username);
07746    if (secret) {
07747       ast_string_field_set(mwi, secret, secret);
07748    }
07749    if (authuser) {
07750       ast_string_field_set(mwi, authuser, authuser);
07751    }
07752    ast_string_field_set(mwi, hostname, hostname);
07753    ast_string_field_set(mwi, mailbox, mailbox);
07754    mwi->resub = -1;
07755    mwi->portno = portnum;
07756    mwi->transport = transport;
07757    
07758    ASTOBJ_CONTAINER_LINK(&submwil, mwi);
07759    ASTOBJ_UNREF(mwi, sip_subscribe_mwi_destroy);
07760    
07761    return 0;
07762 }
07763 
07764 /*! \brief  Parse multiline SIP headers into one header
07765    This is enabled if pedanticsipchecking is enabled */
07766 static int lws2sws(char *msgbuf, int len) 
07767 {
07768    int h = 0, t = 0; 
07769    int lws = 0; 
07770 
07771    for (; h < len;) { 
07772       /* Eliminate all CRs */ 
07773       if (msgbuf[h] == '\r') { 
07774          h++; 
07775          continue; 
07776       } 
07777       /* Check for end-of-line */ 
07778       if (msgbuf[h] == '\n') { 
07779          /* Check for end-of-message */ 
07780          if (h + 1 == len) 
07781             break; 
07782          /* Check for a continuation line */ 
07783          if (msgbuf[h + 1] == ' ' || msgbuf[h + 1] == '\t') { 
07784             /* Merge continuation line */ 
07785             h++; 
07786             continue; 
07787          } 
07788          /* Propagate LF and start new line */ 
07789          msgbuf[t++] = msgbuf[h++]; 
07790          lws = 0;
07791          continue; 
07792       } 
07793       if (msgbuf[h] == ' ' || msgbuf[h] == '\t') { 
07794          if (lws) { 
07795             h++; 
07796             continue; 
07797          } 
07798          msgbuf[t++] = msgbuf[h++]; 
07799          lws = 1; 
07800          continue; 
07801       } 
07802       msgbuf[t++] = msgbuf[h++]; 
07803       if (lws) 
07804          lws = 0; 
07805    } 
07806    msgbuf[t] = '\0'; 
07807    return t; 
07808 }
07809 
07810 /*! \brief Parse a SIP message 
07811    \note this function is used both on incoming and outgoing packets
07812 */
07813 static int parse_request(struct sip_request *req)
07814 {
07815    char *c = req->data->str;
07816    ptrdiff_t *dst = req->header;
07817    int i = 0, lim = SIP_MAX_HEADERS - 1;
07818    unsigned int skipping_headers = 0;
07819    ptrdiff_t current_header_offset = 0;
07820    char *previous_header = "";
07821 
07822    req->header[0] = 0;
07823    req->headers = -1;   /* mark that we are working on the header */
07824    for (; *c; c++) {
07825       if (*c == '\r') {    /* remove \r */
07826          *c = '\0';
07827       } else if (*c == '\n') {   /* end of this line */
07828          *c = '\0';
07829          current_header_offset = (c + 1) - req->data->str;
07830          previous_header = req->data->str + dst[i];
07831          if (skipping_headers) {
07832             /* check to see if this line is blank; if so, turn off
07833                the skipping flag, so the next line will be processed
07834                as a body line */
07835             if (ast_strlen_zero(previous_header)) {
07836                skipping_headers = 0;
07837             }
07838             dst[i] = current_header_offset; /* record start of next line */
07839             continue;
07840          }
07841          if (sipdebug) {
07842             ast_debug(4, "%7s %2d [%3d]: %s\n",
07843                  req->headers < 0 ? "Header" : "Body",
07844                  i, (int) strlen(previous_header), previous_header);
07845          }
07846          if (ast_strlen_zero(previous_header) && req->headers < 0) {
07847             req->headers = i; /* record number of header lines */
07848             dst = req->line;  /* start working on the body */
07849             i = 0;
07850             lim = SIP_MAX_LINES - 1;
07851          } else { /* move to next line, check for overflows */
07852             if (i++ == lim) {
07853                /* if we're processing headers, then skip any remaining
07854                   headers and move on to processing the body, otherwise
07855                   we're done */
07856                if (req->headers != -1) {
07857                   break;
07858                } else {
07859                   req->headers = i;
07860                   dst = req->line;
07861                   i = 0;
07862                   lim = SIP_MAX_LINES - 1;
07863                   skipping_headers = 1;
07864                }
07865             }
07866          }
07867          dst[i] = current_header_offset; /* record start of next line */
07868       }
07869    }
07870 
07871    /* Check for last header or body line without CRLF. The RFC for SDP requires CRLF,
07872       but since some devices send without, we'll be generous in what we accept. However,
07873       if we've already reached the maximum number of lines for portion of the message
07874       we were parsing, we can't accept any more, so just ignore it.
07875    */
07876    previous_header = req->data->str + dst[i];
07877    if ((i < lim) && !ast_strlen_zero(previous_header)) {
07878       if (sipdebug) {
07879          ast_debug(4, "%7s %2d [%3d]: %s\n",
07880               req->headers < 0 ? "Header" : "Body",
07881               i, (int) strlen(previous_header), previous_header );
07882       }
07883       i++;
07884    }
07885 
07886    /* update count of header or body lines */
07887    if (req->headers >= 0) {   /* we are in the body */
07888       req->lines = i;
07889    } else {       /* no body */
07890       req->headers = i;
07891       req->lines = 0;
07892       /* req->data->used will be a NULL byte */
07893       req->line[0] = ast_str_strlen(req->data);
07894    }
07895 
07896    if (*c) {
07897       ast_log(LOG_WARNING, "Too many lines, skipping <%s>\n", c);
07898    }
07899 
07900    /* Split up the first line parts */
07901    return determine_firstline_parts(req);
07902 }
07903 
07904 /*!
07905   \brief Determine whether a SIP message contains an SDP in its body
07906   \param req the SIP request to process
07907   \return 1 if SDP found, 0 if not found
07908 
07909   Also updates req->sdp_start and req->sdp_count to indicate where the SDP
07910   lives in the message body.
07911 */
07912 static int find_sdp(struct sip_request *req)
07913 {
07914    const char *content_type;
07915    const char *content_length;
07916    const char *search;
07917    char *boundary;
07918    unsigned int x;
07919    int boundaryisquoted = FALSE;
07920    int found_application_sdp = FALSE;
07921    int found_end_of_headers = FALSE;
07922 
07923    content_length = get_header(req, "Content-Length");
07924 
07925    if (!ast_strlen_zero(content_length)) {
07926       if (sscanf(content_length, "%30u", &x) != 1) {
07927          ast_log(LOG_WARNING, "Invalid Content-Length: %s\n", content_length);
07928          return 0;
07929       }
07930 
07931       /* Content-Length of zero means there can't possibly be an
07932          SDP here, even if the Content-Type says there is */
07933       if (x == 0)
07934          return 0;
07935    }
07936 
07937    content_type = get_header(req, "Content-Type");
07938 
07939    /* if the body contains only SDP, this is easy */
07940    if (!strncasecmp(content_type, "application/sdp", 15)) {
07941       req->sdp_start = 0;
07942       req->sdp_count = req->lines;
07943       return req->lines ? 1 : 0;
07944    }
07945 
07946    /* if it's not multipart/mixed, there cannot be an SDP */
07947    if (strncasecmp(content_type, "multipart/mixed", 15))
07948       return 0;
07949 
07950    /* if there is no boundary marker, it's invalid */
07951    if ((search = strcasestr(content_type, ";boundary=")))
07952       search += 10;
07953    else if ((search = strcasestr(content_type, "; boundary=")))
07954       search += 11;
07955    else
07956       return 0;
07957 
07958    if (ast_strlen_zero(search))
07959       return 0;
07960 
07961    /* If the boundary is quoted with ", remove quote */
07962    if (*search == '\"')  {
07963       search++;
07964       boundaryisquoted = TRUE;
07965    }
07966 
07967    /* make a duplicate of the string, with two extra characters
07968       at the beginning */
07969    boundary = ast_strdupa(search - 2);
07970    boundary[0] = boundary[1] = '-';
07971    /* Remove final quote */
07972    if (boundaryisquoted)
07973       boundary[strlen(boundary) - 1] = '\0';
07974 
07975    /* search for the boundary marker, the empty line delimiting headers from
07976       sdp part and the end boundry if it exists */
07977 
07978    for (x = 0; x < (req->lines); x++) {
07979       char *line = REQ_OFFSET_TO_STR(req, line[x]);
07980       if (!strncasecmp(line, boundary, strlen(boundary))){
07981          if (found_application_sdp && found_end_of_headers) {
07982             req->sdp_count = (x - 1) - req->sdp_start;
07983             return 1;
07984          }
07985          found_application_sdp = FALSE;
07986       }
07987       if (!strcasecmp(line, "Content-Type: application/sdp"))
07988          found_application_sdp = TRUE;
07989       
07990       if (ast_strlen_zero(line)) {
07991          if (found_application_sdp && !found_end_of_headers){
07992             req->sdp_start = x;
07993             found_end_of_headers = TRUE;
07994          }
07995       }
07996    }
07997    if (found_application_sdp && found_end_of_headers) {
07998       req->sdp_count = x - req->sdp_start;
07999       return TRUE;
08000    }
08001    return FALSE;
08002 }
08003 
08004 enum media_type {
08005    SDP_AUDIO,
08006    SDP_VIDEO,
08007    SDP_IMAGE,
08008    SDP_TEXT,
08009 };
08010 
08011 static int get_ip_and_port_from_sdp(struct sip_request *req, const enum media_type media, struct sockaddr_in *sin)
08012 {
08013    const char *m;
08014    const char *c;
08015    int miterator = req->sdp_start;
08016    int citerator = req->sdp_start;
08017    int x = 0;
08018    int numberofports;
08019    int len;
08020    char host[258] = ""; /*Initialize to empty so we will know if we have any input */
08021    struct ast_hostent audiohp;
08022    struct hostent *hp;
08023 
08024    c = get_sdp_iterate(&citerator, req, "c");
08025    if (sscanf(c, "IN IP4 %256s", host) != 1) {
08026       ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
08027       /* Continue since there may be a valid host in a c= line specific to the audio stream */
08028    }
08029    /* We only want the m and c lines for audio */
08030    for (m = get_sdp_iterate(&miterator, req, "m"); !ast_strlen_zero(m); m = get_sdp_iterate(&miterator, req, "m")) {
08031       if ((media == SDP_AUDIO && ((sscanf(m, "audio %30u/%30u RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
08032           (sscanf(m, "audio %30u RTP/AVP %n", &x, &len) == 1 && len > 0))) ||
08033          (media == SDP_VIDEO && ((sscanf(m, "video %30u/%30u RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
08034           (sscanf(m, "video %30u RTP/AVP %n", &x, &len) == 1 && len > 0)))) {
08035          /* See if there's a c= line for this media stream.
08036           * XXX There is no guarantee that we'll be grabbing the c= line for this
08037           * particular media stream here. However, this is the same logic used in process_sdp.
08038           */
08039          c = get_sdp_iterate(&citerator, req, "c");
08040          if (!ast_strlen_zero(c)) {
08041             sscanf(c, "IN IP4 %256s", host);
08042          }
08043          break;
08044       }
08045    }
08046 
08047    if (ast_strlen_zero(host) || x == 0) {
08048       ast_log(LOG_WARNING, "Failed to read an alternate host or port in SDP. Expect %s problems\n", media == SDP_AUDIO ? "audio" : "video");
08049       return -1;
08050    }
08051 
08052    hp = ast_gethostbyname(host, &audiohp);
08053    if (!hp) {
08054       ast_log(LOG_WARNING, "Could not look up IP address of alternate hostname. Expect %s problems\n", media == SDP_AUDIO? "audio" : "video");
08055       return -1;
08056    }
08057 
08058    memcpy(&sin->sin_addr, hp->h_addr, sizeof(sin->sin_addr));
08059    sin->sin_port = htons(x);
08060    return 0;
08061 }
08062 
08063 /*! \brief Process SIP SDP offer, select formats and activate RTP channels
08064    If offer is rejected, we will not change any properties of the call
08065    Return 0 on success, a negative value on errors.
08066    Must be called after find_sdp().
08067 */
08068 static int process_sdp(struct sip_pvt *p, struct sip_request *req, int t38action)
08069 {
08070    /* Iterators for SDP parsing */
08071    int start = req->sdp_start;
08072    int next = start;
08073    int iterator = start;
08074 
08075    /* Temporary vars for SDP parsing */
08076    char type = '\0';
08077    const char *value = NULL;
08078    const char *m = NULL;           /* SDP media offer */
08079    const char *nextm = NULL;
08080    int len = -1;
08081 
08082    /* Host information */
08083    struct ast_hostent sessionhp;
08084    struct ast_hostent audiohp;
08085    struct ast_hostent videohp;
08086    struct ast_hostent texthp;
08087    struct ast_hostent imagehp;
08088    struct hostent *hp = NULL; /*!< RTP Audio host IP */
08089    struct hostent *vhp = NULL;   /*!< RTP video host IP */
08090    struct hostent *thp = NULL;   /*!< RTP text host IP */
08091    struct hostent *ihp = NULL;     /*!< UDPTL host ip */
08092    int portno = -1;     /*!< RTP Audio port number */
08093    int vportno = -1;    /*!< RTP Video port number */
08094    int tportno = -1;    /*!< RTP Text port number */
08095    int udptlportno = -1;      /*!< UDPTL Image port number */
08096    struct sockaddr_in sin;    /*!< media socket address */
08097    struct sockaddr_in vsin;   /*!< video socket address */
08098    struct sockaddr_in isin;   /*!< image socket address */
08099    struct sockaddr_in tsin;   /*!< text socket address */
08100 
08101    /* Peer capability is the capability in the SDP, non codec is RFC2833 DTMF (101) */ 
08102    int peercapability = 0, peernoncodeccapability = 0;
08103    int vpeercapability = 0, vpeernoncodeccapability = 0;
08104    int tpeercapability = 0, tpeernoncodeccapability = 0;
08105 
08106    struct ast_rtp *newaudiortp, *newvideortp, *newtextrtp;
08107    int newjointcapability;          /* Negotiated capability */
08108    int newpeercapability;
08109    int newnoncodeccapability;
08110 
08111    const char *codecs;
08112    int codec;
08113 
08114    /* Others */
08115    int sendonly = -1;
08116    int vsendonly = -1;
08117    int numberofports;
08118    int numberofmediastreams = 0;
08119    int last_rtpmap_codec = 0;
08120    int red_data_pt[10];    /* For T.140 red */
08121    int red_num_gen = 0;    /* For T.140 red */
08122    char red_fmtp[100] = "empty"; /* For T.140 red */
08123    int debug = sip_debug_test_pvt(p);
08124 
08125    /* START UNKNOWN */
08126    char buf[SIPBUFSIZE];
08127    /* END UNKNOWN */
08128 
08129    /* Initial check */
08130    if (!p->rtp) {
08131       ast_log(LOG_ERROR, "Got SDP but have no RTP session allocated.\n");
08132       return -1;
08133    }
08134 
08135    /* Initialize the temporary RTP structures we use to evaluate the offer from the peer */
08136 #ifdef LOW_MEMORY
08137    newaudiortp = ast_threadstorage_get(&ts_audio_rtp, ast_rtp_alloc_size());
08138 #else
08139    newaudiortp = alloca(ast_rtp_alloc_size());
08140 #endif
08141    memset(newaudiortp, 0, ast_rtp_alloc_size());
08142    ast_rtp_new_init(newaudiortp);
08143    ast_rtp_pt_clear(newaudiortp);
08144 
08145 #ifdef LOW_MEMORY
08146    newvideortp = ast_threadstorage_get(&ts_video_rtp, ast_rtp_alloc_size());
08147 #else
08148    newvideortp = alloca(ast_rtp_alloc_size());
08149 #endif
08150    memset(newvideortp, 0, ast_rtp_alloc_size());
08151    ast_rtp_new_init(newvideortp);
08152    ast_rtp_pt_clear(newvideortp);
08153 
08154 #ifdef LOW_MEMORY
08155    newtextrtp = ast_threadstorage_get(&ts_text_rtp, ast_rtp_alloc_size());
08156 #else
08157    newtextrtp = alloca(ast_rtp_alloc_size());
08158 #endif
08159    memset(newtextrtp, 0, ast_rtp_alloc_size());
08160    ast_rtp_new_init(newtextrtp);
08161    ast_rtp_pt_clear(newtextrtp);
08162 
08163    /* Update our last rtprx when we receive an SDP, too */
08164    p->lastrtprx = p->lastrtptx = time(NULL); /* XXX why both ? */
08165 
08166    memset(p->offered_media, 0, sizeof(p->offered_media));
08167 
08168 
08169    /* default: novideo and notext set */
08170    p->novideo = TRUE;
08171    p->notext = TRUE;
08172 
08173    if (p->vrtp)
08174       ast_rtp_pt_clear(newvideortp);  /* Must be cleared in case no m=video line exists */
08175  
08176    if (p->trtp)
08177       ast_rtp_pt_clear(newtextrtp);  /* Must be cleared in case no m=text line exists */
08178    
08179    /* Scan for the first media stream (m=) line to limit scanning of globals */
08180    nextm = get_sdp_iterate(&next, req, "m");
08181    if (ast_strlen_zero(nextm)) {
08182       ast_log(LOG_WARNING, "Insufficient information for SDP (m= not found)\n");
08183       return -1;
08184    }
08185 
08186    /* Scan session level SDP parameters (lines before first media stream) */
08187    while ((type = get_sdp_line(&iterator, next - 1, req, &value)) != '\0') {
08188       int processed = FALSE;
08189       switch (type) {
08190       case 'o':
08191          /* If we end up receiving SDP that doesn't actually modify the session we don't want to treat this as a fatal
08192           * error. We just want to ignore the SDP and let the rest of the packet be handled as normal.
08193           */
08194          if (!process_sdp_o(value, p))
08195             return (p->session_modify == FALSE) ? 0 : -1;
08196          break;
08197       case 'c':
08198          if (process_sdp_c(value, &sessionhp)) {
08199             processed = TRUE;
08200             hp = &sessionhp.hp;
08201             vhp = hp;
08202             thp = hp;
08203             ihp = hp;
08204          }
08205          break;
08206       case 'a':
08207          if (process_sdp_a_sendonly(value, &sendonly)) {
08208             processed = TRUE;
08209             vsendonly = sendonly;
08210          }
08211          else if (process_sdp_a_audio(value, p, newaudiortp, &last_rtpmap_codec))
08212             processed = TRUE;
08213          else if (process_sdp_a_video(value, p, newvideortp, &last_rtpmap_codec))
08214             processed = TRUE;
08215          else if (process_sdp_a_text(value, p, newtextrtp, red_fmtp, &red_num_gen, red_data_pt, &last_rtpmap_codec))
08216             processed = TRUE;
08217          else if (process_sdp_a_image(value, p))
08218             processed = TRUE;
08219          break;
08220       }
08221 
08222       if (option_debug > 2)
08223          ast_log(LOG_DEBUG, "Processing session-level SDP %c=%s... %s\n", type, value, (processed == TRUE)? "OK." : "UNSUPPORTED.");
08224    }
08225 
08226 
08227 
08228    /* Scan media stream (m=) specific parameters loop */
08229    while (!ast_strlen_zero(nextm)) {
08230       int audio = FALSE;
08231       int video = FALSE;
08232       int image = FALSE;
08233       int text = FALSE;
08234       int x;
08235 
08236       numberofports = 1;
08237       len = -1;
08238       start = next;
08239       m = nextm;
08240       iterator = next;
08241       nextm = get_sdp_iterate(&next, req, "m");
08242 
08243       /* Search for audio media definition */
08244       if ((sscanf(m, "audio %30u/%30u RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
08245           (sscanf(m, "audio %30u RTP/AVP %n", &x, &len) == 1 && len > 0)) {
08246          audio = TRUE;
08247          p->offered_media[SDP_AUDIO].offered = TRUE;
08248          numberofmediastreams++;
08249          portno = x;
08250 
08251          /* Scan through the RTP payload types specified in a "m=" line: */
08252          codecs = m + len;
08253          ast_copy_string(p->offered_media[SDP_AUDIO].text, codecs, sizeof(p->offered_media[SDP_AUDIO].text));
08254          for (; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
08255             if (sscanf(codecs, "%30u%n", &codec, &len) != 1) {
08256                ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
08257                return -1;
08258             }
08259             if (debug)
08260                ast_verbose("Found RTP audio format %d\n", codec);
08261 
08262             ast_rtp_set_m_type(newaudiortp, codec);
08263          }
08264       /* Search for video media definition */
08265       } else if ((sscanf(m, "video %30u/%30u RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
08266             (sscanf(m, "video %30u RTP/AVP %n", &x, &len) == 1 && len >= 0)) {
08267          video = TRUE;
08268          p->novideo = FALSE;
08269          p->offered_media[SDP_VIDEO].offered = TRUE;
08270          numberofmediastreams++;
08271          vportno = x;
08272 
08273          /* Scan through the RTP payload types specified in a "m=" line: */
08274          codecs = m + len;
08275          ast_copy_string(p->offered_media[SDP_VIDEO].text, codecs, sizeof(p->offered_media[SDP_VIDEO].text));
08276          for (; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
08277             if (sscanf(codecs, "%30u%n", &codec, &len) != 1) {
08278                ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
08279                return -1;
08280             }
08281             if (debug)
08282                ast_verbose("Found RTP video format %d\n", codec);
08283             ast_rtp_set_m_type(newvideortp, codec);
08284          }
08285       /* Search for text media definition */
08286       } else if ((sscanf(m, "text %30u/%30u RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
08287             (sscanf(m, "text %30u RTP/AVP %n", &x, &len) == 1 && len > 0)) {
08288          text = TRUE;
08289          p->notext = FALSE;
08290          p->offered_media[SDP_TEXT].offered = TRUE;
08291          numberofmediastreams++;
08292          tportno = x;
08293 
08294          /* Scan through the RTP payload types specified in a "m=" line: */
08295          codecs = m + len;
08296          ast_copy_string(p->offered_media[SDP_TEXT].text, codecs, sizeof(p->offered_media[SDP_TEXT].text));
08297          for (; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
08298             if (sscanf(codecs, "%30u%n", &codec, &len) != 1) {
08299                ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
08300                return -1;
08301             }
08302             if (debug)
08303                ast_verbose("Found RTP text format %d\n", codec);
08304             ast_rtp_set_m_type(newtextrtp, codec);
08305          }
08306       /* Search for image media definition */
08307       } else if (p->udptl && ((sscanf(m, "image %30u udptl t38%n", &x, &len) == 1 && len > 0) ||
08308                (sscanf(m, "image %30u UDPTL t38%n", &x, &len) == 1 && len > 0) )) {
08309          image = TRUE;
08310          if (debug)
08311             ast_verbose("Got T.38 offer in SDP in dialog %s\n", p->callid);
08312          p->offered_media[SDP_IMAGE].offered = TRUE;
08313          udptlportno = x;
08314          numberofmediastreams++;
08315 
08316          if (p->t38.state != T38_ENABLED) {
08317             memset(&p->t38.their_parms, 0, sizeof(p->t38.their_parms));
08318          }
08319       } else {
08320          ast_log(LOG_WARNING, "Unsupported SDP media type in offer: %s\n", m);
08321          continue;
08322       }
08323 
08324       /* Check for number of ports */
08325       if (numberofports > 1)
08326          ast_log(LOG_WARNING, "SDP offered %d ports for media, not supported by Asterisk. Will try anyway...\n", numberofports);
08327       
08328 
08329 
08330       /* Media stream specific parameters */
08331       while ((type = get_sdp_line(&iterator, next - 1, req, &value)) != '\0') {
08332          int processed = FALSE;
08333 
08334          switch (type) {
08335          case 'c':
08336             if (audio) {
08337                if (process_sdp_c(value, &audiohp)) {
08338                   processed = TRUE;
08339                   hp = &audiohp.hp;
08340                }
08341             } else if (video) {
08342                if (process_sdp_c(value, &videohp)) {
08343                   processed = TRUE;
08344                   vhp = &videohp.hp;
08345                }
08346             } else if (text) {
08347                if (process_sdp_c(value, &texthp)) {
08348                   processed = TRUE;
08349                   thp = &texthp.hp;
08350                }
08351             } else if (image) {
08352                if (process_sdp_c(value, &imagehp)) {
08353                   processed = TRUE;
08354                   ihp = &imagehp.hp;
08355                }
08356             }
08357             break;
08358          case 'a':
08359             /* Audio specific scanning */
08360             if (audio) {
08361                if (process_sdp_a_sendonly(value, &sendonly))
08362                   processed = TRUE;
08363                else if (process_sdp_a_audio(value, p, newaudiortp, &last_rtpmap_codec))
08364                   processed = TRUE;
08365             }
08366             /* Video specific scanning */
08367             else if (video) {
08368                if (process_sdp_a_sendonly(value, &vsendonly))
08369                   processed = TRUE;
08370                else if (process_sdp_a_video(value, p, newvideortp, &last_rtpmap_codec))
08371                   processed = TRUE;
08372             }
08373             /* Text (T.140) specific scanning */
08374             else if (text) {
08375                if (process_sdp_a_text(value, p, newtextrtp, red_fmtp, &red_num_gen, red_data_pt, &last_rtpmap_codec))
08376                   processed = TRUE;
08377             }
08378             /* Image (T.38 FAX) specific scanning */
08379             else if (image) {
08380                if (process_sdp_a_image(value, p))
08381                   processed = TRUE;
08382             }
08383             break;
08384          }
08385 
08386          if (option_debug > 2)
08387             ast_log(LOG_DEBUG, "Processing media-level (%s) SDP %c=%s... %s\n",
08388                   (audio == TRUE)? "audio" : (video == TRUE)? "video" : "image",
08389                   type, value,
08390                   (processed == TRUE)? "OK." : "UNSUPPORTED.");
08391       }
08392    }
08393 
08394 
08395    /* Sanity checks */
08396    if (!hp && !vhp && !thp && !ihp) {
08397       ast_log(LOG_WARNING, "Insufficient information in SDP (c=)...\n");
08398       return -1;
08399    }
08400 
08401    if (portno == -1 && vportno == -1 && udptlportno == -1  && tportno == -1)
08402       /* No acceptable offer found in SDP  - we have no ports */
08403       /* Do not change RTP or VRTP if this is a re-invite */
08404       return -2;
08405 
08406    if (numberofmediastreams > 3)
08407       /* We have too many fax, audio and/or video and/or text media streams, fail this offer */
08408       return -3;
08409 
08410    if (udptlportno == -1) {
08411       change_t38_state(p, T38_DISABLED);
08412    }
08413 
08414 
08415    /* Now gather all of the codecs that we are asked for: */
08416    ast_rtp_get_current_formats(newaudiortp, &peercapability, &peernoncodeccapability);
08417    ast_rtp_get_current_formats(newvideortp, &vpeercapability, &vpeernoncodeccapability);
08418    ast_rtp_get_current_formats(newtextrtp, &tpeercapability, &tpeernoncodeccapability);
08419 
08420    newjointcapability = p->capability & (peercapability | vpeercapability | tpeercapability);
08421    newpeercapability = (peercapability | vpeercapability | tpeercapability);
08422    newnoncodeccapability = p->noncodeccapability & peernoncodeccapability;
08423 
08424    if (debug) {
08425       /* shame on whoever coded this.... */
08426       char s1[SIPBUFSIZE], s2[SIPBUFSIZE], s3[SIPBUFSIZE], s4[SIPBUFSIZE], s5[SIPBUFSIZE];
08427 
08428       ast_verbose("Capabilities: us - %s, peer - audio=%s/video=%s/text=%s, combined - %s\n",
08429              ast_getformatname_multiple(s1, SIPBUFSIZE, p->capability),
08430              ast_getformatname_multiple(s2, SIPBUFSIZE, peercapability),
08431              ast_getformatname_multiple(s3, SIPBUFSIZE, vpeercapability),
08432              ast_getformatname_multiple(s4, SIPBUFSIZE, tpeercapability),
08433              ast_getformatname_multiple(s5, SIPBUFSIZE, newjointcapability));
08434 
08435       ast_verbose("Non-codec capabilities (dtmf): us - %s, peer - %s, combined - %s\n",
08436              ast_rtp_lookup_mime_multiple(s1, SIPBUFSIZE, p->noncodeccapability, 0, 0),
08437              ast_rtp_lookup_mime_multiple(s2, SIPBUFSIZE, peernoncodeccapability, 0, 0),
08438              ast_rtp_lookup_mime_multiple(s3, SIPBUFSIZE, newnoncodeccapability, 0, 0));
08439    }
08440    if (!newjointcapability && (portno != -1)) {
08441       ast_log(LOG_NOTICE, "No compatible codecs, not accepting this offer!\n");
08442       /* Do NOT Change current setting */
08443       return -1;
08444    }
08445 
08446    /* Setup audio address and port */
08447    if (p->rtp) {
08448       if (portno > 0) {
08449          sin.sin_family = AF_INET;
08450          sin.sin_port = htons(portno);
08451          memcpy(&sin.sin_addr, hp->h_addr, sizeof(sin.sin_addr));
08452          ast_rtp_set_peer(p->rtp, &sin);
08453          if (debug)
08454             ast_verbose("Peer audio RTP is at port %s:%d\n", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
08455          /* We are now ready to change the sip session and p->rtp and p->vrtp with the offered codecs, since                                                                                                    
08456             they are acceptable */
08457          p->jointcapability = newjointcapability;                /* Our joint codec profile for this call */
08458          p->peercapability = newpeercapability;                  /* The other sides capability in latest offer */
08459          p->jointnoncodeccapability = newnoncodeccapability;     /* DTMF capabilities */
08460 
08461          ast_rtp_pt_copy(p->rtp, newaudiortp);
08462 
08463          if (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO) {
08464             ast_clear_flag(&p->flags[0], SIP_DTMF);
08465             if (newnoncodeccapability & AST_RTP_DTMF) {
08466                /* XXX Would it be reasonable to drop the DSP at this point? XXX */
08467                ast_set_flag(&p->flags[0], SIP_DTMF_RFC2833);
08468                /* Since RFC2833 is now negotiated we need to change some properties of the RTP stream */
08469                ast_rtp_setdtmf(p->rtp, 1);
08470                ast_rtp_setdtmfcompensate(p->rtp, ast_test_flag(&p->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
08471             } else {
08472                ast_set_flag(&p->flags[0], SIP_DTMF_INBAND);
08473             }
08474          }
08475       } else if (udptlportno > 0) {
08476          if (debug)
08477             ast_verbose("Got T.38 Re-invite without audio. Keeping RTP active during T.38 session.\n");
08478       } else {
08479          ast_rtp_stop(p->rtp);
08480          if (debug)
08481             ast_verbose("Peer doesn't provide audio\n");
08482       }
08483    }
08484 
08485    /* Setup video address and port */
08486    if (p->vrtp) {
08487       if (vportno > 0) {
08488          vsin.sin_family = AF_INET;
08489          vsin.sin_port = htons(vportno);
08490          memcpy(&vsin.sin_addr, vhp->h_addr, sizeof(vsin.sin_addr));
08491          ast_rtp_set_peer(p->vrtp, &vsin);
08492          if (debug) 
08493             ast_verbose("Peer video RTP is at port %s:%d\n", ast_inet_ntoa(vsin.sin_addr), ntohs(vsin.sin_port));
08494          ast_rtp_pt_copy(p->vrtp, newvideortp);
08495       } else {
08496          ast_rtp_stop(p->vrtp);
08497          if (debug)
08498             ast_verbose("Peer doesn't provide video\n");
08499       }
08500    }
08501 
08502    /* Setup text address and port */
08503    if (p->trtp) {
08504       if (tportno > 0) {
08505          tsin.sin_family = AF_INET;
08506          tsin.sin_port = htons(tportno);
08507          memcpy(&tsin.sin_addr, thp->h_addr, sizeof(tsin.sin_addr));
08508          ast_rtp_set_peer(p->trtp, &tsin);
08509          if (debug) 
08510             ast_verbose("Peer T.140 RTP is at port %s:%d\n", ast_inet_ntoa(tsin.sin_addr), ntohs(tsin.sin_port));
08511          if ((p->jointcapability & AST_FORMAT_T140RED)) {
08512             p->red = 1;
08513             rtp_red_init(p->trtp, 300, red_data_pt, 2);
08514          } else {
08515             p->red = 0;
08516          }
08517          ast_rtp_pt_copy(p->trtp, newtextrtp);
08518       } else {
08519          ast_rtp_stop(p->trtp);
08520          if (debug)
08521             ast_verbose("Peer doesn't provide T.140\n");
08522       }
08523    }
08524    /* Setup image address and port */
08525    if (p->udptl) {
08526       if (udptlportno > 0) {
08527          isin.sin_family = AF_INET;
08528          isin.sin_port = htons(udptlportno);
08529          if (ast_test_flag(&p->flags[0], SIP_NAT) && ast_test_flag(&p->flags[1], SIP_PAGE2_UDPTL_DESTINATION)) {
08530             struct sockaddr_in remote_address = { 0, };
08531             ast_rtp_get_peer(p->rtp, &remote_address);
08532             if (remote_address.sin_addr.s_addr) {
08533                memcpy(&isin, &remote_address, sizeof(isin));
08534                if (debug) {
08535                   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));
08536                }
08537             }
08538          } else {
08539             memcpy(&isin.sin_addr, ihp->h_addr, sizeof(isin.sin_addr));
08540          }
08541          ast_udptl_set_peer(p->udptl, &isin);
08542          if (debug)
08543             ast_debug(1,"Peer T.38 UDPTL is at port %s:%d\n", ast_inet_ntoa(isin.sin_addr), ntohs(isin.sin_port));
08544 
08545          /* verify the far max ifp can be calculated. this requires far max datagram to be set. */
08546          if (!ast_udptl_get_far_max_datagram(p->udptl)) {
08547             /* setting to zero will force a default if none was provided by the SDP */
08548             ast_udptl_set_far_max_datagram(p->udptl, 0);
08549          }
08550 
08551          /* Remote party offers T38, we need to update state */
08552          if ((t38action == SDP_T38_ACCEPT) &&
08553              (p->t38.state == T38_LOCAL_REINVITE)) {
08554             change_t38_state(p, T38_ENABLED);
08555          } else if ((t38action == SDP_T38_INITIATE) &&
08556                p->owner && p->lastinvite) {
08557             change_t38_state(p, T38_PEER_REINVITE); /* T38 Offered in re-invite from remote party */
08558             /* If fax detection is enabled then send us off to the fax extension */
08559             if (ast_test_flag(&p->flags[1], SIP_PAGE2_FAX_DETECT_T38)) {
08560                ast_channel_lock(p->owner);
08561                if (strcmp(p->owner->exten, "fax")) {
08562                   const char *target_context = S_OR(p->owner->macrocontext, p->owner->context);
08563                   ast_channel_unlock(p->owner);
08564                   if (ast_exists_extension(p->owner, target_context, "fax", 1, p->owner->cid.cid_num)) {
08565                      ast_verbose(VERBOSE_PREFIX_2 "Redirecting '%s' to fax extension due to peer T.38 re-INVITE\n", p->owner->name);
08566                      pbx_builtin_setvar_helper(p->owner, "FAXEXTEN", p->owner->exten);
08567                      if (ast_async_goto(p->owner, target_context, "fax", 1)) {
08568                         ast_log(LOG_NOTICE, "Failed to async goto '%s' into fax of '%s'\n", p->owner->name, target_context);
08569                      }
08570                   } else {
08571                      ast_log(LOG_NOTICE, "T.38 re-INVITE detected but no fax extension\n");
08572                   }
08573                } else {
08574                   ast_channel_unlock(p->owner);
08575                }
08576             }
08577          }
08578       } else {
08579          ast_udptl_stop(p->udptl);
08580          if (debug)
08581             ast_debug(1, "Peer doesn't provide T.38 UDPTL\n");
08582       }
08583    }
08584 
08585    if ((portno == -1) && (p->t38.state != T38_DISABLED)) {
08586       ast_debug(3, "Have T.38 but no audio, accepting offer anyway\n");
08587                 return 0;
08588         }
08589 
08590    /* Ok, we're going with this offer */
08591    ast_debug(2, "We're settling with these formats: %s\n", ast_getformatname_multiple(buf, SIPBUFSIZE, p->jointcapability));
08592 
08593    if (!p->owner)    /* There's no open channel owning us so we can return here. For a re-invite or so, we proceed */
08594       return 0;
08595 
08596    ast_debug(4, "We have an owner, now see if we need to change this call\n");
08597 
08598    if (!(p->owner->nativeformats & p->jointcapability) && (p->jointcapability & AST_FORMAT_AUDIO_MASK)) {
08599       if (debug) {
08600          char s1[SIPBUFSIZE], s2[SIPBUFSIZE];
08601          ast_debug(1, "Oooh, we need to change our audio formats since our peer supports only %s and not %s\n", 
08602             ast_getformatname_multiple(s1, SIPBUFSIZE, p->jointcapability),
08603             ast_getformatname_multiple(s2, SIPBUFSIZE, p->owner->nativeformats));
08604       }
08605       p->owner->nativeformats = ast_codec_choose(&p->prefs, p->jointcapability, 1) | (p->capability & vpeercapability) | (p->capability & tpeercapability);
08606       ast_set_read_format(p->owner, p->owner->readformat);
08607       ast_set_write_format(p->owner, p->owner->writeformat);
08608    }
08609    
08610    if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD) && sin.sin_addr.s_addr && (!sendonly || sendonly == -1)) {
08611       ast_queue_control(p->owner, AST_CONTROL_UNHOLD);
08612       /* Activate a re-invite */
08613       ast_queue_frame(p->owner, &ast_null_frame);
08614       /* Queue Manager Unhold event */
08615       append_history(p, "Unhold", "%s", req->data->str);
08616       if (sip_cfg.callevents)
08617          manager_event(EVENT_FLAG_CALL, "Hold",
08618                   "Status: Off\r\n"
08619                   "Channel: %s\r\n"
08620                   "Uniqueid: %s\r\n",
08621                   p->owner->name,
08622                   p->owner->uniqueid);
08623       if (sip_cfg.notifyhold)
08624          sip_peer_hold(p, FALSE);
08625       ast_clear_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD); /* Clear both flags */
08626    } else if (!sin.sin_addr.s_addr || (sendonly && sendonly != -1)) {
08627       int already_on_hold = ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD);
08628       ast_queue_control_data(p->owner, AST_CONTROL_HOLD, 
08629                    S_OR(p->mohsuggest, NULL),
08630                    !ast_strlen_zero(p->mohsuggest) ? strlen(p->mohsuggest) + 1 : 0);
08631       if (sendonly)
08632          ast_rtp_stop(p->rtp);
08633       /* RTCP needs to go ahead, even if we're on hold!!! */
08634       /* Activate a re-invite */
08635       ast_queue_frame(p->owner, &ast_null_frame);
08636       /* Queue Manager Hold event */
08637       append_history(p, "Hold", "%s", req->data->str);
08638       if (sip_cfg.callevents && !ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
08639          manager_event(EVENT_FLAG_CALL, "Hold",
08640                   "Status: On\r\n"
08641                   "Channel: %s\r\n"
08642                   "Uniqueid: %s\r\n",
08643                   p->owner->name, 
08644                   p->owner->uniqueid);
08645       }
08646       if (sendonly == 1)   /* One directional hold (sendonly/recvonly) */
08647          ast_set_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD_ONEDIR);
08648       else if (sendonly == 2) /* Inactive stream */
08649          ast_set_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD_INACTIVE);
08650       else
08651          ast_set_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD_ACTIVE);
08652       if (sip_cfg.notifyhold && !already_on_hold)
08653          sip_peer_hold(p, TRUE);
08654    }
08655    
08656    return 0;
08657 }
08658 
08659 static int process_sdp_o(const char *o, struct sip_pvt *p)
08660 {
08661    char *o_copy;
08662    char *token;
08663    int64_t rua_version;
08664 
08665    /* Store the SDP version number of remote UA. This will allow us to
08666    distinguish between session modifications and session refreshes. If
08667    the remote UA does not send an incremented SDP version number in a
08668    subsequent RE-INVITE then that means its not changing media session.
08669    The RE-INVITE may have been sent to update connected party, remote
08670    target or to refresh the session (Session-Timers).  Asterisk must not
08671    change media session and increment its own version number in answer
08672    SDP in this case. */
08673 
08674    p->session_modify = TRUE;
08675 
08676    if (ast_strlen_zero(o)) {
08677       ast_log(LOG_WARNING, "SDP syntax error. SDP without an o= line\n");
08678       return FALSE;
08679    }
08680 
08681    o_copy = ast_strdupa(o);
08682    token = strsep(&o_copy, " ");  /* Skip username   */
08683    if (!o_copy) {
08684       ast_log(LOG_WARNING, "SDP syntax error in o= line username\n");
08685       return FALSE;
08686    }
08687    token = strsep(&o_copy, " ");  /* Skip session-id */
08688    if (!o_copy) {
08689       ast_log(LOG_WARNING, "SDP syntax error in o= line session-id\n");
08690       return FALSE;
08691    }
08692    token = strsep(&o_copy, " ");  /* Version         */
08693    if (!o_copy) {
08694       ast_log(LOG_WARNING, "SDP syntax error in o= line\n");
08695       return FALSE;
08696    }
08697    if (!sscanf(token, "%30" SCNd64, &rua_version)) {
08698       ast_log(LOG_WARNING, "SDP syntax error in o= line version\n");
08699       return FALSE;
08700    }
08701 
08702    /* we need to check the SDP version number the other end sent us;
08703     * our rules for deciding what to accept are a bit complex.
08704     *
08705     * 1) if 'ignoresdpversion' has been set for this dialog, then
08706     *    we will just accept whatever they sent and assume it is
08707     *    a modification of the session, even if it is not
08708     * 2) otherwise, if this is the first SDP we've seen from them
08709     *    we accept it
08710     * 3) otherwise, if the new SDP version number is higher than the
08711     *    old one, we accept it
08712     * 4) otherwise, if this SDP is in response to us requesting a switch
08713     *    to T.38, we accept the SDP, but also generate a warning message
08714     *    that this peer should have the 'ignoresdpversion' option set,
08715     *    because it is not following the SDP offer/answer RFC; if we did
08716     *    not request a switch to T.38, then we stop parsing the SDP, as it
08717     *    has not changed from the previous version
08718     */
08719 
08720    if (ast_test_flag(&p->flags[1], SIP_PAGE2_IGNORESDPVERSION) ||
08721        (p->sessionversion_remote < 0) ||
08722        (p->sessionversion_remote < rua_version)) {
08723       p->sessionversion_remote = rua_version;
08724    } else {
08725       if (p->t38.state == T38_LOCAL_REINVITE) {
08726          p->sessionversion_remote = rua_version;
08727          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);
08728       } else {
08729          p->session_modify = FALSE;
08730          ast_debug(2, "Call %s responded to our reinvite without changing SDP version; ignoring SDP.\n", p->callid);
08731          return FALSE;
08732       }
08733    }
08734 
08735    return TRUE;
08736 }
08737 
08738 static int process_sdp_c(const char *c, struct ast_hostent *ast_hp)
08739 {
08740    char host[258];
08741    struct hostent *hp;
08742 
08743    /* Check for Media-description-level-address */
08744    if (sscanf(c, "IN IP4 %255s", host) != 1) {
08745       ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
08746       return FALSE;
08747    } else {
08748       if (!(hp = ast_gethostbyname(host, ast_hp))) {
08749          ast_log(LOG_WARNING, "Unable to lookup RTP Audio host in c= line, '%s'\n", c);
08750          return FALSE;
08751       }
08752       return TRUE;
08753    }
08754    return FALSE;
08755 }
08756 
08757 static int process_sdp_a_sendonly(const char *a, int *sendonly)
08758 {
08759    int found = FALSE;
08760 
08761    if (!strcasecmp(a, "sendonly")) {
08762       if (*sendonly == -1)
08763          *sendonly = 1;
08764       found = TRUE;
08765    } else if (!strcasecmp(a, "inactive")) {
08766       if (*sendonly == -1)
08767          *sendonly = 2;
08768       found = TRUE;
08769    }  else if (!strcasecmp(a, "sendrecv")) {
08770       if (*sendonly == -1)
08771          *sendonly = 0;
08772       found = TRUE;
08773    }
08774    return found;
08775 }
08776 
08777 static int process_sdp_a_audio(const char *a, struct sip_pvt *p, struct ast_rtp *newaudiortp, int *last_rtpmap_codec)
08778 {
08779    int found = FALSE;
08780    int codec;
08781    char mimeSubtype[128];
08782    char fmtp_string[64];
08783    unsigned int sample_rate;
08784    int debug = sip_debug_test_pvt(p);
08785 
08786    if (!strncasecmp(a, "ptime", 5)) {
08787       char *tmp = strrchr(a, ':');
08788       long int framing = 0;
08789       if (tmp) {
08790          tmp++;
08791          framing = strtol(tmp, NULL, 10);
08792          if (framing == LONG_MIN || framing == LONG_MAX) {
08793             framing = 0;
08794             ast_debug(1, "Can't read framing from SDP: %s\n", a);
08795          }
08796       }
08797       if (framing && p->autoframing) {
08798          struct ast_codec_pref *pref = ast_rtp_codec_getpref(p->rtp);
08799          int codec_n;
08800          int format = 0;
08801          for (codec_n = 0; codec_n < MAX_RTP_PT; codec_n++) {
08802             format = ast_rtp_codec_getformat(codec_n);
08803             if (!format)   /* non-codec or not found */
08804                continue;
08805             if (option_debug)
08806                ast_log(LOG_DEBUG, "Setting framing for %d to %ld\n", format, framing);
08807             ast_codec_pref_setsize(pref, format, framing);
08808          }
08809          ast_rtp_codec_setpref(p->rtp, pref);
08810       }
08811       found = TRUE;
08812    } else if (sscanf(a, "rtpmap: %30u %127[^/]/%30u", &codec, mimeSubtype, &sample_rate) == 3) {
08813       /* We have a rtpmap to handle */
08814       if (*last_rtpmap_codec < SDP_MAX_RTPMAP_CODECS) {
08815          if (ast_rtp_set_rtpmap_type_rate(newaudiortp, codec, "audio", mimeSubtype,
08816              ast_test_flag(&p->flags[0], SIP_G726_NONSTANDARD) ? AST_RTP_OPT_G726_NONSTANDARD : 0, sample_rate) != -1) {
08817             if (debug)
08818                ast_verbose("Found audio description format %s for ID %d\n", mimeSubtype, codec);
08819             //found_rtpmap_codecs[last_rtpmap_codec] = codec;
08820             (*last_rtpmap_codec)++;
08821             found = TRUE;
08822          } else {
08823             ast_rtp_unset_m_type(newaudiortp, codec);
08824             if (debug)
08825                ast_verbose("Found unknown media description format %s for ID %d\n", mimeSubtype, codec);
08826          }
08827       } else {
08828          if (debug)
08829             ast_verbose("Discarded description format %s for ID %d\n", mimeSubtype, codec);
08830       }
08831    } else if (sscanf(a, "fmtp: %30u %63s", &codec, fmtp_string) == 2) {
08832       struct rtpPayloadType payload;
08833 
08834       payload = ast_rtp_lookup_pt(newaudiortp, codec);
08835       if (payload.code && payload.isAstFormat) {
08836          unsigned int bit_rate;
08837 
08838          switch (payload.code) {
08839          case AST_FORMAT_SIREN7:
08840             if (sscanf(fmtp_string, "bitrate=%30u", &bit_rate) == 1) {
08841                if (bit_rate != 32000) {
08842                   ast_log(LOG_WARNING, "Got Siren7 offer at %d bps, but only 32000 bps supported; ignoring.\n", bit_rate);
08843                   ast_rtp_unset_m_type(newaudiortp, codec);
08844                } else {
08845                   found = TRUE;
08846                }
08847             }
08848             break;
08849          case AST_FORMAT_SIREN14:
08850             if (sscanf(fmtp_string, "bitrate=%30u", &bit_rate) == 1) {
08851                if (bit_rate != 48000) {
08852                   ast_log(LOG_WARNING, "Got Siren14 offer at %d bps, but only 48000 bps supported; ignoring.\n", bit_rate);
08853                   ast_rtp_unset_m_type(newaudiortp, codec);
08854                } else {
08855                   found = TRUE;
08856                }
08857             }
08858             break;
08859          }
08860       }
08861    }
08862 
08863    return found;
08864 }
08865 
08866 static int process_sdp_a_video(const char *a, struct sip_pvt *p, struct ast_rtp *newvideortp, int *last_rtpmap_codec)
08867 {
08868    int found = FALSE;
08869    int codec;
08870    char mimeSubtype[128];
08871    unsigned int sample_rate;
08872    int debug = sip_debug_test_pvt(p);
08873 
08874    if (sscanf(a, "rtpmap: %30u %127[^/]/%30u", &codec, mimeSubtype, &sample_rate) == 3) {
08875       /* We have a rtpmap to handle */
08876       if (*last_rtpmap_codec < SDP_MAX_RTPMAP_CODECS) {
08877          /* Note: should really look at the '#chans' params too */
08878          if (!strncasecmp(mimeSubtype, "H26", 3) || !strncasecmp(mimeSubtype, "MP4", 3)) {
08879             if (ast_rtp_set_rtpmap_type_rate(newvideortp, codec, "video", mimeSubtype, 0, sample_rate) != -1) {
08880                if (debug)
08881                   ast_verbose("Found video description format %s for ID %d\n", mimeSubtype, codec);
08882                //found_rtpmap_codecs[last_rtpmap_codec] = codec;
08883                (*last_rtpmap_codec)++;
08884                found = TRUE;
08885             } else {
08886                ast_rtp_unset_m_type(newvideortp, codec);
08887                if (debug) 
08888                   ast_verbose("Found unknown media description format %s for ID %d\n", mimeSubtype, codec);
08889             }
08890          }
08891       } else {
08892          if (debug)
08893             ast_verbose("Discarded description format %s for ID %d\n", mimeSubtype, codec);
08894       }
08895    }
08896 
08897    return found;
08898 }
08899 
08900 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)
08901 {
08902    int found = FALSE;
08903    int codec;
08904    char mimeSubtype[128];
08905    unsigned int sample_rate;
08906    char *red_cp;
08907    int debug = sip_debug_test_pvt(p);
08908 
08909    if (sscanf(a, "rtpmap: %30u %127[^/]/%30u", &codec, mimeSubtype, &sample_rate) == 3) {
08910       /* We have a rtpmap to handle */
08911       if (*last_rtpmap_codec < SDP_MAX_RTPMAP_CODECS) {
08912          if (!strncasecmp(mimeSubtype, "T140", 4)) { /* Text */
08913             if (p->trtp) {
08914                /* ast_verbose("Adding t140 mimeSubtype to textrtp struct\n"); */
08915                ast_rtp_set_rtpmap_type(newtextrtp, codec, "text", mimeSubtype, 0);
08916                found = TRUE;
08917             }
08918          } else if (!strncasecmp(mimeSubtype, "RED", 3)) { /* Text with Redudancy */
08919             if (p->trtp) {
08920                ast_rtp_set_rtpmap_type(newtextrtp, codec, "text", mimeSubtype, 0);
08921                sprintf(red_fmtp, "fmtp:%d ", codec); 
08922                if (debug)
08923                   ast_verbose("RED submimetype has payload type: %d\n", codec);
08924                found = TRUE;
08925             }
08926          }
08927       } else {
08928          if (debug)
08929             ast_verbose("Discarded description format %s for ID %d\n", mimeSubtype, codec);
08930       }
08931    } else if (!strncmp(a, red_fmtp, strlen(red_fmtp))) {
08932       /* count numbers of generations in fmtp */
08933       red_cp = &red_fmtp[strlen(red_fmtp)];
08934       strncpy(red_fmtp, a, 100);
08935 
08936       sscanf(red_cp, "%30u", &red_data_pt[*red_num_gen]);
08937       red_cp = strtok(red_cp, "/");
08938       while (red_cp && (*red_num_gen)++ < RED_MAX_GENERATION) {
08939          sscanf(red_cp, "%30u", &red_data_pt[*red_num_gen]);
08940          red_cp = strtok(NULL, "/");
08941       }
08942       red_cp = red_fmtp;
08943       found = TRUE;
08944    }
08945 
08946    return found;
08947 }
08948 
08949 static int process_sdp_a_image(const char *a, struct sip_pvt *p)
08950 {
08951    int found = FALSE;
08952    char s[256];
08953    unsigned int x;
08954 
08955    if ((sscanf(a, "T38FaxMaxBuffer:%30u", &x) == 1)) {
08956       ast_debug(3, "MaxBufferSize:%d\n", x);
08957       found = TRUE;
08958    } else if ((sscanf(a, "T38MaxBitRate:%30u", &x) == 1) || (sscanf(a, "T38FaxMaxRate:%30u", &x) == 1)) {
08959       ast_debug(3, "T38MaxBitRate: %d\n", x);
08960       switch (x) {
08961       case 14400:
08962          p->t38.their_parms.rate = AST_T38_RATE_14400;
08963          break;
08964       case 12000:
08965          p->t38.their_parms.rate = AST_T38_RATE_12000;
08966          break;
08967       case 9600:
08968          p->t38.their_parms.rate = AST_T38_RATE_9600;
08969          break;
08970       case 7200:
08971          p->t38.their_parms.rate = AST_T38_RATE_7200;
08972          break;
08973       case 4800:
08974          p->t38.their_parms.rate = AST_T38_RATE_4800;
08975          break;
08976       case 2400:
08977          p->t38.their_parms.rate = AST_T38_RATE_2400;
08978          break;
08979       }
08980       found = TRUE;
08981    } else if ((sscanf(a, "T38FaxVersion:%30u", &x) == 1)) {
08982       ast_debug(3, "FaxVersion: %u\n", x);
08983       p->t38.their_parms.version = x;
08984       found = TRUE;
08985    } else if ((sscanf(a, "T38FaxMaxDatagram:%30u", &x) == 1) || (sscanf(a, "T38MaxDatagram:%30u", &x) == 1)) {
08986       /* override the supplied value if the configuration requests it */
08987       if (((signed int) p->t38_maxdatagram >= 0) && ((unsigned int) p->t38_maxdatagram > x)) {
08988          ast_debug(1, "Overriding T38FaxMaxDatagram '%d' with '%d'\n", x, p->t38_maxdatagram);
08989          x = p->t38_maxdatagram;
08990       }
08991       ast_debug(3, "FaxMaxDatagram: %u\n", x);
08992       ast_udptl_set_far_max_datagram(p->udptl, x);
08993       found = TRUE;
08994    } else if ((strncmp(a, "T38FaxFillBitRemoval", 20) == 0)) {
08995       if (sscanf(a, "T38FaxFillBitRemoval:%30u", &x) == 1) {
08996          ast_debug(3, "FillBitRemoval: %d\n", x);
08997          if (x == 1) {
08998             p->t38.their_parms.fill_bit_removal = TRUE;
08999          }
09000       } else {
09001          ast_debug(3, "FillBitRemoval\n");
09002          p->t38.their_parms.fill_bit_removal = TRUE;
09003       }
09004       found = TRUE;
09005    } else if ((strncmp(a, "T38FaxTranscodingMMR", 20) == 0)) {
09006       if (sscanf(a, "T38FaxTranscodingMMR:%30u", &x) == 1) {
09007          ast_debug(3, "Transcoding MMR: %d\n", x);
09008          if (x == 1) {
09009             p->t38.their_parms.transcoding_mmr = TRUE;
09010          }
09011       } else {
09012          ast_debug(3, "Transcoding MMR\n");
09013          p->t38.their_parms.transcoding_mmr = TRUE;
09014       }
09015       found = TRUE;
09016    } else if ((strncmp(a, "T38FaxTranscodingJBIG", 21) == 0)) {
09017       if (sscanf(a, "T38FaxTranscodingJBIG:%30u", &x) == 1) {
09018          ast_debug(3, "Transcoding JBIG: %d\n", x);
09019          if (x == 1) {
09020             p->t38.their_parms.transcoding_jbig = TRUE;
09021          }
09022       } else {
09023          ast_debug(3, "Transcoding JBIG\n");
09024          p->t38.their_parms.transcoding_jbig = TRUE;
09025       }
09026       found = TRUE;
09027    } else if ((sscanf(a, "T38FaxRateManagement:%255s", s) == 1)) {
09028       ast_debug(3, "RateManagement: %s\n", s);
09029       if (!strcasecmp(s, "localTCF"))
09030          p->t38.their_parms.rate_management = AST_T38_RATE_MANAGEMENT_LOCAL_TCF;
09031       else if (!strcasecmp(s, "transferredTCF"))
09032          p->t38.their_parms.rate_management = AST_T38_RATE_MANAGEMENT_TRANSFERRED_TCF;
09033       found = TRUE;
09034    } else if ((sscanf(a, "T38FaxUdpEC:%255s", s) == 1)) {
09035       ast_debug(3, "UDP EC: %s\n", s);
09036       if (!strcasecmp(s, "t38UDPRedundancy")) {
09037          ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_REDUNDANCY);
09038       } else if (!strcasecmp(s, "t38UDPFEC")) {
09039          ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_FEC);
09040       } else {
09041          ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_NONE);
09042       }
09043       found = TRUE;
09044    }
09045 
09046    return found;
09047 }
09048 
09049 
09050 #ifdef LOW_MEMORY
09051 static void ts_ast_rtp_destroy(void *data)
09052 {
09053     struct ast_rtp *tmp = data;
09054     ast_rtp_destroy(tmp);
09055 }
09056 #endif
09057 
09058 /*! \brief Add header to SIP message */
09059 static int add_header(struct sip_request *req, const char *var, const char *value)
09060 {
09061    if (req->headers == SIP_MAX_HEADERS) {
09062       ast_log(LOG_WARNING, "Out of SIP header space\n");
09063       return -1;
09064    }
09065 
09066    if (req->lines) {
09067       ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
09068       return -1;
09069    }
09070 
09071    if (sip_cfg.compactheaders) {
09072       var = find_alias(var, var);
09073    }
09074 
09075    ast_str_append(&req->data, 0, "%s: %s\r\n", var, value);
09076    req->header[req->headers] = req->len;
09077 
09078    req->len = ast_str_strlen(req->data);
09079    req->headers++;
09080 
09081    return 0;   
09082 }
09083 
09084 /*! \brief Add 'Content-Length' header to SIP message */
09085 static int add_header_contentLength(struct sip_request *req, int len)
09086 {
09087    char clen[10];
09088 
09089    snprintf(clen, sizeof(clen), "%d", len);
09090    return add_header(req, "Content-Length", clen);
09091 }
09092 
09093 /*! \brief Add content (not header) to SIP message */
09094 static int add_line(struct sip_request *req, const char *line)
09095 {
09096    if (req->lines == SIP_MAX_LINES)  {
09097       ast_log(LOG_WARNING, "Out of SIP line space\n");
09098       return -1;
09099    }
09100    if (!req->lines)
09101       /* Add extra empty return */
09102       req->len += ast_str_append(&req->data, 0, "\r\n");
09103    req->line[req->lines] = req->len;
09104    ast_str_append(&req->data, 0, "%s", line);
09105    req->len = ast_str_strlen(req->data);
09106    req->lines++;
09107    return 0;   
09108 }
09109 
09110 /*! \brief Copy one header field from one request to another */
09111 static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field)
09112 {
09113    const char *tmp = get_header(orig, field);
09114 
09115    if (!ast_strlen_zero(tmp)) /* Add what we're responding to */
09116       return add_header(req, field, tmp);
09117    ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
09118    return -1;
09119 }
09120 
09121 /*! \brief Copy all headers from one request to another */
09122 static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field)
09123 {
09124    int start = 0;
09125    int copied = 0;
09126    for (;;) {
09127       const char *tmp = __get_header(orig, field, &start);
09128 
09129       if (ast_strlen_zero(tmp))
09130          break;
09131       /* Add what we're responding to */
09132       add_header(req, field, tmp);
09133       copied++;
09134    }
09135    return copied ? 0 : -1;
09136 }
09137 
09138 /*! \brief Copy SIP VIA Headers from the request to the response
09139 \note If the client indicates that it wishes to know the port we received from,
09140    it adds ;rport without an argument to the topmost via header. We need to
09141    add the port number (from our point of view) to that parameter.
09142 \verbatim
09143    We always add ;received=<ip address> to the topmost via header.
09144 \endverbatim
09145    Received: RFC 3261, rport RFC 3581 */
09146 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field)
09147 {
09148    int copied = 0;
09149    int start = 0;
09150 
09151    for (;;) {
09152       char new[512];
09153       const char *oh = __get_header(orig, field, &start);
09154 
09155       if (ast_strlen_zero(oh))
09156          break;
09157 
09158       if (!copied) { /* Only check for empty rport in topmost via header */
09159          char leftmost[512], *others, *rport;
09160 
09161          /* Only work on leftmost value */
09162          ast_copy_string(leftmost, oh, sizeof(leftmost));
09163          others = strchr(leftmost, ',');
09164          if (others)
09165              *others++ = '\0';
09166 
09167          /* Find ;rport;  (empty request) */
09168          rport = strstr(leftmost, ";rport");
09169          if (rport && *(rport+6) == '=') 
09170             rport = NULL;     /* We already have a parameter to rport */
09171 
09172          /* Check rport if NAT=yes or NAT=rfc3581 (which is the default setting)  */
09173          if (rport && ((ast_test_flag(&p->flags[0], SIP_NAT) == SIP_NAT_ALWAYS) || (ast_test_flag(&p->flags[0], SIP_NAT) == SIP_NAT_RFC3581))) {
09174             /* We need to add received port - rport */
09175             char *end;
09176 
09177             rport = strstr(leftmost, ";rport");
09178 
09179             if (rport) {
09180                end = strchr(rport + 1, ';');
09181                if (end)
09182                   memmove(rport, end, strlen(end) + 1);
09183                else
09184                   *rport = '\0';
09185             }
09186 
09187             /* Add rport to first VIA header if requested */
09188             snprintf(new, sizeof(new), "%s;received=%s;rport=%d%s%s",
09189                leftmost, ast_inet_ntoa(p->recv.sin_addr),
09190                ntohs(p->recv.sin_port),
09191                others ? "," : "", others ? others : "");
09192          } else {
09193             /* We should *always* add a received to the topmost via */
09194             snprintf(new, sizeof(new), "%s;received=%s%s%s",
09195                leftmost, ast_inet_ntoa(p->recv.sin_addr),
09196                others ? "," : "", others ? others : "");
09197          }
09198          oh = new;   /* the header to copy */
09199       }  /* else add the following via headers untouched */
09200       add_header(req, field, oh);
09201       copied++;
09202    }
09203    if (!copied) {
09204       ast_log(LOG_NOTICE, "No header field '%s' present to copy\n", field);
09205       return -1;
09206    }
09207    return 0;
09208 }
09209 
09210 /*! \brief Add route header into request per learned route */
09211 static void add_route(struct sip_request *req, struct sip_route *route)
09212 {
09213    char r[SIPBUFSIZE*2], *p;
09214    int n, rem = sizeof(r);
09215 
09216    if (!route)
09217       return;
09218 
09219    p = r;
09220    for (;route ; route = route->next) {
09221       n = strlen(route->hop);
09222       if (rem < n+3) /* we need room for ",<route>" */
09223          break;
09224       if (p != r) {  /* add a separator after fist route */
09225          *p++ = ',';
09226          --rem;
09227       }
09228       *p++ = '<';
09229       ast_copy_string(p, route->hop, rem); /* cannot fail */
09230       p += n;
09231       *p++ = '>';
09232       rem -= (n+2);
09233    }
09234    *p = '\0';
09235    add_header(req, "Route", r);
09236 }
09237 
09238 /*! \brief Set destination from SIP URI 
09239  *
09240  * Parse uri to h (host) and port - uri is already just the part inside the <> 
09241  * general form we are expecting is sip[s]:username[:password][;parameter]@host[:port][;...] 
09242  * If there's a port given, turn NAPTR/SRV off. NAPTR might indicate SIPS preference even
09243  * for SIP: uri's
09244  *
09245  * If there's a sips: uri scheme, TLS will be required. 
09246  */
09247 static void set_destination(struct sip_pvt *p, char *uri)
09248 {
09249    char *h, *maddr, hostname[256];
09250    int port, hn;
09251    struct hostent *hp;
09252    struct ast_hostent ahp;
09253    int debug=sip_debug_test_pvt(p);
09254    int tls_on = FALSE;
09255    int use_dns = sip_cfg.srvlookup;
09256 
09257    if (debug)
09258       ast_verbose("set_destination: Parsing <%s> for address/port to send to\n", uri);
09259 
09260    /* Find and parse hostname */
09261    h = strchr(uri, '@');
09262    if (h)
09263       ++h;
09264    else {
09265       h = uri;
09266       if (!strncasecmp(h, "sip:", 4)) {
09267          h += 4;
09268       } else if (!strncasecmp(h, "sips:", 5)) {
09269          h += 5;
09270          tls_on = TRUE;
09271       }
09272    }
09273    hn = strcspn(h, ":;>") + 1;
09274    if (hn > sizeof(hostname)) 
09275       hn = sizeof(hostname);
09276    ast_copy_string(hostname, h, hn);
09277    /* XXX bug here if string has been trimmed to sizeof(hostname) */
09278    h += hn - 1;
09279 
09280    /* Is "port" present? if not default to STANDARD_SIP_PORT */
09281    if (*h == ':') {
09282       /* Parse port */
09283       ++h;
09284       port = strtol(h, &h, 10);
09285       use_dns = FALSE;
09286    } else
09287       port = tls_on ? STANDARD_TLS_PORT : STANDARD_SIP_PORT;
09288 
09289    /* Got the hostname:port - but maybe there's a "maddr=" to override address? */
09290    maddr = strstr(h, "maddr=");
09291    if (maddr) {
09292       maddr += 6;
09293       hn = strspn(maddr, "0123456789.") + 1;
09294       if (hn > sizeof(hostname))
09295          hn = sizeof(hostname);
09296       ast_copy_string(hostname, maddr, hn);
09297    }
09298 
09299    /*! \todo XXX If we have use_dns on, then look for NAPTR/SRV, otherwise, just look for A records */
09300    
09301    hp = ast_gethostbyname(hostname, &ahp);
09302    if (hp == NULL)  {
09303       ast_log(LOG_WARNING, "Can't find address for host '%s'\n", hostname);
09304       return;
09305    }
09306    p->sa.sin_family = AF_INET;
09307    memcpy(&p->sa.sin_addr, hp->h_addr, sizeof(p->sa.sin_addr));
09308    p->sa.sin_port = htons(port);
09309    if (debug)
09310       ast_verbose("set_destination: set destination to %s, port %d\n", ast_inet_ntoa(p->sa.sin_addr), port);
09311 }
09312 
09313 /*! \brief Initialize SIP response, based on SIP request */
09314 static int init_resp(struct sip_request *resp, const char *msg)
09315 {
09316    /* Initialize a response */
09317    memset(resp, 0, sizeof(*resp));
09318    resp->method = SIP_RESPONSE;
09319    if (!(resp->data = ast_str_create(SIP_MIN_PACKET)))
09320       return -1;
09321    resp->header[0] = 0;
09322    ast_str_set(&resp->data, 0, "SIP/2.0 %s\r\n", msg);
09323    resp->len = resp->data->used;
09324    resp->headers++;
09325    return 0;
09326 }
09327 
09328 /*! \brief Initialize SIP request */
09329 static int init_req(struct sip_request *req, int sipmethod, const char *recip)
09330 {
09331    /* Initialize a request */
09332    memset(req, 0, sizeof(*req));
09333    if (!(req->data = ast_str_create(SIP_MIN_PACKET)))
09334       return -1;
09335    req->method = sipmethod;
09336    req->header[0] = 0;
09337    ast_str_set(&req->data, 0, "%s %s SIP/2.0\r\n", sip_methods[sipmethod].text, recip);
09338    req->len = ast_str_strlen(req->data);
09339    req->headers++;
09340    return 0;
09341 }
09342 
09343 /*! \brief Test if this response needs a contact header */
09344 static inline int resp_needs_contact(const char *msg, enum sipmethod method) {
09345    /* Requirements for Contact header inclusion in responses generated
09346     * from the header tables found in the following RFCs.  Where the
09347     * Contact header was marked mandatory (m) or optional (o) this
09348     * function returns 1.
09349     *
09350     * - RFC 3261 (ACK, BYE, CANCEL, INVITE, OPTIONS, REGISTER)
09351     * - RFC 2976 (INFO)
09352     * - RFC 3262 (PRACK)
09353     * - RFC 3265 (SUBSCRIBE, NOTIFY)
09354     * - RFC 3311 (UPDATE)
09355     * - RFC 3428 (MESSAGE)
09356     * - RFC 3515 (REFER)
09357     * - RFC 3903 (PUBLISH)
09358     */
09359 
09360    switch (method) {
09361       /* 1xx, 2xx, 3xx, 485 */
09362       case SIP_INVITE:
09363       case SIP_UPDATE:
09364       case SIP_SUBSCRIBE:
09365       case SIP_NOTIFY:
09366          if ((msg[0] >= '1' && msg[0] <= '3') || !strncmp(msg, "485", 3))
09367             return 1;
09368          break;
09369 
09370       /* 2xx, 3xx, 485 */
09371       case SIP_REGISTER:
09372       case SIP_OPTIONS:
09373          if (msg[0] == '2' || msg[0] == '3' || !strncmp(msg, "485", 3))
09374             return 1;
09375          break;
09376 
09377       /* 3xx, 485 */
09378       case SIP_BYE:
09379       case SIP_PRACK:
09380       case SIP_MESSAGE:
09381       case SIP_PUBLISH:
09382          if (msg[0] == '3' || !strncmp(msg, "485", 3))
09383             return 1;
09384          break;
09385 
09386       /* 2xx, 3xx, 4xx, 5xx, 6xx */
09387       case SIP_REFER:
09388          if (msg[0] >= '2' && msg[0] <= '6')
09389             return 1;
09390          break;
09391 
09392       /* contact will not be included for everything else */
09393       case SIP_ACK:
09394       case SIP_CANCEL:
09395       case SIP_INFO:
09396       case SIP_PING:
09397       default:
09398          return 0;
09399    }
09400    return 0;
09401 }
09402 
09403 /*! \brief Prepare SIP response packet */
09404 static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req)
09405 {
09406    char newto[256];
09407    const char *ot;
09408 
09409    init_resp(resp, msg);
09410    copy_via_headers(p, resp, req, "Via");
09411    if (msg[0] == '1' || msg[0] == '2')
09412       copy_all_header(resp, req, "Record-Route");
09413    copy_header(resp, req, "From");
09414    ot = get_header(req, "To");
09415    if (!strcasestr(ot, "tag=") && strncmp(msg, "100", 3)) {
09416       /* Add the proper tag if we don't have it already.  If they have specified
09417          their tag, use it.  Otherwise, use our own tag */
09418       if (!ast_strlen_zero(p->theirtag) && ast_test_flag(&p->flags[0], SIP_OUTGOING))
09419          snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
09420       else if (p->tag && !ast_test_flag(&p->flags[0], SIP_OUTGOING))
09421          snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->tag);
09422       else
09423          ast_copy_string(newto, ot, sizeof(newto));
09424       ot = newto;
09425    }
09426    add_header(resp, "To", ot);
09427    copy_header(resp, req, "Call-ID");
09428    copy_header(resp, req, "CSeq");
09429    if (!ast_strlen_zero(global_useragent))
09430       add_header(resp, "Server", global_useragent);
09431    add_header(resp, "Allow", ALLOWED_METHODS);
09432    add_header(resp, "Supported", SUPPORTED_EXTENSIONS);
09433 
09434    /* If this is an invite, add Session-Timers related headers if the feature is active for this session */
09435    if (p->method == SIP_INVITE && p->stimer && p->stimer->st_active == TRUE && p->stimer->st_active_peer_ua == TRUE) {
09436       char se_hdr[256];
09437       snprintf(se_hdr, sizeof(se_hdr), "%d;refresher=%s", p->stimer->st_interval, 
09438          strefresher2str(p->stimer->st_ref));
09439       add_header(resp, "Require", "timer");
09440       add_header(resp, "Session-Expires", se_hdr);
09441    }
09442 
09443    if (msg[0] == '2' && (p->method == SIP_SUBSCRIBE || p->method == SIP_REGISTER)) {
09444       /* For registration responses, we also need expiry and
09445          contact info */
09446       char tmp[256];
09447 
09448       snprintf(tmp, sizeof(tmp), "%d", p->expiry);
09449       add_header(resp, "Expires", tmp);
09450       if (p->expiry) {  /* Only add contact if we have an expiry time */
09451          char contact[SIPBUFSIZE];
09452          const char *contact_uri = p->method == SIP_SUBSCRIBE ? p->our_contact : p->fullcontact;
09453          char *brackets = strchr(contact_uri, '<');
09454          snprintf(contact, sizeof(contact), "%s%s%s;expires=%d", brackets ? "" : "<", contact_uri, brackets ? "" : ">", p->expiry);
09455          add_header(resp, "Contact", contact);  /* Not when we unregister */
09456       }
09457    } else if (!ast_strlen_zero(p->our_contact) && resp_needs_contact(msg, p->method)) {
09458       add_header(resp, "Contact", p->our_contact);
09459    }
09460 
09461    if (!ast_strlen_zero(p->url)) {
09462       add_header(resp, "Access-URL", p->url);
09463       ast_string_field_set(p, url, NULL);
09464    }
09465 
09466    return 0;
09467 }
09468 
09469 /*! \brief Initialize a SIP request message (not the initial one in a dialog) */
09470 static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, int seqno, int newbranch)
09471 {
09472    struct sip_request *orig = &p->initreq;
09473    char stripped[80];
09474    char tmp[80];
09475    char newto[256];
09476    const char *c;
09477    const char *ot, *of;
09478    int is_strict = FALSE;     /*!< Strict routing flag */
09479    int is_outbound = ast_test_flag(&p->flags[0], SIP_OUTGOING);   /* Session direction */
09480 
09481    memset(req, 0, sizeof(struct sip_request));
09482    
09483    snprintf(p->lastmsg, sizeof(p->lastmsg), "Tx: %s", sip_methods[sipmethod].text);
09484    
09485    if (!seqno) {
09486       p->ocseq++;
09487       seqno = p->ocseq;
09488    }
09489    
09490    /* A CANCEL must have the same branch as the INVITE that it is canceling. */
09491    if (sipmethod == SIP_CANCEL) {
09492       p->branch = p->invite_branch;
09493       build_via(p);
09494    } else if (newbranch && (sipmethod == SIP_INVITE)) {
09495       p->branch ^= ast_random();
09496       p->invite_branch = p->branch;
09497       build_via(p);
09498    } else if (newbranch) {
09499       p->branch ^= ast_random();
09500       build_via(p);
09501    }
09502 
09503    /* Check for strict or loose router */
09504    if (p->route && !ast_strlen_zero(p->route->hop) && strstr(p->route->hop, ";lr") == NULL) {
09505       is_strict = TRUE;
09506       if (sipdebug)
09507          ast_debug(1, "Strict routing enforced for session %s\n", p->callid);
09508    }
09509    
09510    if (sipmethod == SIP_CANCEL)
09511       c = REQ_OFFSET_TO_STR(&p->initreq, rlPart2); /* Use original URI */
09512    else if (sipmethod == SIP_ACK) {
09513       /* Use URI from Contact: in 200 OK (if INVITE) 
09514       (we only have the contacturi on INVITEs) */
09515       if (!ast_strlen_zero(p->okcontacturi))
09516          c = is_strict ? p->route->hop : p->okcontacturi;
09517       else
09518          c = REQ_OFFSET_TO_STR(&p->initreq, rlPart2);
09519    } else if (!ast_strlen_zero(p->okcontacturi)) 
09520       c = is_strict ? p->route->hop : p->okcontacturi; /* Use for BYE or REINVITE */
09521    else if (!ast_strlen_zero(p->uri)) 
09522       c = p->uri;
09523    else {
09524       char *n;
09525       /* We have no URI, use To: or From:  header as URI (depending on direction) */
09526       ast_copy_string(stripped, get_header(orig, is_outbound ? "To" : "From"),
09527             sizeof(stripped));
09528       n = get_in_brackets(stripped);
09529       c = remove_uri_parameters(n);
09530    }  
09531    init_req(req, sipmethod, c);
09532 
09533    snprintf(tmp, sizeof(tmp), "%d %s", seqno, sip_methods[sipmethod].text);
09534 
09535    add_header(req, "Via", p->via);
09536    if (p->route) {
09537       set_destination(p, p->route->hop);
09538       add_route(req, is_strict ? p->route->next : p->route);
09539    }
09540    add_header(req, "Max-Forwards", DEFAULT_MAX_FORWARDS);
09541 
09542    ot = get_header(orig, "To");
09543    of = get_header(orig, "From");
09544 
09545    /* Add tag *unless* this is a CANCEL, in which case we need to send it exactly
09546       as our original request, including tag (or presumably lack thereof) */
09547    if (!strcasestr(ot, "tag=") && sipmethod != SIP_CANCEL) {
09548       /* Add the proper tag if we don't have it already.  If they have specified
09549          their tag, use it.  Otherwise, use our own tag */
09550       if (is_outbound && !ast_strlen_zero(p->theirtag))
09551          snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
09552       else if (!is_outbound)
09553          snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->tag);
09554       else
09555          snprintf(newto, sizeof(newto), "%s", ot);
09556       ot = newto;
09557    }
09558 
09559    if (is_outbound) {
09560       add_header(req, "From", of);
09561       add_header(req, "To", ot);
09562    } else {
09563       add_header(req, "From", ot);
09564       add_header(req, "To", of);
09565    }
09566    /* Do not add Contact for MESSAGE, BYE and Cancel requests */
09567    if (sipmethod != SIP_BYE && sipmethod != SIP_CANCEL && sipmethod != SIP_MESSAGE)
09568       add_header(req, "Contact", p->our_contact);
09569 
09570    copy_header(req, orig, "Call-ID");
09571    add_header(req, "CSeq", tmp);
09572 
09573    if (!ast_strlen_zero(global_useragent))
09574       add_header(req, "User-Agent", global_useragent);
09575 
09576    if (!ast_strlen_zero(p->rpid))
09577       add_header(req, "Remote-Party-ID", p->rpid);
09578 
09579    if (!ast_strlen_zero(p->url)) {
09580       add_header(req, "Access-URL", p->url);
09581       ast_string_field_set(p, url, NULL);
09582    }
09583 
09584    /* Add Session-Timers related headers if the feature is active for this session.
09585       An exception to this behavior is the ACK request. Since Asterisk never requires 
09586       session-timers support from a remote end-point (UAS) in an INVITE, it must 
09587       not send 'Require: timer' header in the ACK request. 
09588       This should only be added in the INVITE transactions, not MESSAGE or REFER or other
09589       in-dialog messages.
09590    */
09591    if (p->stimer && p->stimer->st_active == TRUE && p->stimer->st_active_peer_ua == TRUE 
09592        && sipmethod == SIP_INVITE) {
09593       char se_hdr[256];
09594       snprintf(se_hdr, sizeof(se_hdr), "%d;refresher=%s", p->stimer->st_interval, 
09595          strefresher2str(p->stimer->st_ref));
09596       add_header(req, "Require", "timer");
09597       add_header(req, "Session-Expires", se_hdr);
09598       snprintf(se_hdr, sizeof(se_hdr), "%d", st_get_se(p, FALSE));
09599       add_header(req, "Min-SE", se_hdr);
09600    }
09601 
09602    return 0;
09603 }
09604 
09605 /*! \brief Base transmit response function */
09606 static int __transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable)
09607 {
09608    struct sip_request resp;
09609    int seqno = 0;
09610 
09611    if (reliable && (sscanf(get_header(req, "CSeq"), "%30d ", &seqno) != 1)) {
09612       ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
09613       return -1;
09614    }
09615    respprep(&resp, p, msg, req);
09616    add_header_contentLength(&resp, 0);
09617    /* If we are cancelling an incoming invite for some reason, add information
09618       about the reason why we are doing this in clear text */
09619    if (p->method == SIP_INVITE && msg[0] != '1' && p->owner && p->owner->hangupcause) {
09620       char buf[10];
09621 
09622       add_header(&resp, "X-Asterisk-HangupCause", ast_cause2str(p->owner->hangupcause));
09623       snprintf(buf, sizeof(buf), "%d", p->owner->hangupcause);
09624       add_header(&resp, "X-Asterisk-HangupCauseCode", buf);
09625    }
09626    return send_response(p, &resp, reliable, seqno);
09627 }
09628 
09629 static int temp_pvt_init(void *data)
09630 {
09631    struct sip_pvt *p = data;
09632 
09633    p->do_history = 0;   /* XXX do we need it ? isn't already all 0 ? */
09634    return ast_string_field_init(p, 512);
09635 }
09636 
09637 static void temp_pvt_cleanup(void *data)
09638 {
09639    struct sip_pvt *p = data;
09640 
09641    ast_string_field_free_memory(p);
09642 
09643    ast_free(data);
09644 }
09645 
09646 /*! \brief Transmit response, no retransmits, using a temporary pvt structure */
09647 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)
09648 {
09649    struct sip_pvt *p = NULL;
09650 
09651    if (!(p = ast_threadstorage_get(&ts_temp_pvt, sizeof(*p)))) {
09652       ast_log(LOG_ERROR, "Failed to get temporary pvt\n");
09653       return -1;
09654    }
09655 
09656    /* XXX the structure may be dirty from previous usage.
09657     * Here we should state clearly how we should reinitialize it
09658     * before using it.
09659     * E.g. certainly the threadstorage should be left alone,
09660     * but other thihngs such as flags etc. maybe need cleanup ?
09661     */
09662     
09663    /* Initialize the bare minimum */
09664    p->method = intended_method;
09665 
09666    if (!sin)
09667       p->ourip = internip;
09668    else {
09669       p->sa = *sin;
09670       ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
09671    }
09672 
09673    p->branch = ast_random();
09674    make_our_tag(p->tag, sizeof(p->tag));
09675    p->ocseq = INITIAL_CSEQ;
09676 
09677    if (useglobal_nat && sin) {
09678       ast_copy_flags(&p->flags[0], &global_flags[0], SIP_NAT);
09679       p->recv = *sin;
09680       do_setnat(p, ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE);
09681    }
09682 
09683    ast_string_field_set(p, fromdomain, default_fromdomain);
09684    build_via(p);
09685    ast_string_field_set(p, callid, callid);
09686 
09687    copy_socket_data(&p->socket, &req->socket);
09688 
09689    /* Use this temporary pvt structure to send the message */
09690    __transmit_response(p, msg, req, XMIT_UNRELIABLE);
09691 
09692    /* Free the string fields, but not the pool space */
09693    ast_string_field_init(p, 0);
09694 
09695    return 0;
09696 }
09697 
09698 /*! \brief Transmit response, no retransmits */
09699 static int transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req) 
09700 {
09701    return __transmit_response(p, msg, req, XMIT_UNRELIABLE);
09702 }
09703 
09704 /*! \brief Transmit response, no retransmits */
09705 static int transmit_response_with_unsupported(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *unsupported) 
09706 {
09707    struct sip_request resp;
09708    respprep(&resp, p, msg, req);
09709    append_date(&resp);
09710    add_header(&resp, "Unsupported", unsupported);
09711    add_header_contentLength(&resp, 0);
09712    return send_response(p, &resp, XMIT_UNRELIABLE, 0);
09713 }
09714 
09715 /*! \brief Transmit 422 response with Min-SE header (Session-Timers)  */
09716 static int transmit_response_with_minse(struct sip_pvt *p, const char *msg, const struct sip_request *req, int minse_int)
09717 {
09718    struct sip_request resp;
09719    char minse_str[20];
09720 
09721    respprep(&resp, p, msg, req);
09722    append_date(&resp);
09723 
09724    snprintf(minse_str, sizeof(minse_str), "%d", minse_int);
09725    add_header(&resp, "Min-SE", minse_str);
09726 
09727    add_header_contentLength(&resp, 0);
09728    return send_response(p, &resp, XMIT_UNRELIABLE, 0);
09729 }
09730 
09731 
09732 /*! \brief Transmit response, Make sure you get an ACK
09733    This is only used for responses to INVITEs, where we need to make sure we get an ACK
09734 */
09735 static int transmit_response_reliable(struct sip_pvt *p, const char *msg, const struct sip_request *req)
09736 {
09737    return __transmit_response(p, msg, req, req->ignore ? XMIT_UNRELIABLE : XMIT_CRITICAL);
09738 }
09739 
09740 /*! \brief Append date to SIP message */
09741 static void append_date(struct sip_request *req)
09742 {
09743    char tmpdat[256];
09744    struct tm tm;
09745    time_t t = time(NULL);
09746 
09747    gmtime_r(&t, &tm);
09748    strftime(tmpdat, sizeof(tmpdat), "%a, %d %b %Y %T GMT", &tm);
09749    add_header(req, "Date", tmpdat);
09750 }
09751 
09752 /*! \brief Append date and content length before transmitting response */
09753 static int transmit_response_with_date(struct sip_pvt *p, const char *msg, const struct sip_request *req)
09754 {
09755    struct sip_request resp;
09756    respprep(&resp, p, msg, req);
09757    append_date(&resp);
09758    add_header_contentLength(&resp, 0);
09759    return send_response(p, &resp, XMIT_UNRELIABLE, 0);
09760 }
09761 
09762 /*! \brief Append Accept header, content length before transmitting response */
09763 static int transmit_response_with_allow(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable)
09764 {
09765    struct sip_request resp;
09766    respprep(&resp, p, msg, req);
09767    add_header(&resp, "Accept", "application/sdp");
09768    add_header_contentLength(&resp, 0);
09769    return send_response(p, &resp, reliable, 0);
09770 }
09771 
09772 /*! \brief Respond with authorization request */
09773 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)
09774 {
09775    struct sip_request resp;
09776    char tmp[512];
09777    int seqno = 0;
09778 
09779    if (reliable && (sscanf(get_header(req, "CSeq"), "%30d ", &seqno) != 1)) {
09780       ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
09781       return -1;
09782    }
09783    /* Stale means that they sent us correct authentication, but 
09784       based it on an old challenge (nonce) */
09785    snprintf(tmp, sizeof(tmp), "Digest algorithm=MD5, realm=\"%s\", nonce=\"%s\"%s", sip_cfg.realm, randdata, stale ? ", stale=true" : "");
09786    respprep(&resp, p, msg, req);
09787    add_header(&resp, header, tmp);
09788    add_header_contentLength(&resp, 0);
09789    append_history(p, "AuthChal", "Auth challenge sent for %s - nc %d", p->username, p->noncecount);
09790    return send_response(p, &resp, reliable, seqno);
09791 }
09792 
09793 /* Only use a static string for the msg, here! */
09794 static int transmit_provisional_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, int with_sdp)
09795 {
09796    int res;
09797 
09798    if (!(res = with_sdp ? transmit_response_with_sdp(p, msg, req, XMIT_UNRELIABLE, FALSE) : transmit_response(p, msg, req))) {
09799       p->last_provisional = msg;
09800       update_provisional_keepalive(p, with_sdp);
09801    }
09802 
09803    return res;
09804 }
09805 
09806 /*! \brief Add text body to SIP message */
09807 static int add_text(struct sip_request *req, const char *text)
09808 {
09809    /* XXX Convert \n's to \r\n's XXX */
09810    add_header(req, "Content-Type", "text/plain;charset=UTF-8");
09811    add_header_contentLength(req, strlen(text));
09812    add_line(req, text);
09813    return 0;
09814 }
09815 
09816 /*! \brief Add DTMF INFO tone to sip message 
09817    Mode =   0 for application/dtmf-relay (Cisco)
09818       1 for application/dtmf
09819 */
09820 static int add_digit(struct sip_request *req, char digit, unsigned int duration, int mode)
09821 {
09822    char tmp[256];
09823    int event;
09824    if (mode) {
09825       /* Application/dtmf short version used by some implementations */
09826       if (digit == '*')
09827          event = 10;
09828       else if (digit == '#')
09829          event = 11;
09830       else if ((digit >= 'A') && (digit <= 'D'))
09831          event = 12 + digit - 'A';
09832       else
09833          event = atoi(&digit);
09834       snprintf(tmp, sizeof(tmp), "%d\r\n", event);
09835       add_header(req, "Content-Type", "application/dtmf");
09836       add_header_contentLength(req, strlen(tmp));
09837       add_line(req, tmp);
09838    } else {
09839       /* Application/dtmf-relay as documented by Cisco */
09840       snprintf(tmp, sizeof(tmp), "Signal=%c\r\nDuration=%u\r\n", digit, duration);
09841       add_header(req, "Content-Type", "application/dtmf-relay");
09842       add_header_contentLength(req, strlen(tmp));
09843       add_line(req, tmp);
09844    }
09845    return 0;
09846 }
09847 
09848 /*! \brief add XML encoded media control with update 
09849    \note XML: The only way to turn 0 bits of information into a few hundred. (markster) */
09850 static int add_vidupdate(struct sip_request *req)
09851 {
09852    const char *xml_is_a_huge_waste_of_space =
09853       "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\r\n"
09854       " <media_control>\r\n"
09855       "  <vc_primitive>\r\n"
09856       "   <to_encoder>\r\n"
09857       "    <picture_fast_update>\r\n"
09858       "    </picture_fast_update>\r\n"
09859       "   </to_encoder>\r\n"
09860       "  </vc_primitive>\r\n"
09861       " </media_control>\r\n";
09862    add_header(req, "Content-Type", "application/media_control+xml");
09863    add_header_contentLength(req, strlen(xml_is_a_huge_waste_of_space));
09864    add_line(req, xml_is_a_huge_waste_of_space);
09865    return 0;
09866 }
09867 
09868 /*! \brief Add codec offer to SDP offer/answer body in INVITE or 200 OK */
09869 static void add_codec_to_sdp(const struct sip_pvt *p, int codec,
09870               struct ast_str **m_buf, struct ast_str **a_buf,
09871               int debug, int *min_packet_size)
09872 {
09873    int rtp_code;
09874    struct ast_format_list fmt;
09875 
09876 
09877    if (debug)
09878       ast_verbose("Adding codec 0x%x (%s) to SDP\n", codec, ast_getformatname(codec));
09879    if ((rtp_code = ast_rtp_lookup_code(p->rtp, 1, codec)) == -1)
09880       return;
09881 
09882    if (p->rtp) {
09883       struct ast_codec_pref *pref = ast_rtp_codec_getpref(p->rtp);
09884       fmt = ast_codec_pref_getsize(pref, codec);
09885    } 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 */
09886       return;
09887    ast_str_append(m_buf, 0, " %d", rtp_code);
09888    ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%d\r\n", rtp_code,
09889              ast_rtp_lookup_mime_subtype(1, codec,
09890                      ast_test_flag(&p->flags[0], SIP_G726_NONSTANDARD) ? AST_RTP_OPT_G726_NONSTANDARD : 0),
09891              ast_rtp_lookup_sample_rate(1, codec));
09892 
09893    switch (codec) {
09894    case AST_FORMAT_G729A:
09895       /* Indicate that we don't support VAD (G.729 annex B) */
09896       ast_str_append(a_buf, 0, "a=fmtp:%d annexb=no\r\n", rtp_code);
09897       break;
09898    case AST_FORMAT_G723_1:
09899       /* Indicate that we don't support VAD (G.723.1 annex A) */
09900       ast_str_append(a_buf, 0, "a=fmtp:%d annexa=no\r\n", rtp_code);
09901       break;
09902    case AST_FORMAT_ILBC:
09903       /* Add information about us using only 20/30 ms packetization */
09904       ast_str_append(a_buf, 0, "a=fmtp:%d mode=%d\r\n", rtp_code, fmt.cur_ms);
09905       break;
09906    case AST_FORMAT_SIREN7:
09907       /* Indicate that we only expect 32Kbps */
09908       ast_str_append(a_buf, 0, "a=fmtp:%d bitrate=32000\r\n", rtp_code);
09909       break;
09910    case AST_FORMAT_SIREN14:
09911       /* Indicate that we only expect 48Kbps */
09912       ast_str_append(a_buf, 0, "a=fmtp:%d bitrate=48000\r\n", rtp_code);
09913       break;
09914    }
09915 
09916    if (fmt.cur_ms && (fmt.cur_ms < *min_packet_size))
09917       *min_packet_size = fmt.cur_ms;
09918 
09919    /* Our first codec packetization processed cannot be zero */
09920    if ((*min_packet_size)==0 && fmt.cur_ms)
09921       *min_packet_size = fmt.cur_ms;
09922 }
09923 
09924 /*! \brief Add video codec offer to SDP offer/answer body in INVITE or 200 OK */
09925 /* This is different to the audio one now so we can add more caps later */
09926 static void add_vcodec_to_sdp(const struct sip_pvt *p, int codec,
09927               struct ast_str **m_buf, struct ast_str **a_buf,
09928               int debug, int *min_packet_size)
09929 {
09930    int rtp_code;
09931 
09932    if (!p->vrtp)
09933       return;
09934 
09935    if (debug)
09936       ast_verbose("Adding video codec 0x%x (%s) to SDP\n", codec, ast_getformatname(codec));
09937 
09938    if ((rtp_code = ast_rtp_lookup_code(p->vrtp, 1, codec)) == -1)
09939       return;
09940 
09941    ast_str_append(m_buf, 0, " %d", rtp_code);
09942    ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%d\r\n", rtp_code,
09943              ast_rtp_lookup_mime_subtype(1, codec, 0),
09944              ast_rtp_lookup_sample_rate(1, codec));
09945    /* Add fmtp code here */
09946 }
09947 
09948 /*! \brief Add text codec offer to SDP offer/answer body in INVITE or 200 OK */
09949 static void add_tcodec_to_sdp(const struct sip_pvt *p, int codec,
09950               struct ast_str **m_buf, struct ast_str **a_buf,
09951               int debug, int *min_packet_size)
09952 {
09953    int rtp_code;
09954 
09955    if (!p->trtp)
09956       return;
09957 
09958    if (debug)
09959       ast_verbose("Adding text codec 0x%x (%s) to SDP\n", codec, ast_getformatname(codec));
09960 
09961    if ((rtp_code = ast_rtp_lookup_code(p->trtp, 1, codec)) == -1)
09962       return;
09963 
09964    ast_str_append(m_buf, 0, " %d", rtp_code);
09965    ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%d\r\n", rtp_code,
09966              ast_rtp_lookup_mime_subtype(1, codec, 0),
09967              ast_rtp_lookup_sample_rate(1, codec));
09968    /* Add fmtp code here */
09969 
09970    if (codec == AST_FORMAT_T140RED) {
09971       ast_str_append(a_buf, 0, "a=fmtp:%d %d/%d/%d\r\n", rtp_code,
09972           ast_rtp_lookup_code(p->trtp, 1, AST_FORMAT_T140),
09973           ast_rtp_lookup_code(p->trtp, 1, AST_FORMAT_T140),
09974           ast_rtp_lookup_code(p->trtp, 1, AST_FORMAT_T140));
09975 
09976    }
09977 }
09978 
09979 
09980 /*! \brief Get Max T.38 Transmission rate from T38 capabilities */
09981 static unsigned int t38_get_rate(enum ast_control_t38_rate rate)
09982 {
09983    switch (rate) {
09984    case AST_T38_RATE_2400:
09985       return 2400;
09986    case AST_T38_RATE_4800:
09987       return 4800;
09988    case AST_T38_RATE_7200:
09989       return 7200;
09990    case AST_T38_RATE_9600:
09991       return 9600;
09992    case AST_T38_RATE_12000:
09993       return 12000;
09994    case AST_T38_RATE_14400:
09995       return 14400;
09996    default:
09997       return 0;
09998    }
09999 }
10000 
10001 /*! \brief Add RFC 2833 DTMF offer to SDP */
10002 static void add_noncodec_to_sdp(const struct sip_pvt *p, int format,
10003             struct ast_str **m_buf, struct ast_str **a_buf,
10004             int debug)
10005 {
10006    int rtp_code;
10007 
10008    if (debug)
10009       ast_verbose("Adding non-codec 0x%x (%s) to SDP\n", format, ast_rtp_lookup_mime_subtype(0, format, 0));
10010    if ((rtp_code = ast_rtp_lookup_code(p->rtp, 0, format)) == -1)
10011       return;
10012 
10013    ast_str_append(m_buf, 0, " %d", rtp_code);
10014    ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%d\r\n", rtp_code,
10015              ast_rtp_lookup_mime_subtype(0, format, 0),
10016              ast_rtp_lookup_sample_rate(0, format));
10017    if (format == AST_RTP_DTMF)   /* Indicate we support DTMF and FLASH... */
10018       ast_str_append(a_buf, 0, "a=fmtp:%d 0-16\r\n", rtp_code);
10019 }
10020 
10021 /*! \brief Set all IP media addresses for this call 
10022    \note called from add_sdp()
10023 */
10024 static void get_our_media_address(struct sip_pvt *p, int needvideo,
10025    struct sockaddr_in *sin, struct sockaddr_in *vsin, struct sockaddr_in *tsin,
10026    struct sockaddr_in *dest, struct sockaddr_in *vdest)
10027 {
10028    /* First, get our address */
10029    ast_rtp_get_us(p->rtp, sin);
10030    if (p->vrtp)
10031       ast_rtp_get_us(p->vrtp, vsin);
10032    if (p->trtp)
10033       ast_rtp_get_us(p->trtp, tsin);
10034 
10035    /* Now, try to figure out where we want them to send data */
10036    /* Is this a re-invite to move the media out, then use the original offer from caller  */
10037    if (p->redirip.sin_addr.s_addr) {   /* If we have a redirection IP, use it */
10038       dest->sin_port = p->redirip.sin_port;
10039       dest->sin_addr = p->redirip.sin_addr;
10040    } else {
10041       dest->sin_addr = p->ourip.sin_addr;
10042       dest->sin_port = sin->sin_port;
10043    }
10044    if (needvideo) {
10045       /* Determine video destination */
10046       if (p->vredirip.sin_addr.s_addr) {
10047          vdest->sin_addr = p->vredirip.sin_addr;
10048          vdest->sin_port = p->vredirip.sin_port;
10049       } else {
10050          vdest->sin_addr = p->ourip.sin_addr;
10051          vdest->sin_port = vsin->sin_port;
10052       }
10053    }
10054 
10055 }
10056 
10057 /*! \brief Add Session Description Protocol message 
10058 
10059     If oldsdp is TRUE, then the SDP version number is not incremented. This mechanism
10060     is used in Session-Timers where RE-INVITEs are used for refreshing SIP sessions 
10061     without modifying the media session in any way. 
10062 */
10063 static enum sip_result add_sdp(struct sip_request *resp, struct sip_pvt *p, int oldsdp, int add_audio, int add_t38)
10064 {
10065    int len = 0;
10066    int alreadysent = 0;
10067 
10068    struct sockaddr_in sin;
10069    struct sockaddr_in vsin;
10070    struct sockaddr_in tsin;
10071    struct sockaddr_in dest;
10072    struct sockaddr_in udptlsin;
10073    struct sockaddr_in vdest = { 0, };
10074    struct sockaddr_in tdest = { 0, };
10075    struct sockaddr_in udptldest = { 0, };
10076 
10077    /* SDP fields */
10078    char *version =   "v=0\r\n";     /* Protocol version */
10079    char subject[256];            /* Subject of the session */
10080    char owner[256];           /* Session owner/creator */
10081    char connection[256];            /* Connection data */
10082    char *session_time = "t=0 0\r\n";         /* Time the session is active */
10083    char bandwidth[256] = "";        /* Max bitrate */
10084    char *hold = "";
10085    struct ast_str *m_audio = ast_str_alloca(256);  /* Media declaration line for audio */
10086    struct ast_str *m_video = ast_str_alloca(256);  /* Media declaration line for video */
10087    struct ast_str *m_text = ast_str_alloca(256);   /* Media declaration line for text */
10088    struct ast_str *m_modem = ast_str_alloca(256);  /* Media declaration line for modem */
10089    struct ast_str *a_audio = ast_str_alloca(1024); /* Attributes for audio */
10090    struct ast_str *a_video = ast_str_alloca(1024); /* Attributes for video */
10091    struct ast_str *a_text = ast_str_alloca(1024);  /* Attributes for text */
10092    struct ast_str *a_modem = ast_str_alloca(1024); /* Attributes for modem */
10093 
10094    int x;
10095    int capability = 0;
10096    int needaudio = FALSE;
10097    int needvideo = FALSE;
10098    int needtext = FALSE;
10099    int debug = sip_debug_test_pvt(p);
10100    int min_audio_packet_size = 0;
10101    int min_video_packet_size = 0;
10102    int min_text_packet_size = 0;
10103 
10104    char codecbuf[SIPBUFSIZE];
10105    char buf[SIPBUFSIZE];
10106    char dummy_answer[256];
10107 
10108    /* Set the SDP session name */
10109    snprintf(subject, sizeof(subject), "s=%s\r\n", ast_strlen_zero(global_sdpsession) ? "-" : global_sdpsession);
10110 
10111    if (!p->rtp) {
10112       ast_log(LOG_WARNING, "No way to add SDP without an RTP structure\n");
10113       return AST_FAILURE;
10114    }
10115    /* XXX We should not change properties in the SIP dialog until 
10116       we have acceptance of the offer if this is a re-invite */
10117 
10118    /* Set RTP Session ID and version */
10119    if (!p->sessionid) {
10120       p->sessionid = (int)ast_random();
10121       p->sessionversion = p->sessionid;
10122    } else {
10123       if (oldsdp == FALSE)
10124          p->sessionversion++;
10125    }
10126 
10127    if (add_audio) {
10128       /* Check if we need video in this call */
10129       if ((p->jointcapability & AST_FORMAT_VIDEO_MASK) && !p->novideo) {
10130          if (p->vrtp) {
10131             needvideo = TRUE;
10132             ast_debug(2, "This call needs video offers!\n");
10133          } else
10134             ast_debug(2, "This call needs video offers, but there's no video support enabled!\n");
10135       }
10136       /* Check if we need text in this call */
10137       if ((p->jointcapability & AST_FORMAT_TEXT_MASK) && !p->notext) {
10138          if (sipdebug_text)
10139             ast_verbose("We think we can do text\n");
10140          if (p->trtp) {
10141             if (sipdebug_text) {
10142                ast_verbose("And we have a text rtp object\n");
10143             }
10144             needtext = TRUE;
10145             ast_debug(2, "This call needs text offers! \n");
10146          } else {
10147             ast_debug(2, "This call needs text offers, but there's no text support enabled ! \n");
10148          }
10149       }
10150    }
10151 
10152    get_our_media_address(p, needvideo, &sin, &vsin, &tsin, &dest, &vdest);
10153 
10154    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));
10155    snprintf(connection, sizeof(connection), "c=IN IP4 %s\r\n", ast_inet_ntoa(dest.sin_addr));
10156 
10157    if (add_audio) {
10158       capability = p->jointcapability;
10159 
10160       /* XXX note, Video and Text are negated - 'true' means 'no' */
10161       ast_debug(1, "** Our capability: %s Video flag: %s Text flag: %s\n", ast_getformatname_multiple(codecbuf, sizeof(codecbuf), capability), 
10162            p->novideo ? "True" : "False", p->notext ? "True" : "False");
10163       ast_debug(1, "** Our prefcodec: %s \n", ast_getformatname_multiple(codecbuf, sizeof(codecbuf), p->prefcodec));
10164 
10165       /* Check if we need audio */
10166       if (capability & AST_FORMAT_AUDIO_MASK)
10167          needaudio = TRUE;
10168 
10169       if (debug) 
10170          ast_verbose("Audio is at %s port %d\n", ast_inet_ntoa(p->ourip.sin_addr), ntohs(sin.sin_port)); 
10171 
10172       /* Ok, we need video. Let's add what we need for video and set codecs.
10173          Video is handled differently than audio since we can not transcode. */
10174       if (needvideo) {
10175          ast_str_append(&m_video, 0, "m=video %d RTP/AVP", ntohs(vdest.sin_port));
10176 
10177          /* Build max bitrate string */
10178          if (p->maxcallbitrate)
10179             snprintf(bandwidth, sizeof(bandwidth), "b=CT:%d\r\n", p->maxcallbitrate);
10180          if (debug) 
10181             ast_verbose("Video is at %s port %d\n", ast_inet_ntoa(p->ourip.sin_addr), ntohs(vdest.sin_port));  
10182       }
10183 
10184       /* Ok, we need text. Let's add what we need for text and set codecs.
10185          Text is handled differently than audio since we can not transcode. */
10186       if (needtext) {
10187          if (sipdebug_text)
10188             ast_verbose("Lets set up the text sdp\n");
10189          /* Determine text destination */
10190          if (p->tredirip.sin_addr.s_addr) {
10191             tdest.sin_addr = p->tredirip.sin_addr;
10192             tdest.sin_port = p->tredirip.sin_port;
10193          } else {
10194             tdest.sin_addr = p->ourip.sin_addr;
10195             tdest.sin_port = tsin.sin_port;
10196          }
10197          ast_str_append(&m_text, 0, "m=text %d RTP/AVP", ntohs(tdest.sin_port));
10198          if (debug) /* XXX should I use tdest below ? */
10199             ast_verbose("Text is at %s port %d\n", ast_inet_ntoa(p->ourip.sin_addr), ntohs(tsin.sin_port)); 
10200 
10201       }
10202 
10203       /* Start building generic SDP headers */
10204 
10205       /* We break with the "recommendation" and send our IP, in order that our
10206          peer doesn't have to ast_gethostbyname() us */
10207 
10208       ast_str_append(&m_audio, 0, "m=audio %d RTP/AVP", ntohs(dest.sin_port));
10209 
10210       if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD) == SIP_PAGE2_CALL_ONHOLD_ONEDIR)
10211          hold = "a=recvonly\r\n";
10212       else if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD) == SIP_PAGE2_CALL_ONHOLD_INACTIVE)
10213          hold = "a=inactive\r\n";
10214       else
10215          hold = "a=sendrecv\r\n";
10216 
10217       /* Now, start adding audio codecs. These are added in this order:
10218          - First what was requested by the calling channel
10219          - Then preferences in order from sip.conf device config for this peer/user
10220          - Then other codecs in capabilities, including video
10221       */
10222 
10223       /* Prefer the audio codec we were requested to use, first, no matter what 
10224          Note that p->prefcodec can include video codecs, so mask them out
10225       */
10226       if (capability & p->prefcodec) {
10227          int codec = p->prefcodec & AST_FORMAT_AUDIO_MASK;
10228 
10229          add_codec_to_sdp(p, codec, &m_audio, &a_audio, debug, &min_audio_packet_size);
10230          alreadysent |= codec;
10231       }
10232 
10233       /* Start by sending our preferred audio/video codecs */
10234       for (x = 0; x < 32; x++) {
10235          int codec;
10236 
10237          if (!(codec = ast_codec_pref_index(&p->prefs, x)))
10238             break; 
10239 
10240          if (!(capability & codec))
10241             continue;
10242 
10243          if (alreadysent & codec)
10244             continue;
10245 
10246          add_codec_to_sdp(p, codec, &m_audio, &a_audio, debug, &min_audio_packet_size);
10247          alreadysent |= codec;
10248       }
10249 
10250       /* Now send any other common audio and video codecs, and non-codec formats: */
10251       for (x = 1; x <= (needtext ? AST_FORMAT_TEXT_MASK : (needvideo ? AST_FORMAT_VIDEO_MASK : AST_FORMAT_AUDIO_MASK)); x <<= 1) {
10252          if (!(capability & x))  /* Codec not requested */
10253             continue;
10254 
10255          if (alreadysent & x) /* Already added to SDP */
10256             continue;
10257 
10258          if (x & AST_FORMAT_AUDIO_MASK)
10259             add_codec_to_sdp(p, x, &m_audio, &a_audio, debug, &min_audio_packet_size);
10260          else if (x & AST_FORMAT_VIDEO_MASK)
10261             add_vcodec_to_sdp(p, x, &m_video, &a_video, debug, &min_video_packet_size);
10262          else if (x & AST_FORMAT_TEXT_MASK)
10263             add_tcodec_to_sdp(p, x, &m_text, &a_text, debug, &min_text_packet_size);
10264       }
10265 
10266       /* Now add DTMF RFC2833 telephony-event as a codec */
10267       for (x = 1; x <= AST_RTP_MAX; x <<= 1) {
10268          if (!(p->jointnoncodeccapability & x))
10269             continue;
10270 
10271          add_noncodec_to_sdp(p, x, &m_audio, &a_audio, debug);
10272       }
10273 
10274       ast_debug(3, "-- Done with adding codecs to SDP\n");
10275 
10276       if (!p->owner || !ast_internal_timing_enabled(p->owner))
10277          ast_str_append(&a_audio, 0, "a=silenceSupp:off - - - -\r\n");
10278 
10279       if (min_audio_packet_size)
10280          ast_str_append(&a_audio, 0, "a=ptime:%d\r\n", min_audio_packet_size);
10281 
10282       /* XXX don't think you can have ptime for video */
10283       if (min_video_packet_size)
10284          ast_str_append(&a_video, 0, "a=ptime:%d\r\n", min_video_packet_size);
10285 
10286       /* XXX don't think you can have ptime for text */
10287       if (min_text_packet_size)
10288          ast_str_append(&a_text, 0, "a=ptime:%d\r\n", min_text_packet_size);
10289  
10290       if (m_audio->len - m_audio->used < 2 || m_video->len - m_video->used < 2 ||
10291           m_text->len - m_text->used < 2 || a_text->len - a_text->used < 2 ||
10292           a_audio->len - a_audio->used < 2 || a_video->len - a_video->used < 2)
10293          ast_log(LOG_WARNING, "SIP SDP may be truncated due to undersized buffer!!\n");
10294    }
10295 
10296    if (add_t38) {
10297       /* Our T.38 end is */
10298       ast_udptl_get_us(p->udptl, &udptlsin);
10299 
10300       /* Determine T.38 UDPTL destination */
10301       if (p->udptlredirip.sin_addr.s_addr) {
10302          udptldest.sin_port = p->udptlredirip.sin_port;
10303          udptldest.sin_addr = p->udptlredirip.sin_addr;
10304       } else {
10305          udptldest.sin_addr = p->ourip.sin_addr;
10306          udptldest.sin_port = udptlsin.sin_port;
10307       }
10308 
10309       if (debug)
10310          ast_debug(1, "T.38 UDPTL is at %s port %d\n", ast_inet_ntoa(p->ourip.sin_addr), ntohs(udptlsin.sin_port));
10311 
10312       /* We break with the "recommendation" and send our IP, in order that our
10313          peer doesn't have to ast_gethostbyname() us */
10314 
10315       ast_str_append(&m_modem, 0, "m=image %d udptl t38\r\n", ntohs(udptldest.sin_port));
10316 
10317       ast_str_append(&a_modem, 0, "a=T38FaxVersion:%d\r\n", p->t38.our_parms.version);
10318       ast_str_append(&a_modem, 0, "a=T38MaxBitRate:%d\r\n", t38_get_rate(p->t38.our_parms.rate));
10319       if (p->t38.our_parms.fill_bit_removal) {
10320          ast_str_append(&a_modem, 0, "a=T38FaxFillBitRemoval\r\n");
10321       }
10322       if (p->t38.our_parms.transcoding_mmr) {
10323          ast_str_append(&a_modem, 0, "a=T38FaxTranscodingMMR\r\n");
10324       }
10325       if (p->t38.our_parms.transcoding_jbig) {
10326          ast_str_append(&a_modem, 0, "a=T38FaxTranscodingJBIG\r\n");
10327       }
10328       switch (p->t38.our_parms.rate_management) {
10329       case AST_T38_RATE_MANAGEMENT_TRANSFERRED_TCF:
10330          ast_str_append(&a_modem, 0, "a=T38FaxRateManagement:transferredTCF\r\n");
10331          break;
10332       case AST_T38_RATE_MANAGEMENT_LOCAL_TCF:
10333          ast_str_append(&a_modem, 0, "a=T38FaxRateManagement:localTCF\r\n");
10334          break;
10335       }
10336       ast_str_append(&a_modem, 0, "a=T38FaxMaxDatagram:%u\r\n", ast_udptl_get_local_max_datagram(p->udptl));
10337       switch (ast_udptl_get_error_correction_scheme(p->udptl)) {
10338       case UDPTL_ERROR_CORRECTION_NONE:
10339          break;
10340       case UDPTL_ERROR_CORRECTION_FEC:
10341          ast_str_append(&a_modem, 0, "a=T38FaxUdpEC:t38UDPFEC\r\n");
10342          break;
10343       case UDPTL_ERROR_CORRECTION_REDUNDANCY:
10344          ast_str_append(&a_modem, 0, "a=T38FaxUdpEC:t38UDPRedundancy\r\n");
10345          break;
10346       }
10347    }
10348 
10349    if (needaudio)
10350       ast_str_append(&m_audio, 0, "\r\n");
10351    if (needvideo)
10352       ast_str_append(&m_video, 0, "\r\n");
10353    if (needtext)
10354       ast_str_append(&m_text, 0, "\r\n");
10355 
10356    len = strlen(version) + strlen(subject) + strlen(owner) +
10357       strlen(connection) + strlen(session_time);
10358    if (needaudio)
10359       len += m_audio->used + a_audio->used + strlen(hold);
10360    if (needvideo) /* only if video response is appropriate */
10361       len += m_video->used + a_video->used + strlen(bandwidth) + strlen(hold);
10362    if (needtext) /* only if text response is appropriate */
10363       len += m_text->used + a_text->used + strlen(hold);
10364    if (add_t38)
10365       len += m_modem->used + a_modem->used;
10366 
10367    add_header(resp, "Content-Type", "application/sdp");
10368    add_header_contentLength(resp, len);
10369    add_line(resp, version);
10370    add_line(resp, owner);
10371    add_line(resp, subject);
10372    add_line(resp, connection);
10373    if (needvideo)    /* only if video response is appropriate */
10374       add_line(resp, bandwidth);
10375    add_line(resp, session_time);
10376    if (needaudio) {
10377       add_line(resp, m_audio->str);
10378       add_line(resp, a_audio->str);
10379       add_line(resp, hold);
10380    } else if (p->offered_media[SDP_AUDIO].offered) {
10381       snprintf(dummy_answer, sizeof(dummy_answer), "m=audio 0 RTP/AVP %s\r\n", p->offered_media[SDP_AUDIO].text);
10382       add_line(resp, dummy_answer);
10383    }
10384    if (needvideo) { /* only if video response is appropriate */
10385       add_line(resp, m_video->str);
10386       add_line(resp, a_video->str);
10387       add_line(resp, hold);   /* Repeat hold for the video stream */
10388    } else if (p->offered_media[SDP_VIDEO].offered) {
10389       snprintf(dummy_answer, sizeof(dummy_answer), "m=video 0 RTP/AVP %s\r\n", p->offered_media[SDP_VIDEO].text);
10390       add_line(resp, dummy_answer);
10391    }
10392    if (needtext) { /* only if text response is appropriate */
10393       add_line(resp, m_text->str);
10394       add_line(resp, a_text->str);
10395       add_line(resp, hold);   /* Repeat hold for the text stream */
10396    } else if (p->offered_media[SDP_TEXT].offered) {
10397       snprintf(dummy_answer, sizeof(dummy_answer), "m=text 0 RTP/AVP %s\r\n", p->offered_media[SDP_TEXT].text);
10398       add_line(resp, dummy_answer);
10399    }
10400    if (add_t38) {
10401       add_line(resp, m_modem->str);
10402       add_line(resp, a_modem->str);
10403    } else if (p->offered_media[SDP_IMAGE].offered) {
10404       add_line(resp, "m=image 0 udptl t38\r\n");
10405    }
10406 
10407    /* Update lastrtprx when we send our SDP */
10408    p->lastrtprx = p->lastrtptx = time(NULL); /* XXX why both ? */
10409 
10410    ast_debug(3, "Done building SDP. Settling with this capability: %s\n", ast_getformatname_multiple(buf, SIPBUFSIZE, capability));
10411 
10412    return AST_SUCCESS;
10413 }
10414 
10415 /*! \brief Used for 200 OK and 183 early media */
10416 static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans)
10417 {
10418    struct sip_request resp;
10419    int seqno;
10420    
10421    if (sscanf(get_header(req, "CSeq"), "%30d ", &seqno) != 1) {
10422       ast_log(LOG_WARNING, "Unable to get seqno from '%s'\n", get_header(req, "CSeq"));
10423       return -1;
10424    }
10425    respprep(&resp, p, msg, req);
10426    if (p->udptl) {
10427       add_sdp(&resp, p, 0, 0, 1);
10428    } else 
10429       ast_log(LOG_ERROR, "Can't add SDP to response, since we have no UDPTL session allocated. Call-ID %s\n", p->callid);
10430    if (retrans && !p->pendinginvite)
10431       p->pendinginvite = seqno;     /* Buggy clients sends ACK on RINGING too */
10432    return send_response(p, &resp, retrans, seqno);
10433 }
10434 
10435 /*! \brief copy SIP request (mostly used to save request for responses) */
10436 static void copy_request(struct sip_request *dst, const struct sip_request *src)
10437 {
10438    struct ast_str *duplicate = dst->data;
10439 
10440    /* First copy stuff */
10441    memcpy(dst, src, sizeof(*dst));
10442    dst->data = duplicate;
10443 
10444    /* All these + 1's are to account for the need to include the NULL terminator
10445     * Using typical string functions like ast_copy_string or ast_str_set will not
10446     * work in this case because the src's data string is riddled with \0's all over
10447     * the place and so a memcpy is the only way to accurately copy the string
10448     */
10449 
10450    if (!dst->data && !(dst->data = ast_str_create(src->data->used + 1)))
10451       return;
10452    else if (dst->data->len < src->data->used + 1)
10453       ast_str_make_space(&dst->data, src->data->used + 1);
10454       
10455    memcpy(dst->data->str, src->data->str, src->data->used + 1);
10456    dst->data->used = src->data->used;
10457 }
10458 
10459 /*! \brief Used for 200 OK and 183 early media 
10460    \return Will return XMIT_ERROR for network errors.
10461 */
10462 static int transmit_response_with_sdp(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable, int oldsdp)
10463 {
10464    struct sip_request resp;
10465    int seqno;
10466    if (sscanf(get_header(req, "CSeq"), "%30d ", &seqno) != 1) {
10467       ast_log(LOG_WARNING, "Unable to get seqno from '%s'\n", get_header(req, "CSeq"));
10468       return -1;
10469    }
10470    respprep(&resp, p, msg, req);
10471    if (p->rtp) {
10472       if (!p->autoframing && !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
10473          ast_debug(1, "Setting framing from config on incoming call\n");
10474          ast_rtp_codec_setpref(p->rtp, &p->prefs);
10475       }
10476       try_suggested_sip_codec(p);
10477       if (p->t38.state == T38_ENABLED) {
10478          add_sdp(&resp, p, oldsdp, TRUE, TRUE);
10479       } else {
10480          add_sdp(&resp, p, oldsdp, TRUE, FALSE);
10481       }
10482    } else 
10483       ast_log(LOG_ERROR, "Can't add SDP to response, since we have no RTP session allocated. Call-ID %s\n", p->callid);
10484    if (reliable && !p->pendinginvite)
10485       p->pendinginvite = seqno;     /* Buggy clients sends ACK on RINGING too */
10486    return send_response(p, &resp, reliable, seqno);
10487 }
10488 
10489 /*! \brief Parse first line of incoming SIP request */
10490 static int determine_firstline_parts(struct sip_request *req) 
10491 {
10492    char *e = ast_skip_blanks(req->data->str);   /* there shouldn't be any */
10493    char *local_rlPart1;
10494 
10495    if (!*e)
10496       return -1;
10497    req->rlPart1 = e - req->data->str;  /* method or protocol */
10498    local_rlPart1 = e;
10499    e = ast_skip_nonblanks(e);
10500    if (*e)
10501       *e++ = '\0';
10502    /* Get URI or status code */
10503    e = ast_skip_blanks(e);
10504    if ( !*e )
10505       return -1;
10506    ast_trim_blanks(e);
10507 
10508    if (!strcasecmp(local_rlPart1, "SIP/2.0") ) { /* We have a response */
10509       if (strlen(e) < 3)   /* status code is 3 digits */
10510          return -1;
10511       req->rlPart2 = e - req->data->str;
10512    } else { /* We have a request */
10513       if ( *e == '<' ) { /* XXX the spec says it must not be in <> ! */
10514          ast_debug(3, "Oops. Bogus uri in <> %s\n", e);
10515          e++;
10516          if (!*e)
10517             return -1; 
10518       }
10519       req->rlPart2 = e - req->data->str;  /* URI */
10520       e = ast_skip_nonblanks(e);
10521       if (*e)
10522          *e++ = '\0';
10523       e = ast_skip_blanks(e);
10524       if (strcasecmp(e, "SIP/2.0") ) {
10525          ast_debug(3, "Skipping packet - Bad request protocol %s\n", e);
10526          return -1;
10527       }
10528    }
10529    return 1;
10530 }
10531 
10532 /*! \brief Transmit reinvite with SDP
10533 \note    A re-invite is basically a new INVITE with the same CALL-ID and TAG as the
10534    INVITE that opened the SIP dialogue 
10535    We reinvite so that the audio stream (RTP) go directly between
10536    the SIP UAs. SIP Signalling stays with * in the path.
10537    
10538    If t38version is TRUE, we send T38 SDP for re-invite from audio/video to
10539    T38 UDPTL transmission on the channel
10540 
10541     If oldsdp is TRUE then the SDP version number is not incremented. This
10542     is needed for Session-Timers so we can send a re-invite to refresh the
10543     SIP session without modifying the media session. 
10544 */
10545 static int transmit_reinvite_with_sdp(struct sip_pvt *p, int t38version, int oldsdp)
10546 {
10547    struct sip_request req;
10548    
10549    reqprep(&req, p, ast_test_flag(&p->flags[0], SIP_REINVITE_UPDATE) ?  SIP_UPDATE : SIP_INVITE, 0, 1);
10550 
10551    add_header(&req, "Allow", ALLOWED_METHODS);
10552    add_header(&req, "Supported", SUPPORTED_EXTENSIONS);
10553    if (sipdebug) {
10554       if (oldsdp == TRUE)
10555          add_header(&req, "X-asterisk-Info", "SIP re-invite (Session-Timers)");
10556       else
10557          add_header(&req, "X-asterisk-Info", "SIP re-invite (External RTP bridge)");
10558    }
10559 
10560    if (p->do_history)
10561       append_history(p, "ReInv", "Re-invite sent");
10562    memset(p->offered_media, 0, sizeof(p->offered_media));
10563 
10564    if (t38version)
10565       add_sdp(&req, p, oldsdp, FALSE, TRUE);
10566    else
10567       add_sdp(&req, p, oldsdp, TRUE, FALSE);
10568 
10569    /* Use this as the basis */
10570    initialize_initreq(p, &req);
10571    p->lastinvite = p->ocseq;
10572    ast_set_flag(&p->flags[0], SIP_OUTGOING);       /* Change direction of this dialog */
10573 
10574    return send_request(p, &req, XMIT_CRITICAL, p->ocseq);
10575 }
10576 
10577 /* \brief Remove URI parameters at end of URI, not in username part though */
10578 static char *remove_uri_parameters(char *uri)
10579 {
10580    char *atsign;
10581    atsign = strchr(uri, '@'); /* First, locate the at sign */
10582    if (!atsign)
10583       atsign = uri;  /* Ok hostname only, let's stick with the rest */
10584    atsign = strchr(atsign, ';'); /* Locate semi colon */
10585    if (atsign)
10586       *atsign = '\0';   /* Kill at the semi colon */
10587    return uri;
10588 }
10589 
10590 /*! \brief Check Contact: URI of SIP message */
10591 static void extract_uri(struct sip_pvt *p, struct sip_request *req)
10592 {
10593    char stripped[SIPBUFSIZE];
10594    char *c;
10595 
10596    ast_copy_string(stripped, get_header(req, "Contact"), sizeof(stripped));
10597    c = get_in_brackets(stripped);
10598    /* Cut the URI at the at sign after the @, not in the username part */
10599    c = remove_uri_parameters(c);
10600    if (!ast_strlen_zero(c))
10601       ast_string_field_set(p, uri, c);
10602 
10603 }
10604 
10605 /*! \brief Build contact header - the contact header we send out */
10606 static void build_contact(struct sip_pvt *p)
10607 {
10608 
10609    int ourport = ntohs(p->ourip.sin_port);
10610    /* only add port if it's non-standard for the transport type */
10611    if (!sip_standard_port(p->socket.type, ourport)) {
10612       if (p->socket.type == SIP_TRANSPORT_UDP)
10613          ast_string_field_build(p, our_contact, "<sip:%s%s%s:%d>", p->exten, ast_strlen_zero(p->exten) ? "" : "@", ast_inet_ntoa(p->ourip.sin_addr), ourport);
10614       else
10615          ast_string_field_build(p, our_contact, "<sip:%s%s%s:%d;transport=%s>", p->exten, ast_strlen_zero(p->exten) ? "" : "@", ast_inet_ntoa(p->ourip.sin_addr), ourport, get_transport(p->socket.type));
10616    } else {
10617       if (p->socket.type == SIP_TRANSPORT_UDP)
10618          ast_string_field_build(p, our_contact, "<sip:%s%s%s>", p->exten, ast_strlen_zero(p->exten) ? "" : "@", ast_inet_ntoa(p->ourip.sin_addr));
10619       else
10620          ast_string_field_build(p, our_contact, "<sip:%s%s%s;transport=%s>", p->exten, ast_strlen_zero(p->exten) ? "" : "@", ast_inet_ntoa(p->ourip.sin_addr), get_transport(p->socket.type));
10621    }
10622 }
10623 
10624 /*! \brief Build the Remote Party-ID & From using callingpres options */
10625 static void build_rpid(struct sip_pvt *p)
10626 {
10627    int send_pres_tags = TRUE;
10628    const char *privacy=NULL;
10629    const char *screen=NULL;
10630    char buf[256];
10631    const char *clid = default_callerid;
10632    const char *clin = NULL;
10633    const char *fromdomain;
10634 
10635    if (!ast_strlen_zero(p->rpid) || !ast_strlen_zero(p->rpid_from))  
10636       return;
10637 
10638    if (p->owner && !ast_strlen_zero(p->owner->cid.cid_num))
10639       clid = p->owner->cid.cid_num;
10640    if (p->owner && p->owner->cid.cid_name)
10641       clin = p->owner->cid.cid_name;
10642    if (ast_strlen_zero(clin))
10643       clin = clid;
10644 
10645    switch (p->callingpres) {
10646    case AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED:
10647       privacy = "off";
10648       screen = "no";
10649       break;
10650    case AST_PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN:
10651       privacy = "off";
10652       screen = "yes";
10653       break;
10654    case AST_PRES_ALLOWED_USER_NUMBER_FAILED_SCREEN:
10655       privacy = "off";
10656       screen = "no";
10657       break;
10658    case AST_PRES_ALLOWED_NETWORK_NUMBER:
10659       privacy = "off";
10660       screen = "yes";
10661       break;
10662    case AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED:
10663       privacy = "full";
10664       screen = "no";
10665       break;
10666    case AST_PRES_PROHIB_USER_NUMBER_PASSED_SCREEN:
10667       privacy = "full";
10668       screen = "yes";
10669       break;
10670    case AST_PRES_PROHIB_USER_NUMBER_FAILED_SCREEN:
10671       privacy = "full";
10672       screen = "no";
10673       break;
10674    case AST_PRES_PROHIB_NETWORK_NUMBER:
10675       privacy = "full";
10676       screen = "yes";
10677       break;
10678    case AST_PRES_NUMBER_NOT_AVAILABLE:
10679       send_pres_tags = FALSE;
10680       break;
10681    default:
10682       ast_log(LOG_WARNING, "Unsupported callingpres (%d)\n", p->callingpres);
10683       if ((p->callingpres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED)
10684          privacy = "full";
10685       else
10686          privacy = "off";
10687       screen = "no";
10688       break;
10689    }
10690    
10691    fromdomain = S_OR(p->fromdomain, ast_inet_ntoa(p->ourip.sin_addr));
10692 
10693    snprintf(buf, sizeof(buf), "\"%s\" <sip:%s@%s>", clin, clid, fromdomain);
10694    if (send_pres_tags)
10695       snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), ";privacy=%s;screen=%s", privacy, screen);
10696    ast_string_field_set(p, rpid, buf);
10697 
10698    ast_string_field_build(p, rpid_from, "\"%s\" <sip:%s@%s>;tag=%s", clin,
10699                 S_OR(p->fromuser, clid),
10700                 fromdomain, p->tag);
10701 }
10702 
10703 /*! \brief Initiate new SIP request to peer/user */
10704 static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod)
10705 {
10706    struct ast_str *invite = ast_str_alloca(256);
10707    char from[256];
10708    char to[256];
10709    char tmp_n[SIPBUFSIZE/2];  /* build a local copy of 'n' if needed */
10710    char tmp_l[SIPBUFSIZE/2];  /* build a local copy of 'l' if needed */
10711    const char *l = NULL;   /* XXX what is this, exactly ? */
10712    const char *n = NULL;   /* XXX what is this, exactly ? */
10713    const char *d = NULL;   /* domain in from header */
10714    const char *urioptions = "";
10715    int ourport;
10716 
10717    if (ast_test_flag(&p->flags[0], SIP_USEREQPHONE)) {
10718       const char *s = p->username;  /* being a string field, cannot be NULL */
10719 
10720       /* Test p->username against allowed characters in AST_DIGIT_ANY
10721          If it matches the allowed characters list, then sipuser = ";user=phone"
10722          If not, then sipuser = ""
10723       */
10724       /* + is allowed in first position in a tel: uri */
10725       if (*s == '+')
10726          s++;
10727       for (; *s; s++) {
10728          if (!strchr(AST_DIGIT_ANYNUM, *s) )
10729             break;
10730       }
10731       /* If we have only digits, add ;user=phone to the uri */
10732       if (!*s)
10733          urioptions = ";user=phone";
10734    }
10735 
10736 
10737    snprintf(p->lastmsg, sizeof(p->lastmsg), "Init: %s", sip_methods[sipmethod].text);
10738 
10739    d = S_OR(p->fromdomain, ast_inet_ntoa(p->ourip.sin_addr));
10740    if (p->owner) {
10741       l = p->owner->cid.cid_num;
10742       n = p->owner->cid.cid_name;
10743    }
10744    /* if we are not sending RPID and user wants his callerid restricted */
10745    if (!ast_test_flag(&p->flags[0], SIP_SENDRPID) &&
10746        ((p->callingpres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED)) {
10747       l = CALLERID_UNKNOWN;
10748       n = l;
10749       d = FROMDOMAIN_INVALID;
10750    }
10751    if (ast_strlen_zero(l))
10752       l = default_callerid;
10753    if (ast_strlen_zero(n))
10754       n = l;
10755    /* Allow user to be overridden */
10756    if (!ast_strlen_zero(p->fromuser))
10757       l = p->fromuser;
10758    else /* Save for any further attempts */
10759       ast_string_field_set(p, fromuser, l);
10760 
10761    /* Allow user to be overridden */
10762    if (!ast_strlen_zero(p->fromname))
10763       n = p->fromname;
10764    else /* Save for any further attempts */
10765       ast_string_field_set(p, fromname, n);
10766 
10767    if (sip_cfg.pedanticsipchecking) {
10768       ast_uri_encode(n, tmp_n, sizeof(tmp_n), 0);
10769       n = tmp_n;
10770       ast_uri_encode(l, tmp_l, sizeof(tmp_l), 0);
10771       l = tmp_l;
10772    }
10773 
10774    ourport = ntohs(p->ourip.sin_port);
10775    if (!sip_standard_port(p->socket.type, ourport) && ast_strlen_zero(p->fromdomain))
10776       snprintf(from, sizeof(from), "\"%s\" <sip:%s@%s:%d>;tag=%s", n, l, d, ourport, p->tag);
10777    else
10778       snprintf(from, sizeof(from), "\"%s\" <sip:%s@%s>;tag=%s", n, l, d, p->tag);
10779 
10780    /* If we're calling a registered SIP peer, use the fullcontact to dial to the peer */
10781    if (!ast_strlen_zero(p->fullcontact)) {
10782       /* If we have full contact, trust it */
10783       ast_str_append(&invite, 0, "%s", p->fullcontact);
10784    } else {
10785       /* Otherwise, use the username while waiting for registration */
10786       ast_str_append(&invite, 0, "sip:");
10787       if (!ast_strlen_zero(p->username)) {
10788          n = p->username;
10789          if (sip_cfg.pedanticsipchecking) {
10790             ast_uri_encode(n, tmp_n, sizeof(tmp_n), 0);
10791             n = tmp_n;
10792          }
10793          ast_str_append(&invite, 0, "%s@", n);
10794       }
10795       ast_str_append(&invite, 0, "%s", p->tohost);
10796       if (p->portinuri)
10797          ast_str_append(&invite, 0, ":%d", ntohs(p->sa.sin_port));
10798       ast_str_append(&invite, 0, "%s", urioptions);
10799    }
10800 
10801    /* If custom URI options have been provided, append them */
10802    if (p->options && !ast_strlen_zero(p->options->uri_options))
10803       ast_str_append(&invite, 0, ";%s", p->options->uri_options);
10804    
10805    /* This is the request URI, which is the next hop of the call
10806       which may or may not be the destination of the call
10807    */
10808    ast_string_field_set(p, uri, invite->str);
10809   
10810    if (!ast_strlen_zero(p->todnid)) {
10811       /*! \todo Need to add back the VXML URL here at some point, possibly use build_string for all this junk */
10812       if (!strchr(p->todnid, '@')) {
10813          /* We have no domain in the dnid */
10814          snprintf(to, sizeof(to), "<sip:%s@%s>%s%s", p->todnid, p->tohost, ast_strlen_zero(p->theirtag) ? "" : ";tag=", p->theirtag);
10815       } else {
10816          snprintf(to, sizeof(to), "<sip:%s>%s%s", p->todnid, ast_strlen_zero(p->theirtag) ? "" : ";tag=", p->theirtag);
10817       }
10818    } else {
10819       if (sipmethod == SIP_NOTIFY && !ast_strlen_zero(p->theirtag)) { 
10820          /* If this is a NOTIFY, use the From: tag in the subscribe (RFC 3265) */
10821          snprintf(to, sizeof(to), "<%s%s>;tag=%s", (strncasecmp(p->uri, "sip:", 4) ? "sip:" : ""), p->uri, p->theirtag);
10822       } else if (p->options && p->options->vxml_url) {
10823          /* If there is a VXML URL append it to the SIP URL */
10824          snprintf(to, sizeof(to), "<%s>;%s", p->uri, p->options->vxml_url);
10825       } else 
10826          snprintf(to, sizeof(to), "<%s>", p->uri);
10827    }
10828 
10829    init_req(req, sipmethod, p->uri);
10830    /* now tmp_n is available so reuse it to build the CSeq */
10831    snprintf(tmp_n, sizeof(tmp_n), "%d %s", ++p->ocseq, sip_methods[sipmethod].text);
10832 
10833    add_header(req, "Via", p->via);
10834    add_header(req, "Max-Forwards", DEFAULT_MAX_FORWARDS);
10835    /* This will be a no-op most of the time. However, under certain circumstances,
10836     * NOTIFY messages will use this function for preparing the request and should
10837     * have Route headers present.
10838     */
10839    add_route(req, p->route);
10840 
10841    /* Build Remote Party-ID and From */
10842    if (ast_test_flag(&p->flags[0], SIP_SENDRPID) && (sipmethod == SIP_INVITE)) {
10843       build_rpid(p);
10844       add_header(req, "From", p->rpid_from);
10845    } else 
10846       add_header(req, "From", from);
10847    add_header(req, "To", to);
10848    ast_string_field_set(p, exten, l);
10849    build_contact(p);
10850    add_header(req, "Contact", p->our_contact);
10851    add_header(req, "Call-ID", p->callid);
10852    add_header(req, "CSeq", tmp_n);
10853    if (!ast_strlen_zero(global_useragent))
10854       add_header(req, "User-Agent", global_useragent);
10855    if (!ast_strlen_zero(p->rpid))
10856       add_header(req, "Remote-Party-ID", p->rpid);
10857 }
10858 
10859 /*! \brief Build REFER/INVITE/OPTIONS/SUBSCRIBE message and transmit it 
10860    \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
10861  \param p sip_pvt structure
10862  \param sdp unknown 
10863  \param sipmethod unknown 
10864  
10865 */
10866 static int transmit_invite(struct sip_pvt *p, int sipmethod, int sdp, int init)
10867 {
10868    struct sip_request req;
10869    struct ast_variable *var;
10870    
10871    req.method = sipmethod;
10872    if (init) {/* Bump branch even on initial requests */
10873       p->branch ^= ast_random();
10874       p->invite_branch = p->branch;
10875       build_via(p);
10876    }
10877    if (init > 1)
10878       initreqprep(&req, p, sipmethod);
10879    else
10880       /* If init=1, we should not generate a new branch. If it's 0, we need a new branch. */
10881       reqprep(&req, p, sipmethod, 0, init ? 0 : 1);
10882       
10883    if (p->options && p->options->auth)
10884       add_header(&req, p->options->authheader, p->options->auth);
10885    append_date(&req);
10886    if (sipmethod == SIP_REFER) { /* Call transfer */
10887       if (p->refer) {
10888          char buf[SIPBUFSIZE];
10889          if (!ast_strlen_zero(p->refer->refer_to))
10890             add_header(&req, "Refer-To", p->refer->refer_to);
10891          if (!ast_strlen_zero(p->refer->referred_by)) {
10892             snprintf(buf, sizeof(buf), "%s <%s>", p->refer->referred_by_name, p->refer->referred_by);
10893             add_header(&req, "Referred-By", buf);
10894          }
10895       }
10896    } else if (sipmethod == SIP_SUBSCRIBE) { /* We only support sending MWI subscriptions right now */
10897       char buf[SIPBUFSIZE];
10898 
10899       add_header(&req, "Event", "message-summary");
10900       add_header(&req, "Accept", "application/simple-message-summary");
10901       snprintf(buf, sizeof(buf), "%d", mwi_expiry);
10902       add_header(&req, "Expires", buf);
10903    }
10904 
10905    /* This new INVITE is part of an attended transfer. Make sure that the
10906    other end knows and replace the current call with this new call */
10907    if (p->options && !ast_strlen_zero(p->options->replaces)) {
10908       add_header(&req, "Replaces", p->options->replaces);
10909       add_header(&req, "Require", "replaces");
10910    }
10911 
10912    /* Add Session-Timers related headers */
10913    if (st_get_mode(p) == SESSION_TIMER_MODE_ORIGINATE) {
10914       char i2astr[10];
10915 
10916       if (!p->stimer->st_interval)
10917          p->stimer->st_interval = st_get_se(p, TRUE);
10918 
10919       p->stimer->st_active = TRUE;
10920       
10921       snprintf(i2astr, sizeof(i2astr), "%d", p->stimer->st_interval);
10922       add_header(&req, "Session-Expires", i2astr);
10923       snprintf(i2astr, sizeof(i2astr), "%d", st_get_se(p, FALSE));
10924       add_header(&req, "Min-SE", i2astr);
10925    }
10926 
10927    add_header(&req, "Allow", ALLOWED_METHODS);
10928    add_header(&req, "Supported", SUPPORTED_EXTENSIONS);
10929 
10930    if(p->notify_headers) {
10931       char buf[512];
10932       for (var = p->notify_headers; var; var = var->next) {
10933          ast_copy_string(buf, var->value, sizeof(buf));
10934          add_header(&req, var->name, ast_unescape_semicolon(buf));
10935       }
10936    }
10937    if (p->options && p->options->addsipheaders && p->owner) {
10938       struct ast_channel *chan = p->owner; /* The owner channel */
10939       struct varshead *headp;
10940    
10941       ast_channel_lock(chan);
10942 
10943       headp = &chan->varshead;
10944 
10945       if (!headp)
10946          ast_log(LOG_WARNING, "No Headp for the channel...ooops!\n");
10947       else {
10948          const struct ast_var_t *current;
10949          AST_LIST_TRAVERSE(headp, current, entries) {  
10950             /* SIPADDHEADER: Add SIP header to outgoing call */
10951             if (!strncasecmp(ast_var_name(current), "SIPADDHEADER", strlen("SIPADDHEADER"))) {
10952                char *content, *end;
10953                const char *header = ast_var_value(current);
10954                char *headdup = ast_strdupa(header);
10955 
10956                /* Strip of the starting " (if it's there) */
10957                if (*headdup == '"')
10958                   headdup++;
10959                if ((content = strchr(headdup, ':'))) {
10960                   *content++ = '\0';
10961                   content = ast_skip_blanks(content); /* Skip white space */
10962                   /* Strip the ending " (if it's there) */
10963                   end = content + strlen(content) -1; 
10964                   if (*end == '"')
10965                      *end = '\0';
10966                
10967                   add_header(&req, headdup, content);
10968                   if (sipdebug)
10969                      ast_debug(1, "Adding SIP Header \"%s\" with content :%s: \n", headdup, content);
10970                }
10971             }
10972          }
10973       }
10974 
10975       ast_channel_unlock(chan);
10976    }
10977    if (sdp) {
10978       memset(p->offered_media, 0, sizeof(p->offered_media));
10979       if (p->udptl && p->t38.state == T38_LOCAL_REINVITE) {
10980          ast_debug(1, "T38 is in state %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
10981          add_sdp(&req, p, FALSE, FALSE, TRUE);
10982       } else if (p->rtp) 
10983          add_sdp(&req, p, FALSE, TRUE, FALSE);
10984    } else {
10985       if (!p->notify_headers) {
10986          add_header_contentLength(&req, 0);
10987       }
10988    }
10989 
10990    if (!p->initreq.headers || init > 2)
10991       initialize_initreq(p, &req);
10992    p->lastinvite = p->ocseq;
10993    return send_request(p, &req, init ? XMIT_CRITICAL : XMIT_RELIABLE, p->ocseq);
10994 }
10995 
10996 /*! \brief Send a subscription or resubscription for MWI */
10997 static int sip_subscribe_mwi_do(const void *data)
10998 {
10999    struct sip_subscription_mwi *mwi = (struct sip_subscription_mwi*)data;
11000    
11001    if (!mwi) {
11002       return -1;
11003    }
11004    
11005    mwi->resub = -1;
11006    __sip_subscribe_mwi_do(mwi);
11007    ASTOBJ_UNREF(mwi, sip_subscribe_mwi_destroy);
11008    
11009    return 0;
11010 }
11011 
11012 /*! \brief Actually setup an MWI subscription or resubscribe */
11013 static int __sip_subscribe_mwi_do(struct sip_subscription_mwi *mwi)
11014 {
11015    /* If we have no DNS manager let's do a lookup */
11016    if (!mwi->dnsmgr) {
11017       char transport[MAXHOSTNAMELEN];
11018       snprintf(transport, sizeof(transport), "_sip._%s", get_transport(mwi->transport));
11019       ast_dnsmgr_lookup(mwi->hostname, &mwi->us, &mwi->dnsmgr, sip_cfg.srvlookup ? transport : NULL);
11020    }
11021 
11022    /* If we already have a subscription up simply send a resubscription */
11023    if (mwi->call) {
11024       transmit_invite(mwi->call, SIP_SUBSCRIBE, 0, 0);
11025       return 0;
11026    }
11027    
11028    /* Create a dialog that we will use for the subscription */
11029    if (!(mwi->call = sip_alloc(NULL, NULL, 0, SIP_SUBSCRIBE, NULL))) {
11030       return -1;
11031    }
11032 
11033    ref_proxy(mwi->call, obproxy_get(mwi->call, NULL));
11034 
11035    if (!mwi->us.sin_port && mwi->portno) {
11036       mwi->us.sin_port = htons(mwi->portno);
11037    }
11038    
11039    /* Setup the destination of our subscription */
11040    if (create_addr(mwi->call, mwi->hostname, &mwi->us, 0)) {
11041       dialog_unlink_all(mwi->call, TRUE, TRUE);
11042       mwi->call = dialog_unref(mwi->call, "unref dialog after unlink_all");
11043       return 0;
11044    }
11045    
11046    if (!mwi->dnsmgr && mwi->portno) {
11047       mwi->call->sa.sin_port = htons(mwi->portno);
11048       mwi->call->recv.sin_port = htons(mwi->portno);
11049    } else {
11050       mwi->portno = ntohs(mwi->call->sa.sin_port);
11051    }
11052    
11053    /* Set various other information */
11054    if (!ast_strlen_zero(mwi->authuser)) {
11055       ast_string_field_set(mwi->call, peername, mwi->authuser);
11056       ast_string_field_set(mwi->call, authname, mwi->authuser);
11057       ast_string_field_set(mwi->call, fromuser, mwi->authuser);
11058    } else {
11059       ast_string_field_set(mwi->call, peername, mwi->username);
11060       ast_string_field_set(mwi->call, authname, mwi->username);
11061       ast_string_field_set(mwi->call, fromuser, mwi->username);
11062    }
11063    ast_string_field_set(mwi->call, username, mwi->username);
11064    if (!ast_strlen_zero(mwi->secret)) {
11065       ast_string_field_set(mwi->call, peersecret, mwi->secret);
11066    }
11067    set_socket_transport(&mwi->call->socket, mwi->transport);
11068    mwi->call->socket.port = htons(mwi->portno);
11069    ast_sip_ouraddrfor(&mwi->call->sa.sin_addr, &mwi->call->ourip, mwi->call);
11070    build_contact(mwi->call);
11071    build_via(mwi->call);
11072    build_callid_pvt(mwi->call);
11073    ast_set_flag(&mwi->call->flags[0], SIP_OUTGOING);
11074    
11075    /* Associate the call with us */
11076    mwi->call->mwi = ASTOBJ_REF(mwi);
11077    
11078    /* Actually send the packet */
11079    transmit_invite(mwi->call, SIP_SUBSCRIBE, 0, 2);
11080 
11081    return 0;
11082 }
11083 
11084 static int find_calling_channel(struct ast_channel *c, void *data) {
11085    struct sip_pvt *p = data;
11086 
11087    return (c->pbx &&
11088          (!strcasecmp(c->macroexten, p->exten) || !strcasecmp(c->exten, p->exten)) &&
11089          (sip_cfg.notifycid == IGNORE_CONTEXT || !strcasecmp(c->context, p->context)));
11090 }
11091 
11092 /*! \brief Used in the SUBSCRIBE notification subsystem (RFC3265) */
11093 static int transmit_state_notify(struct sip_pvt *p, int state, int full, int timeout)
11094 {
11095    struct ast_str *tmp = ast_str_alloca(4000);
11096    char from[256], to[256];
11097    char *c, *mfrom, *mto;
11098    struct sip_request req;
11099    char hint[AST_MAX_EXTENSION];
11100    char *statestring = "terminated";
11101    const struct cfsubscription_types *subscriptiontype;
11102    enum state { NOTIFY_OPEN, NOTIFY_INUSE, NOTIFY_CLOSED } local_state = NOTIFY_OPEN;
11103    char *pidfstate = "--";
11104    char *pidfnote= "Ready";
11105    
11106    memset(from, 0, sizeof(from));
11107    memset(to, 0, sizeof(to));
11108 
11109    switch (state) {
11110    case (AST_EXTENSION_RINGING | AST_EXTENSION_INUSE):
11111       statestring = (sip_cfg.notifyringing) ? "early" : "confirmed";
11112       local_state = NOTIFY_INUSE;
11113       pidfstate = "busy";
11114       pidfnote = "Ringing";
11115       break;
11116    case AST_EXTENSION_RINGING:
11117       statestring = "early";
11118       local_state = NOTIFY_INUSE;
11119       pidfstate = "busy";
11120       pidfnote = "Ringing";
11121       break;
11122    case AST_EXTENSION_INUSE:
11123       statestring = "confirmed";
11124       local_state = NOTIFY_INUSE;
11125       pidfstate = "busy";
11126       pidfnote = "On the phone";
11127       break;
11128    case AST_EXTENSION_BUSY:
11129       statestring = "confirmed";
11130       local_state = NOTIFY_CLOSED;
11131       pidfstate = "busy";
11132       pidfnote = "On the phone";
11133       break;
11134    case AST_EXTENSION_UNAVAILABLE:
11135       statestring = "terminated";
11136       local_state = NOTIFY_CLOSED;
11137       pidfstate = "away";
11138       pidfnote = "Unavailable";
11139       break;
11140    case AST_EXTENSION_ONHOLD:
11141       statestring = "confirmed";
11142       local_state = NOTIFY_CLOSED;
11143       pidfstate = "busy";
11144       pidfnote = "On hold";
11145       break;
11146    case AST_EXTENSION_NOT_INUSE:
11147    default:
11148       /* Default setting */
11149       break;
11150    }
11151 
11152    subscriptiontype = find_subscription_type(p->subscribed);
11153    
11154    /* Check which device/devices we are watching  and if they are registered */
11155    if (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, p->context, p->exten)) {
11156       char *hint2 = hint, *individual_hint = NULL;
11157       int hint_count = 0, unavailable_count = 0;
11158 
11159       while ((individual_hint = strsep(&hint2, "&"))) {
11160          hint_count++;
11161 
11162          if (ast_device_state(individual_hint) == AST_DEVICE_UNAVAILABLE)
11163             unavailable_count++;
11164       }
11165 
11166       /* If none of the hinted devices are registered, we will
11167        * override notification and show no availability.
11168        */
11169       if (hint_count > 0 && hint_count == unavailable_count) {
11170          local_state = NOTIFY_CLOSED;
11171          pidfstate = "away";
11172          pidfnote = "Not online";
11173       }
11174    }
11175 
11176    ast_copy_string(from, get_header(&p->initreq, "From"), sizeof(from));
11177    c = get_in_brackets(from);
11178    if (strncasecmp(c, "sip:", 4) && strncasecmp(c, "sips:", 5)) {
11179       ast_log(LOG_WARNING, "Huh?  Not a SIP header (%s)?\n", c);
11180       return -1;
11181    }
11182    
11183    mfrom = remove_uri_parameters(c);
11184 
11185    ast_copy_string(to, get_header(&p->initreq, "To"), sizeof(to));
11186    c = get_in_brackets(to);
11187    if (strncasecmp(c, "sip:", 4) && strncasecmp(c, "sips:", 5)) {
11188       ast_log(LOG_WARNING, "Huh?  Not a SIP header (%s)?\n", c);
11189       return -1;
11190    }
11191    mto = remove_uri_parameters(c);
11192 
11193    reqprep(&req, p, SIP_NOTIFY, 0, 1);
11194 
11195    
11196    add_header(&req, "Event", subscriptiontype->event);
11197    add_header(&req, "Content-Type", subscriptiontype->mediatype);
11198    switch(state) {
11199    case AST_EXTENSION_DEACTIVATED:
11200       if (timeout)
11201          add_header(&req, "Subscription-State", "terminated;reason=timeout");
11202       else {
11203          add_header(&req, "Subscription-State", "terminated;reason=probation");
11204          add_header(&req, "Retry-After", "60");
11205       }
11206       break;
11207    case AST_EXTENSION_REMOVED:
11208       add_header(&req, "Subscription-State", "terminated;reason=noresource");
11209       break;
11210    default:
11211       if (p->expiry)
11212          add_header(&req, "Subscription-State", "active");
11213       else  /* Expired */
11214          add_header(&req, "Subscription-State", "terminated;reason=timeout");
11215    }
11216    switch (p->subscribed) {
11217    case XPIDF_XML:
11218    case CPIM_PIDF_XML:
11219       ast_str_append(&tmp, 0,
11220          "<?xml version=\"1.0\"?>\n"
11221          "<!DOCTYPE presence PUBLIC \"-//IETF//DTD RFCxxxx XPIDF 1.0//EN\" \"xpidf.dtd\">\n"
11222          "<presence>\n");
11223       ast_str_append(&tmp, 0, "<presentity uri=\"%s;method=SUBSCRIBE\" />\n", mfrom);
11224       ast_str_append(&tmp, 0, "<atom id=\"%s\">\n", p->exten);
11225       ast_str_append(&tmp, 0, "<address uri=\"%s;user=ip\" priority=\"0.800000\">\n", mto);
11226       ast_str_append(&tmp, 0, "<status status=\"%s\" />\n", (local_state ==  NOTIFY_OPEN) ? "open" : (local_state == NOTIFY_INUSE) ? "inuse" : "closed");
11227       ast_str_append(&tmp, 0, "<msnsubstatus substatus=\"%s\" />\n", (local_state == NOTIFY_OPEN) ? "online" : (local_state == NOTIFY_INUSE) ? "onthephone" : "offline");
11228       ast_str_append(&tmp, 0, "</address>\n</atom>\n</presence>\n");
11229       break;
11230    case PIDF_XML: /* Eyebeam supports this format */
11231       ast_str_append(&tmp, 0,
11232          "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n"
11233          "<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);
11234       ast_str_append(&tmp, 0, "<pp:person><status>\n");
11235       if (pidfstate[0] != '-')
11236          ast_str_append(&tmp, 0, "<ep:activities><ep:%s/></ep:activities>\n", pidfstate);
11237       ast_str_append(&tmp, 0, "</status></pp:person>\n");
11238       ast_str_append(&tmp, 0, "<note>%s</note>\n", pidfnote); /* Note */
11239       ast_str_append(&tmp, 0, "<tuple id=\"%s\">\n", p->exten); /* Tuple start */
11240       ast_str_append(&tmp, 0, "<contact priority=\"1\">%s</contact>\n", mto);
11241       if (pidfstate[0] == 'b') /* Busy? Still open ... */
11242          ast_str_append(&tmp, 0, "<status><basic>open</basic></status>\n");
11243       else
11244          ast_str_append(&tmp, 0, "<status><basic>%s</basic></status>\n", (local_state != NOTIFY_CLOSED) ? "open" : "closed");
11245       ast_str_append(&tmp, 0, "</tuple>\n</presence>\n");
11246       break;
11247    case DIALOG_INFO_XML: /* SNOM subscribes in this format */
11248       ast_str_append(&tmp, 0, "<?xml version=\"1.0\"?>\n");
11249       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);
11250       if ((state & AST_EXTENSION_RINGING) && sip_cfg.notifyringing) {
11251          const char *local_display = p->exten;
11252          char *local_target = mto;
11253 
11254          /* There are some limitations to how this works.  The primary one is that the
11255             callee must be dialing the same extension that is being monitored.  Simply dialing
11256             the hint'd device is not sufficient. */
11257          if (sip_cfg.notifycid) {
11258             struct ast_channel *caller = ast_channel_search_locked(find_calling_channel, p);
11259 
11260             if (caller) {
11261                int need = strlen(caller->cid.cid_num) + strlen(p->fromdomain) + sizeof("sip:@");
11262                local_target = alloca(need);
11263                snprintf(local_target, need, "sip:%s@%s", caller->cid.cid_num, p->fromdomain);
11264                local_display = ast_strdupa(caller->cid.cid_name);
11265                ast_channel_unlock(caller);
11266                caller = NULL;
11267             }
11268          }
11269 
11270          /* We create a fake call-id which the phone will send back in an INVITE
11271             Replaces header which we can grab and do some magic with. */
11272          ast_str_append(&tmp, 0, 
11273                "<dialog id=\"%s\" call-id=\"pickup-%s\" direction=\"recipient\">\n"
11274                "<remote>\n"
11275                /* See the limitations of this above.  Luckily the phone seems to still be
11276                   happy when these values are not correct. */
11277                "<identity display=\"%s\">%s</identity>\n"
11278                "<target uri=\"%s\"/>\n"
11279                "</remote>\n"
11280                "<local>\n"
11281                "<identity>%s</identity>\n"
11282                "<target uri=\"%s\"/>\n"
11283                "</local>\n",
11284                p->exten, p->callid, local_display, local_target, local_target, mto, mto);
11285       } else {
11286          ast_str_append(&tmp, 0, "<dialog id=\"%s\">\n", p->exten);
11287       }
11288       ast_str_append(&tmp, 0, "<state>%s</state>\n", statestring);
11289       if (state == AST_EXTENSION_ONHOLD) {
11290          ast_str_append(&tmp, 0, "<local>\n<target uri=\"%s\">\n"
11291                                          "<param pname=\"+sip.rendering\" pvalue=\"no\"/>\n"
11292                                          "</target>\n</local>\n", mto);
11293       }
11294       ast_str_append(&tmp, 0, "</dialog>\n</dialog-info>\n");
11295       break;
11296    case NONE:
11297    default:
11298       break;
11299    }
11300 
11301    add_header_contentLength(&req, tmp->used);
11302    add_line(&req, tmp->str);
11303 
11304    p->pendinginvite = p->ocseq;  /* Remember that we have a pending NOTIFY in order not to confuse the NOTIFY subsystem */
11305 
11306    return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
11307 }
11308 
11309 /*! \brief Notify user of messages waiting in voicemail (RFC3842)
11310 \note - Notification only works for registered peers with mailbox= definitions
11311    in sip.conf
11312    - We use the SIP Event package message-summary
11313     MIME type defaults to  "application/simple-message-summary";
11314  */
11315 static int transmit_notify_with_mwi(struct sip_pvt *p, int newmsgs, int oldmsgs, const char *vmexten)
11316 {
11317    struct sip_request req;
11318    struct ast_str *out = ast_str_alloca(500);
11319    int ourport = ntohs(p->ourip.sin_port);
11320    const char *exten = S_OR(vmexten, default_vmexten);
11321 
11322    initreqprep(&req, p, SIP_NOTIFY);
11323    add_header(&req, "Event", "message-summary");
11324    add_header(&req, "Content-Type", default_notifymime);
11325    ast_str_append(&out, 0, "Messages-Waiting: %s\r\n", newmsgs ? "yes" : "no");
11326 
11327    if (!ast_strlen_zero(p->fromdomain)) {
11328       ast_str_append(&out, 0, "Message-Account: sip:%s@%s\r\n", exten, p->fromdomain);
11329    } else if (!sip_standard_port(p->socket.type, ourport)) {
11330       if (p->socket.type == SIP_TRANSPORT_UDP) {
11331          ast_str_append(&out, 0, "Message-Account: sip:%s@%s:%d\r\n", exten, ast_inet_ntoa(p->ourip.sin_addr), ourport);
11332       } else {
11333          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));
11334       }
11335    } else {
11336       if (p->socket.type == SIP_TRANSPORT_UDP) {
11337          ast_str_append(&out, 0, "Message-Account: sip:%s@%s\r\n", exten, ast_inet_ntoa(p->ourip.sin_addr));
11338       } else {
11339          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));
11340       }
11341    }
11342    /* Cisco has a bug in the SIP stack where it can't accept the
11343       (0/0) notification. This can temporarily be disabled in
11344       sip.conf with the "buggymwi" option */
11345    ast_str_append(&out, 0, "Voice-Message: %d/%d%s\r\n",
11346       newmsgs, oldmsgs, (ast_test_flag(&p->flags[1], SIP_PAGE2_BUGGY_MWI) ? "" : " (0/0)"));
11347 
11348    if (p->subscribed) {
11349       if (p->expiry)
11350          add_header(&req, "Subscription-State", "active");
11351       else  /* Expired */
11352          add_header(&req, "Subscription-State", "terminated;reason=timeout");
11353    }
11354 
11355    add_header_contentLength(&req, out->used);
11356    add_line(&req, out->str);
11357 
11358    if (!p->initreq.headers) 
11359       initialize_initreq(p, &req);
11360    return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
11361 }
11362 
11363 /*! \brief Notify a transferring party of the status of transfer (RFC3515) */
11364 static int transmit_notify_with_sipfrag(struct sip_pvt *p, int cseq, char *message, int terminate)
11365 {
11366    struct sip_request req;
11367    char tmp[SIPBUFSIZE/2];
11368    
11369    reqprep(&req, p, SIP_NOTIFY, 0, 1);
11370    snprintf(tmp, sizeof(tmp), "refer;id=%d", cseq);
11371    add_header(&req, "Event", tmp);
11372    add_header(&req, "Subscription-state", terminate ? "terminated;reason=noresource" : "active");
11373    add_header(&req, "Content-Type", "message/sipfrag;version=2.0");
11374    add_header(&req, "Allow", ALLOWED_METHODS);
11375    add_header(&req, "Supported", SUPPORTED_EXTENSIONS);
11376 
11377    snprintf(tmp, sizeof(tmp), "SIP/2.0 %s\r\n", message);
11378    add_header_contentLength(&req, strlen(tmp));
11379    add_line(&req, tmp);
11380 
11381    if (!p->initreq.headers)
11382       initialize_initreq(p, &req);
11383 
11384    return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
11385 }
11386 
11387 /*! \brief Notify device with custom headers from sip_notify.conf */
11388 static int transmit_notify_custom(struct sip_pvt *p, struct ast_variable *vars) {
11389    struct sip_request req;
11390    struct ast_variable *var, *newvar;
11391 
11392    initreqprep(&req, p, SIP_NOTIFY);
11393 
11394    /* Copy notify vars and add headers */
11395    p->notify_headers = newvar = ast_variable_new("Subscription-State", "terminated", "");
11396    add_header(&req, newvar->name, newvar->value);
11397    for (var = vars; var; var = var->next) {
11398       char buf[512];
11399       ast_debug(2, "  Adding pair %s=%s\n", var->name, var->value);
11400       ast_copy_string(buf, var->value, sizeof(buf));
11401       add_header(&req, var->name, ast_unescape_semicolon(buf));
11402       newvar->next = ast_variable_new(var->name, var->value, "");
11403       newvar = newvar->next;
11404    }
11405 
11406    if (!p->initreq.headers) { /* Initialize first request before sending */
11407       initialize_initreq(p, &req);
11408    }
11409 
11410    return send_request(p, &req, XMIT_UNRELIABLE, p->ocseq);
11411 }
11412 
11413 static int manager_sipnotify(struct mansession *s, const struct message *m)
11414 {
11415    const char *channame = astman_get_header(m, "Channel");
11416    struct ast_variable *vars = astman_get_variables(m);
11417    struct sip_pvt *p;
11418 
11419    if (ast_strlen_zero(channame)) {
11420       astman_send_error(s, m, "SIPNotify requires a channel name");
11421       return 0;
11422    }
11423 
11424    if (!strncasecmp(channame, "sip/", 4)) {
11425       channame += 4;
11426    }
11427 
11428    if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY, NULL))) {
11429       astman_send_error(s, m, "Unable to build sip pvt data for notify (memory/socket error)");
11430       return 0;
11431    }
11432 
11433    if (create_addr(p, channame, NULL, 0)) {
11434       /* Maybe they're not registered, etc. */
11435       dialog_unlink_all(p, TRUE, TRUE);
11436       dialog_unref(p, "unref dialog inside for loop" );
11437       /* sip_destroy(p); */
11438       astman_send_error(s, m, "Could not create address");
11439       return 0;
11440    }
11441 
11442    /* Notify is outgoing call */
11443    ast_set_flag(&p->flags[0], SIP_OUTGOING);
11444 
11445    /* Recalculate our side, and recalculate Call ID */
11446    ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
11447    build_via(p);
11448    ao2_t_unlink(dialogs, p, "About to change the callid -- remove the old name");
11449    build_callid_pvt(p);
11450    ao2_t_link(dialogs, p, "Linking in new name");
11451    dialog_ref(p, "bump the count of p, which transmit_sip_request will decrement.");
11452    sip_scheddestroy(p, SIP_TRANS_TIMEOUT);
11453 
11454    if (!transmit_notify_custom(p, vars)) {
11455       astman_send_ack(s, m, "Notify Sent");
11456    } else {
11457       astman_send_error(s, m, "Unable to send notify");
11458    }
11459    ast_variables_destroy(vars);
11460    return 0;
11461 }
11462 
11463 static char mandescr_sipnotify[] =
11464 "Description: Sends a SIP Notify event\n"
11465 "All parameters for this event must be specified in the body of this request\n"
11466 "via multiple Variable: name=value sequences.\n"
11467 "Variables: \n"
11468 "  *Channel: <peername>       Peer to receive the notify. Required.\n"
11469 "  *Variable: <name>=<value>  At least one variable pair must be specified.\n"
11470 "  ActionID: <id>             Action ID for this transaction. Will be returned.\n";
11471 
11472 static const struct _map_x_s regstatestrings[] = {
11473    { REG_STATE_FAILED,     "Failed" },
11474    { REG_STATE_UNREGISTERED, "Unregistered"},
11475    { REG_STATE_REGSENT, "Request Sent"},
11476    { REG_STATE_AUTHSENT, "Auth. Sent"},
11477    { REG_STATE_REGISTERED, "Registered"},
11478    { REG_STATE_REJECTED, "Rejected"},
11479    { REG_STATE_TIMEOUT, "Timeout"},
11480    { REG_STATE_NOAUTH, "No Authentication"},
11481    { -1, NULL } /* terminator */
11482 };
11483 
11484 /*! \brief Convert registration state status to string */
11485 static const char *regstate2str(enum sipregistrystate regstate)
11486 {
11487    return map_x_s(regstatestrings, regstate, "Unknown");
11488 }
11489 
11490 /*! \brief Update registration with SIP Proxy.
11491  * Called from the scheduler when the previous registration expires,
11492  * so we don't have to cancel the pending event.
11493  * We assume the reference so the sip_registry is valid, since it
11494  * is stored in the scheduled event anyways.
11495  */
11496 static int sip_reregister(const void *data) 
11497 {
11498    /* if we are here, we know that we need to reregister. */
11499    struct sip_registry *r= (struct sip_registry *) data;
11500 
11501    /* if we couldn't get a reference to the registry object, punt */
11502    if (!r)
11503       return 0;
11504 
11505    if (r->call && r->call->do_history)
11506       append_history(r->call, "RegistryRenew", "Account: %s@%s", r->username, r->hostname);
11507    /* Since registry's are only added/removed by the the monitor thread, this
11508       may be overkill to reference/dereference at all here */
11509    if (sipdebug)
11510       ast_log(LOG_NOTICE, "   -- Re-registration for  %s@%s\n", r->username, r->hostname);
11511 
11512    r->expire = -1;
11513    r->expiry = r->configured_expiry;
11514    __sip_do_register(r);
11515    registry_unref(r, "unref the re-register scheduled event");
11516    return 0;
11517 }
11518 
11519 /*! \brief Register with SIP proxy */
11520 static int __sip_do_register(struct sip_registry *r)
11521 {
11522    int res;
11523 
11524    res = transmit_register(r, SIP_REGISTER, NULL, NULL);
11525    return res;
11526 }
11527 
11528 /*! \brief Registration timeout, register again
11529  * Registered as a timeout handler during transmit_register(),
11530  * to retransmit the packet if a reply does not come back.
11531  * This is called by the scheduler so the event is not pending anymore when
11532  * we are called.
11533  */
11534 static int sip_reg_timeout(const void *data)
11535 {
11536 
11537    /* if we are here, our registration timed out, so we'll just do it over */
11538    struct sip_registry *r = (struct sip_registry *)data; /* the ref count should have been bumped when the sched item was added */
11539    struct sip_pvt *p;
11540    int res;
11541 
11542    /* if we couldn't get a reference to the registry object, punt */
11543    if (!r)
11544       return 0;
11545 
11546    if (r->dnsmgr) {
11547       /* If the registration has timed out, maybe the IP changed.  Force a refresh. */
11548       ast_dnsmgr_refresh(r->dnsmgr);
11549    }
11550 
11551    ast_log(LOG_NOTICE, "   -- Registration for '%s@%s' timed out, trying again (Attempt #%d)\n", r->username, r->hostname, r->regattempts); 
11552    /* If the initial tranmission failed, we may not have an existing dialog,
11553     * so it is possible that r->call == NULL.
11554     * Otherwise destroy it, as we have a timeout so we don't want it.
11555     */
11556    if (r->call) {
11557       /* Unlink us, destroy old call.  Locking is not relevant here because all this happens
11558          in the single SIP manager thread. */
11559       p = r->call;
11560       sip_pvt_lock(p);
11561       pvt_set_needdestroy(p, "registration timeout");
11562       /* Pretend to ACK anything just in case */
11563       __sip_pretend_ack(p);
11564       sip_pvt_unlock(p);
11565 
11566       /* decouple the two objects */
11567       /* p->registry == r, so r has 2 refs, and the unref won't take the object away */
11568       if (p->registry)
11569          p->registry = registry_unref(p->registry, "p->registry unreffed");
11570       r->call = dialog_unref(r->call, "unrefing r->call");
11571    }
11572    /* If we have a limit, stop registration and give up */
11573    r->timeout = -1;
11574    if (global_regattempts_max && r->regattempts > global_regattempts_max) {
11575       /* Ok, enough is enough. Don't try any more */
11576       /* We could add an external notification here... 
11577          steal it from app_voicemail :-) */
11578       ast_log(LOG_NOTICE, "   -- Giving up forever trying to register '%s@%s'\n", r->username, r->hostname);
11579       r->regstate = REG_STATE_FAILED;
11580    } else {
11581       r->regstate = REG_STATE_UNREGISTERED;
11582       res=transmit_register(r, SIP_REGISTER, NULL, NULL);
11583    }
11584    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));
11585    registry_unref(r, "unreffing registry_unref r");
11586    return 0;
11587 }
11588 
11589 /*! \brief Transmit register to SIP proxy or UA
11590  * auth = NULL on the initial registration (from sip_reregister())
11591  */
11592 static int transmit_register(struct sip_registry *r, int sipmethod, const char *auth, const char *authheader)
11593 {
11594    struct sip_request req;
11595    char from[256];
11596    char to[256];
11597    char tmp[80];
11598    char addr[80];
11599    struct sip_pvt *p;
11600    struct sip_peer *peer = NULL;
11601    int res;
11602    char *fromdomain;
11603    char *domainport = NULL;
11604 
11605    /* exit if we are already in process with this registrar ?*/
11606    if (r == NULL || ((auth == NULL) && (r->regstate == REG_STATE_REGSENT || r->regstate == REG_STATE_AUTHSENT))) {
11607       if (r) {
11608          ast_log(LOG_NOTICE, "Strange, trying to register %s@%s when registration already pending\n", r->username, r->hostname);
11609       }
11610       return 0;
11611    }
11612 
11613    if (r->dnsmgr == NULL) {
11614       char transport[MAXHOSTNAMELEN];
11615       peer = find_peer(r->hostname, NULL, TRUE, FINDPEERS, FALSE, 0);
11616       snprintf(transport, sizeof(transport), "_sip._%s", get_transport(r->transport)); /* have to use static get_transport function */
11617       ast_dnsmgr_lookup(peer ? peer->tohost : r->hostname, &r->us, &r->dnsmgr, sip_cfg.srvlookup ? transport : NULL);
11618       if (peer) {
11619          peer = unref_peer(peer, "removing peer ref for dnsmgr_lookup");
11620       }
11621    }
11622 
11623    if (r->call) { /* We have a registration */
11624       if (!auth) {
11625          ast_log(LOG_WARNING, "Already have a REGISTER going on to %s@%s?? \n", r->username, r->hostname);
11626          return 0;
11627       } else {
11628          p = dialog_ref(r->call, "getting a copy of the r->call dialog in transmit_register");
11629          make_our_tag(p->tag, sizeof(p->tag));  /* create a new local tag for every register attempt */
11630          ast_string_field_set(p, theirtag, NULL);  /* forget their old tag, so we don't match tags when getting response */
11631       }
11632    } else {
11633       /* Build callid for registration if we haven't registered before */
11634       if (!r->callid_valid) {
11635          build_callid_registry(r, internip.sin_addr, default_fromdomain);
11636          r->callid_valid = TRUE;
11637       }
11638       /* Allocate SIP dialog for registration */
11639       if (!(p = sip_alloc( r->callid, NULL, 0, SIP_REGISTER, NULL))) {
11640          ast_log(LOG_WARNING, "Unable to allocate registration transaction (memory or socket error)\n");
11641          return 0;
11642       }
11643       
11644       if (p->do_history)
11645          append_history(p, "RegistryInit", "Account: %s@%s", r->username, r->hostname);
11646 
11647       if (!ast_strlen_zero(r->peername)) {
11648          if (!(peer = find_peer(r->peername, NULL, 1, FINDPEERS, FALSE, 0))) {
11649             ast_log(LOG_WARNING, "Could not find peer %s in transmit_register\n", r->peername);
11650          } else {
11651             p->peerauth = peer->auth;
11652          }
11653       }
11654       ref_proxy(p, obproxy_get(p, peer)); /* it is ok to pass a NULL peer into obproxy_get() */
11655       if (peer) {
11656          unref_peer(peer, "transmit_registration: from find_peer operation");
11657       }
11658       /* Use port number specified if no SRV record was found */
11659       if (!r->us.sin_port && r->portno)
11660          r->us.sin_port = htons(r->portno);
11661 
11662       /* Find address to hostname */
11663       if (create_addr(p, r->hostname, &r->us, 0)) {
11664          /* we have what we hope is a temporary network error,
11665           * probably DNS.  We need to reschedule a registration try */
11666          dialog_unlink_all(p, TRUE, TRUE);
11667          p = dialog_unref(p, "unref dialog after unlink_all");
11668          if (r->timeout > -1) {
11669             AST_SCHED_REPLACE_UNREF(r->timeout, sched, global_reg_timeout * 1000, sip_reg_timeout, r,
11670                               registry_unref(_data, "del for REPLACE of registry ptr"), 
11671                               registry_unref(r, "object ptr dec when SCHED_REPLACE add failed"),
11672                               registry_addref(r,"add for REPLACE registry ptr"));
11673             ast_log(LOG_WARNING, "Still have a registration timeout for %s@%s (create_addr() error), %d\n", r->username, r->hostname, r->timeout);
11674          } else {
11675             r->timeout = ast_sched_add(sched, global_reg_timeout * 1000, sip_reg_timeout, registry_addref(r, "add for REPLACE registry ptr"));
11676             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);
11677          }
11678          r->regattempts++;
11679          return 0;
11680       }
11681 
11682       /* Copy back Call-ID in case create_addr changed it */
11683       ast_string_field_set(r, callid, p->callid);
11684       if (!r->dnsmgr && r->portno) {
11685          p->sa.sin_port = htons(r->portno);
11686          p->recv.sin_port = htons(r->portno);
11687       } else { /* Set registry port to the port set from the peer definition/srv or default */
11688          r->portno = ntohs(p->sa.sin_port);
11689       }
11690       ast_set_flag(&p->flags[0], SIP_OUTGOING); /* Registration is outgoing call */
11691       r->call = dialog_ref(p, "copying dialog into registry r->call");     /* Save pointer to SIP dialog */
11692       p->registry = registry_addref(r, "transmit_register: addref to p->registry in transmit_register"); /* Add pointer to registry in packet */
11693       if (!ast_strlen_zero(r->secret)) {  /* Secret (password) */
11694          ast_string_field_set(p, peersecret, r->secret);
11695       }
11696       if (!ast_strlen_zero(r->md5secret))
11697          ast_string_field_set(p, peermd5secret, r->md5secret);
11698       /* User name in this realm  
11699       - if authuser is set, use that, otherwise use username */
11700       if (!ast_strlen_zero(r->authuser)) {   
11701          ast_string_field_set(p, peername, r->authuser);
11702          ast_string_field_set(p, authname, r->authuser);
11703       } else if (!ast_strlen_zero(r->username)) {
11704          ast_string_field_set(p, peername, r->username);
11705          ast_string_field_set(p, authname, r->username);
11706          ast_string_field_set(p, fromuser, r->username);
11707       }
11708       if (!ast_strlen_zero(r->username))
11709          ast_string_field_set(p, username, r->username);
11710       /* Save extension in packet */
11711       if (!ast_strlen_zero(r->callback))
11712          ast_string_field_set(p, exten, r->callback);
11713 
11714       /* Set transport and port so the correct contact is built */
11715       set_socket_transport(&p->socket, r->transport);
11716       if (r->transport == SIP_TRANSPORT_TLS || r->transport == SIP_TRANSPORT_TCP) {
11717          p->socket.port = sip_tcp_desc.local_address.sin_port;
11718       }
11719 
11720       /*
11721         check which address we should use in our contact header 
11722         based on whether the remote host is on the external or
11723         internal network so we can register through nat
11724        */
11725       ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
11726       build_contact(p);
11727    }
11728 
11729    /* set up a timeout */
11730    if (auth == NULL)  {
11731       if (r->timeout > -1)
11732          ast_log(LOG_WARNING, "Still have a registration timeout, #%d - deleting it\n", r->timeout);
11733       AST_SCHED_REPLACE_UNREF(r->timeout, sched, global_reg_timeout * 1000, sip_reg_timeout, r,
11734                         registry_unref(_data,"reg ptr unrefed from del in SCHED_REPLACE"),
11735                         registry_unref(r,"reg ptr unrefed from add failure in SCHED_REPLACE"),
11736                         registry_addref(r,"reg ptr reffed from add in SCHED_REPLACE"));
11737       ast_debug(1, "Scheduled a registration timeout for %s id  #%d \n", r->hostname, r->timeout);
11738    }
11739 
11740    if ((fromdomain = strchr(r->username, '@'))) {
11741       /* the domain name is just behind '@' */
11742       fromdomain++ ;
11743       /* We have a domain in the username for registration */
11744       snprintf(from, sizeof(from), "<sip:%s>;tag=%s", r->username, p->tag);
11745       if (!ast_strlen_zero(p->theirtag))
11746          snprintf(to, sizeof(to), "<sip:%s>;tag=%s", r->username, p->theirtag);
11747       else
11748          snprintf(to, sizeof(to), "<sip:%s>", r->username);
11749 
11750       /* If the registration username contains '@', then the domain should be used as
11751          the equivalent of "fromdomain" for the registration */
11752       if (ast_strlen_zero(p->fromdomain)) {
11753          ast_string_field_set(p, fromdomain, fromdomain);
11754       }
11755    } else {
11756       snprintf(from, sizeof(from), "<sip:%s@%s>;tag=%s", r->username, p->tohost, p->tag);
11757       if (!ast_strlen_zero(p->theirtag))
11758          snprintf(to, sizeof(to), "<sip:%s@%s>;tag=%s", r->username, p->tohost, p->theirtag);
11759       else
11760          snprintf(to, sizeof(to), "<sip:%s@%s>", r->username, p->tohost);
11761    }
11762    
11763    /* Fromdomain is what we are registering to, regardless of actual
11764       host name from SRV */
11765    if (!ast_strlen_zero(p->fromdomain)) {
11766       domainport = strrchr(p->fromdomain, ':');
11767       if (domainport) {
11768          *domainport++ = '\0'; /* trim off domainport from p->fromdomain */
11769          if (ast_strlen_zero(domainport))
11770             domainport = NULL;
11771       }     
11772       if (domainport) {       
11773          if (atoi(domainport) != STANDARD_SIP_PORT)
11774             snprintf(addr, sizeof(addr), "sip:%s:%s", p->fromdomain, domainport);
11775          else
11776             snprintf(addr, sizeof(addr), "sip:%s", p->fromdomain);
11777       } else {
11778          if (r->portno && r->portno != STANDARD_SIP_PORT)
11779             snprintf(addr, sizeof(addr), "sip:%s:%d", p->fromdomain, r->portno);
11780          else
11781             snprintf(addr, sizeof(addr), "sip:%s", p->fromdomain);
11782       }
11783    } else {
11784       if (r->portno && r->portno != STANDARD_SIP_PORT)
11785          snprintf(addr, sizeof(addr), "sip:%s:%d", r->hostname, r->portno);
11786       else
11787          snprintf(addr, sizeof(addr), "sip:%s", r->hostname);
11788    }
11789    ast_string_field_set(p, uri, addr);
11790 
11791    p->branch ^= ast_random();
11792 
11793    init_req(&req, sipmethod, addr);
11794 
11795    /* Add to CSEQ */
11796    snprintf(tmp, sizeof(tmp), "%u %s", ++r->ocseq, sip_methods[sipmethod].text);
11797    p->ocseq = r->ocseq;
11798 
11799    build_via(p);
11800    add_header(&req, "Via", p->via);
11801    add_header(&req, "Max-Forwards", DEFAULT_MAX_FORWARDS);
11802    add_header(&req, "From", from);
11803    add_header(&req, "To", to);
11804    add_header(&req, "Call-ID", p->callid);
11805    add_header(&req, "CSeq", tmp);
11806    if (!ast_strlen_zero(global_useragent))
11807       add_header(&req, "User-Agent", global_useragent);
11808 
11809    
11810    if (auth)   /* Add auth header */
11811       add_header(&req, authheader, auth);
11812    else if (!ast_strlen_zero(r->nonce)) {
11813       char digest[1024];
11814 
11815       /* We have auth data to reuse, build a digest header.
11816        * Note, this is not always useful because some parties do not
11817        * like nonces to be reused (for good reasons!) so they will
11818        * challenge us anyways.
11819        */
11820       if (sipdebug)
11821          ast_debug(1, "   >>> Re-using Auth data for %s@%s\n", r->username, r->hostname);
11822       ast_string_field_set(p, realm, r->realm);
11823       ast_string_field_set(p, nonce, r->nonce);
11824       ast_string_field_set(p, domain, r->domain);
11825       ast_string_field_set(p, opaque, r->opaque);
11826       ast_string_field_set(p, qop, r->qop);
11827       p->noncecount = ++r->noncecount;
11828 
11829       memset(digest, 0, sizeof(digest));
11830       if(!build_reply_digest(p, sipmethod, digest, sizeof(digest)))
11831          add_header(&req, "Authorization", digest);
11832       else
11833          ast_log(LOG_NOTICE, "No authorization available for authentication of registration to %s@%s\n", r->username, r->hostname);
11834    
11835    }
11836 
11837    snprintf(tmp, sizeof(tmp), "%d", r->expiry);
11838    add_header(&req, "Expires", tmp);
11839    add_header(&req, "Contact", p->our_contact);
11840    add_header_contentLength(&req, 0);
11841 
11842    initialize_initreq(p, &req);
11843    if (sip_debug_test_pvt(p)) {
11844       ast_verbose("REGISTER %d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
11845    }
11846    r->regstate = auth ? REG_STATE_AUTHSENT : REG_STATE_REGSENT;
11847    r->regattempts++; /* Another attempt */
11848    ast_debug(4, "REGISTER attempt %d to %s@%s\n", r->regattempts, r->username, r->hostname);
11849    res = send_request(p, &req, XMIT_CRITICAL, p->ocseq);
11850    dialog_unref(p, "p is finished here at the end of transmit_register");
11851    return res;
11852 }
11853 
11854 /*! \brief Transmit text with SIP MESSAGE method */
11855 static int transmit_message_with_text(struct sip_pvt *p, const char *text)
11856 {
11857    struct sip_request req;
11858    
11859    reqprep(&req, p, SIP_MESSAGE, 0, 1);
11860    add_text(&req, text);
11861    return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
11862 }
11863 
11864 /*! \brief Allocate SIP refer structure */
11865 static int sip_refer_allocate(struct sip_pvt *p)
11866 {
11867    p->refer = ast_calloc(1, sizeof(struct sip_refer)); 
11868    return p->refer ? 1 : 0;
11869 }
11870 
11871 /*! \brief Transmit SIP REFER message (initiated by the transfer() dialplan application
11872    \note this is currently broken as we have no way of telling the dialplan
11873    engine whether a transfer succeeds or fails.
11874    \todo Fix the transfer() dialplan function so that a transfer may fail
11875 */
11876 static int transmit_refer(struct sip_pvt *p, const char *dest)
11877 {
11878    struct sip_request req = { 
11879       .headers = 0,  
11880    };
11881    char from[256];
11882    const char *of;
11883    char *c;
11884    char referto[256];
11885    char *ttag, *ftag;
11886    char *theirtag = ast_strdupa(p->theirtag);
11887    int   use_tls=FALSE;
11888 
11889    if (sipdebug)
11890       ast_debug(1, "SIP transfer of %s to %s\n", p->callid, dest);
11891 
11892    /* Are we transfering an inbound or outbound call ? */
11893    if (ast_test_flag(&p->flags[0], SIP_OUTGOING))  {
11894       of = get_header(&p->initreq, "To");
11895       ttag = theirtag;
11896       ftag = p->tag;
11897    } else {
11898       of = get_header(&p->initreq, "From");
11899       ftag = theirtag;
11900       ttag = p->tag;
11901    }
11902 
11903    ast_copy_string(from, of, sizeof(from));
11904    of = get_in_brackets(from);
11905    ast_string_field_set(p, from, of);
11906    if (!strncasecmp(of, "sip:", 4)) {
11907       of += 4;
11908    }else if (!strncasecmp(of, "sips:", 5)) {
11909       of += 5;
11910       use_tls = TRUE;
11911    } else {
11912       ast_log(LOG_NOTICE, "From address missing 'sip(s):', assuming sip:\n");
11913    }
11914    /* Get just the username part */
11915    if ((c = strchr(dest, '@')))
11916       c = NULL;
11917    else if ((c = strchr(of, '@')))
11918       *c++ = '\0';
11919    if (c) 
11920       snprintf(referto, sizeof(referto), "<sip%s:%s@%s>", use_tls ? "s" : "", dest, c);
11921    else
11922       snprintf(referto, sizeof(referto), "<sip%s:%s>", use_tls ? "s" : "", dest);
11923 
11924    /* save in case we get 407 challenge */
11925    sip_refer_allocate(p);
11926    ast_copy_string(p->refer->refer_to, referto, sizeof(p->refer->refer_to));
11927    ast_copy_string(p->refer->referred_by, p->our_contact, sizeof(p->refer->referred_by));
11928    p->refer->status = REFER_SENT;   /* Set refer status */
11929 
11930    reqprep(&req, p, SIP_REFER, 0, 1);
11931 
11932    add_header(&req, "Refer-To", referto);
11933    add_header(&req, "Allow", ALLOWED_METHODS);
11934    add_header(&req, "Supported", SUPPORTED_EXTENSIONS);
11935    if (!ast_strlen_zero(p->our_contact))
11936       add_header(&req, "Referred-By", p->our_contact);
11937 
11938    return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
11939 
11940    /* We should propably wait for a NOTIFY here until we ack the transfer */
11941    /* Maybe fork a new thread and wait for a STATUS of REFER_200OK on the refer status before returning to app_transfer */
11942 
11943    /*! \todo In theory, we should hang around and wait for a reply, before
11944    returning to the dial plan here. Don't know really how that would
11945    affect the transfer() app or the pbx, but, well, to make this
11946    useful we should have a STATUS code on transfer().
11947    */
11948 }
11949 
11950 
11951 /*! \brief Send SIP INFO dtmf message, see Cisco documentation on cisco.com */
11952 static int transmit_info_with_digit(struct sip_pvt *p, const char digit, unsigned int duration)
11953 {
11954    struct sip_request req;
11955    
11956    reqprep(&req, p, SIP_INFO, 0, 1);
11957    add_digit(&req, digit, duration, (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_SHORTINFO));
11958    return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
11959 }
11960 
11961 /*! \brief Send SIP INFO with video update request */
11962 static int transmit_info_with_vidupdate(struct sip_pvt *p)
11963 {
11964    struct sip_request req;
11965    
11966    reqprep(&req, p, SIP_INFO, 0, 1);
11967    add_vidupdate(&req);
11968    return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
11969 }
11970 
11971 /*! \brief Transmit generic SIP request 
11972    returns XMIT_ERROR if transmit failed with a critical error (don't retry)
11973 */
11974 static int transmit_request(struct sip_pvt *p, int sipmethod, int seqno, enum xmittype reliable, int newbranch)
11975 {
11976    struct sip_request resp;
11977    
11978    if (sipmethod == SIP_ACK)
11979       p->invitestate = INV_CONFIRMED;
11980 
11981    reqprep(&resp, p, sipmethod, seqno, newbranch);
11982    if (sipmethod == SIP_CANCEL && p->answered_elsewhere) 
11983       add_header(&resp, "Reason", "SIP;cause=200;text=\"Call completed elsewhere\"");
11984 
11985    add_header_contentLength(&resp, 0);
11986    return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);
11987 }
11988 
11989 /*! \brief return the request and response heade for a 401 or 407 code */
11990 static void auth_headers(enum sip_auth_type code, char **header, char **respheader)
11991 {
11992    if (code == WWW_AUTH) {       /* 401 */
11993       *header = "WWW-Authenticate";
11994       *respheader = "Authorization";
11995    } else if (code == PROXY_AUTH) { /* 407 */
11996       *header = "Proxy-Authenticate";
11997       *respheader = "Proxy-Authorization";
11998    } else {
11999       ast_verbose("-- wrong response code %d\n", code);
12000       *header = *respheader = "Invalid";
12001    }
12002 }
12003 
12004 /*! \brief Transmit SIP request, auth added */
12005 static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, int seqno, enum xmittype reliable, int newbranch)
12006 {
12007    struct sip_request resp;
12008    
12009    reqprep(&resp, p, sipmethod, seqno, newbranch);
12010    if (!ast_strlen_zero(p->realm)) {
12011       char digest[1024];
12012 
12013       memset(digest, 0, sizeof(digest));
12014       if(!build_reply_digest(p, sipmethod, digest, sizeof(digest))) {
12015          char *dummy, *response;
12016          enum sip_auth_type code = p->options ? p->options->auth_type : PROXY_AUTH; /* XXX force 407 if unknown */
12017          auth_headers(code, &dummy, &response);
12018          add_header(&resp, response, digest);
12019       } else
12020          ast_log(LOG_WARNING, "No authentication available for call %s\n", p->callid);
12021    }
12022    /* If we are hanging up and know a cause for that, send it in clear text to make
12023       debugging easier. */
12024    if (sipmethod == SIP_BYE)  {
12025       char buf[10];
12026 
12027       add_header(&resp, "X-Asterisk-HangupCause", ast_cause2str(p->hangupcause));
12028       snprintf(buf, sizeof(buf), "%d", p->hangupcause);
12029       add_header(&resp, "X-Asterisk-HangupCauseCode", buf);
12030    }
12031 
12032    add_header_contentLength(&resp, 0);
12033    return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);   
12034 }
12035 
12036 /*! \brief Remove registration data from realtime database or AST/DB when registration expires */
12037 static void destroy_association(struct sip_peer *peer)
12038 {
12039    int realtimeregs = ast_check_realtime("sipregs");
12040    char *tablename = (realtimeregs) ? "sipregs" : "sippeers";
12041 
12042    if (!sip_cfg.ignore_regexpire) {
12043       if (peer->rt_fromcontact && sip_cfg.peer_rtupdate) {
12044          ast_update_realtime(tablename, "name", peer->name, "fullcontact", "", "ipaddr", "", "port", "", "regseconds", "0", peer->deprecated_username ? "username" : "defaultuser", "", "regserver", "", "useragent", "", "lastms", "", SENTINEL);
12045       } else {
12046          ast_db_del("SIP/Registry", peer->name);
12047       }
12048    }
12049 }
12050 
12051 static void set_socket_transport(struct sip_socket *socket, int transport)
12052 {
12053    /* if the transport type changes, clear all socket data */
12054    if (socket->type != transport) {
12055       socket->fd = -1;
12056       socket->type = transport;
12057       if (socket->tcptls_session) {
12058          ao2_ref(socket->tcptls_session, -1);
12059          socket->tcptls_session = NULL;
12060       }
12061    }
12062 }
12063 
12064 /*! \brief Expire registration of SIP peer */
12065 static int expire_register(const void *data)
12066 {
12067    struct sip_peer *peer = (struct sip_peer *)data;
12068 
12069    if (!peer)     /* Hmmm. We have no peer. Weird. */
12070       return 0;
12071 
12072    peer->expire = -1;
12073    peer->portinuri = 0;
12074    memset(&peer->addr, 0, sizeof(peer->addr));
12075 
12076    destroy_association(peer); /* remove registration data from storage */
12077    set_socket_transport(&peer->socket, peer->default_outbound_transport);
12078 
12079    if (peer->socket.tcptls_session) {
12080       ao2_ref(peer->socket.tcptls_session, -1);
12081       peer->socket.tcptls_session = NULL;
12082    }
12083 
12084    manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: Unregistered\r\nCause: Expired\r\n", peer->name);
12085    register_peer_exten(peer, FALSE);   /* Remove regexten */
12086    ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", peer->name);
12087 
12088    /* Do we need to release this peer from memory? 
12089       Only for realtime peers and autocreated peers
12090    */
12091    if (peer->is_realtime)
12092       ast_debug(3, "-REALTIME- peer expired registration. Name: %s. Realtime peer objects now %d\n", peer->name, rpeerobjs);
12093 
12094    if (peer->selfdestruct ||
12095        ast_test_flag(&peer->flags[1], SIP_PAGE2_RTAUTOCLEAR)) {
12096       ao2_t_unlink(peers, peer, "ao2_unlink of peer from peers table");
12097       if (peer->addr.sin_addr.s_addr) {
12098          ao2_t_unlink(peers_by_ip, peer, "ao2_unlink of peer from peers_by_ip table");
12099       }
12100    }
12101 
12102    unref_peer(peer, "removing peer ref for expire_register");
12103 
12104    return 0;
12105 }
12106 
12107 /*! \brief Poke peer (send qualify to check if peer is alive and well) */
12108 static int sip_poke_peer_s(const void *data)
12109 {
12110    struct sip_peer *peer = (struct sip_peer *)data;
12111 
12112    peer->pokeexpire = -1;
12113 
12114    sip_poke_peer(peer, 0);
12115 
12116    unref_peer(peer, "removing poke peer ref");
12117 
12118    return 0;
12119 }
12120 
12121 /*! \brief Get registration details from Asterisk DB */
12122 static void reg_source_db(struct sip_peer *peer)
12123 {
12124    char data[256];
12125    struct in_addr in;
12126    int expire;
12127    int port;
12128    char *scan, *addr, *port_str, *expiry_str, *username, *contact;
12129 
12130    if (peer->rt_fromcontact) 
12131       return;
12132    if (ast_db_get("SIP/Registry", peer->name, data, sizeof(data)))
12133       return;
12134 
12135    scan = data;
12136    addr = strsep(&scan, ":");
12137    port_str = strsep(&scan, ":");
12138    expiry_str = strsep(&scan, ":");
12139    username = strsep(&scan, ":");
12140    contact = scan;   /* Contact include sip: and has to be the last part of the database entry as long as we use : as a separator */
12141 
12142    if (!inet_aton(addr, &in))
12143       return;
12144 
12145    if (port_str)
12146       port = atoi(port_str);
12147    else
12148       return;
12149 
12150    if (expiry_str)
12151       expire = atoi(expiry_str);
12152    else
12153       return;
12154 
12155    if (username)
12156       ast_string_field_set(peer, username, username);
12157    if (contact)
12158       ast_string_field_set(peer, fullcontact, contact);
12159 
12160    ast_debug(2, "SIP Seeding peer from astdb: '%s' at %s@%s:%d for %d\n",
12161        peer->name, peer->username, ast_inet_ntoa(in), port, expire);
12162 
12163    memset(&peer->addr, 0, sizeof(peer->addr));
12164    peer->addr.sin_family = AF_INET;
12165    peer->addr.sin_addr = in;
12166    peer->addr.sin_port = htons(port);
12167    if (sipsock < 0) {
12168       /* SIP isn't up yet, so schedule a poke only, pretty soon */
12169       AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched, ast_random() % 5000 + 1, sip_poke_peer_s, peer,
12170             unref_peer(_data, "removing poke peer ref"),
12171             unref_peer(peer, "removing poke peer ref"),
12172             ref_peer(peer, "adding poke peer ref"));
12173    } else {
12174       sip_poke_peer(peer, 0);
12175    }
12176    AST_SCHED_REPLACE_UNREF(peer->expire, sched, (expire + 10) * 1000, expire_register, peer,
12177          unref_peer(_data, "remove registration ref"),
12178          unref_peer(peer, "remove registration ref"),
12179          ref_peer(peer, "add registration ref"));
12180    register_peer_exten(peer, TRUE);
12181 }
12182 
12183 /*! \brief Save contact header for 200 OK on INVITE */
12184 static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req)
12185 {
12186    char contact[SIPBUFSIZE]; 
12187    char *c;
12188 
12189    /* Look for brackets */
12190    ast_copy_string(contact, get_header(req, "Contact"), sizeof(contact));
12191    c = get_in_brackets(contact);
12192 
12193    /* Save full contact to call pvt for later bye or re-invite */
12194    ast_string_field_set(pvt, fullcontact, c);
12195 
12196    /* Save URI for later ACKs, BYE or RE-invites */
12197    ast_string_field_set(pvt, okcontacturi, c);
12198 
12199    /* We should return false for URI:s we can't handle,
12200       like tel:, mailto:,ldap: etc */
12201    return TRUE;      
12202 }
12203 
12204 static int __set_address_from_contact(const char *fullcontact, struct sockaddr_in *sin, int tcp)
12205 {
12206    struct hostent *hp;
12207    struct ast_hostent ahp;
12208    int port = STANDARD_SIP_PORT;
12209    char *host, *pt, *transport;
12210    char contact_buf[256];
12211    char *contact;
12212 
12213    /* Work on a copy */
12214    ast_copy_string(contact_buf, fullcontact, sizeof(contact_buf));
12215    contact = contact_buf;
12216 
12217    /* 
12218     * We have only the part in <brackets> here so we just need to parse a SIP URI.
12219     *
12220     * Note: The outbound proxy could be using UDP between the proxy and Asterisk.
12221     * We still need to be able to send to the remote agent through the proxy.
12222     */
12223 
12224    if (parse_uri(contact, "sip:,sips:", &contact, NULL, &host, &pt, NULL, &transport)) {
12225       ast_log(LOG_WARNING, "Invalid contact uri %s (missing sip: or sips:), attempting to use anyway\n", fullcontact);
12226    }
12227 
12228    /* set port */
12229    if (((get_transport_str2enum(transport) == SIP_TRANSPORT_TLS)) || !(strncasecmp(fullcontact, "sips", 4))) {
12230       port = port_str2int(pt, STANDARD_TLS_PORT);
12231    } else {
12232       port = port_str2int(pt, STANDARD_SIP_PORT);
12233    }
12234 
12235 
12236    /* XXX This could block for a long time XXX */
12237    /* We should only do this if it's a name, not an IP */
12238    /* \todo - if there's no PORT number in contact - we are required to check NAPTR/SRV records
12239       to find transport, port address and hostname. If there's a port number, we have to
12240       assume that the domain part is a host name and only look for an A/AAAA record in DNS.
12241    */
12242    hp = ast_gethostbyname(host, &ahp);
12243    if (!hp)  {
12244       ast_log(LOG_WARNING, "Invalid host name in Contact: (can't resolve in DNS) : '%s'\n", host);
12245       return -1;
12246    }
12247    sin->sin_family = AF_INET;
12248    memcpy(&sin->sin_addr, hp->h_addr, sizeof(sin->sin_addr));
12249    sin->sin_port = htons(port);
12250 
12251    return 0;
12252 }
12253 
12254 /*! \brief Change the other partys IP address based on given contact */
12255 static int set_address_from_contact(struct sip_pvt *pvt)
12256 {
12257    if (ast_test_flag(&pvt->flags[0], SIP_NAT_ROUTE)) {
12258       /* NAT: Don't trust the contact field.  Just use what they came to us
12259          with. */
12260       /*! \todo We need to save the TRANSPORT here too */
12261       pvt->sa = pvt->recv;
12262       return 0;
12263    }
12264 
12265    return __set_address_from_contact(pvt->fullcontact, &pvt->sa, pvt->socket.type == SIP_TRANSPORT_TLS ? 1 : 0);
12266 }
12267 
12268 /*! \brief Parse contact header and save registration (peer registration) */
12269 static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *peer, struct sip_request *req)
12270 {
12271    char contact[SIPBUFSIZE];
12272    char data[SIPBUFSIZE];
12273    const char *expires = get_header(req, "Expires");
12274    int expire = atoi(expires);
12275    char *curi, *host, *pt, *transport;
12276    int port;
12277    int transport_type;
12278    const char *useragent;
12279    struct hostent *hp;
12280    struct ast_hostent ahp;
12281    struct sockaddr_in oldsin, testsin;
12282 
12283 
12284    ast_copy_string(contact, get_header(req, "Contact"), sizeof(contact));
12285 
12286    if (ast_strlen_zero(expires)) {  /* No expires header, try look in Contact: */
12287       char *s = strcasestr(contact, ";expires=");
12288       if (s) {
12289          expires = strsep(&s, ";"); /* trim ; and beyond */
12290          if (sscanf(expires + 9, "%30d", &expire) != 1)
12291             expire = default_expiry;
12292       } else {
12293          /* Nothing has been specified */
12294          expire = default_expiry;
12295       }
12296    }
12297 
12298    copy_socket_data(&pvt->socket, &req->socket);
12299 
12300    /* Look for brackets */
12301    curi = contact;
12302    if (strchr(contact, '<') == NULL)   /* No <, check for ; and strip it */
12303       strsep(&curi, ";");  /* This is Header options, not URI options */
12304    curi = get_in_brackets(contact);
12305 
12306    /* if they did not specify Contact: or Expires:, they are querying
12307       what we currently have stored as their contact address, so return
12308       it
12309    */
12310    if (ast_strlen_zero(curi) && ast_strlen_zero(expires)) {
12311       /* If we have an active registration, tell them when the registration is going to expire */
12312       if (peer->expire > -1 && !ast_strlen_zero(peer->fullcontact))
12313          pvt->expiry = ast_sched_when(sched, peer->expire);
12314       return PARSE_REGISTER_QUERY;
12315    } else if (!strcasecmp(curi, "*") || !expire) { /* Unregister this peer */
12316       /* This means remove all registrations and return OK */
12317       memset(&peer->addr, 0, sizeof(peer->addr));
12318       set_socket_transport(&peer->socket, peer->default_outbound_transport);
12319 
12320       AST_SCHED_DEL_UNREF(sched, peer->expire,
12321             unref_peer(peer, "remove register expire ref"));
12322 
12323       destroy_association(peer);
12324 
12325       register_peer_exten(peer, FALSE);   /* Remove extension from regexten= setting in sip.conf */
12326       ast_string_field_set(peer, fullcontact, "");
12327       ast_string_field_set(peer, useragent, "");
12328       peer->sipoptions = 0;
12329       peer->lastms = 0;
12330       peer->portinuri = 0;
12331       pvt->expiry = 0;
12332 
12333       ast_verb(3, "Unregistered SIP '%s'\n", peer->name);
12334 
12335       manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: Unregistered\r\n", peer->name);
12336       return PARSE_REGISTER_UPDATE;
12337    }
12338 
12339    /* Store whatever we got as a contact from the client */
12340    ast_string_field_set(peer, fullcontact, curi);
12341 
12342    /* For the 200 OK, we should use the received contact */
12343    ast_string_field_build(pvt, our_contact, "<%s>", curi);
12344 
12345    /* Make sure it's a SIP URL */
12346    if (parse_uri(curi, "sip:,sips:", &curi, NULL, &host, &pt, NULL, &transport)) {
12347       ast_log(LOG_NOTICE, "Not a valid SIP contact (missing sip:) trying to use anyway\n");
12348    }
12349 
12350    /* If we have a port number in the given URI, make sure we do remember to not check for NAPTR/SRV records. 
12351       The domain part is actually a host. */
12352    peer->portinuri = !ast_strlen_zero(pt) ? TRUE : FALSE;
12353 
12354    /* handle the transport type specified in Contact header. */
12355    if ((transport_type = get_transport_str2enum(transport))) {
12356       /* if the port is not specified but the transport is, make sure to set the
12357        * default port to match the specified transport.  This may or may not be the
12358        * same transport used by the pvt struct for the Register dialog. */
12359       
12360       port = port_str2int(pt, (transport_type == SIP_TRANSPORT_TLS) ? STANDARD_TLS_PORT : STANDARD_SIP_PORT);
12361    } else {
12362       port = port_str2int(pt, STANDARD_SIP_PORT);
12363       transport_type = pvt->socket.type;
12364    }
12365 
12366    /* if the peer's socket type is different than the Registration
12367     * transport type, change it.  If it got this far, it is a
12368     * supported type, but check just in case */
12369    if ((peer->socket.type != transport_type) && (peer->transports & transport_type)) {
12370       set_socket_transport(&peer->socket, transport_type);
12371    }
12372 
12373    oldsin = peer->addr;
12374 
12375    /* If we were already linked into the peers_by_ip container unlink ourselves so nobody can find us */
12376    if (peer->addr.sin_addr.s_addr) {
12377       ao2_t_unlink(peers_by_ip, peer, "ao2_unlink of peer from peers_by_ip table");
12378    }
12379 
12380    /* Check that they're allowed to register at this IP */
12381    /* XXX This could block for a long time XXX */
12382    /*! \todo Check NAPTR/SRV if we have not got a port in the URI */
12383    hp = ast_gethostbyname(host, &ahp);
12384    if (!hp)  {
12385       ast_log(LOG_WARNING, "Invalid host '%s'\n", host);
12386       ast_string_field_set(peer, fullcontact, "");
12387       ast_string_field_set(pvt, our_contact, "");
12388       return PARSE_REGISTER_FAILED;
12389    }
12390    memcpy(&testsin.sin_addr, hp->h_addr, sizeof(testsin.sin_addr));
12391    if (ast_apply_ha(global_contact_ha, &testsin) != AST_SENSE_ALLOW ||
12392          ast_apply_ha(peer->contactha, &testsin) != AST_SENSE_ALLOW) {
12393       ast_log(LOG_WARNING, "Host '%s' disallowed by contact ACL (violating IP %s)\n", host, ast_inet_ntoa(testsin.sin_addr));
12394       ast_string_field_set(peer, fullcontact, "");
12395       ast_string_field_set(pvt, our_contact, "");
12396       return PARSE_REGISTER_DENIED;
12397    }
12398 
12399    /*! \todo This could come before the checking of DNS earlier on, to avoid 
12400       DNS lookups where we don't need it... */
12401    if (!ast_test_flag(&peer->flags[0], SIP_NAT_ROUTE)) {
12402       peer->addr.sin_family = AF_INET;
12403       memcpy(&peer->addr.sin_addr, hp->h_addr, sizeof(peer->addr.sin_addr));
12404       peer->addr.sin_port = htons(port);
12405    } else {
12406       /* Don't trust the contact field.  Just use what they came to us
12407          with */
12408       peer->addr = pvt->recv;
12409    }
12410 
12411    /* if the Contact header information copied into peer->addr matches the
12412     * received address, and the transport types are the same, then copy socket
12413     * data into the peer struct */
12414    if ((peer->socket.type == pvt->socket.type) &&
12415       (peer->addr.sin_addr.s_addr == pvt->recv.sin_addr.s_addr) &&
12416       (peer->addr.sin_port == pvt->recv.sin_port)){
12417 
12418       copy_socket_data(&peer->socket, &pvt->socket);
12419    }
12420 
12421    /* Now that our address has been updated put ourselves back into the container for lookups */
12422    ao2_t_link(peers_by_ip, peer, "ao2_link into peers_by_ip table");
12423 
12424    /* Save SIP options profile */
12425    peer->sipoptions = pvt->sipoptions;
12426 
12427    if (!ast_strlen_zero(curi) && ast_strlen_zero(peer->username))
12428       ast_string_field_set(peer, username, curi);
12429 
12430    AST_SCHED_DEL_UNREF(sched, peer->expire,
12431          unref_peer(peer, "remove register expire ref"));
12432 
12433    if (expire > max_expiry)
12434       expire = max_expiry;
12435    if (expire < min_expiry)
12436       expire = min_expiry;
12437    if (peer->is_realtime && !ast_test_flag(&peer->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
12438       peer->expire = -1;
12439    } else {
12440       peer->expire = ast_sched_add(sched, (expire + 10) * 1000, expire_register,
12441             ref_peer(peer, "add registration ref"));
12442       if (peer->expire == -1) {
12443          unref_peer(peer, "remote registration ref");
12444       }
12445    }
12446    pvt->expiry = expire;
12447    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);
12448    /* Saving TCP connections is useless, we won't be able to reconnect 
12449       XXX WHY???? XXX
12450       \todo Fix this immediately.
12451    */
12452    if (!peer->rt_fromcontact && (peer->socket.type & SIP_TRANSPORT_UDP))
12453       ast_db_put("SIP/Registry", peer->name, data);
12454    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));
12455 
12456    /* Is this a new IP address for us? */
12457    if (VERBOSITY_ATLEAST(2) && inaddrcmp(&peer->addr, &oldsin)) {
12458       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));
12459    }
12460    sip_poke_peer(peer, 0);
12461    register_peer_exten(peer, 1);
12462    
12463    /* Save User agent */
12464    useragent = get_header(req, "User-Agent");
12465    if (strcasecmp(useragent, peer->useragent)) {
12466       ast_string_field_set(peer, useragent, useragent);
12467       ast_verb(4, "Saved useragent \"%s\" for peer %s\n", peer->useragent, peer->name);
12468    }
12469    return PARSE_REGISTER_UPDATE;
12470 }
12471 
12472 /*! \brief Remove route from route list */
12473 static void free_old_route(struct sip_route *route)
12474 {
12475    struct sip_route *next;
12476 
12477    while (route) {
12478       next = route->next;
12479       ast_free(route);
12480       route = next;
12481    }
12482 }
12483 
12484 /*! \brief List all routes - mostly for debugging */
12485 static void list_route(struct sip_route *route)
12486 {
12487    if (!route)
12488       ast_verbose("list_route: no route\n");
12489    else {
12490       for (;route; route = route->next)
12491          ast_verbose("list_route: hop: <%s>\n", route->hop);
12492    }
12493 }
12494 
12495 /*! \brief Build route list from Record-Route header */
12496 static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards)
12497 {
12498    struct sip_route *thishop, *head, *tail;
12499    int start = 0;
12500    int len;
12501    const char *rr, *contact, *c;
12502 
12503    /* Once a persistant route is set, don't fool with it */
12504    if (p->route && p->route_persistant) {
12505       ast_debug(1, "build_route: Retaining previous route: <%s>\n", p->route->hop);
12506       return;
12507    }
12508 
12509    if (p->route) {
12510       free_old_route(p->route);
12511       p->route = NULL;
12512    }
12513 
12514    /* We only want to create the route set the first time this is called */
12515    p->route_persistant = 1;
12516    
12517    /* Build a tailq, then assign it to p->route when done.
12518     * If backwards, we add entries from the head so they end up
12519     * in reverse order. However, we do need to maintain a correct
12520     * tail pointer because the contact is always at the end.
12521     */
12522    head = NULL;
12523    tail = head;
12524    /* 1st we pass through all the hops in any Record-Route headers */
12525    for (;;) {
12526       /* Each Record-Route header */
12527       rr = __get_header(req, "Record-Route", &start);
12528       if (*rr == '\0')
12529          break;
12530       for (; (rr = strchr(rr, '<')) ; rr += len) { /* Each route entry */
12531          ++rr;
12532          len = strcspn(rr, ">") + 1;
12533          /* Make a struct route */
12534          if ((thishop = ast_malloc(sizeof(*thishop) + len))) {
12535             /* ast_calloc is not needed because all fields are initialized in this block */
12536             ast_copy_string(thishop->hop, rr, len);
12537             ast_debug(2, "build_route: Record-Route hop: <%s>\n", thishop->hop);
12538             /* Link in */
12539             if (backwards) {
12540                /* Link in at head so they end up in reverse order */
12541                thishop->next = head;
12542                head = thishop;
12543                /* If this was the first then it'll be the tail */
12544                if (!tail)
12545                   tail = thishop;
12546             } else {
12547                thishop->next = NULL;
12548                /* Link in at the end */
12549                if (tail)
12550                   tail->next = thishop;
12551                else
12552                   head = thishop;
12553                tail = thishop;
12554             }
12555          }
12556       }
12557    }
12558 
12559    /* Only append the contact if we are dealing with a strict router */
12560    if (!head || (!ast_strlen_zero(head->hop) && strstr(head->hop, ";lr") == NULL) ) {
12561       /* 2nd append the Contact: if there is one */
12562       /* Can be multiple Contact headers, comma separated values - we just take the first */
12563       contact = get_header(req, "Contact");
12564       if (!ast_strlen_zero(contact)) {
12565          ast_debug(2, "build_route: Contact hop: %s\n", contact);
12566          /* Look for <: delimited address */
12567          c = strchr(contact, '<');
12568          if (c) {
12569             /* Take to > */
12570             ++c;
12571             len = strcspn(c, ">") + 1;
12572          } else {
12573             /* No <> - just take the lot */
12574             c = contact;
12575             len = strlen(contact) + 1;
12576          }
12577          if ((thishop = ast_malloc(sizeof(*thishop) + len))) {
12578             /* ast_calloc is not needed because all fields are initialized in this block */
12579             ast_copy_string(thishop->hop, c, len);
12580             thishop->next = NULL;
12581             /* Goes at the end */
12582             if (tail)
12583                tail->next = thishop;
12584             else
12585                head = thishop;
12586          }
12587       }
12588    }
12589 
12590    /* Store as new route */
12591    p->route = head;
12592 
12593    /* For debugging dump what we ended up with */
12594    if (sip_debug_test_pvt(p))
12595       list_route(p->route);
12596 }
12597 
12598 /*! \brief builds the sip_pvt's randdata field which is used for the nonce
12599  *  challenge.  When forceupdate is not set, the nonce is only updated if
12600  *  the current one is stale.  In this case, a stalenonce is one which
12601  *  has already received a response, if a nonce has not received a response
12602  *  it is not always necessary or beneficial to create a new one. */
12603 
12604 static void set_nonce_randdata(struct sip_pvt *p, int forceupdate)
12605 {
12606    if (p->stalenonce || forceupdate || ast_strlen_zero(p->randdata)) {
12607       ast_string_field_build(p, randdata, "%08lx", ast_random()); /* Create nonce for challenge */
12608       p->stalenonce = 0;
12609    }
12610 }
12611 
12612 AST_THREADSTORAGE(check_auth_buf);
12613 #define CHECK_AUTH_BUF_INITLEN   256
12614 
12615 /*! \brief  Check user authorization from peer definition 
12616    Some actions, like REGISTER and INVITEs from peers require
12617    authentication (if peer have secret set) 
12618     \return 0 on success, non-zero on error
12619 */
12620 static enum check_auth_result check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
12621                 const char *secret, const char *md5secret, int sipmethod,
12622                 char *uri, enum xmittype reliable, int ignore)
12623 {
12624    const char *response;
12625    char *reqheader, *respheader;
12626    const char *authtoken;
12627    char a1_hash[256];
12628    char resp_hash[256]="";
12629    char *c;
12630    int  wrongnonce = FALSE;
12631    int  good_response;
12632    const char *usednonce = p->randdata;
12633    struct ast_str *buf;
12634    int res;
12635 
12636    /* table of recognised keywords, and their value in the digest */
12637    enum keys { K_RESP, K_URI, K_USER, K_NONCE, K_LAST };
12638    struct x {
12639       const char *key;
12640       const char *s;
12641    } *i, keys[] = {
12642       [K_RESP] = { "response=", "" },
12643       [K_URI] = { "uri=", "" },
12644       [K_USER] = { "username=", "" },
12645       [K_NONCE] = { "nonce=", "" },
12646       [K_LAST] = { NULL, NULL}
12647    };
12648 
12649    /* Always OK if no secret */
12650    if (ast_strlen_zero(secret) && ast_strlen_zero(md5secret))
12651       return AUTH_SUCCESSFUL;
12652 
12653    /* Always auth with WWW-auth since we're NOT a proxy */
12654    /* Using proxy-auth in a B2BUA may block proxy authorization in the same transaction */
12655    response = "401 Unauthorized";
12656 
12657    /*
12658     * Note the apparent swap of arguments below, compared to other
12659     * usages of auth_headers().
12660     */
12661    auth_headers(WWW_AUTH, &respheader, &reqheader);
12662 
12663    authtoken =  get_header(req, reqheader);  
12664    if (ignore && !ast_strlen_zero(p->randdata) && ast_strlen_zero(authtoken)) {
12665       /* This is a retransmitted invite/register/etc, don't reconstruct authentication
12666          information */
12667       if (!reliable) {
12668          /* Resend message if this was NOT a reliable delivery.   Otherwise the
12669             retransmission should get it */
12670          transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, 0);
12671          /* Schedule auto destroy in 32 seconds (according to RFC 3261) */
12672          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
12673       }
12674       return AUTH_CHALLENGE_SENT;
12675    } else if (ast_strlen_zero(p->randdata) || ast_strlen_zero(authtoken)) {
12676       /* We have no auth, so issue challenge and request authentication */
12677       set_nonce_randdata(p, 1); /* Create nonce for challenge */
12678       transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, 0);
12679       /* Schedule auto destroy in 32 seconds */
12680       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
12681       return AUTH_CHALLENGE_SENT;
12682    } 
12683 
12684    /* --- We have auth, so check it */
12685 
12686    /* Whoever came up with the authentication section of SIP can suck my %&#$&* for not putting
12687       an example in the spec of just what it is you're doing a hash on. */
12688 
12689    if (!(buf = ast_str_thread_get(&check_auth_buf, CHECK_AUTH_BUF_INITLEN)))
12690       return AUTH_SECRET_FAILED; /*! XXX \todo need a better return code here */
12691 
12692    /* Make a copy of the response and parse it */
12693    res = ast_str_set(&buf, 0, "%s", authtoken);
12694 
12695    if (res == AST_DYNSTR_BUILD_FAILED)
12696       return AUTH_SECRET_FAILED; /*! XXX \todo need a better return code here */
12697 
12698    c = buf->str;
12699 
12700    while(c && *(c = ast_skip_blanks(c)) ) { /* lookup for keys */
12701       for (i = keys; i->key != NULL; i++) {
12702          const char *separator = ",";  /* default */
12703 
12704          if (strncasecmp(c, i->key, strlen(i->key)) != 0)
12705             continue;
12706          /* Found. Skip keyword, take text in quotes or up to the separator. */
12707          c += strlen(i->key);
12708          if (*c == '"') { /* in quotes. Skip first and look for last */
12709             c++;
12710             separator = "\"";
12711          }
12712          i->s = c;
12713          strsep(&c, separator);
12714          break;
12715       }
12716       if (i->key == NULL) /* not found, jump after space or comma */
12717          strsep(&c, " ,");
12718    }
12719 
12720    /* Verify that digest username matches  the username we auth as */
12721    if (strcmp(username, keys[K_USER].s)) {
12722       ast_log(LOG_WARNING, "username mismatch, have <%s>, digest has <%s>\n",
12723          username, keys[K_USER].s);
12724       /* Oops, we're trying something here */
12725       return AUTH_USERNAME_MISMATCH;
12726    }
12727 
12728    /* Verify nonce from request matches our nonce, and the nonce has not already been responded to.
12729     * If this check fails, send 401 with new nonce */
12730    if (strcasecmp(p->randdata, keys[K_NONCE].s) || p->stalenonce) { /* XXX it was 'n'casecmp ? */
12731       wrongnonce = TRUE;
12732       usednonce = keys[K_NONCE].s;
12733    } else {
12734       p->stalenonce = 1; /* now, since the nonce has a response, mark it as stale so it can't be sent or responded to again */
12735    }
12736 
12737    if (!ast_strlen_zero(md5secret))
12738       ast_copy_string(a1_hash, md5secret, sizeof(a1_hash));
12739    else {
12740       char a1[256];
12741       snprintf(a1, sizeof(a1), "%s:%s:%s", username, sip_cfg.realm, secret);
12742       ast_md5_hash(a1_hash, a1);
12743    }
12744 
12745    /* compute the expected response to compare with what we received */
12746    {
12747       char a2[256];
12748       char a2_hash[256];
12749       char resp[256];
12750 
12751       snprintf(a2, sizeof(a2), "%s:%s", sip_methods[sipmethod].text,
12752             S_OR(keys[K_URI].s, uri));
12753       ast_md5_hash(a2_hash, a2);
12754       snprintf(resp, sizeof(resp), "%s:%s:%s", a1_hash, usednonce, a2_hash);
12755       ast_md5_hash(resp_hash, resp);
12756    }
12757 
12758    good_response = keys[K_RESP].s &&
12759          !strncasecmp(keys[K_RESP].s, resp_hash, strlen(resp_hash));
12760    if (wrongnonce) {
12761       if (good_response) {
12762          if (sipdebug)
12763             ast_log(LOG_NOTICE, "Correct auth, but based on stale nonce received from '%s'\n", get_header(req, "To"));
12764          /* We got working auth token, based on stale nonce . */
12765          set_nonce_randdata(p, 0);
12766          transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, TRUE);
12767       } else {
12768          /* Everything was wrong, so give the device one more try with a new challenge */
12769          if (!req->ignore) {
12770             if (sipdebug)
12771                ast_log(LOG_NOTICE, "Bad authentication received from '%s'\n", get_header(req, "To"));
12772             set_nonce_randdata(p, 1);
12773          } else {
12774             if (sipdebug)
12775                ast_log(LOG_NOTICE, "Duplicate authentication received from '%s'\n", get_header(req, "To"));
12776          }
12777          transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, FALSE);
12778       }
12779 
12780       /* Schedule auto destroy in 32 seconds */
12781       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
12782       return AUTH_CHALLENGE_SENT;
12783    } 
12784    if (good_response) {
12785       append_history(p, "AuthOK", "Auth challenge succesful for %s", username);
12786       return AUTH_SUCCESSFUL;
12787    }
12788 
12789    /* Ok, we have a bad username/secret pair */
12790    /* Tell the UAS not to re-send this authentication data, because
12791       it will continue to fail
12792    */
12793 
12794    return AUTH_SECRET_FAILED;
12795 }
12796 
12797 /*! \brief Change onhold state of a peer using a pvt structure */
12798 static void sip_peer_hold(struct sip_pvt *p, int hold)
12799 {
12800    struct sip_peer *peer = find_peer(p->peername, NULL, 1, FINDALLDEVICES, FALSE, 0);
12801 
12802    if (!peer)
12803       return;
12804 
12805    /* If they put someone on hold, increment the value... otherwise decrement it */
12806    ast_atomic_fetchadd_int(&peer->onHold, (hold ? +1 : -1));
12807 
12808    /* Request device state update */
12809    ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", peer->name);
12810    unref_peer(peer, "sip_peer_hold: from find_peer operation");
12811    
12812    return;
12813 }
12814 
12815 /*! \brief Receive MWI events that we have subscribed to */
12816 static void mwi_event_cb(const struct ast_event *event, void *userdata)
12817 {
12818    struct sip_peer *peer = userdata;
12819 
12820    ao2_lock(peer);
12821    sip_send_mwi_to_peer(peer, event, 0);
12822    ao2_unlock(peer);
12823 }
12824 
12825 /*! \brief Callback for the devicestate notification (SUBSCRIBE) support subsystem
12826 \note If you add an "hint" priority to the extension in the dial plan,
12827    you will get notifications on device state changes */
12828 static int cb_extensionstate(char *context, char* exten, int state, void *data)
12829 {
12830    struct sip_pvt *p = data;
12831 
12832    sip_pvt_lock(p);
12833 
12834    switch(state) {
12835    case AST_EXTENSION_DEACTIVATED:  /* Retry after a while */
12836    case AST_EXTENSION_REMOVED:   /* Extension is gone */
12837       if (p->autokillid > -1 && sip_cancel_destroy(p))   /* Remove subscription expiry for renewals */
12838          ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
12839       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);  /* Delete subscription in 32 secs */
12840       ast_verb(2, "Extension state: Watcher for hint %s %s. Notify User %s\n", exten, state == AST_EXTENSION_DEACTIVATED ? "deactivated" : "removed", p->username);
12841       p->stateid = -1;
12842       p->subscribed = NONE;
12843       append_history(p, "Subscribestatus", "%s", state == AST_EXTENSION_REMOVED ? "HintRemoved" : "Deactivated");
12844       break;
12845    default: /* Tell user */
12846       p->laststate = state;
12847       break;
12848    }
12849    if (p->subscribed != NONE) {  /* Only send state NOTIFY if we know the format */
12850       if (!p->pendinginvite) {
12851          transmit_state_notify(p, state, 1, FALSE);
12852       } else {
12853          /* We already have a NOTIFY sent that is not answered. Queue the state up.
12854             if many state changes happen meanwhile, we will only send a notification of the last one */
12855          ast_set_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE);
12856       }
12857    }
12858    ast_verb(2, "Extension Changed %s[%s] new state %s for Notify User %s %s\n", exten, context, ast_extension_state2str(state), p->username,
12859          ast_test_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE) ? "(queued)" : "");
12860 
12861    sip_pvt_unlock(p);
12862 
12863    return 0;
12864 }
12865 
12866 /*! \brief Send a fake 401 Unauthorized response when the administrator
12867   wants to hide the names of local devices  from fishers
12868  */
12869 static void transmit_fake_auth_response(struct sip_pvt *p, int sipmethod, struct sip_request *req, enum xmittype reliable)
12870 {
12871    /* We have to emulate EXACTLY what we'd get with a good peer
12872     * and a bad password, or else we leak information. */
12873    const char *response = "407 Proxy Authentication Required";
12874    const char *reqheader = "Proxy-Authorization";
12875    const char *respheader = "Proxy-Authenticate";
12876    const char *authtoken;
12877    struct ast_str *buf;
12878    char *c;
12879 
12880    /* table of recognised keywords, and their value in the digest */
12881    enum keys { K_NONCE, K_LAST };
12882    struct x {
12883       const char *key;
12884       const char *s;
12885    } *i, keys[] = {
12886       [K_NONCE] = { "nonce=", "" },
12887       [K_LAST] = { NULL, NULL}
12888    };
12889 
12890    if (sipmethod == SIP_REGISTER || sipmethod == SIP_SUBSCRIBE) {
12891       response = "401 Unauthorized";
12892       reqheader = "Authorization";
12893       respheader = "WWW-Authenticate";
12894    }
12895    authtoken = get_header(req, reqheader);
12896    if (req->ignore && !ast_strlen_zero(p->randdata) && ast_strlen_zero(authtoken)) {
12897       /* This is a retransmitted invite/register/etc, don't reconstruct authentication
12898        * information */
12899       transmit_response_with_auth(p, response, req, p->randdata, 0, respheader, 0);
12900       /* Schedule auto destroy in 32 seconds (according to RFC 3261) */
12901       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
12902       return;
12903    } else if (ast_strlen_zero(p->randdata) || ast_strlen_zero(authtoken)) {
12904       /* We have no auth, so issue challenge and request authentication */
12905       set_nonce_randdata(p, 1);
12906       transmit_response_with_auth(p, response, req, p->randdata, 0, respheader, 0);
12907       /* Schedule auto destroy in 32 seconds */
12908       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
12909       return;
12910    }
12911 
12912    if (!(buf = ast_str_thread_get(&check_auth_buf, CHECK_AUTH_BUF_INITLEN))) {
12913       transmit_response(p, "403 Forbidden (Bad auth)", &p->initreq);
12914       return;
12915    }
12916 
12917    /* Make a copy of the response and parse it */
12918    if (ast_str_set(&buf, 0, "%s", authtoken) == AST_DYNSTR_BUILD_FAILED) {
12919       transmit_response(p, "403 Forbidden (Bad auth)", &p->initreq);
12920       return;
12921    }
12922 
12923    c = buf->str;
12924 
12925    while (c && *(c = ast_skip_blanks(c))) { /* lookup for keys */
12926       for (i = keys; i->key != NULL; i++) {
12927          const char *separator = ",";  /* default */
12928 
12929          if (strncasecmp(c, i->key, strlen(i->key)) != 0) {
12930             continue;
12931          }
12932          /* Found. Skip keyword, take text in quotes or up to the separator. */
12933          c += strlen(i->key);
12934          if (*c == '"') { /* in quotes. Skip first and look for last */
12935             c++;
12936             separator = "\"";
12937          }
12938          i->s = c;
12939          strsep(&c, separator);
12940          break;
12941       }
12942       if (i->key == NULL) { /* not found, jump after space or comma */
12943          strsep(&c, " ,");
12944       }
12945    }
12946 
12947    /* Verify nonce from request matches our nonce.  If not, send 401 with new nonce */
12948    if (strcasecmp(p->randdata, keys[K_NONCE].s)) {
12949       if (!req->ignore) {
12950          set_nonce_randdata(p, 1);
12951       }
12952       transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, FALSE);
12953 
12954       /* Schedule auto destroy in 32 seconds */
12955       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
12956    } else {
12957       transmit_response(p, "403 Forbidden (Bad auth)", &p->initreq);
12958    }
12959 }
12960 
12961 /*!
12962  * Terminate the uri at the first ';' or space.
12963  * Technically we should ignore escaped space per RFC3261 (19.1.1 etc)
12964  * but don't do it for the time being. Remember the uri format is:
12965  * (User-parameters was added after RFC 3261)
12966  *\verbatim
12967  *
12968  * sip:user:password;user-parameters@host:port;uri-parameters?headers
12969  * sips:user:password;user-parameters@host:port;uri-parameters?headers
12970  *
12971  *\endverbatim
12972  * \todo As this function does not support user-parameters, it's considered broken
12973  * and needs fixing.
12974  */
12975 static char *terminate_uri(char *uri)
12976 {
12977    char *t = uri;
12978    while (*t && *t > ' ' && *t != ';')
12979       t++;
12980    *t = '\0';
12981    return uri;
12982 }
12983 
12984 /*! \brief Verify registration of user 
12985    - Registration is done in several steps, first a REGISTER without auth
12986      to get a challenge (nonce) then a second one with auth
12987    - Registration requests are only matched with peers that are marked as "dynamic"
12988  */
12989 static enum check_auth_result register_verify(struct sip_pvt *p, struct sockaddr_in *sin,
12990                      struct sip_request *req, char *uri)
12991 {
12992    enum check_auth_result res = AUTH_NOT_FOUND;
12993    struct sip_peer *peer;
12994    char tmp[256];
12995    char *name, *c;
12996    char *domain;
12997 
12998    terminate_uri(uri);  /* warning, overwrite the string */
12999 
13000    ast_copy_string(tmp, get_header(req, "To"), sizeof(tmp));
13001    if (sip_cfg.pedanticsipchecking)
13002       ast_uri_decode(tmp);
13003 
13004    c = get_in_brackets(tmp);
13005    c = remove_uri_parameters(c);
13006 
13007    if (!strncasecmp(c, "sip:", 4)) {
13008       name = c + 4;
13009    } else if (!strncasecmp(c, "sips:", 5)) {
13010       name = c + 5;
13011    } else {
13012       name = c;
13013       ast_log(LOG_NOTICE, "Invalid to address: '%s' from %s (missing sip:) trying to use anyway...\n", c, ast_inet_ntoa(sin->sin_addr));
13014    }
13015 
13016    /*! \todo XXX here too we interpret a missing @domain as a name-only
13017     * URI, whereas the RFC says this is a domain-only uri.
13018     */
13019    /* Strip off the domain name */
13020    if ((c = strchr(name, '@'))) {
13021       *c++ = '\0';
13022       domain = c;
13023       if ((c = strchr(domain, ':')))   /* Remove :port */
13024          *c = '\0';
13025       if (!AST_LIST_EMPTY(&domain_list)) {
13026          if (!check_sip_domain(domain, NULL, 0)) {
13027             transmit_response(p, "404 Not found (unknown domain)", &p->initreq);
13028             return AUTH_UNKNOWN_DOMAIN;
13029          }
13030       }
13031    }
13032    c = strchr(name, ';');  /* Remove any Username parameters */
13033    if (c)
13034       *c = '\0';
13035 
13036    ast_string_field_set(p, exten, name);
13037    build_contact(p);
13038    if (req->ignore) {
13039       /* Expires is a special case, where we only want to load the peer if this isn't a deregistration attempt */
13040       const char *expires = get_header(req, "Expires");
13041       int expire = atoi(expires);
13042 
13043       if (ast_strlen_zero(expires)) { /* No expires header; look in Contact */
13044          if ((expires = strcasestr(get_header(req, "Contact"), ";expires="))) {
13045             expire = atoi(expires + 9);
13046          }
13047       }
13048       if (!ast_strlen_zero(expires) && expire == 0) {
13049          transmit_response_with_date(p, "200 OK", req);
13050          return 0;
13051       }
13052    }
13053    peer = find_peer(name, NULL, TRUE, FINDPEERS, FALSE, 0);
13054    if (!(peer && ast_apply_ha(peer->ha, sin))) {
13055       /* Peer fails ACL check */
13056       if (peer) {
13057          unref_peer(peer, "register_verify: unref_peer: from find_peer operation");
13058          peer = NULL;
13059          res = AUTH_ACL_FAILED;
13060       } else
13061          res = AUTH_NOT_FOUND;
13062    }
13063 
13064    if (peer) {
13065       /*! \todo OEJ Remove this - there's never RTP in a REGISTER dialog... */
13066       /* Set Frame packetization */
13067       if (p->rtp) {
13068          ast_rtp_codec_setpref(p->rtp, &peer->prefs);
13069          p->autoframing = peer->autoframing;
13070       }
13071       if (!peer->host_dynamic) {
13072          ast_log(LOG_ERROR, "Peer '%s' is trying to register, but not configured as host=dynamic\n", peer->name);
13073          res = AUTH_PEER_NOT_DYNAMIC;
13074       } else {
13075          ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_NAT);
13076          if (ast_test_flag(&p->flags[1], SIP_PAGE2_REGISTERTRYING))
13077             transmit_response(p, "100 Trying", req);
13078          if (!(res = check_auth(p, req, peer->name, peer->secret, peer->md5secret, SIP_REGISTER, uri, XMIT_UNRELIABLE, req->ignore))) {
13079             if (sip_cancel_destroy(p))
13080                ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
13081 
13082             if (check_request_transport(peer, req)) {
13083                ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
13084                transmit_response_with_date(p, "403 Forbidden", req);
13085                res = AUTH_BAD_TRANSPORT;
13086             } else {
13087 
13088                /* We have a successful registration attempt with proper authentication,
13089                   now, update the peer */
13090                switch (parse_register_contact(p, peer, req)) {
13091                case PARSE_REGISTER_DENIED:
13092                   ast_log(LOG_WARNING, "Registration denied because of contact ACL\n");
13093                   transmit_response_with_date(p, "603 Denied", req);
13094                   peer->lastmsgssent = -1;
13095                   res = 0;
13096                   break;
13097                case PARSE_REGISTER_FAILED:
13098                   ast_log(LOG_WARNING, "Failed to parse contact info\n");
13099                   transmit_response_with_date(p, "400 Bad Request", req);
13100                   peer->lastmsgssent = -1;
13101                   res = 0;
13102                   break;
13103                case PARSE_REGISTER_QUERY:
13104                   ast_string_field_set(p, fullcontact, peer->fullcontact);
13105                   transmit_response_with_date(p, "200 OK", req);
13106                   peer->lastmsgssent = -1;
13107                   res = 0;
13108                   break;
13109                case PARSE_REGISTER_UPDATE:
13110                   ast_string_field_set(p, fullcontact, peer->fullcontact);
13111                   update_peer(peer, p->expiry);
13112                   /* Say OK and ask subsystem to retransmit msg counter */
13113                   transmit_response_with_date(p, "200 OK", req);
13114                   if (!ast_test_flag((&peer->flags[1]), SIP_PAGE2_SUBSCRIBEMWIONLY))
13115                      peer->lastmsgssent = -1;
13116                   res = 0;
13117                   break;
13118                }
13119             }
13120 
13121          } 
13122       }
13123    }
13124    if (!peer && sip_cfg.autocreatepeer) {
13125       /* Create peer if we have autocreate mode enabled */
13126       peer = temp_peer(name);
13127       if (peer) {
13128          ao2_t_link(peers, peer, "link peer into peer table");
13129          if (peer->addr.sin_addr.s_addr) {
13130             ao2_t_link(peers_by_ip, peer, "link peer into peers-by-ip table");
13131          }
13132          
13133          if (sip_cancel_destroy(p))
13134             ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
13135          switch (parse_register_contact(p, peer, req)) {
13136          case PARSE_REGISTER_DENIED:
13137             ast_log(LOG_WARNING, "Registration denied because of contact ACL\n");
13138             transmit_response_with_date(p, "403 Forbidden (ACL)", req);
13139             peer->lastmsgssent = -1;
13140             res = 0;
13141             break;
13142          case PARSE_REGISTER_FAILED:
13143             ast_log(LOG_WARNING, "Failed to parse contact info\n");
13144             transmit_response_with_date(p, "400 Bad Request", req);
13145             peer->lastmsgssent = -1;
13146             res = 0;
13147             break;
13148          case PARSE_REGISTER_QUERY:
13149             ast_string_field_set(p, fullcontact, peer->fullcontact);
13150             transmit_response_with_date(p, "200 OK", req);
13151             peer->lastmsgssent = -1;
13152             res = 0;
13153             break;
13154          case PARSE_REGISTER_UPDATE:
13155             ast_string_field_set(p, fullcontact, peer->fullcontact);
13156             /* Say OK and ask subsystem to retransmit msg counter */
13157             transmit_response_with_date(p, "200 OK", req);
13158             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));
13159             peer->lastmsgssent = -1;
13160             res = 0;
13161             break;
13162          }
13163       }
13164    }
13165    if (!peer && sip_cfg.alwaysauthreject) {
13166       /* If we found a peer, we transmit a 100 Trying.  Therefore, if we're
13167        * trying to avoid leaking information, we MUST also transmit the same
13168        * response when we DON'T find a peer. */
13169       transmit_response(p, "100 Trying", req);
13170       /* Insert a fake delay between the 100 and the subsequent failure. */
13171       sched_yield();
13172    }
13173    if (!res) {
13174       ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", peer->name);
13175    }
13176    if (res < 0) {
13177       switch (res) {
13178       case AUTH_SECRET_FAILED:
13179          /* Wrong password in authentication. Go away, don't try again until you fixed it */
13180          transmit_response(p, "403 Forbidden (Bad auth)", &p->initreq);
13181          if (global_authfailureevents)
13182             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", 
13183                name, ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
13184          break;
13185       case AUTH_USERNAME_MISMATCH:
13186          /* Username and digest username does not match.
13187             Asterisk uses the From: username for authentication. We need the
13188             devices to use the same authentication user name until we support
13189             proper authentication by digest auth name */
13190       case AUTH_NOT_FOUND:
13191       case AUTH_PEER_NOT_DYNAMIC:
13192       case AUTH_ACL_FAILED:
13193          if (sip_cfg.alwaysauthreject) {
13194             transmit_fake_auth_response(p, SIP_REGISTER, &p->initreq, XMIT_UNRELIABLE);
13195             if (global_authfailureevents) {
13196                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",
13197                   name, res == AUTH_PEER_NOT_DYNAMIC ? "AUTH_PEER_NOT_DYNAMIC" : "URI_NOT_FOUND",
13198                   ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
13199             }
13200          } else {
13201             /* URI not found */
13202             if (res == AUTH_PEER_NOT_DYNAMIC) {
13203                transmit_response(p, "403 Forbidden", &p->initreq);
13204                if (global_authfailureevents) {
13205                   manager_event(EVENT_FLAG_SYSTEM, "PeerStatus",
13206                      "ChannelType: SIP\r\n"
13207                      "Peer: SIP/%s\r\n"
13208                      "PeerStatus: Rejected\r\n"
13209                      "Cause: AUTH_PEER_NOT_DYNAMIC\r\n"
13210                      "Address: %s\r\n"
13211                      "Port: %d\r\n",
13212                      name, ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
13213                }
13214             } else {
13215                transmit_response(p, "404 Not found", &p->initreq);
13216                if (global_authfailureevents) {
13217                   manager_event(EVENT_FLAG_SYSTEM, "PeerStatus",
13218                      "ChannelType: SIP\r\n"
13219                      "Peer: SIP/%s\r\n"
13220                      "PeerStatus: Rejected\r\n"
13221                      "Cause: %s\r\n"
13222                      "Address: %s\r\n"
13223                      "Port: %d\r\n",
13224                      name,
13225                      (res == AUTH_USERNAME_MISMATCH) ? "AUTH_USERNAME_MISMATCH" : "URI_NOT_FOUND",
13226                      ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
13227                }
13228             }
13229          }
13230          break;
13231       case AUTH_BAD_TRANSPORT:
13232       default:
13233          break;
13234       }
13235    }
13236    if (peer)
13237       unref_peer(peer, "register_verify: unref_peer: tossing stack peer pointer at end of func");
13238 
13239    return res;
13240 }
13241 
13242 /*! \brief Translate referring cause */
13243 static void sip_set_redirstr(struct sip_pvt *p, char *reason) {
13244 
13245    if (!strcmp(reason, "unknown")) {
13246       ast_string_field_set(p, redircause, "UNKNOWN");
13247    } else if (!strcmp(reason, "user-busy")) {
13248       ast_string_field_set(p, redircause, "BUSY");
13249    } else if (!strcmp(reason, "no-answer")) {
13250       ast_string_field_set(p, redircause, "NOANSWER");
13251    } else if (!strcmp(reason, "unavailable")) {
13252       ast_string_field_set(p, redircause, "UNREACHABLE");
13253    } else if (!strcmp(reason, "unconditional")) {
13254       ast_string_field_set(p, redircause, "UNCONDITIONAL");
13255    } else if (!strcmp(reason, "time-of-day")) {
13256       ast_string_field_set(p, redircause, "UNKNOWN");
13257    } else if (!strcmp(reason, "do-not-disturb")) {
13258       ast_string_field_set(p, redircause, "UNKNOWN");
13259    } else if (!strcmp(reason, "deflection")) {
13260       ast_string_field_set(p, redircause, "UNKNOWN");
13261    } else if (!strcmp(reason, "follow-me")) {
13262       ast_string_field_set(p, redircause, "UNKNOWN");
13263    } else if (!strcmp(reason, "out-of-service")) {
13264       ast_string_field_set(p, redircause, "UNREACHABLE");
13265    } else if (!strcmp(reason, "away")) {
13266       ast_string_field_set(p, redircause, "UNREACHABLE");
13267    } else {
13268       ast_string_field_set(p, redircause, "UNKNOWN");
13269    }
13270 }
13271 
13272 /*! \brief Get referring dnis */
13273 static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq)
13274 {
13275    char tmp[256], *exten, *rexten, *rdomain;
13276    char *params, *reason = NULL;
13277    struct sip_request *req;
13278    
13279    req = oreq ? oreq : &p->initreq;
13280 
13281    ast_copy_string(tmp, get_header(req, "Diversion"), sizeof(tmp));
13282    if (ast_strlen_zero(tmp))
13283       return 0;
13284 
13285    /*! \todo This function does not take user-parameters into consideration.
13286       First look for @, then start looking for ; to find uri-parameters.
13287    */
13288    params = strchr(tmp, ';');
13289 
13290    exten = get_in_brackets(tmp);
13291    if (!strncasecmp(exten, "sip:", 4)) {
13292       exten += 4;
13293    } else if (!strncasecmp(exten, "sips:", 5)) {
13294       exten += 5;
13295    } else {
13296       ast_log(LOG_WARNING, "Huh?  Not an RDNIS SIP header (%s)?\n", exten);
13297       return -1;
13298    }
13299 
13300    /* Get diversion-reason param if present */
13301    if (params) {
13302       *params = '\0';   /* Cut off parameters  */
13303       params++;
13304       while (*params == ';' || *params == ' ')
13305          params++;
13306       /* Check if we have a reason parameter */
13307       if ((reason = strcasestr(params, "reason="))) {
13308          reason+=7;
13309          /* Remove enclosing double-quotes */
13310          if (*reason == '"') 
13311             ast_strip_quoted(reason, "\"", "\"");
13312          if (!ast_strlen_zero(reason)) {
13313             sip_set_redirstr(p, reason);
13314             if (p->owner) {
13315                pbx_builtin_setvar_helper(p->owner, "__PRIREDIRECTREASON", p->redircause);
13316                pbx_builtin_setvar_helper(p->owner, "__SIPREDIRECTREASON", reason);
13317             }
13318          }
13319       }
13320    }
13321 
13322    rdomain = exten;
13323    rexten = strsep(&rdomain, "@");  /* trim anything after @ */
13324    if (p->owner) 
13325       pbx_builtin_setvar_helper(p->owner, "__SIPRDNISDOMAIN", rdomain);
13326 
13327    if (sip_debug_test_pvt(p))
13328       ast_verbose("RDNIS for this call is is %s (reason %s)\n", exten, reason ? reason : "");
13329 
13330    ast_string_field_set(p, rdnis, rexten);
13331 
13332    return 0;
13333 }
13334 
13335 /*! \brief Find out who the call is for.
13336    We use the request uri as a destination. 
13337    This code assumes authentication has been done, so that the
13338    device (peer/user) context is already set.
13339    \return 0 on success (found a matching extension),
13340    1 for pickup extension or overlap dialling support (if we support it),
13341    -1 on error.
13342 
13343   \note If the incoming uri is a SIPS: uri, we are required to carry this across
13344    the dialplan, so that the outbound call also is a sips: call or encrypted
13345    IAX2 call. If that's not available, the call should FAIL.
13346 */
13347 static int get_destination(struct sip_pvt *p, struct sip_request *oreq)
13348 {
13349    char tmp[256] = "", *uri, *a;
13350    char tmpf[256] = "", *from = NULL;
13351    struct sip_request *req;
13352    char *colon;
13353    char *decoded_uri;
13354    
13355    req = oreq;
13356    if (!req)
13357       req = &p->initreq;
13358 
13359    /* Find the request URI */
13360    if (req->rlPart2)
13361       ast_copy_string(tmp, REQ_OFFSET_TO_STR(req, rlPart2), sizeof(tmp));
13362    
13363    if (sip_cfg.pedanticsipchecking)
13364       ast_uri_decode(tmp);
13365 
13366    uri = get_in_brackets(tmp);
13367    
13368    if (!strncasecmp(uri, "sip:", 4)) {
13369       uri += 4;
13370    } else if (!strncasecmp(uri, "sips:", 5)) {
13371       uri += 5;
13372    } else {
13373       ast_log(LOG_WARNING, "Huh?  Not a SIP header (%s)?\n", uri);
13374       return -1;
13375    }
13376 
13377    /* Now find the From: caller ID and name */
13378    /* XXX Why is this done in get_destination? Isn't it already done?
13379       Needs to be checked 
13380         */
13381    ast_copy_string(tmpf, get_header(req, "From"), sizeof(tmpf));
13382    if (!ast_strlen_zero(tmpf)) {
13383       if (sip_cfg.pedanticsipchecking)
13384          ast_uri_decode(tmpf);
13385       from = get_in_brackets(tmpf);
13386    } 
13387    
13388    if (!ast_strlen_zero(from)) {
13389       if (!strncasecmp(from, "sip:", 4)) {
13390          from += 4;
13391       } else if (!strncasecmp(from, "sips:", 5)) {
13392          from += 5;
13393       } else {
13394          ast_log(LOG_WARNING, "Huh?  Not a SIP header (%s)?\n", from);
13395          return -1;
13396       }
13397       if ((a = strchr(from, '@')))
13398          *a++ = '\0';
13399       else
13400          a = from;   /* just a domain */
13401       from = strsep(&from, ";"); /* Remove userinfo options */
13402       a = strsep(&a, ";");    /* Remove URI options */
13403       ast_string_field_set(p, fromdomain, a);
13404    }
13405 
13406    /* Skip any options and find the domain */
13407 
13408    /* Get the target domain */
13409    if ((a = strchr(uri, '@'))) {
13410       *a++ = '\0';
13411    } else { /* No username part */
13412       a = uri;
13413       uri = "s";  /* Set extension to "s" */
13414    }
13415    colon = strchr(a, ':'); /* Remove :port */
13416    if (colon)
13417       *colon = '\0';
13418 
13419    uri = strsep(&uri, ";");   /* Remove userinfo options */
13420    a = strsep(&a, ";");    /* Remove URI options */
13421 
13422    ast_string_field_set(p, domain, a);
13423 
13424    if (!AST_LIST_EMPTY(&domain_list)) {
13425       char domain_context[AST_MAX_EXTENSION];
13426 
13427       domain_context[0] = '\0';
13428       if (!check_sip_domain(p->domain, domain_context, sizeof(domain_context))) {
13429          if (!sip_cfg.allow_external_domains && (req->method == SIP_INVITE || req->method == SIP_REFER)) {
13430             ast_debug(1, "Got SIP %s to non-local domain '%s'; refusing request.\n", sip_methods[req->method].text, p->domain);
13431             return -2;
13432          }
13433       }
13434       /* If we don't have a peer (i.e. we're a guest call),
13435        * overwrite the original context */
13436       if (!ast_test_flag(&p->flags[1], SIP_PAGE2_HAVEPEERCONTEXT) && !ast_strlen_zero(domain_context))
13437          ast_string_field_set(p, context, domain_context);
13438    }
13439 
13440    /* If the request coming in is a subscription and subscribecontext has been specified use it */
13441    if (req->method == SIP_SUBSCRIBE && !ast_strlen_zero(p->subscribecontext))
13442       ast_string_field_set(p, context, p->subscribecontext);
13443 
13444    if (sip_debug_test_pvt(p))
13445       ast_verbose("Looking for %s in %s (domain %s)\n", uri, p->context, p->domain);
13446 
13447    /* If this is a subscription we actually just need to see if a hint exists for the extension */
13448    if (req->method == SIP_SUBSCRIBE) {
13449       char hint[AST_MAX_EXTENSION];
13450       return (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, p->context, p->exten) ? 0 : -1);
13451    } else {
13452       decoded_uri = ast_strdupa(uri);
13453       ast_uri_decode(decoded_uri);
13454       /* Check the dialplan for the username part of the request URI,
13455          the domain will be stored in the SIPDOMAIN variable
13456          Since extensions.conf can have unescaped characters, try matching a decoded
13457          uri in addition to the non-decoded uri
13458          Return 0 if we have a matching extension */
13459       if (ast_exists_extension(NULL, p->context, uri, 1, S_OR(p->cid_num, from)) || ast_exists_extension(NULL, p->context, decoded_uri, 1, S_OR(p->cid_num, from)) ||
13460           !strcmp(decoded_uri, ast_pickup_ext())) {
13461          if (!oreq)
13462             ast_string_field_set(p, exten, decoded_uri);
13463          return 0;
13464       } 
13465    }
13466 
13467    /* Return 1 for pickup extension or overlap dialling support (if we support it) */
13468    if((ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP) && 
13469        ast_canmatch_extension(NULL, p->context, decoded_uri, 1, S_OR(p->cid_num, from))) ||
13470        !strncmp(decoded_uri, ast_pickup_ext(), strlen(decoded_uri))) {
13471       return 1;
13472    }
13473    
13474    return -1;
13475 }
13476 
13477 /*! \brief Lock dialog lock and find matching pvt lock  
13478    \return a reference, remember to release it when done 
13479 */
13480 static struct sip_pvt *get_sip_pvt_byid_locked(const char *callid, const char *totag, const char *fromtag) 
13481 {
13482    struct sip_pvt *sip_pvt_ptr;
13483    struct sip_pvt tmp_dialog = {
13484       .callid = callid,
13485    };
13486 
13487    if (totag)
13488       ast_debug(4, "Looking for callid %s (fromtag %s totag %s)\n", callid, fromtag ? fromtag : "<no fromtag>", totag ? totag : "<no totag>");
13489 
13490    /* Search dialogs and find the match */
13491    
13492    sip_pvt_ptr = ao2_t_find(dialogs, &tmp_dialog, OBJ_POINTER, "ao2_find of dialog in dialogs table");
13493    if (sip_pvt_ptr) {
13494       /* Go ahead and lock it (and its owner) before returning */
13495       sip_pvt_lock(sip_pvt_ptr);
13496       if (sip_cfg.pedanticsipchecking) {
13497          unsigned char frommismatch = 0, tomismatch = 0;
13498 
13499          if (ast_strlen_zero(fromtag)) {
13500             sip_pvt_unlock(sip_pvt_ptr);
13501             ast_debug(4, "Matched %s call for callid=%s - no from tag specified, pedantic check fails\n",
13502                  sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid);
13503             return NULL;
13504          }
13505 
13506          if (ast_strlen_zero(totag)) {
13507             sip_pvt_unlock(sip_pvt_ptr);
13508             ast_debug(4, "Matched %s call for callid=%s - no to tag specified, pedantic check fails\n",
13509                  sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid);
13510             return NULL;
13511          }
13512          /* RFC 3891
13513           * > 3.  User Agent Server Behavior: Receiving a Replaces Header
13514           * > The Replaces header contains information used to match an existing
13515           * > SIP dialog (call-id, to-tag, and from-tag).  Upon receiving an INVITE
13516           * > with a Replaces header, the User Agent (UA) attempts to match this
13517           * > information with a confirmed or early dialog.  The User Agent Server
13518           * > (UAS) matches the to-tag and from-tag parameters as if they were tags
13519           * > present in an incoming request.  In other words, the to-tag parameter
13520           * > is compared to the local tag, and the from-tag parameter is compared
13521           * > to the remote tag.
13522           *
13523           * Thus, the totag is always compared to the local tag, regardless if
13524           * this our call is an incoming or outgoing call.
13525           */
13526          frommismatch = !!strcmp(fromtag, sip_pvt_ptr->theirtag);
13527          tomismatch = !!strcmp(totag, sip_pvt_ptr->tag);
13528 
13529          if (frommismatch || tomismatch) {
13530             sip_pvt_unlock(sip_pvt_ptr);
13531             if (frommismatch) {
13532                ast_debug(4, "Matched %s call for callid=%s - pedantic from tag check fails; their tag is %s our tag is %s\n",
13533                     sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid, 
13534                     fromtag, sip_pvt_ptr->theirtag);
13535             }
13536             if (tomismatch) {
13537                ast_debug(4, "Matched %s call for callid=%s - pedantic to tag check fails; their tag is %s our tag is %s\n",
13538                     sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid, 
13539                     totag, sip_pvt_ptr->tag);
13540             }
13541             return NULL;
13542          }
13543       }
13544       
13545       if (totag)
13546          ast_debug(4, "Matched %s call - their tag is %s Our tag is %s\n",
13547                  sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING",
13548                  sip_pvt_ptr->theirtag, sip_pvt_ptr->tag);
13549 
13550       /* deadlock avoidance... */
13551       while (sip_pvt_ptr->owner && ast_channel_trylock(sip_pvt_ptr->owner)) {
13552          sip_pvt_unlock(sip_pvt_ptr);
13553          usleep(1);
13554          sip_pvt_lock(sip_pvt_ptr);
13555       }
13556    }
13557    
13558    return sip_pvt_ptr;
13559 }
13560 
13561 /*! \brief Call transfer support (the REFER method) 
13562  *    Extracts Refer headers into pvt dialog structure 
13563  *
13564  * \note If we get a SIPS uri in the refer-to header, we're required to set up a secure signalling path
13565  * to that extension. As a minimum, this needs to be added to a channel variable, if not a channel
13566  * flag.
13567  */
13568 static int get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req)
13569 {
13570 
13571    const char *p_referred_by = NULL;
13572    char *h_refer_to = NULL; 
13573    char *h_referred_by = NULL;
13574    char *refer_to;
13575    const char *p_refer_to;
13576    char *referred_by_uri = NULL;
13577    char *ptr;
13578    struct sip_request *req = NULL;
13579    const char *transfer_context = NULL;
13580    struct sip_refer *referdata;
13581 
13582 
13583    req = outgoing_req;
13584    referdata = transferer->refer;
13585 
13586    if (!req)
13587       req = &transferer->initreq;
13588 
13589    p_refer_to = get_header(req, "Refer-To");
13590    if (ast_strlen_zero(p_refer_to)) {
13591       ast_log(LOG_WARNING, "Refer-To Header missing. Skipping transfer.\n");
13592       return -2;  /* Syntax error */
13593    }
13594    h_refer_to = ast_strdupa(p_refer_to);
13595    refer_to = get_in_brackets(h_refer_to);
13596    if (sip_cfg.pedanticsipchecking)
13597       ast_uri_decode(refer_to);
13598 
13599    if (!strncasecmp(refer_to, "sip:", 4)) {
13600       refer_to += 4;       /* Skip sip: */
13601    } else if (!strncasecmp(refer_to, "sips:", 5)) {
13602       refer_to += 5;
13603    } else {
13604       ast_log(LOG_WARNING, "Can't transfer to non-sip: URI.  (Refer-to: %s)?\n", refer_to);
13605       return -3;
13606    }
13607 
13608    /* Get referred by header if it exists */
13609    p_referred_by = get_header(req, "Referred-By");
13610 
13611    /* Give useful transfer information to the dialplan */
13612    if (transferer->owner) {
13613       struct ast_channel *peer = ast_bridged_channel(transferer->owner);
13614       if (peer) {
13615          pbx_builtin_setvar_helper(peer, "SIPREFERRINGCONTEXT", transferer->context);
13616          pbx_builtin_setvar_helper(peer, "SIPREFERREDBYHDR", p_referred_by);
13617       }
13618    }
13619 
13620    if (!ast_strlen_zero(p_referred_by)) {
13621       char *lessthan;
13622       h_referred_by = ast_strdupa(p_referred_by);
13623       if (sip_cfg.pedanticsipchecking)
13624          ast_uri_decode(h_referred_by);
13625 
13626       /* Store referrer's caller ID name */
13627       ast_copy_string(referdata->referred_by_name, h_referred_by, sizeof(referdata->referred_by_name));
13628       if ((lessthan = strchr(referdata->referred_by_name, '<'))) {
13629          *(lessthan - 1) = '\0'; /* Space */
13630       }
13631 
13632       referred_by_uri = get_in_brackets(h_referred_by);
13633       if (!strncasecmp(referred_by_uri, "sip:", 4)) {
13634          referred_by_uri += 4;      /* Skip sip: */
13635       } else if (!strncasecmp(referred_by_uri, "sips:", 5)) {
13636          referred_by_uri += 5;      /* Skip sips: */
13637       } else {
13638          ast_log(LOG_WARNING, "Huh?  Not a sip: header (Referred-by: %s). Skipping.\n", referred_by_uri);
13639          referred_by_uri = NULL;
13640       }
13641    }
13642 
13643    /* Check for arguments in the refer_to header */
13644    if ((ptr = strcasestr(refer_to, "replaces="))) {
13645       char *to = NULL, *from = NULL;
13646       
13647       /* This is an attended transfer */
13648       referdata->attendedtransfer = 1;
13649       ast_copy_string(referdata->replaces_callid, ptr+9, sizeof(referdata->replaces_callid));
13650       ast_uri_decode(referdata->replaces_callid);
13651       if ((ptr = strchr(referdata->replaces_callid, ';')))  /* Find options */ {
13652          *ptr++ = '\0';
13653       }
13654       
13655       if (ptr) {
13656          /* Find the different tags before we destroy the string */
13657          to = strcasestr(ptr, "to-tag=");
13658          from = strcasestr(ptr, "from-tag=");
13659       }
13660       
13661       /* Grab the to header */
13662       if (to) {
13663          ptr = to + 7;
13664          if ((to = strchr(ptr, '&')))
13665             *to = '\0';
13666          if ((to = strchr(ptr, ';')))
13667             *to = '\0';
13668          ast_copy_string(referdata->replaces_callid_totag, ptr, sizeof(referdata->replaces_callid_totag));
13669       }
13670       
13671       if (from) {
13672          ptr = from + 9;
13673          if ((to = strchr(ptr, '&')))
13674             *to = '\0';
13675          if ((to = strchr(ptr, ';')))
13676             *to = '\0';
13677          ast_copy_string(referdata->replaces_callid_fromtag, ptr, sizeof(referdata->replaces_callid_fromtag));
13678       }
13679       
13680       if (!sip_cfg.pedanticsipchecking)
13681          ast_debug(2, "Attended transfer: Will use Replace-Call-ID : %s (No check of from/to tags)\n", referdata->replaces_callid );
13682       else
13683          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>" );
13684    }
13685    
13686    if ((ptr = strchr(refer_to, '@'))) {   /* Separate domain */
13687       char *urioption = NULL, *domain;
13688       *ptr++ = '\0';
13689 
13690       if ((urioption = strchr(ptr, ';'))) /* Separate urioptions */
13691          *urioption++ = '\0';
13692       
13693       domain = ptr;
13694       if ((ptr = strchr(domain, ':'))) /* Remove :port */
13695          *ptr = '\0';
13696       
13697       /* Save the domain for the dial plan */
13698       ast_copy_string(referdata->refer_to_domain, domain, sizeof(referdata->refer_to_domain));
13699       if (urioption)
13700          ast_copy_string(referdata->refer_to_urioption, urioption, sizeof(referdata->refer_to_urioption));
13701    }
13702 
13703    if ((ptr = strchr(refer_to, ';')))  /* Remove options */
13704       *ptr = '\0';
13705    ast_copy_string(referdata->refer_to, refer_to, sizeof(referdata->refer_to));
13706    
13707    if (referred_by_uri) {
13708       if ((ptr = strchr(referred_by_uri, ';')))    /* Remove options */
13709          *ptr = '\0';
13710       ast_copy_string(referdata->referred_by, referred_by_uri, sizeof(referdata->referred_by));
13711    } else {
13712       referdata->referred_by[0] = '\0';
13713    }
13714 
13715    /* Determine transfer context */
13716    if (transferer->owner)  /* Mimic behaviour in res_features.c */
13717       transfer_context = pbx_builtin_getvar_helper(transferer->owner, "TRANSFER_CONTEXT");
13718 
13719    /* By default, use the context in the channel sending the REFER */
13720    if (ast_strlen_zero(transfer_context)) {
13721       transfer_context = S_OR(transferer->owner->macrocontext,
13722                S_OR(transferer->context, sip_cfg.default_context));
13723    }
13724 
13725    ast_copy_string(referdata->refer_to_context, transfer_context, sizeof(referdata->refer_to_context));
13726    
13727    /* Either an existing extension or the parking extension */
13728    if (referdata->attendedtransfer || ast_exists_extension(NULL, transfer_context, refer_to, 1, NULL) ) {
13729       if (sip_debug_test_pvt(transferer)) {
13730          ast_verbose("SIP transfer to extension %s@%s by %s\n", refer_to, transfer_context, referred_by_uri);
13731       }
13732       /* We are ready to transfer to the extension */
13733       return 0;
13734    } 
13735    if (sip_debug_test_pvt(transferer))
13736       ast_verbose("Failed SIP Transfer to non-existing extension %s in context %s\n n", refer_to, transfer_context);
13737 
13738    /* Failure, we can't find this extension */
13739    return -1;
13740 }
13741 
13742 
13743 /*! \brief Call transfer support (old way, deprecated by the IETF)
13744  * \note does not account for SIPS: uri requirements, nor check transport
13745  */
13746 static int get_also_info(struct sip_pvt *p, struct sip_request *oreq)
13747 {
13748    char tmp[256] = "", *c, *a;
13749    struct sip_request *req = oreq ? oreq : &p->initreq;
13750    struct sip_refer *referdata = NULL;
13751    const char *transfer_context = NULL;
13752    
13753    if (!p->refer && !sip_refer_allocate(p))
13754       return -1;
13755 
13756    referdata = p->refer;
13757 
13758    ast_copy_string(tmp, get_header(req, "Also"), sizeof(tmp));
13759    c = get_in_brackets(tmp);
13760 
13761    if (sip_cfg.pedanticsipchecking)
13762       ast_uri_decode(c);
13763 
13764    if (!strncasecmp(c, "sip:", 4)) {
13765       c += 4;
13766    } else if (!strncasecmp(c, "sips:", 5)) {
13767       c += 5;
13768    } else {
13769       ast_log(LOG_WARNING, "Huh?  Not a SIP header in Also: transfer (%s)?\n", c);
13770       return -1;
13771    }
13772 
13773    if ((a = strchr(c, ';')))  /* Remove arguments */
13774       *a = '\0';
13775    
13776    if ((a = strchr(c, '@'))) {   /* Separate Domain */
13777       *a++ = '\0';
13778       ast_copy_string(referdata->refer_to_domain, a, sizeof(referdata->refer_to_domain));
13779    }
13780    
13781    if (sip_debug_test_pvt(p))
13782       ast_verbose("Looking for %s in %s\n", c, p->context);
13783 
13784    if (p->owner)  /* Mimic behaviour in res_features.c */
13785       transfer_context = pbx_builtin_getvar_helper(p->owner, "TRANSFER_CONTEXT");
13786 
13787    /* By default, use the context in the channel sending the REFER */
13788    if (ast_strlen_zero(transfer_context)) {
13789       transfer_context = S_OR(p->owner->macrocontext,
13790                S_OR(p->context, sip_cfg.default_context));
13791    }
13792    if (ast_exists_extension(NULL, transfer_context, c, 1, NULL)) {
13793       /* This is a blind transfer */
13794       ast_debug(1, "SIP Bye-also transfer to Extension %s@%s \n", c, transfer_context);
13795       ast_copy_string(referdata->refer_to, c, sizeof(referdata->refer_to));
13796       ast_copy_string(referdata->referred_by, "", sizeof(referdata->referred_by));
13797       ast_copy_string(referdata->refer_contact, "", sizeof(referdata->refer_contact));
13798       referdata->refer_call = dialog_unref(referdata->refer_call, "unreffing referdata->refer_call");
13799       /* Set new context */
13800       ast_string_field_set(p, context, transfer_context);
13801       return 0;
13802    } else if (ast_canmatch_extension(NULL, p->context, c, 1, NULL)) {
13803       return 1;
13804    }
13805 
13806    return -1;
13807 }
13808 
13809 /*! \brief check received= and rport= in a SIP response.
13810  * If we get a response with received= and/or rport= in the Via:
13811  * line, use them as 'p->ourip' (see RFC 3581 for rport,
13812  * and RFC 3261 for received).
13813  * Using these two fields SIP can produce the correct
13814  * address and port in the SIP headers without the need for STUN.
13815  * The address part is also reused for the media sessions.
13816  * Note that ast_sip_ouraddrfor() still rewrites p->ourip
13817  * if you specify externip/seternaddr/stunaddr.
13818  */
13819 static attribute_unused void check_via_response(struct sip_pvt *p, struct sip_request *req)
13820 {
13821    char via[256];
13822    char *cur, *opts;
13823 
13824    ast_copy_string(via, get_header(req, "Via"), sizeof(via));
13825 
13826    /* Work on the leftmost value of the topmost Via header */
13827    opts = strchr(via, ',');
13828    if (opts)
13829       *opts = '\0';
13830 
13831    /* parse all relevant options */
13832    opts = strchr(via, ';');
13833    if (!opts)
13834       return;  /* no options to parse */
13835    *opts++ = '\0';
13836    while ( (cur = strsep(&opts, ";")) ) {
13837       if (!strncmp(cur, "rport=", 6)) {
13838          int port = strtol(cur+6, NULL, 10);
13839          /* XXX add error checking */
13840          p->ourip.sin_port = ntohs(port);
13841       } else if (!strncmp(cur, "received=", 9)) {
13842          if (ast_parse_arg(cur+9, PARSE_INADDR, &p->ourip))
13843             ;  /* XXX add error checking */
13844       }
13845    }
13846 }
13847 
13848 /*! \brief check Via: header for hostname, port and rport request/answer */
13849 static void check_via(struct sip_pvt *p, struct sip_request *req)
13850 {
13851    char via[512];
13852    char *c, *pt, *maddr;
13853    struct hostent *hp;
13854    struct ast_hostent ahp;
13855 
13856    ast_copy_string(via, get_header(req, "Via"), sizeof(via));
13857 
13858    /* Work on the leftmost value of the topmost Via header */
13859    c = strchr(via, ',');
13860    if (c)
13861       *c = '\0';
13862 
13863    /* Check for rport */
13864    c = strstr(via, ";rport");
13865    if (c && (c[6] != '=')) /* rport query, not answer */
13866       ast_set_flag(&p->flags[1], SIP_PAGE2_RPORT_PRESENT);
13867 
13868    /* Check for maddr */
13869    maddr = strstr(via, "maddr=");
13870    if (maddr) {
13871       maddr += 6;
13872       c = maddr + strspn(maddr, "0123456789.");
13873       *c = '\0';
13874    }
13875 
13876    c = strchr(via, ';');
13877    if (c)
13878       *c = '\0';
13879 
13880    c = strchr(via, ' ');
13881    if (c) {
13882       *c = '\0';
13883       c = ast_skip_blanks(c+1);
13884       if (strcasecmp(via, "SIP/2.0/UDP") && strcasecmp(via, "SIP/2.0/TCP") && strcasecmp(via, "SIP/2.0/TLS")) {
13885          ast_log(LOG_WARNING, "Don't know how to respond via '%s'\n", via);
13886          return;
13887       }
13888       pt = strchr(c, ':');
13889       if (pt)
13890          *pt++ = '\0';  /* remember port pointer */
13891       /* Use maddr if found */
13892       if (maddr)
13893          c = maddr;
13894       hp = ast_gethostbyname(c, &ahp);
13895       if (!hp) {
13896          ast_log(LOG_WARNING, "'%s' is not a valid host\n", c);
13897          return;
13898       }
13899       memset(&p->sa, 0, sizeof(p->sa));
13900       p->sa.sin_family = AF_INET;
13901       memcpy(&p->sa.sin_addr, hp->h_addr, sizeof(p->sa.sin_addr));
13902       p->sa.sin_port = htons(port_str2int(pt, STANDARD_SIP_PORT));
13903 
13904       if (sip_debug_test_pvt(p)) {
13905          const struct sockaddr_in *dst = sip_real_dst(p);
13906          ast_verbose("Sending to %s : %d (%s)\n", ast_inet_ntoa(dst->sin_addr), ntohs(dst->sin_port), sip_nat_mode(p));
13907       }
13908    }
13909 }
13910 
13911 /*! \brief  Get caller id name from SIP headers */
13912 static char *get_calleridname(const char *input, char *output, size_t outputsize)
13913 {
13914    const char *end = strchr(input, '<');  /* first_bracket */
13915    const char *tmp = strchr(input, '"');  /* first quote */
13916    int bytes = 0;
13917    int maxbytes = outputsize - 1;
13918 
13919    if (!end || end == input)  /* we require a part in brackets */
13920       return NULL;
13921 
13922    end--; /* move just before "<" */
13923 
13924    if (tmp && tmp <= end) {
13925       /* The quote (tmp) precedes the bracket (end+1).
13926        * Find the matching quote and return the content.
13927        */
13928       end = strchr(tmp+1, '"');
13929       if (!end)
13930          return NULL;
13931       bytes = (int) (end - tmp);
13932       /* protect the output buffer */
13933       if (bytes > maxbytes)
13934          bytes = maxbytes;
13935       ast_copy_string(output, tmp + 1, bytes);
13936    } else {
13937       /* No quoted string, or it is inside brackets. */
13938       /* clear the empty characters in the begining*/
13939       input = ast_skip_blanks(input);
13940       /* clear the empty characters in the end */
13941       while(*end && *end < 33 && end > input)
13942          end--;
13943       if (end >= input) {
13944          bytes = (int) (end - input) + 2;
13945          /* protect the output buffer */
13946          if (bytes > maxbytes)
13947             bytes = maxbytes;
13948          ast_copy_string(output, input, bytes);
13949       } else
13950          return NULL;
13951    }
13952    return output;
13953 }
13954 
13955 /*! \brief  Get caller id number from Remote-Party-ID header field 
13956  * Returns true if number should be restricted (privacy setting found)
13957  * output is set to NULL if no number found
13958  */
13959 static int get_rpid_num(const char *input, char *output, int maxlen)
13960 {
13961    char *start;
13962    char *end;
13963 
13964    start = strchr(input, ':');
13965    if (!start) {
13966       output[0] = '\0';
13967       return 0;
13968    }
13969    start++;
13970 
13971    /* we found "number" */
13972    ast_copy_string(output, start, maxlen);
13973    output[maxlen-1] = '\0';
13974 
13975    end = strchr(output, '@');
13976    if (end)
13977       *end = '\0';
13978    else
13979       output[0] = '\0';
13980    if (strstr(input, "privacy=full") || strstr(input, "privacy=uri"))
13981       return AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED;
13982 
13983    return 0;
13984 }
13985 
13986 
13987 /*! \brief helper function for check_{user|peer}_ok() */
13988 static void replace_cid(struct sip_pvt *p, const char *rpid_num, const char *calleridname)
13989 {
13990    /* replace callerid if rpid found, and not restricted */
13991    if (!ast_strlen_zero(rpid_num) && ast_test_flag(&p->flags[0], SIP_TRUSTRPID)) {
13992       char *tmp = ast_strdupa(rpid_num); /* XXX the copy can be done later */
13993       if (!ast_strlen_zero(calleridname))
13994          ast_string_field_set(p, cid_name, calleridname);
13995       if (global_shrinkcallerid && ast_is_shrinkable_phonenumber(tmp))
13996          ast_shrink_phone_number(tmp);
13997       ast_string_field_set(p, cid_num, tmp);
13998    }
13999 }
14000 
14001 /*! \brief Validate device authentication */
14002 static enum check_auth_result check_peer_ok(struct sip_pvt *p, char *of,
14003    struct sip_request *req, int sipmethod, struct sockaddr_in *sin,
14004    struct sip_peer **authpeer,
14005    enum xmittype reliable,
14006    char *rpid_num, char *calleridname, char *uri2)
14007 {
14008    enum check_auth_result res;
14009    int debug=sip_debug_test_addr(sin);
14010    struct sip_peer *peer;
14011 
14012    if (sipmethod == SIP_SUBSCRIBE) {
14013       /* For subscribes, match on device name only; for other methods,
14014       * match on IP address-port of the incoming request.
14015       */
14016       peer = find_peer(of, NULL, TRUE, FINDALLDEVICES, FALSE, 0);
14017    } else {
14018       /* First find devices based on username (avoid all type=peer's) */
14019       peer = find_peer(of, NULL, TRUE, FINDUSERS, FALSE, 0);
14020 
14021       /* Then find devices based on IP */
14022       if (!peer) {
14023          peer = find_peer(NULL, &p->recv, TRUE, FINDPEERS, FALSE, p->socket.type);
14024       }
14025    }
14026 
14027    if (!peer) {
14028       if (debug)
14029          ast_verbose("No matching peer for '%s' from '%s:%d'\n",
14030             of, ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
14031       return AUTH_DONT_KNOW;
14032    }
14033    if (!ast_apply_ha(peer->ha, sin)) {
14034       ast_debug(2, "Found peer '%s' for '%s', but fails host access\n", peer->name, of);
14035       unref_peer(peer, "unref_peer: check_peer_ok: from find_peer call, early return of AUTH_ACL_FAILED");
14036       return AUTH_ACL_FAILED;
14037    }
14038    if (debug)
14039       ast_verbose("Found peer '%s' for '%s' from %s:%d\n",
14040          peer->name, of, ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
14041 
14042    /* XXX what about p->prefs = peer->prefs; ? */
14043    /* Set Frame packetization */
14044    if (p->rtp) {
14045       ast_rtp_codec_setpref(p->rtp, &peer->prefs);
14046       p->autoframing = peer->autoframing;
14047    }
14048 
14049    /* Take the peer */
14050    ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
14051    ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
14052 
14053    if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) && p->udptl) {
14054       p->t38_maxdatagram = peer->t38_maxdatagram;
14055       set_t38_capabilities(p);
14056    }
14057 
14058    /* Copy SIP extensions profile to peer */
14059    /* XXX is this correct before a successful auth ? */
14060    if (p->sipoptions)
14061       peer->sipoptions = p->sipoptions;
14062 
14063    replace_cid(p, rpid_num, calleridname);
14064    do_setnat(p, ast_test_flag(&p->flags[0], SIP_NAT_ROUTE));
14065 
14066    ast_string_field_set(p, peersecret, peer->secret);
14067    ast_string_field_set(p, peermd5secret, peer->md5secret);
14068    ast_string_field_set(p, subscribecontext, peer->subscribecontext);
14069    ast_string_field_set(p, mohinterpret, peer->mohinterpret);
14070    ast_string_field_set(p, mohsuggest, peer->mohsuggest);
14071    ast_string_field_set(p, parkinglot, peer->parkinglot);
14072    if (peer->callingpres)  /* Peer calling pres setting will override RPID */
14073       p->callingpres = peer->callingpres;
14074    if (peer->maxms && peer->lastms)
14075       p->timer_t1 = peer->lastms < global_t1min ? global_t1min : peer->lastms;
14076    else
14077       p->timer_t1 = peer->timer_t1;
14078  
14079    /* Set timer B to control transaction timeouts */
14080    if (peer->timer_b)
14081       p->timer_b = peer->timer_b;
14082    else
14083       p->timer_b = 64 * p->timer_t1;
14084  
14085    if (ast_test_flag(&peer->flags[0], SIP_INSECURE_INVITE)) {
14086       /* Pretend there is no required authentication */
14087       ast_string_field_set(p, peersecret, NULL);
14088       ast_string_field_set(p, peermd5secret, NULL);
14089    }
14090    if (!(res = check_auth(p, req, peer->name, p->peersecret, p->peermd5secret, sipmethod, uri2, reliable, req->ignore))) {
14091       ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
14092       ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
14093       /* If we have a call limit, set flag */
14094       if (peer->call_limit)
14095          ast_set_flag(&p->flags[0], SIP_CALL_LIMIT);
14096       ast_string_field_set(p, peername, peer->name);
14097       ast_string_field_set(p, authname, peer->name);
14098 
14099       if (sipmethod == SIP_INVITE) {
14100          /* copy channel vars */
14101          p->chanvars = copy_vars(peer->chanvars);
14102       }
14103 
14104       if (authpeer) {
14105          ao2_t_ref(peer, 1, "copy pointer into (*authpeer)");
14106          (*authpeer) = peer;  /* Add a ref to the object here, to keep it in memory a bit longer if it is realtime */
14107       }
14108 
14109       if (!ast_strlen_zero(peer->username)) {
14110          ast_string_field_set(p, username, peer->username);
14111          /* Use the default username for authentication on outbound calls */
14112          /* XXX this takes the name from the caller... can we override ? */
14113          ast_string_field_set(p, authname, peer->username);
14114       }
14115       if (!ast_strlen_zero(peer->cid_num)) {
14116          char *tmp = ast_strdupa(peer->cid_num);
14117          if (global_shrinkcallerid && ast_is_shrinkable_phonenumber(tmp))
14118             ast_shrink_phone_number(tmp);
14119          ast_string_field_set(p, cid_num, tmp);
14120       }
14121       if (!ast_strlen_zero(peer->cid_name)) 
14122          ast_string_field_set(p, cid_name, peer->cid_name);
14123       ast_string_field_set(p, fullcontact, peer->fullcontact);
14124       if (!ast_strlen_zero(peer->context))
14125          ast_string_field_set(p, context, peer->context);
14126       ast_string_field_set(p, peersecret, peer->secret);
14127       ast_string_field_set(p, peermd5secret, peer->md5secret);
14128       ast_string_field_set(p, language, peer->language);
14129       ast_string_field_set(p, accountcode, peer->accountcode);
14130       p->amaflags = peer->amaflags;
14131       p->callgroup = peer->callgroup;
14132       p->pickupgroup = peer->pickupgroup;
14133       p->capability = peer->capability;
14134       p->prefs = peer->prefs;
14135       p->jointcapability = peer->capability;
14136       if (p->peercapability)
14137          p->jointcapability &= p->peercapability;
14138       p->maxcallbitrate = peer->maxcallbitrate;
14139       if (!ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS) &&
14140             (!ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT) ||
14141                !(p->capability & AST_FORMAT_VIDEO_MASK)) &&
14142             p->vrtp) {
14143          ast_rtp_destroy(p->vrtp);
14144          p->vrtp = NULL;
14145       }
14146       if ((!ast_test_flag(&p->flags[1], SIP_PAGE2_TEXTSUPPORT) || !(p->capability & AST_FORMAT_TEXT_MASK)) && p->trtp) {
14147          ast_rtp_destroy(p->trtp);
14148          p->trtp = NULL;
14149       }
14150       if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
14151           (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
14152          p->noncodeccapability |= AST_RTP_DTMF;
14153       else
14154          p->noncodeccapability &= ~AST_RTP_DTMF;
14155       p->jointnoncodeccapability = p->noncodeccapability;
14156    }
14157    unref_peer(peer, "check_peer_ok: unref_peer: tossing temp ptr to peer from find_peer");
14158    return res;
14159 }
14160 
14161 
14162 /*! \brief  Check if matching user or peer is defined 
14163    Match user on From: user name and peer on IP/port
14164    This is used on first invite (not re-invites) and subscribe requests 
14165     \return 0 on success, non-zero on failure
14166 */
14167 static enum check_auth_result check_user_full(struct sip_pvt *p, struct sip_request *req,
14168                      int sipmethod, char *uri, enum xmittype reliable,
14169                      struct sockaddr_in *sin, struct sip_peer **authpeer)
14170 {
14171    char from[256];
14172    char *dummy;   /* dummy return value for parse_uri */
14173    char *domain;  /* dummy return value for parse_uri */
14174    char *of;
14175    char rpid_num[50];
14176    const char *rpid;
14177    enum check_auth_result res;
14178    char calleridname[50];
14179    char *uri2 = ast_strdupa(uri);
14180 
14181    terminate_uri(uri2); /* trim extra stuff */
14182 
14183    ast_copy_string(from, get_header(req, "From"), sizeof(from));
14184    if (sip_cfg.pedanticsipchecking)
14185       ast_uri_decode(from);
14186    /* XXX here tries to map the username for invite things */
14187    memset(calleridname, 0, sizeof(calleridname));
14188    get_calleridname(from, calleridname, sizeof(calleridname));
14189    if (calleridname[0])
14190       ast_string_field_set(p, cid_name, calleridname);
14191 
14192    rpid = get_header(req, "Remote-Party-ID");
14193    memset(rpid_num, 0, sizeof(rpid_num));
14194    if (!ast_strlen_zero(rpid)) 
14195       p->callingpres = get_rpid_num(rpid, rpid_num, sizeof(rpid_num));
14196 
14197    of = get_in_brackets(from);
14198    if (ast_strlen_zero(p->exten)) {
14199       char *t = uri2;
14200       if (!strncasecmp(t, "sip:", 4))
14201          t+= 4;
14202       else if (!strncasecmp(t, "sips:", 5))
14203          t += 5;
14204       ast_string_field_set(p, exten, t);
14205       t = strchr(p->exten, '@');
14206       if (t)
14207          *t = '\0';
14208       if (ast_strlen_zero(p->our_contact))
14209          build_contact(p);
14210    }
14211    /* save the URI part of the From header */
14212    ast_string_field_set(p, from, of);
14213 
14214    /* ignore all fields but name */
14215    if (parse_uri(of, "sip:,sips:", &of, &dummy, &domain, &dummy, &dummy, NULL)) {
14216       ast_log(LOG_NOTICE, "From address missing 'sip:', using it anyway\n");
14217    }
14218 
14219    if (ast_strlen_zero(of)) {
14220       /* XXX note: the original code considered a missing @host
14221        * as a username-only URI. The SIP RFC (19.1.1) says that
14222        * this is wrong, and it should be considered as a domain-only URI.
14223        * For backward compatibility, we keep this block, but it is
14224        * really a mistake and should go away.
14225        */
14226       of = domain;
14227    } else {
14228       char *tmp = ast_strdupa(of);
14229       /* We need to be able to handle auth-headers looking like
14230          <sip:8164444422;phone-context=+1@1.2.3.4:5060;user=phone;tag=SDadkoa01-gK0c3bdb43>
14231       */
14232       tmp = strsep(&tmp, ";");
14233       if (global_shrinkcallerid && ast_is_shrinkable_phonenumber(tmp))
14234          ast_shrink_phone_number(tmp);
14235       ast_string_field_set(p, cid_num, tmp);
14236    }
14237 
14238    if (global_match_auth_username) {
14239       /*
14240        * XXX This is experimental code to grab the search key from the
14241        * Auth header's username instead of the 'From' name, if available.
14242        * Do not enable this block unless you understand the side effects (if any!)
14243        * Note, the search for "username" should be done in a more robust way.
14244        * Note2, at the moment we check both fields, though maybe we should
14245        * pick one or another depending on the request ? XXX
14246        */
14247       const char *hdr = get_header(req, "Authorization");
14248       if (ast_strlen_zero(hdr))
14249          hdr = get_header(req, "Proxy-Authorization");
14250 
14251       if ( !ast_strlen_zero(hdr) && (hdr = strstr(hdr, "username=\"")) ) {
14252          ast_copy_string(from, hdr + strlen("username=\""), sizeof(from));
14253          of = from;
14254          of = strsep(&of, "\"");
14255       }
14256    }
14257 
14258    res = check_peer_ok(p, of, req, sipmethod, sin,
14259          authpeer, reliable, rpid_num, calleridname, uri2);
14260    if (res != AUTH_DONT_KNOW)
14261       return res;
14262 
14263    /* Finally, apply the guest policy */
14264    if (sip_cfg.allowguest) {
14265       replace_cid(p, rpid_num, calleridname);
14266       res = AUTH_SUCCESSFUL;
14267    } else if (sip_cfg.alwaysauthreject)
14268       res = AUTH_FAKE_AUTH; /* reject with fake authorization request */
14269    else
14270       res = AUTH_SECRET_FAILED; /* we don't want any guests, authentication will fail */
14271 
14272 
14273    if (ast_test_flag(&p->flags[1], SIP_PAGE2_RPORT_PRESENT)) {
14274       ast_set_flag(&p->flags[0], SIP_NAT_ROUTE);
14275    }
14276 
14277    return res;
14278 }
14279 
14280 /*! \brief  Find user 
14281    If we get a match, this will add a reference pointer to the user object in ASTOBJ, that needs to be unreferenced
14282 */
14283 static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, char *uri, enum xmittype reliable, struct sockaddr_in *sin)
14284 {
14285    return check_user_full(p, req, sipmethod, uri, reliable, sin, NULL);
14286 }
14287 
14288 /*! \brief  Get text out of a SIP MESSAGE packet */
14289 static int get_msg_text(char *buf, int len, struct sip_request *req, int addnewline)
14290 {
14291    int x;
14292    int y;
14293 
14294    buf[0] = '\0';
14295    /*XXX isn't strlen(buf) going to always be 0? */
14296    y = len - strlen(buf) - 5;
14297    if (y < 0)
14298       y = 0;
14299    for (x = 0; x < req->lines; x++) {
14300       char *line = REQ_OFFSET_TO_STR(req, line[x]);
14301       strncat(buf, line, y); /* safe */
14302       y -= strlen(line) + 1;
14303       if (y < 0)
14304          y = 0;
14305       if (y != 0 && addnewline)
14306          strcat(buf, "\n"); /* safe */
14307    }
14308    return 0;
14309 }
14310 
14311 
14312 /*! \brief  Receive SIP MESSAGE method messages
14313 \note We only handle messages within current calls currently 
14314    Reference: RFC 3428 */
14315 static void receive_message(struct sip_pvt *p, struct sip_request *req)
14316 {
14317    char buf[1400];   
14318    struct ast_frame f;
14319    const char *content_type = get_header(req, "Content-Type");
14320 
14321    if (strncmp(content_type, "text/plain", strlen("text/plain"))) { /* No text/plain attachment */
14322       transmit_response(p, "415 Unsupported Media Type", req); /* Good enough, or? */
14323       if (!p->owner)
14324          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14325       return;
14326    }
14327 
14328    if (get_msg_text(buf, sizeof(buf), req, FALSE)) {
14329       ast_log(LOG_WARNING, "Unable to retrieve text from %s\n", p->callid);
14330       transmit_response(p, "202 Accepted", req);
14331       if (!p->owner)
14332          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14333       return;
14334    }
14335 
14336    if (p->owner) {
14337       if (sip_debug_test_pvt(p))
14338          ast_verbose("SIP Text message received: '%s'\n", buf);
14339       memset(&f, 0, sizeof(f));
14340       f.frametype = AST_FRAME_TEXT;
14341       f.subclass = 0;
14342       f.offset = 0;
14343       f.data.ptr = buf;
14344       f.datalen = strlen(buf);
14345       ast_queue_frame(p->owner, &f);
14346       transmit_response(p, "202 Accepted", req); /* We respond 202 accepted, since we relay the message */
14347       return;
14348    }
14349 
14350    /* Message outside of a call, we do not support that */
14351    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);
14352    transmit_response(p, "405 Method Not Allowed", req);
14353    sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14354    return;
14355 }
14356 
14357 /*! \brief  CLI Command to show calls within limits set by call_limit */
14358 static char *sip_show_inuse(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14359 {
14360 #define FORMAT "%-25.25s %-15.15s %-15.15s \n"
14361 #define FORMAT2 "%-25.25s %-15.15s %-15.15s \n"
14362    char ilimits[40];
14363    char iused[40];
14364    int showall = FALSE;
14365    struct ao2_iterator i;
14366    struct sip_peer *peer;
14367    
14368    switch (cmd) {
14369    case CLI_INIT:
14370       e->command = "sip show inuse";
14371       e->usage =
14372          "Usage: sip show inuse [all]\n"
14373          "       List all SIP devices usage counters and limits.\n"
14374          "       Add option \"all\" to show all devices, not only those with a limit.\n";
14375       return NULL;
14376    case CLI_GENERATE:
14377       return NULL;
14378    }
14379 
14380    if (a->argc < 3) 
14381       return CLI_SHOWUSAGE;
14382 
14383    if (a->argc == 4 && !strcmp(a->argv[3], "all")) 
14384       showall = TRUE;
14385    
14386    ast_cli(a->fd, FORMAT, "* Peer name", "In use", "Limit");
14387 
14388    i = ao2_iterator_init(peers, 0);
14389    while ((peer = ao2_t_iterator_next(&i, "iterate thru peer table"))) {
14390       ao2_lock(peer);
14391       if (peer->call_limit)
14392          snprintf(ilimits, sizeof(ilimits), "%d", peer->call_limit);
14393       else 
14394          ast_copy_string(ilimits, "N/A", sizeof(ilimits));
14395       snprintf(iused, sizeof(iused), "%d/%d/%d", peer->inUse, peer->inRinging, peer->onHold);
14396       if (showall || peer->call_limit)
14397          ast_cli(a->fd, FORMAT2, peer->name, iused, ilimits);
14398       ao2_unlock(peer);
14399       unref_peer(peer, "toss iterator pointer");
14400    }
14401    ao2_iterator_destroy(&i);
14402 
14403    return CLI_SUCCESS;
14404 #undef FORMAT
14405 #undef FORMAT2
14406 }
14407 
14408 
14409 /*! \brief Convert transfer mode to text string */
14410 static char *transfermode2str(enum transfermodes mode)
14411 {
14412    if (mode == TRANSFER_OPENFORALL)
14413       return "open";
14414    else if (mode == TRANSFER_CLOSED)
14415       return "closed";
14416    return "strict";
14417 }
14418 
14419 static struct _map_x_s natmodes[] = {
14420    { SIP_NAT_NEVER,        "No"},
14421    { SIP_NAT_ROUTE,        "Route"},
14422    { SIP_NAT_ALWAYS,       "Always"},
14423    { SIP_NAT_RFC3581,      "RFC3581"},
14424    { -1,                   NULL}, /* terminator */
14425 };
14426 
14427 /*! \brief  Convert NAT setting to text string */
14428 static const char *nat2str(int nat)
14429 {
14430    return map_x_s(natmodes, nat, "Unknown");
14431 }
14432 
14433 #ifdef NOTUSED
14434 /* OEJ: This is not used, but may be useful in the future, so I don't want to 
14435    delete it. Keeping it enabled generates compiler warnings.
14436  */
14437 
14438 static struct _map_x_s natcfgmodes[] = {
14439    { SIP_NAT_NEVER,        "never"},
14440    { SIP_NAT_ROUTE,        "route"},
14441    { SIP_NAT_ALWAYS,       "yes"},
14442    { SIP_NAT_RFC3581,      "no"},
14443    { -1,                   NULL}, /* terminator */
14444 };
14445 
14446 /*! \brief  Convert NAT setting to text string appropriate for config files */
14447 static const char *nat2strconfig(int nat)
14448 {
14449    return map_x_s(natcfgmodes, nat, "Unknown");
14450 }
14451 #endif
14452 
14453 /*! \brief  Report Peer status in character string
14454  *  \return 0 if peer is unreachable, 1 if peer is online, -1 if unmonitored
14455  */
14456 
14457 
14458 /* Session-Timer Modes */
14459 static struct _map_x_s stmodes[] = {
14460         { SESSION_TIMER_MODE_ACCEPT,    "Accept"},
14461         { SESSION_TIMER_MODE_ORIGINATE, "Originate"},
14462         { SESSION_TIMER_MODE_REFUSE,    "Refuse"},
14463         { -1,                           NULL},
14464 };
14465 
14466 static const char *stmode2str(enum st_mode m)
14467 {
14468    return map_x_s(stmodes, m, "Unknown");
14469 }
14470 
14471 static enum st_mode str2stmode(const char *s)
14472 {
14473    return map_s_x(stmodes, s, -1);
14474 }
14475 
14476 /* Session-Timer Refreshers */
14477 static struct _map_x_s strefreshers[] = {
14478         { SESSION_TIMER_REFRESHER_AUTO,     "auto"},
14479         { SESSION_TIMER_REFRESHER_UAC,      "uac"},
14480         { SESSION_TIMER_REFRESHER_UAS,      "uas"},
14481         { -1,                               NULL},
14482 };
14483 
14484 static const char *strefresher2str(enum st_refresher r)
14485 {
14486    return map_x_s(strefreshers, r, "Unknown");
14487 }
14488 
14489 static enum st_refresher str2strefresher(const char *s)
14490 {
14491    return map_s_x(strefreshers, s, -1);
14492 }
14493 
14494 
14495 static int peer_status(struct sip_peer *peer, char *status, int statuslen)
14496 {
14497    int res = 0;
14498    if (peer->maxms) {
14499       if (peer->lastms < 0) {
14500          ast_copy_string(status, "UNREACHABLE", statuslen);
14501       } else if (peer->lastms > peer->maxms) {
14502          snprintf(status, statuslen, "LAGGED (%d ms)", peer->lastms);
14503          res = 1;
14504       } else if (peer->lastms) {
14505          snprintf(status, statuslen, "OK (%d ms)", peer->lastms);
14506          res = 1;
14507       } else {
14508          ast_copy_string(status, "UNKNOWN", statuslen);
14509       }
14510    } else { 
14511       ast_copy_string(status, "Unmonitored", statuslen);
14512       /* Checking if port is 0 */
14513       res = -1;
14514    }
14515    return res;
14516 }
14517 
14518 /*! \brief return Yes or No depending on the argument.
14519  * This is used in many places in CLI command, having a function to generate
14520  * this helps maintaining a consistent output (and possibly emitting the
14521  * output in other languages, at some point).
14522  */
14523 static const char *cli_yesno(int x)
14524 {
14525    return x ? "Yes" : "No";
14526 }
14527 
14528 /*! \brief  Show active TCP connections */
14529 static char *sip_show_tcp(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14530 {
14531    struct sip_threadinfo *th;
14532    struct ao2_iterator i;
14533 
14534 #define FORMAT2 "%-30.30s %3.6s %9.9s %6.6s\n"
14535 #define FORMAT  "%-30.30s %-6d %-9.9s %-6.6s\n"
14536 
14537    switch (cmd) {
14538    case CLI_INIT:
14539       e->command = "sip show tcp";
14540       e->usage =
14541          "Usage: sip show tcp\n"
14542          "       Lists all active TCP/TLS sessions.\n";
14543       return NULL;
14544    case CLI_GENERATE:
14545       return NULL;
14546    }
14547 
14548    if (a->argc != 3)
14549       return CLI_SHOWUSAGE;
14550 
14551    ast_cli(a->fd, FORMAT2, "Host", "Port", "Transport", "Type");
14552    i = ao2_iterator_init(threadt, 0);
14553    while ((th = ao2_t_iterator_next(&i, "iterate through tcp threads for 'sip show tcp'"))) {
14554       ast_cli(a->fd, FORMAT, ast_inet_ntoa(th->tcptls_session->remote_address.sin_addr), 
14555          ntohs(th->tcptls_session->remote_address.sin_port), 
14556          get_transport(th->type), 
14557          (th->tcptls_session->client ? "Client" : "Server"));
14558       ao2_t_ref(th, -1, "decrement ref from iterator");
14559    }
14560    ao2_iterator_destroy(&i);
14561    return CLI_SUCCESS;
14562 #undef FORMAT
14563 #undef FORMAT2
14564 }
14565 
14566 /*! \brief  CLI Command 'SIP Show Users' */
14567 static char *sip_show_users(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14568 {
14569    regex_t regexbuf;
14570    int havepattern = FALSE;
14571    struct ao2_iterator user_iter;
14572    struct sip_peer *user;
14573 
14574 #define FORMAT  "%-25.25s  %-15.15s  %-15.15s  %-15.15s  %-5.5s%-10.10s\n"
14575 
14576    switch (cmd) {
14577    case CLI_INIT:
14578       e->command = "sip show users";
14579       e->usage =
14580          "Usage: sip show users [like <pattern>]\n"
14581          "       Lists all known SIP users.\n"
14582          "       Optional regular expression pattern is used to filter the user list.\n";
14583       return NULL;
14584    case CLI_GENERATE:
14585       return NULL;
14586    }
14587 
14588    switch (a->argc) {
14589    case 5:
14590       if (!strcasecmp(a->argv[3], "like")) {
14591          if (regcomp(&regexbuf, a->argv[4], REG_EXTENDED | REG_NOSUB))
14592             return CLI_SHOWUSAGE;
14593          havepattern = TRUE;
14594       } else
14595          return CLI_SHOWUSAGE;
14596    case 3:
14597       break;
14598    default:
14599       return CLI_SHOWUSAGE;
14600    }
14601 
14602    ast_cli(a->fd, FORMAT, "Username", "Secret", "Accountcode", "Def.Context", "ACL", "NAT");
14603 
14604    user_iter = ao2_iterator_init(peers, 0);
14605    while ((user = ao2_iterator_next(&user_iter))) {
14606       ao2_lock(user);
14607       if (!(user->type & SIP_TYPE_USER)) {
14608          ao2_unlock(user);
14609          unref_peer(user, "sip show users");
14610          continue;
14611       }
14612 
14613       if (havepattern && regexec(&regexbuf, user->name, 0, NULL, 0)) {
14614          ao2_unlock(user);
14615          unref_peer(user, "sip show users");
14616          continue;
14617       }
14618 
14619       ast_cli(a->fd, FORMAT, user->name, 
14620          user->secret, 
14621          user->accountcode,
14622          user->context,
14623          cli_yesno(user->ha != NULL),
14624          nat2str(ast_test_flag(&user->flags[0], SIP_NAT)));
14625       ao2_unlock(user);
14626       unref_peer(user, "sip show users");
14627    }
14628    ao2_iterator_destroy(&user_iter);
14629 
14630    if (havepattern)
14631       regfree(&regexbuf);
14632 
14633    return CLI_SUCCESS;
14634 #undef FORMAT
14635 }
14636 
14637 /*! \brief Manager Action SIPShowRegistry description */
14638 static char mandescr_show_registry[] =
14639 "Description: Lists all registration requests and status\n"
14640 "Registrations will follow as separate events. followed by a final event called\n"
14641 "RegistrationsComplete.\n"
14642 "Variables: \n"
14643 "  ActionID: <id>       Action ID for this transaction. Will be returned.\n";
14644 
14645 /*! \brief Show SIP registrations in the manager API */
14646 static int manager_show_registry(struct mansession *s, const struct message *m)
14647 {
14648    const char *id = astman_get_header(m, "ActionID");
14649    char idtext[256] = "";
14650    int total = 0;
14651 
14652    if (!ast_strlen_zero(id))
14653       snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
14654 
14655    astman_send_listack(s, m, "Registrations will follow", "start");
14656 
14657    ASTOBJ_CONTAINER_TRAVERSE(&regl, 1, do {
14658       ASTOBJ_RDLOCK(iterator);
14659       astman_append(s,
14660          "Event: RegistryEntry\r\n"
14661          "%s"
14662          "Host: %s\r\n"
14663          "Port: %d\r\n"
14664          "Username: %s\r\n"
14665          "Refresh: %d\r\n"
14666          "State: %s\r\n"
14667          "RegistrationTime: %ld\r\n"
14668          "\r\n", idtext, iterator->hostname, iterator->portno ? iterator->portno : STANDARD_SIP_PORT,
14669                  iterator->username, iterator->refresh, regstate2str(iterator->regstate), (long) iterator->regtime.tv_sec);
14670       ASTOBJ_UNLOCK(iterator);
14671       total++;
14672    } while(0));
14673 
14674    astman_append(s,
14675       "Event: RegistrationsComplete\r\n"
14676       "EventList: Complete\r\n"
14677       "ListItems: %d\r\n"
14678       "%s"
14679       "\r\n", total, idtext);
14680    
14681    return 0;
14682 }
14683 
14684 static char mandescr_show_peers[] = 
14685 "Description: Lists SIP peers in text format with details on current status.\n"
14686 "Peerlist will follow as separate events, followed by a final event called\n"
14687 "PeerlistComplete.\n"
14688 "Variables: \n"
14689 "  ActionID: <id> Action ID for this transaction. Will be returned.\n";
14690 
14691 /*! \brief  Show SIP peers in the manager API */
14692 /*    Inspired from chan_iax2 */
14693 static int manager_sip_show_peers(struct mansession *s, const struct message *m)
14694 {
14695    const char *id = astman_get_header(m, "ActionID");
14696    const char *a[] = {"sip", "show", "peers"};
14697    char idtext[256] = "";
14698    int total = 0;
14699 
14700    if (!ast_strlen_zero(id))
14701       snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
14702 
14703    astman_send_listack(s, m, "Peer status list will follow", "start");
14704    /* List the peers in separate manager events */
14705    _sip_show_peers(-1, &total, s, m, 3, a);
14706    /* Send final confirmation */
14707    astman_append(s,
14708    "Event: PeerlistComplete\r\n"
14709    "EventList: Complete\r\n"
14710    "ListItems: %d\r\n"
14711    "%s"
14712    "\r\n", total, idtext);
14713    return 0;
14714 }
14715 
14716 /*! \brief  CLI Show Peers command */
14717 static char *sip_show_peers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14718 {
14719    switch (cmd) {
14720    case CLI_INIT:
14721       e->command = "sip show peers";
14722       e->usage =
14723          "Usage: sip show peers [like <pattern>]\n"
14724          "       Lists all known SIP peers.\n"
14725          "       Optional regular expression pattern is used to filter the peer list.\n";
14726       return NULL;
14727    case CLI_GENERATE:
14728       return NULL;
14729    }
14730 
14731    return _sip_show_peers(a->fd, NULL, NULL, NULL, a->argc, (const char **) a->argv);
14732 }
14733 
14734 int peercomparefunc(const void *a, const void *b);
14735 
14736 int peercomparefunc(const void *a, const void *b)
14737 {
14738    struct sip_peer **ap = (struct sip_peer **)a;
14739    struct sip_peer **bp = (struct sip_peer **)b;
14740    return strcmp((*ap)->name, (*bp)->name);
14741 }
14742 
14743 
14744 /*! \brief Execute sip show peers command */
14745 static char *_sip_show_peers(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char *argv[])
14746 {
14747    regex_t regexbuf;
14748    int havepattern = FALSE;
14749    struct sip_peer *peer;
14750    struct ao2_iterator i;
14751    
14752 /* the last argument is left-aligned, so we don't need a size anyways */
14753 #define FORMAT2 "%-25.25s  %-15.15s %-3.3s %-3.3s %-3.3s %-8s %-10s %s\n"
14754 #define FORMAT  "%-25.25s  %-15.15s %-3.3s %-3.3s %-3.3s %-8d %-10s %s\n"
14755 
14756    char name[256];
14757    int total_peers = 0;
14758    int peers_mon_online = 0;
14759    int peers_mon_offline = 0;
14760    int peers_unmon_offline = 0;
14761    int peers_unmon_online = 0;
14762    const char *id;
14763    char idtext[256] = "";
14764    int realtimepeers;
14765    int objcount = ao2_container_count(peers);
14766    struct sip_peer **peerarray;
14767    int k;
14768    
14769    
14770    realtimepeers = ast_check_realtime("sippeers");
14771    peerarray = ast_calloc(sizeof(struct sip_peer *), objcount);
14772 
14773    if (s) { /* Manager - get ActionID */
14774       id = astman_get_header(m, "ActionID");
14775       if (!ast_strlen_zero(id))
14776          snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
14777    }
14778 
14779    switch (argc) {
14780    case 5:
14781       if (!strcasecmp(argv[3], "like")) {
14782          if (regcomp(&regexbuf, argv[4], REG_EXTENDED | REG_NOSUB))
14783             return CLI_SHOWUSAGE;
14784          havepattern = TRUE;
14785       } else
14786          return CLI_SHOWUSAGE;
14787    case 3:
14788       break;
14789    default:
14790       return CLI_SHOWUSAGE;
14791    }
14792 
14793    if (!s) /* Normal list */
14794       ast_cli(fd, FORMAT2, "Name/username", "Host", "Dyn", "Nat", "ACL", "Port", "Status", (realtimepeers ? "Realtime" : ""));
14795    
14796 
14797    i = ao2_iterator_init(peers, 0);
14798    while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {  
14799       ao2_lock(peer);
14800 
14801       if (!(peer->type & SIP_TYPE_PEER)) {
14802          ao2_unlock(peer);
14803          unref_peer(peer, "unref peer because it's actually a user");
14804          continue;
14805       }
14806 
14807       if (havepattern && regexec(&regexbuf, peer->name, 0, NULL, 0)) {
14808          objcount--;
14809          ao2_unlock(peer);
14810          unref_peer(peer, "toss iterator peer ptr before continue");
14811          continue;
14812       }
14813 
14814       peerarray[total_peers++] = peer;
14815       ao2_unlock(peer);
14816    }
14817    ao2_iterator_destroy(&i);
14818    
14819    qsort(peerarray, total_peers, sizeof(struct sip_peer *), peercomparefunc);
14820 
14821    for(k=0; k < total_peers; k++) {
14822       char status[20] = "";
14823       char srch[2000];
14824       char pstatus;
14825       peer = peerarray[k];
14826       
14827       ao2_lock(peer);
14828       if (havepattern && regexec(&regexbuf, peer->name, 0, NULL, 0)) {
14829          ao2_unlock(peer);
14830          unref_peer(peer, "toss iterator peer ptr before continue");
14831          continue;
14832       }
14833 
14834       if (!ast_strlen_zero(peer->username) && !s)
14835          snprintf(name, sizeof(name), "%s/%s", peer->name, peer->username);
14836       else
14837          ast_copy_string(name, peer->name, sizeof(name));
14838       
14839       pstatus = peer_status(peer, status, sizeof(status));
14840       if (pstatus == 1)
14841          peers_mon_online++;
14842       else if (pstatus == 0)
14843          peers_mon_offline++;
14844       else {
14845          if (peer->addr.sin_port == 0)
14846             peers_unmon_offline++;
14847          else
14848             peers_unmon_online++;
14849       }
14850 
14851       snprintf(srch, sizeof(srch), FORMAT, name,
14852          peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "(Unspecified)",
14853          peer->host_dynamic ? " D " : "   ",    /* Dynamic or not? */
14854          ast_test_flag(&peer->flags[0], SIP_NAT_ROUTE) ? " N " : "   ", /* NAT=yes? */
14855          peer->ha ? " A " : "   ",  /* permit/deny */
14856          ntohs(peer->addr.sin_port), status,
14857          realtimepeers ? (peer->is_realtime ? "Cached RT":"") : "");
14858 
14859       if (!s)  {/* Normal CLI list */
14860          ast_cli(fd, FORMAT, name, 
14861          peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "(Unspecified)",
14862          peer->host_dynamic ? " D " : "   ",    /* Dynamic or not? */
14863          ast_test_flag(&peer->flags[0], SIP_NAT_ROUTE) ? " N " : "   ", /* NAT=yes? */
14864          peer->ha ? " A " : "   ",       /* permit/deny */
14865          
14866          ntohs(peer->addr.sin_port), status,
14867          realtimepeers ? (peer->is_realtime ? "Cached RT":"") : "");
14868       } else { /* Manager format */
14869          /* The names here need to be the same as other channels */
14870          astman_append(s, 
14871          "Event: PeerEntry\r\n%s"
14872          "Channeltype: SIP\r\n"
14873          "ObjectName: %s\r\n"
14874          "ChanObjectType: peer\r\n" /* "peer" or "user" */
14875          "IPaddress: %s\r\n"
14876          "IPport: %d\r\n"
14877          "Dynamic: %s\r\n"
14878          "Natsupport: %s\r\n"
14879          "VideoSupport: %s\r\n"
14880          "TextSupport: %s\r\n"
14881          "ACL: %s\r\n"
14882          "Status: %s\r\n"
14883          "RealtimeDevice: %s\r\n\r\n", 
14884          idtext,
14885          peer->name, 
14886          peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "-none-",
14887          ntohs(peer->addr.sin_port), 
14888          peer->host_dynamic ? "yes" : "no",  /* Dynamic or not? */
14889          ast_test_flag(&peer->flags[0], SIP_NAT_ROUTE) ? "yes" : "no",  /* NAT=yes? */
14890          ast_test_flag(&peer->flags[1], SIP_PAGE2_VIDEOSUPPORT) ? "yes" : "no",  /* VIDEOSUPPORT=yes? */
14891          ast_test_flag(&peer->flags[1], SIP_PAGE2_TEXTSUPPORT) ? "yes" : "no",   /* TEXTSUPPORT=yes? */
14892          peer->ha ? "yes" : "no",       /* permit/deny */
14893          status,
14894          realtimepeers ? (peer->is_realtime ? "yes":"no") : "no");
14895       }
14896       ao2_unlock(peer);
14897       unref_peer(peer, "toss iterator peer ptr");
14898    }
14899    
14900    if (!s)
14901       ast_cli(fd, "%d sip peers [Monitored: %d online, %d offline Unmonitored: %d online, %d offline]\n",
14902               total_peers, peers_mon_online, peers_mon_offline, peers_unmon_online, peers_unmon_offline);
14903 
14904    if (havepattern)
14905       regfree(&regexbuf);
14906 
14907    if (total)
14908       *total = total_peers;
14909    
14910    ast_free(peerarray);
14911    
14912    return CLI_SUCCESS;
14913 #undef FORMAT
14914 #undef FORMAT2
14915 }
14916 
14917 static int peer_dump_func(void *userobj, void *arg, int flags)
14918 {
14919    struct sip_peer *peer = userobj;
14920    int refc = ao2_t_ref(userobj, 0, "");
14921    int *fd = arg;
14922    
14923    ast_cli(*fd, "name: %s\ntype: peer\nobjflags: %d\nrefcount: %d\n\n", 
14924           peer->name, 0, refc);
14925    return 0;
14926 }
14927 
14928 static int dialog_dump_func(void *userobj, void *arg, int flags)
14929 {
14930    struct sip_pvt *pvt = userobj;
14931    int refc = ao2_t_ref(userobj, 0, "");
14932    int *fd = arg;
14933    
14934    ast_cli(*fd, "name: %s\ntype: dialog\nobjflags: %d\nrefcount: %d\n\n", 
14935           pvt->callid, 0, refc);
14936    return 0;
14937 }
14938 
14939 
14940 /*! \brief List all allocated SIP Objects (realtime or static) */
14941 static char *sip_show_objects(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14942 {
14943    char tmp[256];
14944    
14945    switch (cmd) {
14946    case CLI_INIT:
14947       e->command = "sip show objects";
14948       e->usage =
14949          "Usage: sip show objects\n"
14950          "       Lists status of known SIP objects\n";
14951       return NULL;
14952    case CLI_GENERATE:
14953       return NULL;
14954    }  
14955 
14956    if (a->argc != 3)
14957       return CLI_SHOWUSAGE;
14958    ast_cli(a->fd, "-= Peer objects: %d static, %d realtime, %d autocreate =-\n\n", speerobjs, rpeerobjs, apeerobjs);
14959    ao2_t_callback(peers, OBJ_NODATA, peer_dump_func, &a->fd, "initiate ao2_callback to dump peers");
14960    ast_cli(a->fd, "-= Registry objects: %d =-\n\n", regobjs);
14961    ASTOBJ_CONTAINER_DUMP(a->fd, tmp, sizeof(tmp), &regl);
14962    ast_cli(a->fd, "-= Dialog objects:\n\n");
14963    ao2_t_callback(dialogs, OBJ_NODATA, dialog_dump_func, &a->fd, "initiate ao2_callback to dump dialogs");
14964    return CLI_SUCCESS;
14965 }
14966 /*! \brief Print call group and pickup group */
14967 static void  print_group(int fd, ast_group_t group, int crlf)
14968 {
14969    char buf[256];
14970    ast_cli(fd, crlf ? "%s\r\n" : "%s\n", ast_print_group(buf, sizeof(buf), group) );
14971 }
14972 
14973 /*! \brief mapping between dtmf flags and strings */
14974 static struct _map_x_s dtmfstr[] = {
14975    { SIP_DTMF_RFC2833,     "rfc2833" },
14976    { SIP_DTMF_INFO,        "info" },
14977    { SIP_DTMF_SHORTINFO,   "shortinfo" },
14978    { SIP_DTMF_INBAND,      "inband" },
14979    { SIP_DTMF_AUTO,        "auto" },
14980    { -1,                   NULL }, /* terminator */
14981 };
14982 
14983 /*! \brief Convert DTMF mode to printable string */
14984 static const char *dtmfmode2str(int mode)
14985 {
14986    return map_x_s(dtmfstr, mode, "<error>");
14987 }
14988 
14989 /*! \brief maps a string to dtmfmode, returns -1 on error */
14990 static int str2dtmfmode(const char *str)
14991 {
14992    return map_s_x(dtmfstr, str, -1);
14993 }
14994 
14995 static struct _map_x_s insecurestr[] = {
14996    { SIP_INSECURE_PORT,    "port" },
14997    { SIP_INSECURE_INVITE,  "invite" },
14998    { SIP_INSECURE_PORT | SIP_INSECURE_INVITE, "port,invite" },
14999    { 0,                    "no" },
15000    { -1,                   NULL }, /* terminator */
15001 };
15002 
15003 /*! \brief Convert Insecure setting to printable string */
15004 static const char *insecure2str(int mode)
15005 {
15006    return map_x_s(insecurestr, mode, "<error>");
15007 }
15008 
15009 /*! \brief Destroy disused contexts between reloads
15010    Only used in reload_config so the code for regcontext doesn't get ugly
15011 */
15012 static void cleanup_stale_contexts(char *new, char *old)
15013 {
15014    char *oldcontext, *newcontext, *stalecontext, *stringp, newlist[AST_MAX_CONTEXT];
15015 
15016    while ((oldcontext = strsep(&old, "&"))) {
15017       stalecontext = '\0';
15018       ast_copy_string(newlist, new, sizeof(newlist));
15019       stringp = newlist;
15020       while ((newcontext = strsep(&stringp, "&"))) {
15021          if (!strcmp(newcontext, oldcontext)) {
15022             /* This is not the context you're looking for */
15023             stalecontext = '\0';
15024             break;
15025          } else if (strcmp(newcontext, oldcontext)) {
15026             stalecontext = oldcontext;
15027          }
15028          
15029       }
15030       if (stalecontext)
15031          ast_context_destroy(ast_context_find(stalecontext), "SIP");
15032    }
15033 }
15034 
15035 /*! 
15036  * \brief Match dialogs that need to be destroyed
15037  *
15038  * \details This is used with ao2_callback to unlink/delete all dialogs that
15039  * are marked needdestroy. It will return CMP_MATCH for candidates, and they
15040  * will be unlinked.
15041  *
15042  * \todo Re-work this to improve efficiency.  Currently, this function is called
15043  * on _every_ dialog after processing _every_ incoming SIP/UDP packet, or
15044  * potentially even more often when the scheduler has entries to run.
15045  */
15046 
15047 static int dialog_needdestroy(void *dialogobj, void *arg, int flags) 
15048 {
15049    struct sip_pvt *dialog = dialogobj;
15050    time_t *t = arg;
15051 
15052    if (sip_pvt_trylock(dialog)) {
15053       /* Don't block the monitor thread.  This function is called often enough
15054        * that we can wait for the next time around. */
15055       return 0;
15056    }
15057    
15058    /* Check RTP timeouts and kill calls if we have a timeout set and do not get RTP */
15059    check_rtp_timeout(dialog, *t);
15060 
15061    /* If we have sessions that needs to be destroyed, do it now */
15062    /* Check if we have outstanding requests not responsed to or an active call
15063       - if that's the case, wait with destruction */
15064    if (dialog->needdestroy && !dialog->packets && !dialog->owner) {
15065       /* We absolutely cannot destroy the rtp struct while a bridge is active or we WILL crash */
15066       if (dialog->rtp && ast_rtp_get_bridged(dialog->rtp)) {
15067          ast_debug(2, "Bridge still active.  Delaying destruction of SIP dialog '%s' Method: %s\n", dialog->callid, sip_methods[dialog->method].text);
15068          sip_pvt_unlock(dialog);
15069          return 0;
15070       }
15071       
15072       if (dialog->vrtp && ast_rtp_get_bridged(dialog->vrtp)) {
15073          ast_debug(2, "Bridge still active.  Delaying destroy of SIP dialog '%s' Method: %s\n", dialog->callid, sip_methods[dialog->method].text);
15074          sip_pvt_unlock(dialog);
15075          return 0;
15076       }
15077 
15078       sip_pvt_unlock(dialog);
15079       /* no, the unlink should handle this: dialog_unref(dialog, "needdestroy: one more refcount decrement to allow dialog to be destroyed"); */
15080       /* the CMP_MATCH will unlink this dialog from the dialog hash table */
15081       dialog_unlink_all(dialog, TRUE, FALSE);
15082       return 0; /* the unlink_all should unlink this from the table, so.... no need to return a match */
15083    }
15084 
15085    sip_pvt_unlock(dialog);
15086 
15087    return 0;
15088 }
15089 
15090 /* this func is used with ao2_callback to unlink/delete all marked
15091    peers */
15092 static int peer_is_marked(void *peerobj, void *arg, int flags)
15093 {
15094    struct sip_peer *peer = peerobj;
15095    return peer->the_mark ? CMP_MATCH : 0;
15096 }
15097 
15098 /*! \brief Remove temporary realtime objects from memory (CLI) */
15099 /*! \todo XXXX Propably needs an overhaul after removal of the devices */
15100 static char *sip_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15101 {
15102    struct sip_peer *peer, *pi;
15103    int prunepeer = FALSE;
15104    int multi = FALSE;
15105    char *name = NULL;
15106    regex_t regexbuf;
15107    struct ao2_iterator i;
15108    static char *choices[] = { "all", "like", NULL };
15109    char *cmplt;
15110    
15111    if (cmd == CLI_INIT) {
15112       e->command = "sip prune realtime [peer|all]";
15113       e->usage =
15114          "Usage: sip prune realtime [peer [<name>|all|like <pattern>]|all]\n"
15115          "       Prunes object(s) from the cache.\n"
15116          "       Optional regular expression pattern is used to filter the objects.\n";
15117       return NULL;
15118    } else if (cmd == CLI_GENERATE) {
15119       if (a->pos == 4 && !strcasecmp(a->argv[3], "peer")) {
15120          cmplt = ast_cli_complete(a->word, choices, a->n);
15121          if (!cmplt)
15122             cmplt = complete_sip_peer(a->word, a->n - sizeof(choices), SIP_PAGE2_RTCACHEFRIENDS);
15123          return cmplt;
15124       }
15125       if (a->pos == 5 && !strcasecmp(a->argv[4], "like"))
15126          return complete_sip_peer(a->word, a->n, SIP_PAGE2_RTCACHEFRIENDS);
15127       return NULL;
15128    }
15129    switch (a->argc) {
15130    case 4:
15131       name = a->argv[3];
15132       /* we accept a name in position 3, but keywords are not good. */
15133       if (!strcasecmp(name, "peer") || !strcasecmp(name, "like"))
15134          return CLI_SHOWUSAGE;
15135       prunepeer = TRUE;
15136       if (!strcasecmp(name, "all")) {
15137          multi = TRUE;
15138          name = NULL;
15139       }
15140       /* else a single name, already set */
15141       break;
15142    case 5:
15143       /* sip prune realtime {peer|like} name */
15144       name = a->argv[4];
15145       if (!strcasecmp(a->argv[3], "peer"))
15146          prunepeer = TRUE;
15147       else if (!strcasecmp(a->argv[3], "like")) {
15148          prunepeer = TRUE;
15149          multi = TRUE;
15150       } else
15151          return CLI_SHOWUSAGE;
15152       if (!strcasecmp(name, "like"))
15153          return CLI_SHOWUSAGE;
15154       if (!multi && !strcasecmp(name, "all")) {
15155          multi = TRUE;
15156          name = NULL;
15157       }
15158       break;
15159    case 6:
15160       name = a->argv[5];
15161       multi = TRUE;
15162       /* sip prune realtime {peer} like name */
15163       if (strcasecmp(a->argv[4], "like"))
15164          return CLI_SHOWUSAGE;
15165       if (!strcasecmp(a->argv[3], "peer")) {
15166          prunepeer = TRUE;
15167       } else
15168          return CLI_SHOWUSAGE;
15169       break;
15170    default:
15171       return CLI_SHOWUSAGE;
15172    }
15173 
15174    if (multi && name) {
15175       if (regcomp(&regexbuf, name, REG_EXTENDED | REG_NOSUB))
15176          return CLI_SHOWUSAGE;
15177    }
15178 
15179    if (multi) {
15180       if (prunepeer) {
15181          int pruned = 0;
15182          
15183          i = ao2_iterator_init(peers, 0);
15184          while ((pi = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
15185             ao2_lock(pi);
15186             if (name && regexec(&regexbuf, pi->name, 0, NULL, 0)) {
15187                unref_peer(pi, "toss iterator peer ptr before continue");
15188                ao2_unlock(pi);
15189                continue;
15190             };
15191             if (ast_test_flag(&pi->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
15192                pi->the_mark = 1;
15193                pruned++;
15194             }
15195             ao2_unlock(pi);
15196             unref_peer(pi, "toss iterator peer ptr");
15197          }
15198          ao2_iterator_destroy(&i);
15199          if (pruned) {
15200             ao2_t_callback(peers, OBJ_NODATA | OBJ_UNLINK | OBJ_MULTIPLE, peer_is_marked, NULL,
15201                   "initiating callback to remove marked peers");
15202             ast_cli(a->fd, "%d peers pruned.\n", pruned);
15203          } else
15204             ast_cli(a->fd, "No peers found to prune.\n");
15205       }
15206    } else {
15207       if (prunepeer) {
15208          struct sip_peer tmp;
15209          ast_copy_string(tmp.name, name, sizeof(tmp.name));
15210          if ((peer = ao2_t_find(peers, &tmp, OBJ_POINTER | OBJ_UNLINK, "finding to unlink from peers"))) {
15211             if (peer->addr.sin_addr.s_addr) {
15212                ao2_t_unlink(peers_by_ip, peer, "unlinking peer from peers_by_ip also");
15213             }
15214             if (!ast_test_flag(&peer->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
15215                ast_cli(a->fd, "Peer '%s' is not a Realtime peer, cannot be pruned.\n", name);
15216                /* put it back! */
15217                ao2_t_link(peers, peer, "link peer into peer table");
15218                if (peer->addr.sin_addr.s_addr) {
15219                   ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
15220                }
15221                
15222             } else
15223                ast_cli(a->fd, "Peer '%s' pruned.\n", name);
15224             unref_peer(peer, "sip_prune_realtime: unref_peer: tossing temp peer ptr");
15225          } else
15226             ast_cli(a->fd, "Peer '%s' not found.\n", name);
15227       }
15228    }
15229 
15230    return CLI_SUCCESS;
15231 }
15232 
15233 /*! \brief Print codec list from preference to CLI/manager */
15234 static void print_codec_to_cli(int fd, struct ast_codec_pref *pref)
15235 {
15236    int x, codec;
15237 
15238    for(x = 0; x < 32 ; x++) {
15239       codec = ast_codec_pref_index(pref, x);
15240       if (!codec)
15241          break;
15242       ast_cli(fd, "%s", ast_getformatname(codec));
15243       ast_cli(fd, ":%d", pref->framing[x]);
15244       if (x < 31 && ast_codec_pref_index(pref, x + 1))
15245          ast_cli(fd, ",");
15246    }
15247    if (!x)
15248       ast_cli(fd, "none");
15249 }
15250 
15251 /*! \brief Print domain mode to cli */
15252 static const char *domain_mode_to_text(const enum domain_mode mode)
15253 {
15254    switch (mode) {
15255    case SIP_DOMAIN_AUTO:
15256       return "[Automatic]";
15257    case SIP_DOMAIN_CONFIG:
15258       return "[Configured]";
15259    }
15260 
15261    return "";
15262 }
15263 
15264 /*! \brief CLI command to list local domains */
15265 static char *sip_show_domains(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15266 {
15267    struct domain *d;
15268 #define FORMAT "%-40.40s %-20.20s %-16.16s\n"
15269 
15270    switch (cmd) {
15271    case CLI_INIT:
15272       e->command = "sip show domains";
15273       e->usage =
15274          "Usage: sip show domains\n"
15275          "       Lists all configured SIP local domains.\n"
15276          "       Asterisk only responds to SIP messages to local domains.\n";
15277       return NULL;
15278    case CLI_GENERATE:
15279       return NULL;
15280    }
15281 
15282    if (AST_LIST_EMPTY(&domain_list)) {
15283       ast_cli(a->fd, "SIP Domain support not enabled.\n\n");
15284       return CLI_SUCCESS;
15285    } else {
15286       ast_cli(a->fd, FORMAT, "Our local SIP domains:", "Context", "Set by");
15287       AST_LIST_LOCK(&domain_list);
15288       AST_LIST_TRAVERSE(&domain_list, d, list)
15289          ast_cli(a->fd, FORMAT, d->domain, S_OR(d->context, "(default)"),
15290             domain_mode_to_text(d->mode));
15291       AST_LIST_UNLOCK(&domain_list);
15292       ast_cli(a->fd, "\n");
15293       return CLI_SUCCESS;
15294    }
15295 }
15296 #undef FORMAT
15297 
15298 static char mandescr_show_peer[] = 
15299 "Description: Show one SIP peer with details on current status.\n"
15300 "Variables: \n"
15301 "  Peer: <name>           The peer name you want to check.\n"
15302 "  ActionID: <id>   Optional action ID for this AMI transaction.\n";
15303 
15304 /*! \brief Show SIP peers in the manager API  */
15305 static int manager_sip_show_peer(struct mansession *s, const struct message *m)
15306 {
15307    const char *a[4];
15308    const char *peer;
15309 
15310    peer = astman_get_header(m, "Peer");
15311    if (ast_strlen_zero(peer)) {
15312       astman_send_error(s, m, "Peer: <name> missing.");
15313       return 0;
15314    }
15315    a[0] = "sip";
15316    a[1] = "show";
15317    a[2] = "peer";
15318    a[3] = peer;
15319 
15320    _sip_show_peer(1, -1, s, m, 4, a);
15321    astman_append(s, "\r\n\r\n" );
15322    return 0;
15323 }
15324 
15325 /*! \brief Show one peer in detail */
15326 static char *sip_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15327 {
15328    switch (cmd) {
15329    case CLI_INIT:
15330       e->command = "sip show peer";
15331       e->usage =
15332          "Usage: sip show peer <name> [load]\n"
15333          "       Shows all details on one SIP peer and the current status.\n"
15334          "       Option \"load\" forces lookup of peer in realtime storage.\n";
15335       return NULL;
15336    case CLI_GENERATE:
15337       return complete_sip_show_peer(a->line, a->word, a->pos, a->n);
15338    }
15339    return _sip_show_peer(0, a->fd, NULL, NULL, a->argc, (const char **) a->argv);
15340 }
15341 
15342 /*! \brief Send qualify message to peer from cli or manager. Mostly for debugging. */
15343 static char *_sip_qualify_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[])
15344 {
15345    struct sip_peer *peer;
15346    int load_realtime;
15347 
15348    if (argc < 4)
15349       return CLI_SHOWUSAGE;
15350 
15351    load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? TRUE : FALSE;
15352    if ((peer = find_peer(argv[3], NULL, load_realtime, FINDPEERS, FALSE, 0))) {
15353       sip_poke_peer(peer, 1);
15354       unref_peer(peer, "qualify: done with peer");
15355    } else if (type == 0) {
15356       ast_cli(fd, "Peer '%s' not found\n", argv[3]);
15357    } else {
15358       astman_send_error(s, m, "Peer not found");
15359    }
15360    return CLI_SUCCESS;
15361 }
15362 
15363 /*! \brief Qualify SIP peers in the manager API  */
15364 static int manager_sip_qualify_peer(struct mansession *s, const struct message *m)
15365 {
15366    const char *a[4];
15367    const char *peer;
15368 
15369    peer = astman_get_header(m, "Peer");
15370    if (ast_strlen_zero(peer)) {
15371       astman_send_error(s, m, "Peer: <name> missing.");
15372       return 0;
15373    }
15374    a[0] = "sip";
15375    a[1] = "qualify";
15376    a[2] = "peer";
15377    a[3] = peer;
15378 
15379    _sip_qualify_peer(1, -1, s, m, 4, a);
15380    astman_append(s, "\r\n\r\n" );
15381    return 0;
15382 }
15383 
15384 /*! \brief Send an OPTIONS packet to a SIP peer */
15385 static char *sip_qualify_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15386 {
15387    switch (cmd) {
15388    case CLI_INIT:
15389       e->command = "sip qualify peer";
15390       e->usage =
15391          "Usage: sip qualify peer <name> [load]\n"
15392          "       Requests a response from one SIP peer and the current status.\n"
15393          "       Option \"load\" forces lookup of peer in realtime storage.\n";
15394       return NULL;
15395    case CLI_GENERATE:
15396       return complete_sip_show_peer(a->line, a->word, a->pos, a->n);
15397    }
15398    return _sip_qualify_peer(0, a->fd, NULL, NULL, a->argc, (const char **) a->argv);
15399 }
15400 
15401 /*! \brief list peer mailboxes to CLI */
15402 static void peer_mailboxes_to_str(struct ast_str **mailbox_str, struct sip_peer *peer)
15403 {
15404    struct sip_mailbox *mailbox;
15405 
15406    AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
15407       ast_str_append(mailbox_str, 0, "%s%s%s%s",
15408          mailbox->mailbox,
15409          ast_strlen_zero(mailbox->context) ? "" : "@",
15410          S_OR(mailbox->context, ""),
15411          AST_LIST_NEXT(mailbox, entry) ? "," : "");
15412    }
15413 }
15414 
15415 static struct _map_x_s faxecmodes[] = {
15416    { SIP_PAGE2_T38SUPPORT_UDPTL,       "None"},
15417    { SIP_PAGE2_T38SUPPORT_UDPTL_FEC,      "FEC"},
15418    { SIP_PAGE2_T38SUPPORT_UDPTL_REDUNDANCY,  "Redundancy"},
15419    { -1,                NULL},
15420 };
15421 
15422 static const char *faxec2str(int faxec)
15423 {
15424    return map_x_s(faxecmodes, faxec, "Unknown");
15425 }
15426 
15427 /*! \brief Show one peer in detail (main function) */
15428 static char *_sip_show_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[])
15429 {
15430    char status[30] = "";
15431    char cbuf[256];
15432    struct sip_peer *peer;
15433    char codec_buf[512];
15434    struct ast_codec_pref *pref;
15435    struct ast_variable *v;
15436    struct sip_auth *auth;
15437    int x = 0, codec = 0, load_realtime;
15438    int realtimepeers;
15439 
15440    realtimepeers = ast_check_realtime("sippeers");
15441 
15442    if (argc < 4)
15443       return CLI_SHOWUSAGE;
15444 
15445    load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? TRUE : FALSE;
15446    peer = find_peer(argv[3], NULL, load_realtime, FINDPEERS, FALSE, 0);
15447 
15448    if (s) {    /* Manager */
15449       if (peer) {
15450          const char *id = astman_get_header(m, "ActionID");
15451 
15452          astman_append(s, "Response: Success\r\n");
15453          if (!ast_strlen_zero(id))
15454             astman_append(s, "ActionID: %s\r\n", id);
15455       } else {
15456          snprintf (cbuf, sizeof(cbuf), "Peer %s not found.", argv[3]);
15457          astman_send_error(s, m, cbuf);
15458          return CLI_SUCCESS;
15459       }
15460    }
15461    if (peer && type==0 ) { /* Normal listing */
15462       struct ast_str *mailbox_str = ast_str_alloca(512);
15463       ast_cli(fd, "\n\n");
15464       ast_cli(fd, "  * Name       : %s\n", peer->name);
15465       if (realtimepeers) { /* Realtime is enabled */
15466          ast_cli(fd, "  Realtime peer: %s\n", peer->is_realtime ? "Yes, cached" : "No");
15467       }
15468       ast_cli(fd, "  Secret       : %s\n", ast_strlen_zero(peer->secret)?"<Not set>":"<Set>");
15469       ast_cli(fd, "  MD5Secret    : %s\n", ast_strlen_zero(peer->md5secret)?"<Not set>":"<Set>");
15470       ast_cli(fd, "  Remote Secret: %s\n", ast_strlen_zero(peer->remotesecret)?"<Not set>":"<Set>");
15471       for (auth = peer->auth; auth; auth = auth->next) {
15472          ast_cli(fd, "  Realm-auth   : Realm %-15.15s User %-10.20s ", auth->realm, auth->username);
15473          ast_cli(fd, "%s\n", !ast_strlen_zero(auth->secret)?"<Secret set>":(!ast_strlen_zero(auth->md5secret)?"<MD5secret set>" : "<Not set>"));
15474       }
15475       ast_cli(fd, "  Context      : %s\n", peer->context);
15476       ast_cli(fd, "  Subscr.Cont. : %s\n", S_OR(peer->subscribecontext, "<Not set>") );
15477       ast_cli(fd, "  Language     : %s\n", peer->language);
15478       if (!ast_strlen_zero(peer->accountcode))
15479          ast_cli(fd, "  Accountcode  : %s\n", peer->accountcode);
15480       ast_cli(fd, "  AMA flags    : %s\n", ast_cdr_flags2str(peer->amaflags));
15481       ast_cli(fd, "  Transfer mode: %s\n", transfermode2str(peer->allowtransfer));
15482       ast_cli(fd, "  CallingPres  : %s\n", ast_describe_caller_presentation(peer->callingpres));
15483       if (!ast_strlen_zero(peer->fromuser))
15484          ast_cli(fd, "  FromUser     : %s\n", peer->fromuser);
15485       if (!ast_strlen_zero(peer->fromdomain))
15486          ast_cli(fd, "  FromDomain   : %s\n", peer->fromdomain);
15487       ast_cli(fd, "  Callgroup    : ");
15488       print_group(fd, peer->callgroup, 0);
15489       ast_cli(fd, "  Pickupgroup  : ");
15490       print_group(fd, peer->pickupgroup, 0);
15491       peer_mailboxes_to_str(&mailbox_str, peer);
15492       ast_cli(fd, "  Mailbox      : %s\n", mailbox_str->str);
15493       ast_cli(fd, "  VM Extension : %s\n", peer->vmexten);
15494       ast_cli(fd, "  LastMsgsSent : %d/%d\n", (peer->lastmsgssent & 0x7fff0000) >> 16, peer->lastmsgssent & 0xffff);
15495       ast_cli(fd, "  Call limit   : %d\n", peer->call_limit);
15496       if (peer->busy_level)
15497          ast_cli(fd, "  Busy level   : %d\n", peer->busy_level);
15498       ast_cli(fd, "  Dynamic      : %s\n", cli_yesno(peer->host_dynamic));
15499       ast_cli(fd, "  Callerid     : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, "<unspecified>"));
15500       ast_cli(fd, "  MaxCallBR    : %d kbps\n", peer->maxcallbitrate);
15501       ast_cli(fd, "  Expire       : %ld\n", ast_sched_when(sched, peer->expire));
15502       ast_cli(fd, "  Insecure     : %s\n", insecure2str(ast_test_flag(&peer->flags[0], SIP_INSECURE)));
15503       ast_cli(fd, "  Nat          : %s\n", nat2str(ast_test_flag(&peer->flags[0], SIP_NAT)));
15504       ast_cli(fd, "  ACL          : %s\n", cli_yesno(peer->ha != NULL));
15505       ast_cli(fd, "  T.38 support : %s\n", cli_yesno(ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)));
15506       ast_cli(fd, "  T.38 EC mode : %s\n", faxec2str(ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)));
15507       ast_cli(fd, "  T.38 MaxDtgrm: %d\n", peer->t38_maxdatagram);
15508       ast_cli(fd, "  DirectMedia  : %s\n", cli_yesno(ast_test_flag(&peer->flags[0], SIP_DIRECT_MEDIA)));
15509       ast_cli(fd, "  PromiscRedir : %s\n", cli_yesno(ast_test_flag(&peer->flags[0], SIP_PROMISCREDIR)));
15510       ast_cli(fd, "  User=Phone   : %s\n", cli_yesno(ast_test_flag(&peer->flags[0], SIP_USEREQPHONE)));
15511       ast_cli(fd, "  Video Support: %s\n", cli_yesno(ast_test_flag(&peer->flags[1], SIP_PAGE2_VIDEOSUPPORT)));
15512       ast_cli(fd, "  Text Support : %s\n", cli_yesno(ast_test_flag(&peer->flags[1], SIP_PAGE2_TEXTSUPPORT)));
15513       ast_cli(fd, "  Ign SDP ver  : %s\n", cli_yesno(ast_test_flag(&peer->flags[1], SIP_PAGE2_IGNORESDPVERSION)));
15514       ast_cli(fd, "  Trust RPID   : %s\n", cli_yesno(ast_test_flag(&peer->flags[0], SIP_TRUSTRPID)));
15515       ast_cli(fd, "  Send RPID    : %s\n", cli_yesno(ast_test_flag(&peer->flags[0], SIP_SENDRPID)));
15516       ast_cli(fd, "  Subscriptions: %s\n", cli_yesno(ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)));
15517       ast_cli(fd, "  Overlap dial : %s\n", cli_yesno(ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWOVERLAP)));
15518       if (peer->outboundproxy)
15519          ast_cli(fd, "  Outb. proxy  : %s %s\n", ast_strlen_zero(peer->outboundproxy->name) ? "<not set>" : peer->outboundproxy->name,
15520                      peer->outboundproxy->force ? "(forced)" : "");
15521 
15522       /* - is enumerated */
15523       ast_cli(fd, "  DTMFmode     : %s\n", dtmfmode2str(ast_test_flag(&peer->flags[0], SIP_DTMF)));
15524       ast_cli(fd, "  Timer T1     : %d\n", peer->timer_t1);
15525       ast_cli(fd, "  Timer B      : %d\n", peer->timer_b);
15526       ast_cli(fd, "  ToHost       : %s\n", peer->tohost);
15527       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));
15528       ast_cli(fd, "  Defaddr->IP  : %s Port %d\n", ast_inet_ntoa(peer->defaddr.sin_addr), ntohs(peer->defaddr.sin_port));
15529       ast_cli(fd, "  Prim.Transp. : %s\n", get_transport(peer->socket.type));
15530       ast_cli(fd, "  Allowed.Trsp : %s\n", get_transport_list(peer->transports)); 
15531       if (!ast_strlen_zero(global_regcontext))
15532          ast_cli(fd, "  Reg. exten   : %s\n", peer->regexten);
15533       ast_cli(fd, "  Def. Username: %s\n", peer->username);
15534       ast_cli(fd, "  SIP Options  : ");
15535       if (peer->sipoptions) {
15536          int lastoption = -1;
15537          for (x = 0 ; x < ARRAY_LEN(sip_options); x++) {
15538             if (sip_options[x].id != lastoption) {
15539                if (peer->sipoptions & sip_options[x].id)
15540                   ast_cli(fd, "%s ", sip_options[x].text);
15541                lastoption = x;
15542             }
15543          }
15544       } else
15545          ast_cli(fd, "(none)");
15546 
15547       ast_cli(fd, "\n");
15548       ast_cli(fd, "  Codecs       : ");
15549       ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
15550       ast_cli(fd, "%s\n", codec_buf);
15551       ast_cli(fd, "  Codec Order  : (");
15552       print_codec_to_cli(fd, &peer->prefs);
15553       ast_cli(fd, ")\n");
15554 
15555       ast_cli(fd, "  Auto-Framing :  %s \n", cli_yesno(peer->autoframing));
15556       ast_cli(fd, "  100 on REG   : %s\n", ast_test_flag(&peer->flags[1], SIP_PAGE2_REGISTERTRYING) ? "Yes" : "No");
15557       ast_cli(fd, "  Status       : ");
15558       peer_status(peer, status, sizeof(status));
15559       ast_cli(fd, "%s\n", status);
15560       ast_cli(fd, "  Useragent    : %s\n", peer->useragent);
15561       ast_cli(fd, "  Reg. Contact : %s\n", peer->fullcontact);
15562       ast_cli(fd, "  Qualify Freq : %d ms\n", peer->qualifyfreq);
15563       if (peer->chanvars) {
15564          ast_cli(fd, "  Variables    :\n");
15565          for (v = peer->chanvars ; v ; v = v->next)
15566             ast_cli(fd, "                 %s = %s\n", v->name, v->value);
15567       }
15568 
15569       ast_cli(fd, "  Sess-Timers  : %s\n", stmode2str(peer->stimer.st_mode_oper));
15570       ast_cli(fd, "  Sess-Refresh : %s\n", strefresher2str(peer->stimer.st_ref));
15571       ast_cli(fd, "  Sess-Expires : %d secs\n", peer->stimer.st_max_se);
15572       ast_cli(fd, "  Min-Sess     : %d secs\n", peer->stimer.st_min_se);
15573       ast_cli(fd, "  Parkinglot   : %s\n", peer->parkinglot);
15574       ast_cli(fd, "\n");
15575       peer = unref_peer(peer, "sip_show_peer: unref_peer: done with peer ptr");
15576    } else  if (peer && type == 1) { /* manager listing */
15577       char buffer[256];
15578       struct ast_str *mailbox_str = ast_str_alloca(512);
15579       astman_append(s, "Channeltype: SIP\r\n");
15580       astman_append(s, "ObjectName: %s\r\n", peer->name);
15581       astman_append(s, "ChanObjectType: peer\r\n");
15582       astman_append(s, "SecretExist: %s\r\n", ast_strlen_zero(peer->secret)?"N":"Y");
15583       astman_append(s, "RemoteSecretExist: %s\r\n", ast_strlen_zero(peer->remotesecret)?"N":"Y");
15584       astman_append(s, "MD5SecretExist: %s\r\n", ast_strlen_zero(peer->md5secret)?"N":"Y");
15585       astman_append(s, "Context: %s\r\n", peer->context);
15586       astman_append(s, "Language: %s\r\n", peer->language);
15587       if (!ast_strlen_zero(peer->accountcode))
15588          astman_append(s, "Accountcode: %s\r\n", peer->accountcode);
15589       astman_append(s, "AMAflags: %s\r\n", ast_cdr_flags2str(peer->amaflags));
15590       astman_append(s, "CID-CallingPres: %s\r\n", ast_describe_caller_presentation(peer->callingpres));
15591       if (!ast_strlen_zero(peer->fromuser))
15592          astman_append(s, "SIP-FromUser: %s\r\n", peer->fromuser);
15593       if (!ast_strlen_zero(peer->fromdomain))
15594          astman_append(s, "SIP-FromDomain: %s\r\n", peer->fromdomain);
15595       astman_append(s, "Callgroup: ");
15596       astman_append(s, "%s\r\n", ast_print_group(buffer, sizeof(buffer), peer->callgroup));
15597       astman_append(s, "Pickupgroup: ");
15598       astman_append(s, "%s\r\n", ast_print_group(buffer, sizeof(buffer), peer->pickupgroup));
15599       peer_mailboxes_to_str(&mailbox_str, peer);
15600       astman_append(s, "VoiceMailbox: %s\r\n", mailbox_str->str);
15601       astman_append(s, "TransferMode: %s\r\n", transfermode2str(peer->allowtransfer));
15602       astman_append(s, "LastMsgsSent: %d\r\n", peer->lastmsgssent);
15603       astman_append(s, "Call-limit: %d\r\n", peer->call_limit);
15604       astman_append(s, "Busy-level: %d\r\n", peer->busy_level);
15605       astman_append(s, "MaxCallBR: %d kbps\r\n", peer->maxcallbitrate);
15606       astman_append(s, "Dynamic: %s\r\n", peer->host_dynamic?"Y":"N");
15607       astman_append(s, "Callerid: %s\r\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, ""));
15608       astman_append(s, "RegExpire: %ld seconds\r\n", ast_sched_when(sched, peer->expire));
15609       astman_append(s, "SIP-AuthInsecure: %s\r\n", insecure2str(ast_test_flag(&peer->flags[0], SIP_INSECURE)));
15610       astman_append(s, "SIP-NatSupport: %s\r\n", nat2str(ast_test_flag(&peer->flags[0], SIP_NAT)));
15611       astman_append(s, "ACL: %s\r\n", (peer->ha?"Y":"N"));
15612       astman_append(s, "SIP-CanReinvite: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_DIRECT_MEDIA)?"Y":"N"));
15613       astman_append(s, "SIP-DirectMedia: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_DIRECT_MEDIA)?"Y":"N"));
15614       astman_append(s, "SIP-PromiscRedir: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_PROMISCREDIR)?"Y":"N"));
15615       astman_append(s, "SIP-UserPhone: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_USEREQPHONE)?"Y":"N"));
15616       astman_append(s, "SIP-VideoSupport: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_VIDEOSUPPORT)?"Y":"N"));
15617       astman_append(s, "SIP-TextSupport: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_TEXTSUPPORT)?"Y":"N"));
15618       astman_append(s, "SIP-T.38Support: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)?"Y":"N"));
15619       astman_append(s, "SIP-T.38EC: %s\r\n", faxec2str(ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)));
15620       astman_append(s, "SIP-T.38MaxDtgrm: %d\r\n", peer->t38_maxdatagram);
15621       astman_append(s, "SIP-Sess-Timers: %s\r\n", stmode2str(peer->stimer.st_mode_oper));
15622       astman_append(s, "SIP-Sess-Refresh: %s\r\n", strefresher2str(peer->stimer.st_ref));
15623       astman_append(s, "SIP-Sess-Expires: %d\r\n", peer->stimer.st_max_se);
15624       astman_append(s, "SIP-Sess-Min: %d\r\n", peer->stimer.st_min_se);
15625 
15626       /* - is enumerated */
15627       astman_append(s, "SIP-DTMFmode: %s\r\n", dtmfmode2str(ast_test_flag(&peer->flags[0], SIP_DTMF)));
15628       astman_append(s, "ToHost: %s\r\n", peer->tohost);
15629       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));
15630       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));
15631       astman_append(s, "Default-Username: %s\r\n", peer->username);
15632       if (!ast_strlen_zero(global_regcontext))
15633          astman_append(s, "RegExtension: %s\r\n", peer->regexten);
15634       astman_append(s, "Codecs: ");
15635       ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
15636       astman_append(s, "%s\r\n", codec_buf);
15637       astman_append(s, "CodecOrder: ");
15638       pref = &peer->prefs;
15639       for(x = 0; x < 32 ; x++) {
15640          codec = ast_codec_pref_index(pref, x);
15641          if (!codec)
15642             break;
15643          astman_append(s, "%s", ast_getformatname(codec));
15644          if (x < 31 && ast_codec_pref_index(pref, x+1))
15645             astman_append(s, ",");
15646       }
15647 
15648       astman_append(s, "\r\n");
15649       astman_append(s, "Status: ");
15650       peer_status(peer, status, sizeof(status));
15651       astman_append(s, "%s\r\n", status);
15652       astman_append(s, "SIP-Useragent: %s\r\n", peer->useragent);
15653       astman_append(s, "Reg-Contact: %s\r\n", peer->fullcontact);
15654       astman_append(s, "QualifyFreq: %d ms\r\n", peer->qualifyfreq);
15655       astman_append(s, "Parkinglot: %s\r\n", peer->parkinglot);
15656       if (peer->chanvars) {
15657          for (v = peer->chanvars ; v ; v = v->next) {
15658             astman_append(s, "ChanVariable: %s=%s\r\n", v->name, v->value);
15659          }
15660       }
15661 
15662       peer = unref_peer(peer, "sip_show_peer: unref_peer: done with peer");
15663 
15664    } else {
15665       ast_cli(fd, "Peer %s not found.\n", argv[3]);
15666       ast_cli(fd, "\n");
15667    }
15668 
15669    return CLI_SUCCESS;
15670 }
15671 
15672 /*! \brief Do completion on user name */
15673 static char *complete_sip_user(const char *word, int state)
15674 {
15675    char *result = NULL;
15676    int wordlen = strlen(word);
15677    int which = 0;
15678    struct ao2_iterator user_iter;
15679    struct sip_peer *user;
15680 
15681    user_iter = ao2_iterator_init(peers, 0);
15682    while ((user = ao2_iterator_next(&user_iter))) {
15683       ao2_lock(user);
15684       if (!(user->type & SIP_TYPE_USER)) {
15685          ao2_unlock(user);
15686          unref_peer(user, "complete sip user");
15687          continue;
15688       }
15689       /* locking of the object is not required because only the name and flags are being compared */
15690       if (!strncasecmp(word, user->name, wordlen) && ++which > state) {
15691          result = ast_strdup(user->name);
15692       }
15693       ao2_unlock(user);
15694       unref_peer(user, "complete sip user");
15695    }
15696    ao2_iterator_destroy(&user_iter);
15697    return result;
15698 }
15699 /*! \brief Support routine for 'sip show user' CLI */
15700 static char *complete_sip_show_user(const char *line, const char *word, int pos, int state)
15701 {
15702    if (pos == 3)
15703       return complete_sip_user(word, state);
15704 
15705    return NULL;
15706 }
15707 
15708 /*! \brief Show one user in detail */
15709 static char *sip_show_user(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15710 {
15711    char cbuf[256];
15712    struct sip_peer *user;
15713    struct ast_variable *v;
15714    int load_realtime;
15715 
15716    switch (cmd) {
15717    case CLI_INIT:
15718       e->command = "sip show user";
15719       e->usage =
15720          "Usage: sip show user <name> [load]\n"
15721          "       Shows all details on one SIP user and the current status.\n"
15722          "       Option \"load\" forces lookup of peer in realtime storage.\n";
15723       return NULL;
15724    case CLI_GENERATE:
15725       return complete_sip_show_user(a->line, a->word, a->pos, a->n);
15726    }
15727 
15728    if (a->argc < 4)
15729       return CLI_SHOWUSAGE;
15730 
15731    /* Load from realtime storage? */
15732    load_realtime = (a->argc == 5 && !strcmp(a->argv[4], "load")) ? TRUE : FALSE;
15733 
15734    if ((user = find_peer(a->argv[3], NULL, load_realtime, FINDUSERS, FALSE, 0))) {
15735       ao2_lock(user);
15736       ast_cli(a->fd, "\n\n");
15737       ast_cli(a->fd, "  * Name       : %s\n", user->name);
15738       ast_cli(a->fd, "  Secret       : %s\n", ast_strlen_zero(user->secret)?"<Not set>":"<Set>");
15739       ast_cli(a->fd, "  MD5Secret    : %s\n", ast_strlen_zero(user->md5secret)?"<Not set>":"<Set>");
15740       ast_cli(a->fd, "  Context      : %s\n", user->context);
15741       ast_cli(a->fd, "  Language     : %s\n", user->language);
15742       if (!ast_strlen_zero(user->accountcode))
15743          ast_cli(a->fd, "  Accountcode  : %s\n", user->accountcode);
15744       ast_cli(a->fd, "  AMA flags    : %s\n", ast_cdr_flags2str(user->amaflags));
15745       ast_cli(a->fd, "  Transfer mode: %s\n", transfermode2str(user->allowtransfer));
15746       ast_cli(a->fd, "  MaxCallBR    : %d kbps\n", user->maxcallbitrate);
15747       ast_cli(a->fd, "  CallingPres  : %s\n", ast_describe_caller_presentation(user->callingpres));
15748       ast_cli(a->fd, "  Call limit   : %d\n", user->call_limit);
15749       ast_cli(a->fd, "  Callgroup    : ");
15750       print_group(a->fd, user->callgroup, 0);
15751       ast_cli(a->fd, "  Pickupgroup  : ");
15752       print_group(a->fd, user->pickupgroup, 0);
15753       ast_cli(a->fd, "  Callerid     : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), user->cid_name, user->cid_num, "<unspecified>"));
15754       ast_cli(a->fd, "  ACL          : %s\n", cli_yesno(user->ha != NULL));
15755       ast_cli(a->fd, "  Sess-Timers  : %s\n", stmode2str(user->stimer.st_mode_oper));
15756       ast_cli(a->fd, "  Sess-Refresh : %s\n", strefresher2str(user->stimer.st_ref));
15757       ast_cli(a->fd, "  Sess-Expires : %d secs\n", user->stimer.st_max_se);
15758       ast_cli(a->fd, "  Sess-Min-SE  : %d secs\n", user->stimer.st_min_se);
15759 
15760       ast_cli(a->fd, "  Codec Order  : (");
15761       print_codec_to_cli(a->fd, &user->prefs);
15762       ast_cli(a->fd, ")\n");
15763 
15764       ast_cli(a->fd, "  Auto-Framing:  %s \n", cli_yesno(user->autoframing));
15765       if (user->chanvars) {
15766          ast_cli(a->fd, "  Variables    :\n");
15767          for (v = user->chanvars ; v ; v = v->next)
15768             ast_cli(a->fd, "                 %s = %s\n", v->name, v->value);
15769       }
15770 
15771       ast_cli(a->fd, "\n");
15772 
15773       ao2_unlock(user);
15774       unref_peer(user, "sip show user");
15775    } else {
15776       ast_cli(a->fd, "User %s not found.\n", a->argv[3]);
15777       ast_cli(a->fd, "\n");
15778    }
15779 
15780    return CLI_SUCCESS;
15781 }
15782 
15783 
15784 static char *sip_show_sched(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15785 {
15786    struct ast_str *cbuf;
15787    struct ast_cb_names cbnames = {9, { "retrans_pkt",
15788                                         "__sip_autodestruct",
15789                                         "expire_register",
15790                                         "auto_congest",
15791                                         "sip_reg_timeout",
15792                                         "sip_poke_peer_s",
15793                                         "sip_poke_noanswer",
15794                                         "sip_reregister",
15795                                         "sip_reinvite_retry"},
15796                            { retrans_pkt,
15797                                      __sip_autodestruct,
15798                                      expire_register,
15799                                      auto_congest,
15800                                      sip_reg_timeout,
15801                                      sip_poke_peer_s,
15802                                      sip_poke_noanswer,
15803                                      sip_reregister,
15804                                      sip_reinvite_retry}};
15805    
15806    switch (cmd) {
15807    case CLI_INIT:
15808       e->command = "sip show sched";
15809       e->usage =
15810          "Usage: sip show sched\n"
15811          "       Shows stats on what's in the sched queue at the moment\n";
15812       return NULL;
15813    case CLI_GENERATE:
15814       return NULL;
15815    }
15816 
15817    cbuf = ast_str_alloca(2048);
15818 
15819    ast_cli(a->fd, "\n");
15820    ast_sched_report(sched, &cbuf, &cbnames);
15821    ast_cli(a->fd, "%s", cbuf->str);
15822 
15823    return CLI_SUCCESS;
15824 }
15825 
15826 /*! \brief  Show SIP Registry (registrations with other SIP proxies */
15827 static char *sip_show_registry(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15828 {
15829 #define FORMAT2 "%-30.30s %-6.6s %-12.12s  %8.8s %-20.20s %-25.25s\n"
15830 #define FORMAT  "%-30.30s %-6.6s %-12.12s  %8d %-20.20s %-25.25s\n"
15831    char host[80];
15832    char tmpdat[256];
15833    struct ast_tm tm;
15834    int counter = 0;
15835 
15836    switch (cmd) {
15837    case CLI_INIT:
15838       e->command = "sip show registry";
15839       e->usage =
15840          "Usage: sip show registry\n"
15841          "       Lists all registration requests and status.\n";
15842       return NULL;
15843    case CLI_GENERATE:
15844       return NULL;
15845    }
15846 
15847    if (a->argc != 3)
15848       return CLI_SHOWUSAGE;
15849    ast_cli(a->fd, FORMAT2, "Host", "dnsmgr", "Username", "Refresh", "State", "Reg.Time");
15850    
15851    ASTOBJ_CONTAINER_TRAVERSE(&regl, 1, do {
15852       ASTOBJ_RDLOCK(iterator);
15853       snprintf(host, sizeof(host), "%s:%d", iterator->hostname, iterator->portno ? iterator->portno : STANDARD_SIP_PORT);
15854       if (iterator->regtime.tv_sec) {
15855          ast_localtime(&iterator->regtime, &tm, NULL);
15856          ast_strftime(tmpdat, sizeof(tmpdat), "%a, %d %b %Y %T", &tm);
15857       } else 
15858          tmpdat[0] = '\0';
15859       ast_cli(a->fd, FORMAT, host, (iterator->dnsmgr) ? "Y" : "N", iterator->username, iterator->refresh, regstate2str(iterator->regstate), tmpdat);
15860       ASTOBJ_UNLOCK(iterator);
15861       counter++;
15862    } while(0));
15863    ast_cli(a->fd, "%d SIP registrations.\n", counter);
15864    return CLI_SUCCESS;
15865 #undef FORMAT
15866 #undef FORMAT2
15867 }
15868 
15869 /*! \brief Unregister (force expiration) a SIP peer in the registry via CLI 
15870    \note This function does not tell the SIP device what's going on,
15871    so use it with great care.
15872 */
15873 static char *sip_unregister(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15874 {
15875    struct sip_peer *peer;
15876    int load_realtime = 0;
15877 
15878    switch (cmd) {
15879    case CLI_INIT:
15880       e->command = "sip unregister";
15881       e->usage =
15882          "Usage: sip unregister <peer>\n"
15883          "       Unregister (force expiration) a SIP peer from the registry\n";
15884       return NULL;
15885    case CLI_GENERATE:
15886       return complete_sip_unregister(a->line, a->word, a->pos, a->n);
15887    }
15888    
15889    if (a->argc != 3)
15890       return CLI_SHOWUSAGE;
15891    
15892    if ((peer = find_peer(a->argv[2], NULL, load_realtime, FINDPEERS, TRUE, 0))) {
15893       if (peer->expire > 0) {
15894          AST_SCHED_DEL_UNREF(sched, peer->expire,
15895             unref_peer(peer, "remove register expire ref"));
15896          expire_register(ref_peer(peer, "ref for expire_register"));
15897          ast_cli(a->fd, "Unregistered peer \'%s\'\n\n", a->argv[2]);
15898       } else {
15899          ast_cli(a->fd, "Peer %s not registered\n", a->argv[2]);
15900       }
15901       unref_peer(peer, "sip_unregister: unref_peer via sip_unregister: done with peer from find_peer call");
15902    } else {
15903       ast_cli(a->fd, "Peer unknown: \'%s\'. Not unregistered.\n", a->argv[2]);
15904    }
15905    
15906    return CLI_SUCCESS;
15907 }
15908 
15909 /*! \brief Callback for show_chanstats */
15910 static int show_chanstats_cb(void *__cur, void *__arg, int flags)
15911 {
15912 #define FORMAT2 "%-15.15s  %-11.11s  %-8.8s %-10.10s  %-10.10s (     %%) %-6.6s %-10.10s  %-10.10s (     %%) %-6.6s\n"
15913 #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"
15914    struct sip_pvt *cur = __cur;
15915    unsigned int rxcount, txcount, rxploss, txploss;
15916    char durbuf[10];
15917         int duration;
15918         int durh, durm, durs;
15919    struct ast_channel *c = cur->owner;
15920    struct __show_chan_arg *arg = __arg;
15921    int fd = arg->fd;
15922 
15923 
15924    if (cur->subscribed != NONE) /* Subscriptions */
15925       return 0;   /* don't care, we scan all channels */
15926 
15927    if (!cur->rtp) {
15928       if (sipdebug)
15929          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");
15930       return 0;   /* don't care, we scan all channels */
15931    }
15932    rxcount = ast_rtp_get_qosvalue(cur->rtp, AST_RTP_RXCOUNT);
15933    txcount = ast_rtp_get_qosvalue(cur->rtp, AST_RTP_TXCOUNT);
15934    rxploss = ast_rtp_get_qosvalue(cur->rtp, AST_RTP_RXPLOSS);
15935    txploss = ast_rtp_get_qosvalue(cur->rtp, AST_RTP_TXPLOSS);
15936 
15937    /* Find the duration of this channel */
15938    if (c && c->cdr && !ast_tvzero(c->cdr->start)) {
15939       duration = (int)(ast_tvdiff_ms(ast_tvnow(), c->cdr->start) / 1000);
15940       durh = duration / 3600;
15941       durm = (duration % 3600) / 60;
15942       durs = duration % 60;
15943       snprintf(durbuf, sizeof(durbuf), "%02d:%02d:%02d", durh, durm, durs);
15944    } else {
15945       durbuf[0] = '\0';
15946    }
15947    /* Print stats for every call with RTP */
15948    ast_cli(fd, FORMAT, 
15949       ast_inet_ntoa(cur->sa.sin_addr), 
15950       cur->callid, 
15951       durbuf,
15952       rxcount > (unsigned int) 100000 ? (unsigned int) (rxcount)/(unsigned int) 1000 : rxcount,
15953       rxcount > (unsigned int) 100000 ? "K":" ",
15954       rxploss,
15955       (rxcount + rxploss) > 0 ? (double) rxploss / (rxcount + rxploss) * 100 : 0,
15956       ast_rtp_get_qosvalue(cur->rtp, AST_RTP_RXJITTER),
15957       txcount > (unsigned int) 100000 ? (unsigned int) (txcount)/(unsigned int) 1000 : txcount,
15958       txcount > (unsigned int) 100000 ? "K":" ",
15959       txploss,
15960       txcount > 0 ? (double) txploss / txcount * 100 : 0,
15961       ast_rtp_get_qosvalue(cur->rtp, AST_RTP_TXJITTER)
15962    );
15963    arg->numchans++;
15964 
15965    return 0;   /* don't care, we scan all channels */
15966 }
15967 
15968 /*! \brief SIP show channelstats CLI (main function) */
15969 static char *sip_show_channelstats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15970 {
15971    struct __show_chan_arg arg = { .fd = a->fd, .numchans = 0 };
15972 
15973    switch (cmd) {
15974    case CLI_INIT:
15975       e->command = "sip show channelstats";
15976       e->usage =
15977          "Usage: sip show channelstats\n"
15978          "       Lists all currently active SIP channel's RTCP statistics.\n"
15979          "       Note that calls in the much optimized RTP P2P bridge mode will not show any packets here.";
15980       return NULL;
15981    case CLI_GENERATE:
15982       return NULL;
15983    }
15984 
15985    if (a->argc != 3)
15986       return CLI_SHOWUSAGE;
15987 
15988    ast_cli(a->fd, FORMAT2, "Peer", "Call ID", "Duration", "Recv: Pack", "Lost", "Jitter", "Send: Pack", "Lost", "Jitter");
15989    /* iterate on the container and invoke the callback on each item */
15990    ao2_t_callback(dialogs, OBJ_NODATA, show_chanstats_cb, &arg, "callback to sip show chanstats");
15991    ast_cli(a->fd, "%d active SIP channel%s\n", arg.numchans, (arg.numchans != 1) ? "s" : ""); 
15992    return CLI_SUCCESS;
15993 }
15994 #undef FORMAT
15995 #undef FORMAT2
15996 
15997 /*! \brief List global settings for the SIP channel */
15998 static char *sip_show_settings(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15999 {
16000    int realtimepeers;
16001    int realtimeregs;
16002    char codec_buf[SIPBUFSIZE];
16003    const char *msg;  /* temporary msg pointer */
16004 
16005    switch (cmd) {
16006    case CLI_INIT:
16007       e->command = "sip show settings";
16008       e->usage =
16009          "Usage: sip show settings\n"
16010          "       Provides detailed list of the configuration of the SIP channel.\n";
16011       return NULL;
16012    case CLI_GENERATE:
16013       return NULL;
16014    }
16015 
16016 
16017    realtimepeers = ast_check_realtime("sippeers");
16018    realtimeregs = ast_check_realtime("sipregs");
16019 
16020    if (a->argc != 3)
16021       return CLI_SHOWUSAGE;
16022    ast_cli(a->fd, "\n\nGlobal Settings:\n");
16023    ast_cli(a->fd, "----------------\n");
16024    ast_cli(a->fd, "  UDP SIP Port:           %d\n", ntohs(bindaddr.sin_port));
16025    ast_cli(a->fd, "  UDP Bindaddress:        %s\n", ast_inet_ntoa(bindaddr.sin_addr));
16026    ast_cli(a->fd, "  TCP SIP Port:           ");
16027    if (sip_tcp_desc.local_address.sin_family == AF_INET) {
16028       ast_cli(a->fd, "%d\n", ntohs(sip_tcp_desc.local_address.sin_port));
16029       ast_cli(a->fd, "  TCP Bindaddress:        %s\n", ast_inet_ntoa(sip_tcp_desc.local_address.sin_addr));
16030    } else {
16031       ast_cli(a->fd, "Disabled\n");
16032    }
16033    ast_cli(a->fd, "  TLS SIP Port:           ");
16034    if (default_tls_cfg.enabled != FALSE) {
16035       ast_cli(a->fd, "%d\n", ntohs(sip_tls_desc.local_address.sin_port));
16036       ast_cli(a->fd, "  TLS Bindaddress:        %s\n", ast_inet_ntoa(sip_tls_desc.local_address.sin_addr));
16037    } else {
16038       ast_cli(a->fd, "Disabled\n");
16039    }
16040    ast_cli(a->fd, "  Videosupport:           %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_VIDEOSUPPORT)));
16041    ast_cli(a->fd, "  Textsupport:            %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_TEXTSUPPORT)));
16042    ast_cli(a->fd, "  Ignore SDP sess. ver.:  %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_IGNORESDPVERSION)));
16043    ast_cli(a->fd, "  AutoCreate Peer:        %s\n", cli_yesno(sip_cfg.autocreatepeer));
16044    ast_cli(a->fd, "  Match Auth Username:    %s\n", cli_yesno(global_match_auth_username));
16045    ast_cli(a->fd, "  Allow unknown access:   %s\n", cli_yesno(sip_cfg.allowguest));
16046    ast_cli(a->fd, "  Allow subscriptions:    %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)));
16047    ast_cli(a->fd, "  Allow overlap dialing:  %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP)));
16048    ast_cli(a->fd, "  Allow promsic. redir:   %s\n", cli_yesno(ast_test_flag(&global_flags[0], SIP_PROMISCREDIR)));
16049    ast_cli(a->fd, "  Enable call counters:   %s\n", cli_yesno(global_callcounter));
16050    ast_cli(a->fd, "  SIP domain support:     %s\n", cli_yesno(!AST_LIST_EMPTY(&domain_list)));
16051    ast_cli(a->fd, "  Realm. auth:            %s\n", cli_yesno(authl != NULL));
16052    ast_cli(a->fd, "  Our auth realm          %s\n", sip_cfg.realm);
16053    ast_cli(a->fd, "  Call to non-local dom.: %s\n", cli_yesno(sip_cfg.allow_external_domains));
16054    ast_cli(a->fd, "  URI user is phone no:   %s\n", cli_yesno(ast_test_flag(&global_flags[0], SIP_USEREQPHONE)));
16055    ast_cli(a->fd, "  Always auth rejects:    %s\n", cli_yesno(sip_cfg.alwaysauthreject));
16056    ast_cli(a->fd, "  Direct RTP setup:       %s\n", cli_yesno(sip_cfg.directrtpsetup));
16057    ast_cli(a->fd, "  User Agent:             %s\n", global_useragent);
16058    ast_cli(a->fd, "  SDP Session Name:       %s\n", ast_strlen_zero(global_sdpsession) ? "-" : global_sdpsession);
16059    ast_cli(a->fd, "  SDP Owner Name:         %s\n", ast_strlen_zero(global_sdpowner) ? "-" : global_sdpowner);
16060    ast_cli(a->fd, "  Reg. context:           %s\n", S_OR(global_regcontext, "(not set)"));
16061    ast_cli(a->fd, "  Regexten on Qualify:    %s\n", cli_yesno(sip_cfg.regextenonqualify));
16062    ast_cli(a->fd, "  Caller ID:              %s\n", default_callerid);
16063    ast_cli(a->fd, "  From: Domain:           %s\n", default_fromdomain);
16064    ast_cli(a->fd, "  Record SIP history:     %s\n", recordhistory ? "On" : "Off");
16065    ast_cli(a->fd, "  Call Events:            %s\n", sip_cfg.callevents ? "On" : "Off");
16066    ast_cli(a->fd, "  Auth. Failure Events:   %s\n", global_authfailureevents ? "On" : "Off");
16067 
16068    ast_cli(a->fd, "  T.38 support:           %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_T38SUPPORT)));
16069    ast_cli(a->fd, "  T.38 EC mode:           %s\n", faxec2str(ast_test_flag(&global_flags[1], SIP_PAGE2_T38SUPPORT)));
16070    ast_cli(a->fd, "  T.38 MaxDtgrm:          %d\n", global_t38_maxdatagram);
16071 
16072    if (!realtimepeers && !realtimeregs)
16073       ast_cli(a->fd, "  SIP realtime:           Disabled\n" );
16074    else
16075       ast_cli(a->fd, "  SIP realtime:           Enabled\n" );
16076    ast_cli(a->fd, "  Qualify Freq :          %d ms\n", global_qualifyfreq);
16077    ast_cli(a->fd, "\nNetwork QoS Settings:\n");
16078    ast_cli(a->fd, "---------------------------\n");
16079    ast_cli(a->fd, "  IP ToS SIP:             %s\n", ast_tos2str(global_tos_sip));
16080    ast_cli(a->fd, "  IP ToS RTP audio:       %s\n", ast_tos2str(global_tos_audio));
16081    ast_cli(a->fd, "  IP ToS RTP video:       %s\n", ast_tos2str(global_tos_video));
16082    ast_cli(a->fd, "  IP ToS RTP text:        %s\n", ast_tos2str(global_tos_text));
16083    ast_cli(a->fd, "  802.1p CoS SIP:         %d\n", global_cos_sip);
16084    ast_cli(a->fd, "  802.1p CoS RTP audio:   %d\n", global_cos_audio);
16085    ast_cli(a->fd, "  802.1p CoS RTP video:   %d\n", global_cos_video);
16086    ast_cli(a->fd, "  802.1p CoS RTP text:    %d\n", global_cos_text);
16087    ast_cli(a->fd, "  Jitterbuffer enabled:   %s\n", cli_yesno(ast_test_flag(&global_jbconf, AST_JB_ENABLED)));
16088    ast_cli(a->fd, "  Jitterbuffer forced:    %s\n", cli_yesno(ast_test_flag(&global_jbconf, AST_JB_FORCED)));
16089    ast_cli(a->fd, "  Jitterbuffer max size:  %ld\n", global_jbconf.max_size);
16090    ast_cli(a->fd, "  Jitterbuffer resync:    %ld\n", global_jbconf.resync_threshold);
16091    ast_cli(a->fd, "  Jitterbuffer impl:      %s\n", global_jbconf.impl);
16092    ast_cli(a->fd, "  Jitterbuffer log:       %s\n", cli_yesno(ast_test_flag(&global_jbconf, AST_JB_LOG)));
16093 
16094    ast_cli(a->fd, "\nNetwork Settings:\n");
16095    ast_cli(a->fd, "---------------------------\n");
16096    /* determine if/how SIP address can be remapped */
16097    if (localaddr == NULL)
16098       msg = "Disabled, no localnet list";
16099    else if (externip.sin_addr.s_addr == 0)
16100       msg = "Disabled, externip is 0.0.0.0";
16101    else if (stunaddr.sin_addr.s_addr != 0)
16102       msg = "Enabled using STUN";
16103    else if (!ast_strlen_zero(externhost))
16104       msg = "Enabled using externhost";
16105    else
16106       msg = "Enabled using externip";
16107    ast_cli(a->fd, "  SIP address remapping:  %s\n", msg);
16108    ast_cli(a->fd, "  Externhost:             %s\n", S_OR(externhost, "<none>"));
16109    ast_cli(a->fd, "  Externip:               %s:%d\n", ast_inet_ntoa(externip.sin_addr), ntohs(externip.sin_port));
16110    ast_cli(a->fd, "  Externrefresh:          %d\n", externrefresh);
16111    ast_cli(a->fd, "  Internal IP:            %s:%d\n", ast_inet_ntoa(internip.sin_addr), ntohs(internip.sin_port));
16112    {
16113       struct ast_ha *d;
16114       const char *prefix = "Localnet:";
16115       char buf[INET_ADDRSTRLEN]; /* need to print two addresses */
16116 
16117       for (d = localaddr; d ; prefix = "", d = d->next) {
16118          ast_cli(a->fd, "  %-24s%s/%s\n",
16119              prefix, ast_inet_ntoa(d->netaddr),
16120              inet_ntop(AF_INET, &d->netmask, buf, sizeof(buf)) );
16121       }
16122    }
16123    ast_cli(a->fd, "  STUN server:            %s:%d\n", ast_inet_ntoa(stunaddr.sin_addr), ntohs(stunaddr.sin_port));
16124  
16125    ast_cli(a->fd, "\nGlobal Signalling Settings:\n");
16126    ast_cli(a->fd, "---------------------------\n");
16127    ast_cli(a->fd, "  Codecs:                 ");
16128    ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, global_capability);
16129    ast_cli(a->fd, "%s\n", codec_buf);
16130    ast_cli(a->fd, "  Codec Order:            ");
16131    print_codec_to_cli(a->fd, &default_prefs);
16132    ast_cli(a->fd, "\n");
16133    ast_cli(a->fd, "  Relax DTMF:             %s\n", cli_yesno(global_relaxdtmf));
16134    ast_cli(a->fd, "  RFC2833 Compensation:   %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_RFC2833_COMPENSATE)));
16135    ast_cli(a->fd, "  Compact SIP headers:    %s\n", cli_yesno(sip_cfg.compactheaders));
16136    ast_cli(a->fd, "  RTP Keepalive:          %d %s\n", global_rtpkeepalive, global_rtpkeepalive ? "" : "(Disabled)" );
16137    ast_cli(a->fd, "  RTP Timeout:            %d %s\n", global_rtptimeout, global_rtptimeout ? "" : "(Disabled)" );
16138    ast_cli(a->fd, "  RTP Hold Timeout:       %d %s\n", global_rtpholdtimeout, global_rtpholdtimeout ? "" : "(Disabled)");
16139    ast_cli(a->fd, "  MWI NOTIFY mime type:   %s\n", default_notifymime);
16140    ast_cli(a->fd, "  DNS SRV lookup:         %s\n", cli_yesno(sip_cfg.srvlookup));
16141    ast_cli(a->fd, "  Pedantic SIP support:   %s\n", cli_yesno(sip_cfg.pedanticsipchecking));
16142    ast_cli(a->fd, "  Reg. min duration       %d secs\n", min_expiry);
16143    ast_cli(a->fd, "  Reg. max duration:      %d secs\n", max_expiry);
16144    ast_cli(a->fd, "  Reg. default duration:  %d secs\n", default_expiry);
16145    ast_cli(a->fd, "  Outbound reg. timeout:  %d secs\n", global_reg_timeout);
16146    ast_cli(a->fd, "  Outbound reg. attempts: %d\n", global_regattempts_max);
16147    ast_cli(a->fd, "  Notify ringing state:   %s\n", cli_yesno(sip_cfg.notifyringing));
16148    if (sip_cfg.notifyringing) {
16149       ast_cli(a->fd, "    Include CID:          %s%s\n",
16150             cli_yesno(sip_cfg.notifycid),
16151             sip_cfg.notifycid == IGNORE_CONTEXT ? " (Ignoring context)" : "");
16152    }
16153    ast_cli(a->fd, "  Notify hold state:      %s\n", cli_yesno(sip_cfg.notifyhold));
16154    ast_cli(a->fd, "  SIP Transfer mode:      %s\n", transfermode2str(sip_cfg.allowtransfer));
16155    ast_cli(a->fd, "  Max Call Bitrate:       %d kbps\n", default_maxcallbitrate);
16156    ast_cli(a->fd, "  Auto-Framing:           %s\n", cli_yesno(global_autoframing));
16157    ast_cli(a->fd, "  Outb. proxy:            %s %s\n", ast_strlen_zero(sip_cfg.outboundproxy.name) ? "<not set>" : sip_cfg.outboundproxy.name,
16158                      sip_cfg.outboundproxy.force ? "(forced)" : "");
16159    ast_cli(a->fd, "  Session Timers:         %s\n", stmode2str(global_st_mode));
16160    ast_cli(a->fd, "  Session Refresher:      %s\n", strefresher2str (global_st_refresher));
16161    ast_cli(a->fd, "  Session Expires:        %d secs\n", global_max_se);
16162    ast_cli(a->fd, "  Session Min-SE:         %d secs\n", global_min_se);
16163    ast_cli(a->fd, "  Timer T1:               %d\n", global_t1);
16164    ast_cli(a->fd, "  Timer T1 minimum:       %d\n", global_t1min);
16165    ast_cli(a->fd, "  Timer B:                %d\n", global_timer_b);
16166    ast_cli(a->fd, "  No premature media:     %s\n", global_prematuremediafilter ? "Yes" : "No");
16167 
16168    ast_cli(a->fd, "\nDefault Settings:\n");
16169    ast_cli(a->fd, "-----------------\n");
16170    ast_cli(a->fd, "  Allowed transports:     %s\n", get_transport_list(default_transports)); 
16171    ast_cli(a->fd, "  Outbound transport:    %s\n", get_transport(default_primary_transport));
16172    ast_cli(a->fd, "  Context:                %s\n", sip_cfg.default_context);
16173    ast_cli(a->fd, "  Nat:                    %s\n", nat2str(ast_test_flag(&global_flags[0], SIP_NAT)));
16174    ast_cli(a->fd, "  DTMF:                   %s\n", dtmfmode2str(ast_test_flag(&global_flags[0], SIP_DTMF)));
16175    ast_cli(a->fd, "  Qualify:                %d\n", default_qualify);
16176    ast_cli(a->fd, "  Use ClientCode:         %s\n", cli_yesno(ast_test_flag(&global_flags[0], SIP_USECLIENTCODE)));
16177    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" );
16178    ast_cli(a->fd, "  Language:               %s\n", default_language);
16179    ast_cli(a->fd, "  MOH Interpret:          %s\n", default_mohinterpret);
16180    ast_cli(a->fd, "  MOH Suggest:            %s\n", default_mohsuggest);
16181    ast_cli(a->fd, "  Voice Mail Extension:   %s\n", default_vmexten);
16182 
16183    
16184    if (realtimepeers || realtimeregs) {
16185       ast_cli(a->fd, "\nRealtime SIP Settings:\n");
16186       ast_cli(a->fd, "----------------------\n");
16187       ast_cli(a->fd, "  Realtime Peers:         %s\n", cli_yesno(realtimepeers));
16188       ast_cli(a->fd, "  Realtime Regs:          %s\n", cli_yesno(realtimeregs));
16189       ast_cli(a->fd, "  Cache Friends:          %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)));
16190       ast_cli(a->fd, "  Update:                 %s\n", cli_yesno(sip_cfg.peer_rtupdate));
16191       ast_cli(a->fd, "  Ignore Reg. Expire:     %s\n", cli_yesno(sip_cfg.ignore_regexpire));
16192       ast_cli(a->fd, "  Save sys. name:         %s\n", cli_yesno(sip_cfg.rtsave_sysname));
16193       ast_cli(a->fd, "  Auto Clear:             %d\n", sip_cfg.rtautoclear);
16194    }
16195    ast_cli(a->fd, "\n----\n");
16196    return CLI_SUCCESS;
16197 }
16198 
16199 static char *sip_show_mwi(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16200 {
16201 #define FORMAT  "%-30.30s  %-12.12s  %-10.10s  %-10.10s\n"
16202    char host[80];
16203    
16204    switch (cmd) {
16205    case CLI_INIT:
16206       e->command = "sip show mwi";
16207       e->usage =
16208          "Usage: sip show mwi\n"
16209          "       Provides a list of MWI subscriptions and status.\n";
16210       return NULL;
16211    case CLI_GENERATE:
16212       return NULL;
16213    }
16214    
16215    ast_cli(a->fd, FORMAT, "Host", "Username", "Mailbox", "Subscribed");
16216    
16217    ASTOBJ_CONTAINER_TRAVERSE(&submwil, 1, do {
16218       ASTOBJ_RDLOCK(iterator);
16219       snprintf(host, sizeof(host), "%s:%d", iterator->hostname, iterator->portno ? iterator->portno : STANDARD_SIP_PORT);
16220       ast_cli(a->fd, FORMAT, host, iterator->username, iterator->mailbox, iterator->subscribed ? "Yes" : "No");
16221       ASTOBJ_UNLOCK(iterator);
16222    } while(0));
16223 
16224    return CLI_SUCCESS;
16225 #undef FORMAT
16226 }
16227 
16228 
16229 /*! \brief Show subscription type in string format */
16230 static const char *subscription_type2str(enum subscriptiontype subtype)
16231 {
16232    int i;
16233 
16234    for (i = 1; i < ARRAY_LEN(subscription_types); i++) {
16235       if (subscription_types[i].type == subtype) {
16236          return subscription_types[i].text;
16237       }
16238    }
16239    return subscription_types[0].text;
16240 }
16241 
16242 /*! \brief Find subscription type in array */
16243 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype)
16244 {
16245    int i;
16246 
16247    for (i = 1; i < ARRAY_LEN(subscription_types); i++) {
16248       if (subscription_types[i].type == subtype) {
16249          return &subscription_types[i];
16250       }
16251    }
16252    return &subscription_types[0];
16253 }
16254 
16255 /*
16256  * We try to structure all functions that loop on data structures as
16257  * a handler for individual entries, and a mainloop that iterates
16258  * on the main data structure. This way, moving the code to containers
16259  * that support iteration through callbacks will be a lot easier.
16260  */
16261 
16262 #define FORMAT4 "%-15.15s  %-15.15s  %-15.15s  %-15.15s  %-13.13s  %-15.15s %-10.10s %-6.6d\n"
16263 #define FORMAT3 "%-15.15s  %-15.15s  %-15.15s  %-15.15s  %-13.13s  %-15.15s %-10.10s %-6.6s\n"
16264 #define FORMAT2 "%-15.15s  %-15.15s  %-15.15s  %-15.15s  %-7.7s  %-15.15s %-6.6s\n"
16265 #define FORMAT  "%-15.15s  %-15.15s  %-15.15s  %-15.15s  %-3.3s %-3.3s  %-15.15s %-10.10s\n"
16266 
16267 /*! \brief callback for show channel|subscription */
16268 static int show_channels_cb(void *__cur, void *__arg, int flags)
16269 {
16270    struct sip_pvt *cur = __cur;
16271    struct __show_chan_arg *arg = __arg;
16272    const struct sockaddr_in *dst = sip_real_dst(cur);
16273    
16274    /* XXX indentation preserved to reduce diff. Will be fixed later */
16275    if (cur->subscribed == NONE && !arg->subscriptions) {
16276       /* set if SIP transfer in progress */
16277       const char *referstatus = cur->refer ? referstatus2str(cur->refer->status) : "";
16278       char formatbuf[SIPBUFSIZE/2];
16279       
16280       ast_cli(arg->fd, FORMAT, ast_inet_ntoa(dst->sin_addr), 
16281             S_OR(cur->username, S_OR(cur->cid_num, "(None)")),
16282             cur->callid, 
16283             ast_getformatname_multiple(formatbuf, sizeof(formatbuf), cur->owner ? cur->owner->nativeformats : 0),
16284             cli_yesno(ast_test_flag(&cur->flags[1], SIP_PAGE2_CALL_ONHOLD)),
16285             cur->needdestroy ? "(d)" : "",
16286             cur->lastmsg ,
16287             referstatus
16288          );
16289       arg->numchans++;
16290    }
16291    if (cur->subscribed != NONE && arg->subscriptions) {
16292       struct ast_str *mailbox_str = ast_str_alloca(512);
16293       if (cur->subscribed == MWI_NOTIFICATION && cur->relatedpeer)
16294          peer_mailboxes_to_str(&mailbox_str, cur->relatedpeer);
16295       ast_cli(arg->fd, FORMAT4, ast_inet_ntoa(dst->sin_addr),
16296             S_OR(cur->username, S_OR(cur->cid_num, "(None)")), 
16297                cur->callid,
16298             /* the 'complete' exten/context is hidden in the refer_to field for subscriptions */
16299             cur->subscribed == MWI_NOTIFICATION ? "--" : cur->subscribeuri,
16300             cur->subscribed == MWI_NOTIFICATION ? "<none>" : ast_extension_state2str(cur->laststate), 
16301             subscription_type2str(cur->subscribed),
16302             cur->subscribed == MWI_NOTIFICATION ? S_OR(mailbox_str->str, "<none>") : "<none>",
16303             cur->expiry
16304          );
16305       arg->numchans++;
16306    }
16307    return 0;   /* don't care, we scan all channels */
16308 }
16309 
16310 /*! \brief CLI for show channels or subscriptions.
16311  * This is a new-style CLI handler so a single function contains
16312  * the prototype for the function, the 'generator' to produce multiple
16313  * entries in case it is required, and the actual handler for the command.
16314  */
16315 static char *sip_show_channels(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16316 {
16317    struct __show_chan_arg arg = { .fd = a->fd, .numchans = 0 };
16318 
16319 
16320    if (cmd == CLI_INIT) {
16321       e->command = "sip show {channels|subscriptions}";
16322       e->usage =
16323          "Usage: sip show channels\n"
16324          "       Lists all currently active SIP calls (dialogs).\n"
16325          "Usage: sip show subscriptions\n"
16326          "       Lists active SIP subscriptions.\n";
16327       return NULL;
16328    } else if (cmd == CLI_GENERATE)
16329       return NULL;
16330 
16331    if (a->argc != e->args)
16332       return CLI_SHOWUSAGE;
16333    arg.subscriptions = !strcasecmp(a->argv[e->args - 1], "subscriptions");
16334    if (!arg.subscriptions)
16335       ast_cli(arg.fd, FORMAT2, "Peer", "User/ANR", "Call ID", "Format", "Hold", "Last Message", "Expiry");
16336    else
16337       ast_cli(arg.fd, FORMAT3, "Peer", "User", "Call ID", "Extension", "Last state", "Type", "Mailbox", "Expiry");
16338 
16339    /* iterate on the container and invoke the callback on each item */
16340    ao2_t_callback(dialogs, OBJ_NODATA, show_channels_cb, &arg, "callback to show channels");
16341    
16342    /* print summary information */
16343    ast_cli(arg.fd, "%d active SIP %s%s\n", arg.numchans,
16344       (arg.subscriptions ? "subscription" : "dialog"),
16345       ESS(arg.numchans));  /* ESS(n) returns an "s" if n>1 */
16346    return CLI_SUCCESS;
16347 #undef FORMAT
16348 #undef FORMAT2
16349 #undef FORMAT3
16350 }
16351 
16352 /*! \brief Support routine for 'sip show channel' and 'sip show history' CLI
16353  * This is in charge of generating all strings that match a prefix in the
16354  * given position. As many functions of this kind, each invokation has
16355  * O(state) time complexity so be careful in using it.
16356  */
16357 static char *complete_sipch(const char *line, const char *word, int pos, int state)
16358 {
16359    int which=0;
16360    struct sip_pvt *cur;
16361    char *c = NULL;
16362    int wordlen = strlen(word);
16363    struct ao2_iterator i;
16364 
16365    if (pos != 3) {
16366       return NULL;
16367    }
16368 
16369    i = ao2_iterator_init(dialogs, 0);
16370    while ((cur = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
16371       sip_pvt_lock(cur);
16372       if (!strncasecmp(word, cur->callid, wordlen) && ++which > state) {
16373          c = ast_strdup(cur->callid);
16374          sip_pvt_unlock(cur);
16375          dialog_unref(cur, "drop ref in iterator loop break");
16376          break;
16377       }
16378       sip_pvt_unlock(cur);
16379       dialog_unref(cur, "drop ref in iterator loop");
16380    }
16381    ao2_iterator_destroy(&i);
16382    return c;
16383 }
16384 
16385 
16386 /*! \brief Do completion on peer name */
16387 static char *complete_sip_peer(const char *word, int state, int flags2)
16388 {
16389    char *result = NULL;
16390    int wordlen = strlen(word);
16391    int which = 0;
16392    struct ao2_iterator i = ao2_iterator_init(peers, 0);
16393    struct sip_peer *peer;
16394 
16395    while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
16396       /* locking of the object is not required because only the name and flags are being compared */
16397       if (!strncasecmp(word, peer->name, wordlen) &&
16398             (!flags2 || ast_test_flag(&peer->flags[1], flags2)) &&
16399             ++which > state)
16400          result = ast_strdup(peer->name);
16401       unref_peer(peer, "toss iterator peer ptr before break");
16402       if (result) {
16403          break;
16404       }
16405    }
16406    ao2_iterator_destroy(&i);
16407    return result;
16408 }
16409 
16410 /*! \brief Do completion on registered peer name */
16411 static char *complete_sip_registered_peer(const char *word, int state, int flags2)
16412 {
16413        char *result = NULL;
16414        int wordlen = strlen(word);
16415        int which = 0;
16416        struct ao2_iterator i;
16417        struct sip_peer *peer;
16418        
16419        i = ao2_iterator_init(peers, 0);
16420        while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
16421           if (!strncasecmp(word, peer->name, wordlen) &&
16422          (!flags2 || ast_test_flag(&peer->flags[1], flags2)) &&
16423          ++which > state && peer->expire > 0)
16424              result = ast_strdup(peer->name);
16425           if (result) {
16426              unref_peer(peer, "toss iterator peer ptr before break");
16427              break;
16428           }
16429           unref_peer(peer, "toss iterator peer ptr");
16430        }
16431        ao2_iterator_destroy(&i);
16432        return result;
16433 }
16434 
16435 /*! \brief Support routine for 'sip show history' CLI */
16436 static char *complete_sip_show_history(const char *line, const char *word, int pos, int state)
16437 {
16438    if (pos == 3)
16439       return complete_sipch(line, word, pos, state);
16440 
16441    return NULL;
16442 }
16443 
16444 /*! \brief Support routine for 'sip show peer' CLI */
16445 static char *complete_sip_show_peer(const char *line, const char *word, int pos, int state)
16446 {
16447    if (pos == 3) {
16448       return complete_sip_peer(word, state, 0);
16449    }
16450 
16451    return NULL;
16452 }
16453 
16454 /*! \brief Support routine for 'sip unregister' CLI */
16455 static char *complete_sip_unregister(const char *line, const char *word, int pos, int state)
16456 {
16457        if (pos == 2)
16458                return complete_sip_registered_peer(word, state, 0);
16459 
16460        return NULL;
16461 }
16462 
16463 /*! \brief Support routine for 'sip notify' CLI */
16464 static char *complete_sipnotify(const char *line, const char *word, int pos, int state)
16465 {
16466    char *c = NULL;
16467 
16468    if (pos == 2) {
16469       int which = 0;
16470       char *cat = NULL;
16471       int wordlen = strlen(word);
16472 
16473       /* do completion for notify type */
16474 
16475       if (!notify_types)
16476          return NULL;
16477       
16478       while ( (cat = ast_category_browse(notify_types, cat)) ) {
16479          if (!strncasecmp(word, cat, wordlen) && ++which > state) {
16480             c = ast_strdup(cat);
16481             break;
16482          }
16483       }
16484       return c;
16485    }
16486 
16487    if (pos > 2)
16488       return complete_sip_peer(word, state, 0);
16489 
16490    return NULL;
16491 }
16492 
16493 /*! \brief Show details of one active dialog */
16494 static char *sip_show_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16495 {
16496    struct sip_pvt *cur;
16497    size_t len;
16498    int found = 0;
16499    struct ao2_iterator i;
16500 
16501    switch (cmd) {
16502    case CLI_INIT:
16503       e->command = "sip show channel";
16504       e->usage =
16505          "Usage: sip show channel <call-id>\n"
16506          "       Provides detailed status on a given SIP dialog (identified by SIP call-id).\n";
16507       return NULL;
16508    case CLI_GENERATE:
16509       return complete_sipch(a->line, a->word, a->pos, a->n);
16510    }
16511 
16512    if (a->argc != 4)
16513       return CLI_SHOWUSAGE;
16514    len = strlen(a->argv[3]);
16515    
16516    i = ao2_iterator_init(dialogs, 0);
16517    while ((cur = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
16518       sip_pvt_lock(cur);
16519 
16520       if (!strncasecmp(cur->callid, a->argv[3], len)) {
16521          char formatbuf[SIPBUFSIZE/2];
16522          ast_cli(a->fd, "\n");
16523          if (cur->subscribed != NONE)
16524             ast_cli(a->fd, "  * Subscription (type: %s)\n", subscription_type2str(cur->subscribed));
16525          else
16526             ast_cli(a->fd, "  * SIP Call\n");
16527          ast_cli(a->fd, "  Curr. trans. direction:  %s\n", ast_test_flag(&cur->flags[0], SIP_OUTGOING) ? "Outgoing" : "Incoming");
16528          ast_cli(a->fd, "  Call-ID:                %s\n", cur->callid);
16529          ast_cli(a->fd, "  Owner channel ID:       %s\n", cur->owner ? cur->owner->name : "<none>");
16530          ast_cli(a->fd, "  Our Codec Capability:   %d\n", cur->capability);
16531          ast_cli(a->fd, "  Non-Codec Capability (DTMF):   %d\n", cur->noncodeccapability);
16532          ast_cli(a->fd, "  Their Codec Capability:   %d\n", cur->peercapability);
16533          ast_cli(a->fd, "  Joint Codec Capability:   %d\n", cur->jointcapability);
16534          ast_cli(a->fd, "  Format:                 %s\n", ast_getformatname_multiple(formatbuf, sizeof(formatbuf), cur->owner ? cur->owner->nativeformats : 0) );
16535          ast_cli(a->fd, "  T.38 support            %s\n", cli_yesno(cur->udptl != NULL));
16536          ast_cli(a->fd, "  Video support           %s\n", cli_yesno(cur->vrtp != NULL));
16537          ast_cli(a->fd, "  MaxCallBR:              %d kbps\n", cur->maxcallbitrate);
16538          ast_cli(a->fd, "  Theoretical Address:    %s:%d\n", ast_inet_ntoa(cur->sa.sin_addr), ntohs(cur->sa.sin_port));
16539          ast_cli(a->fd, "  Received Address:       %s:%d\n", ast_inet_ntoa(cur->recv.sin_addr), ntohs(cur->recv.sin_port));
16540          ast_cli(a->fd, "  SIP Transfer mode:      %s\n", transfermode2str(cur->allowtransfer));
16541          ast_cli(a->fd, "  NAT Support:            %s\n", nat2str(ast_test_flag(&cur->flags[0], SIP_NAT)));
16542          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)" );
16543          ast_cli(a->fd, "  Our Tag:                %s\n", cur->tag);
16544          ast_cli(a->fd, "  Their Tag:              %s\n", cur->theirtag);
16545          ast_cli(a->fd, "  SIP User agent:         %s\n", cur->useragent);
16546          if (!ast_strlen_zero(cur->username))
16547             ast_cli(a->fd, "  Username:               %s\n", cur->username);
16548          if (!ast_strlen_zero(cur->peername))
16549             ast_cli(a->fd, "  Peername:               %s\n", cur->peername);
16550          if (!ast_strlen_zero(cur->uri))
16551             ast_cli(a->fd, "  Original uri:           %s\n", cur->uri);
16552          if (!ast_strlen_zero(cur->cid_num))
16553             ast_cli(a->fd, "  Caller-ID:              %s\n", cur->cid_num);
16554          ast_cli(a->fd, "  Need Destroy:           %s\n", cli_yesno(cur->needdestroy));
16555          ast_cli(a->fd, "  Last Message:           %s\n", cur->lastmsg);
16556          ast_cli(a->fd, "  Promiscuous Redir:      %s\n", cli_yesno(ast_test_flag(&cur->flags[0], SIP_PROMISCREDIR)));
16557          ast_cli(a->fd, "  Route:                  %s\n", cur->route ? cur->route->hop : "N/A");
16558          ast_cli(a->fd, "  DTMF Mode:              %s\n", dtmfmode2str(ast_test_flag(&cur->flags[0], SIP_DTMF)));
16559          ast_cli(a->fd, "  SIP Options:            ");
16560          if (cur->sipoptions) {
16561             int x;
16562             for (x = 0 ; x < ARRAY_LEN(sip_options); x++) {
16563                if (cur->sipoptions & sip_options[x].id)
16564                   ast_cli(a->fd, "%s ", sip_options[x].text);
16565             }
16566             ast_cli(a->fd, "\n");
16567          } else
16568             ast_cli(a->fd, "(none)\n");
16569 
16570          if (!cur->stimer)
16571             ast_cli(a->fd, "  Session-Timer:          Uninitiallized\n");
16572          else {
16573             ast_cli(a->fd, "  Session-Timer:          %s\n", cur->stimer->st_active ? "Active" : "Inactive");
16574             if (cur->stimer->st_active == TRUE) {
16575                ast_cli(a->fd, "  S-Timer Interval:       %d\n", cur->stimer->st_interval);
16576                ast_cli(a->fd, "  S-Timer Refresher:      %s\n", strefresher2str(cur->stimer->st_ref));
16577                ast_cli(a->fd, "  S-Timer Expirys:        %d\n", cur->stimer->st_expirys);
16578                ast_cli(a->fd, "  S-Timer Sched Id:       %d\n", cur->stimer->st_schedid);
16579                ast_cli(a->fd, "  S-Timer Peer Sts:       %s\n", cur->stimer->st_active_peer_ua ? "Active" : "Inactive");
16580                ast_cli(a->fd, "  S-Timer Cached Min-SE:  %d\n", cur->stimer->st_cached_min_se);
16581                ast_cli(a->fd, "  S-Timer Cached SE:      %d\n", cur->stimer->st_cached_max_se);
16582                ast_cli(a->fd, "  S-Timer Cached Ref:     %s\n", strefresher2str(cur->stimer->st_cached_ref));
16583                ast_cli(a->fd, "  S-Timer Cached Mode:    %s\n", stmode2str(cur->stimer->st_cached_mode));
16584             }
16585          }
16586 
16587          ast_cli(a->fd, "\n\n");
16588 
16589          found++;
16590       }
16591 
16592       sip_pvt_unlock(cur);
16593 
16594       ao2_t_ref(cur, -1, "toss dialog ptr set by iterator_next");
16595    }
16596    ao2_iterator_destroy(&i);
16597 
16598    if (!found) 
16599       ast_cli(a->fd, "No such SIP Call ID starting with '%s'\n", a->argv[3]);
16600 
16601    return CLI_SUCCESS;
16602 }
16603 
16604 /*! \brief Show history details of one dialog */
16605 static char *sip_show_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16606 {
16607    struct sip_pvt *cur;
16608    size_t len;
16609    int found = 0;
16610    struct ao2_iterator i;
16611 
16612    switch (cmd) {
16613    case CLI_INIT:
16614       e->command = "sip show history";
16615       e->usage =
16616          "Usage: sip show history <call-id>\n"
16617          "       Provides detailed dialog history on a given SIP call (specified by call-id).\n";
16618       return NULL;
16619    case CLI_GENERATE:
16620       return complete_sip_show_history(a->line, a->word, a->pos, a->n);
16621    }
16622 
16623    if (a->argc != 4)
16624       return CLI_SHOWUSAGE;
16625 
16626    if (!recordhistory)
16627       ast_cli(a->fd, "\n***Note: History recording is currently DISABLED.  Use 'sip set history on' to ENABLE.\n");
16628 
16629    len = strlen(a->argv[3]);
16630 
16631    i = ao2_iterator_init(dialogs, 0);
16632    while ((cur = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
16633       sip_pvt_lock(cur);
16634       if (!strncasecmp(cur->callid, a->argv[3], len)) {
16635          struct sip_history *hist;
16636          int x = 0;
16637 
16638          ast_cli(a->fd, "\n");
16639          if (cur->subscribed != NONE)
16640             ast_cli(a->fd, "  * Subscription\n");
16641          else
16642             ast_cli(a->fd, "  * SIP Call\n");
16643          if (cur->history)
16644             AST_LIST_TRAVERSE(cur->history, hist, list)
16645                ast_cli(a->fd, "%d. %s\n", ++x, hist->event);
16646          if (x == 0)
16647             ast_cli(a->fd, "Call '%s' has no history\n", cur->callid);
16648          found++;
16649       }
16650       sip_pvt_unlock(cur);
16651       ao2_t_ref(cur, -1, "toss dialog ptr from iterator_next");
16652    }
16653    ao2_iterator_destroy(&i);
16654 
16655    if (!found) 
16656       ast_cli(a->fd, "No such SIP Call ID starting with '%s'\n", a->argv[3]);
16657 
16658    return CLI_SUCCESS;
16659 }
16660 
16661 /*! \brief Dump SIP history to debug log file at end of lifespan for SIP dialog */
16662 static void sip_dump_history(struct sip_pvt *dialog)
16663 {
16664    int x = 0;
16665    struct sip_history *hist;
16666    static int errmsg = 0;
16667 
16668    if (!dialog)
16669       return;
16670 
16671    if (!option_debug && !sipdebug) {
16672       if (!errmsg) {
16673          ast_log(LOG_NOTICE, "You must have debugging enabled (SIP or Asterisk) in order to dump SIP history.\n");
16674          errmsg = 1;
16675       }
16676       return;
16677    }
16678 
16679    ast_debug(1, "\n---------- SIP HISTORY for '%s' \n", dialog->callid);
16680    if (dialog->subscribed)
16681       ast_debug(1, "  * Subscription\n");
16682    else
16683       ast_debug(1, "  * SIP Call\n");
16684    if (dialog->history)
16685       AST_LIST_TRAVERSE(dialog->history, hist, list)
16686          ast_debug(1, "  %-3.3d. %s\n", ++x, hist->event);
16687    if (!x)
16688       ast_debug(1, "Call '%s' has no history\n", dialog->callid);
16689    ast_debug(1, "\n---------- END SIP HISTORY for '%s' \n", dialog->callid);
16690 }
16691 
16692 
16693 /*! \brief  Receive SIP INFO Message */
16694 static void handle_request_info(struct sip_pvt *p, struct sip_request *req)
16695 {
16696    char buf[1024];
16697    unsigned int event;
16698    const char *c = get_header(req, "Content-Type");
16699 
16700    /* Need to check the media/type */
16701    if (!strcasecmp(c, "application/dtmf-relay") ||
16702        !strcasecmp(c, "application/vnd.nortelnetworks.digits")) {
16703       unsigned int duration = 0;
16704 
16705       if (!p->owner) {  /* not a PBX call */
16706          transmit_response(p, "481 Call leg/transaction does not exist", req);
16707          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
16708          return;
16709       }
16710 
16711       /* Try getting the "signal=" part */
16712       if (ast_strlen_zero(c = get_body(req, "Signal", '=')) && ast_strlen_zero(c = get_body(req, "d", '='))) {
16713          ast_log(LOG_WARNING, "Unable to retrieve DTMF signal from INFO message from %s\n", p->callid);
16714          transmit_response(p, "200 OK", req); /* Should return error */
16715          return;
16716       } else {
16717          ast_copy_string(buf, c, sizeof(buf));
16718       }
16719 
16720       if (!ast_strlen_zero((c = get_body(req, "Duration", '='))))
16721          duration = atoi(c);
16722       if (!duration)
16723          duration = 100; /* 100 ms */
16724 
16725 
16726       if (ast_strlen_zero(buf)) {
16727          transmit_response(p, "200 OK", req);
16728          return;
16729       }
16730 
16731       if (buf[0] == '*')
16732          event = 10;
16733       else if (buf[0] == '#')
16734          event = 11;
16735       else if ((buf[0] >= 'A') && (buf[0] <= 'D'))
16736          event = 12 + buf[0] - 'A';
16737       else if (buf[0] == '!')
16738          event = 16;
16739       else
16740          event = atoi(buf);
16741       if (event == 16) {
16742          /* send a FLASH event */
16743          struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_FLASH, };
16744          ast_queue_frame(p->owner, &f);
16745          if (sipdebug)
16746             ast_verbose("* DTMF-relay event received: FLASH\n");
16747       } else {
16748          /* send a DTMF event */
16749          struct ast_frame f = { AST_FRAME_DTMF, };
16750          if (event < 10) {
16751             f.subclass = '0' + event;
16752          } else if (event < 11) {
16753             f.subclass = '*';
16754          } else if (event < 12) {
16755             f.subclass = '#';
16756          } else if (event < 16) {
16757             f.subclass = 'A' + (event - 12);
16758          }
16759          f.len = duration;
16760          ast_queue_frame(p->owner, &f);
16761          if (sipdebug)
16762             ast_verbose("* DTMF-relay event received: %c\n", f.subclass);
16763       }
16764       transmit_response(p, "200 OK", req);
16765       return;
16766    } else if (!strcasecmp(c, "application/dtmf")) {
16767       /*! \todo Note: Doesn't read the duration of the DTMF. Should be fixed. */
16768       unsigned int duration = 0;
16769 
16770       if (!p->owner) {  /* not a PBX call */
16771          transmit_response(p, "481 Call leg/transaction does not exist", req);
16772          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
16773          return;
16774       }
16775 
16776       get_msg_text(buf, sizeof(buf), req, TRUE);
16777       duration = 100; /* 100 ms */
16778 
16779       if (ast_strlen_zero(buf)) {
16780          transmit_response(p, "200 OK", req);
16781          return;
16782       }
16783       event = atoi(buf);
16784       if (event == 16) {
16785          /* send a FLASH event */
16786          struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_FLASH, };
16787          ast_queue_frame(p->owner, &f);
16788          if (sipdebug)
16789             ast_verbose("* DTMF-relay event received: FLASH\n");
16790       } else {
16791          /* send a DTMF event */
16792          struct ast_frame f = { AST_FRAME_DTMF, };
16793          if (event < 10) {
16794             f.subclass = '0' + event;
16795          } else if (event < 11) {
16796             f.subclass = '*';
16797          } else if (event < 12) {
16798             f.subclass = '#';
16799          } else if (event < 16) {
16800             f.subclass = 'A' + (event - 12);
16801          }
16802          f.len = duration;
16803          ast_queue_frame(p->owner, &f);
16804          if (sipdebug)
16805             ast_verbose("* DTMF-relay event received: %c\n", f.subclass);
16806       }
16807       transmit_response(p, "200 OK", req);
16808       return;
16809 
16810    } else if (!strcasecmp(c, "application/media_control+xml")) {
16811       /* Eh, we'll just assume it's a fast picture update for now */
16812       if (p->owner)
16813          ast_queue_control(p->owner, AST_CONTROL_VIDUPDATE);
16814       transmit_response(p, "200 OK", req);
16815       return;
16816    } else if (!ast_strlen_zero(c = get_header(req, "X-ClientCode"))) {
16817       /* Client code (from SNOM phone) */
16818       if (ast_test_flag(&p->flags[0], SIP_USECLIENTCODE)) {
16819          if (p->owner && p->owner->cdr)
16820             ast_cdr_setuserfield(p->owner, c);
16821          if (p->owner && ast_bridged_channel(p->owner) && ast_bridged_channel(p->owner)->cdr)
16822             ast_cdr_setuserfield(ast_bridged_channel(p->owner), c);
16823          transmit_response(p, "200 OK", req);
16824       } else {
16825          transmit_response(p, "403 Forbidden", req);
16826       }
16827       return;
16828    } else if (!ast_strlen_zero(c = get_header(req, "Record"))) {
16829       /* INFO messages generated by some phones to start/stop recording
16830          on phone calls. 
16831          OEJ: I think this should be something that is enabled/disabled
16832          per device. I don't want incoming callers to record calls in my
16833          pbx.
16834       */
16835       /* first, get the feature string, if it exists */
16836       struct ast_call_feature *feat;
16837       int j;
16838       struct ast_frame f = { AST_FRAME_DTMF, };
16839 
16840       ast_rdlock_call_features();
16841       feat = ast_find_call_feature("automon");
16842       if (!feat || ast_strlen_zero(feat->exten)) {
16843          ast_log(LOG_WARNING, "Recording requested, but no One Touch Monitor registered. (See features.conf)\n");
16844          /* 403 means that we don't support this feature, so don't request it again */
16845          transmit_response(p, "403 Forbidden", req);
16846          ast_unlock_call_features();
16847          return;
16848       } 
16849       /* Send the feature code to the PBX as DTMF, just like the handset had sent it */
16850       f.len = 100;
16851       for (j=0; j < strlen(feat->exten); j++) {
16852          f.subclass = feat->exten[j];
16853          ast_queue_frame(p->owner, &f);
16854          if (sipdebug)
16855             ast_verbose("* DTMF-relay event faked: %c\n", f.subclass);
16856       }
16857       ast_unlock_call_features();
16858 
16859       ast_debug(1, "Got a Request to Record the channel, state %s\n", c);
16860       transmit_response(p, "200 OK", req);
16861       return;
16862    } else if (ast_strlen_zero(c = get_header(req, "Content-Length")) || !strcasecmp(c, "0")) {
16863       /* This is probably just a packet making sure the signalling is still up, just send back a 200 OK */
16864       transmit_response(p, "200 OK", req);
16865       return;
16866    }
16867 
16868    /* Other type of INFO message, not really understood by Asterisk */
16869    /* if (get_msg_text(buf, sizeof(buf), req)) { */
16870 
16871    ast_log(LOG_WARNING, "Unable to parse INFO message from %s. Content %s\n", p->callid, buf);
16872    transmit_response(p, "415 Unsupported media type", req);
16873    return;
16874 }
16875 
16876 /*! \brief Enable SIP Debugging for a single IP */
16877 static char *sip_do_debug_ip(int fd, char *arg)
16878 {
16879    struct hostent *hp;
16880    struct ast_hostent ahp;
16881    int port = 0;
16882    char *p;
16883 
16884    p = arg;
16885    strsep(&p, ":");
16886    if (p)
16887       port = atoi(p);
16888    hp = ast_gethostbyname(arg, &ahp);
16889    if (hp == NULL)
16890       return CLI_SHOWUSAGE;
16891 
16892    debugaddr.sin_family = AF_INET;
16893    memcpy(&debugaddr.sin_addr, hp->h_addr, sizeof(debugaddr.sin_addr));
16894    debugaddr.sin_port = htons(port);
16895    if (port == 0)
16896       ast_cli(fd, "SIP Debugging Enabled for IP: %s\n", ast_inet_ntoa(debugaddr.sin_addr));
16897    else
16898       ast_cli(fd, "SIP Debugging Enabled for IP: %s:%d\n", ast_inet_ntoa(debugaddr.sin_addr), port);
16899 
16900    sipdebug |= sip_debug_console;
16901 
16902    return CLI_SUCCESS;
16903 }
16904 
16905 /*! \brief  Turn on SIP debugging for a given peer */
16906 static char *sip_do_debug_peer(int fd, char *arg)
16907 {
16908    struct sip_peer *peer = find_peer(arg, NULL, TRUE, FINDPEERS, FALSE, 0);
16909    if (!peer)
16910       ast_cli(fd, "No such peer '%s'\n", arg);
16911    else if (peer->addr.sin_addr.s_addr == 0)
16912       ast_cli(fd, "Unable to get IP address of peer '%s'\n", arg);
16913    else {
16914       debugaddr.sin_family = AF_INET;
16915       debugaddr.sin_addr = peer->addr.sin_addr;
16916       debugaddr.sin_port = peer->addr.sin_port;
16917       ast_cli(fd, "SIP Debugging Enabled for IP: %s:%d\n",
16918          ast_inet_ntoa(debugaddr.sin_addr), ntohs(debugaddr.sin_port));
16919       sipdebug |= sip_debug_console;
16920    }
16921    if (peer)
16922       unref_peer(peer, "sip_do_debug_peer: unref_peer, from find_peer call");
16923    return CLI_SUCCESS;
16924 }
16925 
16926 /*! \brief Turn on SIP debugging (CLI command) */
16927 static char *sip_do_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16928 {
16929    int oldsipdebug = sipdebug & sip_debug_console;
16930    char *what;
16931 
16932    if (cmd == CLI_INIT) {
16933       e->command = "sip set debug {on|off|ip|peer}";
16934       e->usage =
16935          "Usage: sip set debug {off|on|ip addr[:port]|peer peername}\n"
16936          "       Globally disables dumping of SIP packets,\n"
16937          "       or enables it either globally or for a (single)\n"
16938          "       IP address or registered peer.\n";
16939       return NULL;
16940    } else if (cmd == CLI_GENERATE) {
16941       if (a->pos == 4 && !strcasecmp(a->argv[3], "peer")) 
16942          return complete_sip_peer(a->word, a->n, 0);
16943       return NULL;
16944         }
16945 
16946    what = a->argv[e->args-1];      /* guaranteed to exist */
16947    if (a->argc == e->args) {       /* on/off */
16948       if (!strcasecmp(what, "on")) {
16949          sipdebug |= sip_debug_console;
16950          sipdebug_text = 1;   /*! \note this can be a special debug command - "sip debug text" or something */
16951          memset(&debugaddr, 0, sizeof(debugaddr));
16952          ast_cli(a->fd, "SIP Debugging %senabled\n", oldsipdebug ? "re-" : "");
16953          return CLI_SUCCESS;
16954       } else if (!strcasecmp(what, "off")) {
16955          sipdebug &= ~sip_debug_console;
16956          sipdebug_text = 0;
16957          ast_cli(a->fd, "SIP Debugging Disabled\n");
16958          return CLI_SUCCESS;
16959       }
16960    } else if (a->argc == e->args +1) {/* ip/peer */
16961       if (!strcasecmp(what, "ip"))
16962          return sip_do_debug_ip(a->fd, a->argv[e->args]);
16963       else if (!strcasecmp(what, "peer"))
16964          return sip_do_debug_peer(a->fd, a->argv[e->args]);
16965    }
16966    return CLI_SHOWUSAGE;   /* default, failure */
16967 }
16968 
16969 /*! \brief Cli command to send SIP notify to peer */
16970 static char *sip_cli_notify(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16971 {
16972    struct ast_variable *varlist;
16973    int i;
16974 
16975    switch (cmd) {
16976    case CLI_INIT:
16977       e->command = "sip notify";
16978       e->usage =
16979          "Usage: sip notify <type> <peer> [<peer>...]\n"
16980          "       Send a NOTIFY message to a SIP peer or peers\n"
16981          "       Message types are defined in sip_notify.conf\n";
16982       return NULL;
16983    case CLI_GENERATE:
16984       return complete_sipnotify(a->line, a->word, a->pos, a->n);
16985    }
16986 
16987    if (a->argc < 4)
16988       return CLI_SHOWUSAGE;
16989 
16990    if (!notify_types) {
16991       ast_cli(a->fd, "No %s file found, or no types listed there\n", notify_config);
16992       return CLI_FAILURE;
16993    }
16994 
16995    varlist = ast_variable_browse(notify_types, a->argv[2]);
16996 
16997    if (!varlist) {
16998       ast_cli(a->fd, "Unable to find notify type '%s'\n", a->argv[2]);
16999       return CLI_FAILURE;
17000    }
17001 
17002    for (i = 3; i < a->argc; i++) {
17003       struct sip_pvt *p;
17004 
17005       if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY, NULL))) {
17006          ast_log(LOG_WARNING, "Unable to build sip pvt data for notify (memory/socket error)\n");
17007          return CLI_FAILURE;
17008       }
17009 
17010       if (create_addr(p, a->argv[i], NULL, 1)) {
17011          /* Maybe they're not registered, etc. */
17012          dialog_unlink_all(p, TRUE, TRUE);
17013          dialog_unref(p, "unref dialog inside for loop" );
17014          /* sip_destroy(p); */
17015          ast_cli(a->fd, "Could not create address for '%s'\n", a->argv[i]);
17016          continue;
17017       }
17018 
17019       /* Notify is outgoing call */
17020       ast_set_flag(&p->flags[0], SIP_OUTGOING);
17021 
17022       /* Recalculate our side, and recalculate Call ID */
17023       ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
17024       build_via(p);
17025       ao2_t_unlink(dialogs, p, "About to change the callid -- remove the old name");
17026       build_callid_pvt(p);
17027       ao2_t_link(dialogs, p, "Linking in new name");
17028       ast_cli(a->fd, "Sending NOTIFY of type '%s' to '%s'\n", a->argv[2], a->argv[i]);
17029       dialog_ref(p, "bump the count of p, which transmit_sip_request will decrement.");
17030       sip_scheddestroy(p, SIP_TRANS_TIMEOUT);
17031       transmit_notify_custom(p, varlist);
17032    }
17033 
17034    return CLI_SUCCESS;
17035 }
17036 
17037 /*! \brief Enable/Disable SIP History logging (CLI) */
17038 static char *sip_set_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
17039 {
17040    switch (cmd) {
17041    case CLI_INIT:
17042       e->command = "sip set history {on|off}";
17043       e->usage =
17044          "Usage: sip set history {on|off}\n"
17045          "       Enables/Disables recording of SIP dialog history for debugging purposes.\n"
17046          "       Use 'sip show history' to view the history of a call number.\n";
17047       return NULL;
17048    case CLI_GENERATE:
17049       return NULL;
17050    }
17051 
17052    if (a->argc != e->args)
17053       return CLI_SHOWUSAGE;
17054 
17055    if (!strncasecmp(a->argv[e->args - 1], "on", 2)) {
17056       recordhistory = TRUE;
17057       ast_cli(a->fd, "SIP History Recording Enabled (use 'sip show history')\n");
17058    } else if (!strncasecmp(a->argv[e->args - 1], "off", 3)) {
17059       recordhistory = FALSE;
17060       ast_cli(a->fd, "SIP History Recording Disabled\n");
17061    } else {
17062       return CLI_SHOWUSAGE;
17063    }
17064    return CLI_SUCCESS;
17065 }
17066 
17067 /*! \brief Authenticate for outbound registration */
17068 static int do_register_auth(struct sip_pvt *p, struct sip_request *req, enum sip_auth_type code)
17069 {
17070    char *header, *respheader;
17071    char digest[1024];
17072 
17073    p->authtries++;
17074    auth_headers(code, &header, &respheader);
17075    memset(digest, 0, sizeof(digest));
17076    if (reply_digest(p, req, header, SIP_REGISTER, digest, sizeof(digest))) {
17077       /* There's nothing to use for authentication */
17078       /* No digest challenge in request */
17079       if (sip_debug_test_pvt(p) && p->registry)
17080          ast_verbose("No authentication challenge, sending blank registration to domain/host name %s\n", p->registry->hostname);
17081          /* No old challenge */
17082       return -1;
17083    }
17084    if (p->do_history)
17085       append_history(p, "RegistryAuth", "Try: %d", p->authtries);
17086    if (sip_debug_test_pvt(p) && p->registry)
17087       ast_verbose("Responding to challenge, registration to domain/host name %s\n", p->registry->hostname);
17088    return transmit_register(p->registry, SIP_REGISTER, digest, respheader); 
17089 }
17090 
17091 /*! \brief Add authentication on outbound SIP packet */
17092 static int do_proxy_auth(struct sip_pvt *p, struct sip_request *req, enum sip_auth_type code, int sipmethod, int init)
17093 {
17094    char *header, *respheader;
17095    char digest[1024];
17096 
17097    if (!p->options && !(p->options = ast_calloc(1, sizeof(*p->options))))
17098       return -2;
17099 
17100    p->authtries++;
17101    auth_headers(code, &header, &respheader);
17102    ast_debug(2, "Auth attempt %d on %s\n", p->authtries, sip_methods[sipmethod].text);
17103    memset(digest, 0, sizeof(digest));
17104    if (reply_digest(p, req, header, sipmethod, digest, sizeof(digest) )) {
17105       /* No way to authenticate */
17106       return -1;
17107    }
17108    /* Now we have a reply digest */
17109    p->options->auth = digest;
17110    p->options->authheader = respheader;
17111    return transmit_invite(p, sipmethod, sipmethod == SIP_INVITE, init); 
17112 }
17113 
17114 /*! \brief  reply to authentication for outbound registrations
17115 \return  Returns -1 if we have no auth 
17116 \note This is used for register= servers in sip.conf, SIP proxies we register
17117    with  for receiving calls from.  */
17118 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod,  char *digest, int digest_len)
17119 {
17120    char tmp[512];
17121    char *c;
17122    char oldnonce[256];
17123 
17124    /* table of recognised keywords, and places where they should be copied */
17125    const struct x {
17126       const char *key;
17127       const ast_string_field *field;
17128    } *i, keys[] = {
17129       { "realm=", &p->realm },
17130       { "nonce=", &p->nonce },
17131       { "opaque=", &p->opaque },
17132       { "qop=", &p->qop },
17133       { "domain=", &p->domain },
17134       { NULL, 0 },
17135    };
17136 
17137    ast_copy_string(tmp, get_header(req, header), sizeof(tmp));
17138    if (ast_strlen_zero(tmp)) 
17139       return -1;
17140    if (strncasecmp(tmp, "Digest ", strlen("Digest "))) {
17141       ast_log(LOG_WARNING, "missing Digest.\n");
17142       return -1;
17143    }
17144    c = tmp + strlen("Digest ");
17145    ast_copy_string(oldnonce, p->nonce, sizeof(oldnonce));
17146    while (c && *(c = ast_skip_blanks(c))) {  /* lookup for keys */
17147       for (i = keys; i->key != NULL; i++) {
17148          char *src, *separator;
17149          if (strncasecmp(c, i->key, strlen(i->key)) != 0)
17150             continue;
17151          /* Found. Skip keyword, take text in quotes or up to the separator. */
17152          c += strlen(i->key);
17153          if (*c == '"') {
17154             src = ++c;
17155             separator = "\"";
17156          } else {
17157             src = c;
17158             separator = ",";
17159          }
17160          strsep(&c, separator); /* clear separator and move ptr */
17161          ast_string_field_ptr_set(p, i->field, src);
17162          break;
17163       }
17164       if (i->key == NULL) /* not found, try ',' */
17165          strsep(&c, ",");
17166    }
17167    /* Reset nonce count */
17168    if (strcmp(p->nonce, oldnonce)) 
17169       p->noncecount = 0;
17170 
17171    /* Save auth data for following registrations */
17172    if (p->registry) {
17173       struct sip_registry *r = p->registry;
17174 
17175       if (strcmp(r->nonce, p->nonce)) {
17176          ast_string_field_set(r, realm, p->realm);
17177          ast_string_field_set(r, nonce, p->nonce);
17178          ast_string_field_set(r, domain, p->domain);
17179          ast_string_field_set(r, opaque, p->opaque);
17180          ast_string_field_set(r, qop, p->qop);
17181          r->noncecount = 0;
17182       }
17183    }
17184    return build_reply_digest(p, sipmethod, digest, digest_len); 
17185 }
17186 
17187 /*! \brief  Build reply digest 
17188 \return  Returns -1 if we have no auth 
17189 \note Build digest challenge for authentication of registrations and calls
17190    Also used for authentication of BYE 
17191 */
17192 static int build_reply_digest(struct sip_pvt *p, int method, char* digest, int digest_len)
17193 {
17194    char a1[256];
17195    char a2[256];
17196    char a1_hash[256];
17197    char a2_hash[256];
17198    char resp[256];
17199    char resp_hash[256];
17200    char uri[256];
17201    char opaque[256] = "";
17202    char cnonce[80];
17203    const char *username;
17204    const char *secret;
17205    const char *md5secret;
17206    struct sip_auth *auth = NULL; /* Realm authentication */
17207 
17208    if (!ast_strlen_zero(p->domain))
17209       ast_copy_string(uri, p->domain, sizeof(uri));
17210    else if (!ast_strlen_zero(p->uri))
17211       ast_copy_string(uri, p->uri, sizeof(uri));
17212    else
17213       snprintf(uri, sizeof(uri), "sip:%s@%s", p->username, ast_inet_ntoa(p->sa.sin_addr));
17214 
17215    snprintf(cnonce, sizeof(cnonce), "%08lx", ast_random());
17216 
17217    /* Check if we have separate auth credentials */
17218    if(!(auth = find_realm_authentication(p->peerauth, p->realm))) /* Start with peer list */
17219       auth = find_realm_authentication(authl, p->realm); /* If not, global list */
17220 
17221    if (auth) {
17222       ast_debug(3, "use realm [%s] from peer [%s][%s]\n", auth->username, p->peername, p->username);
17223       username = auth->username;
17224       secret = auth->secret;
17225       md5secret = auth->md5secret;
17226       if (sipdebug)
17227          ast_debug(1, "Using realm %s authentication for call %s\n", p->realm, p->callid);
17228    } else {
17229       /* No authentication, use peer or register= config */
17230       username = p->authname;
17231       secret =  p->peersecret;
17232       md5secret = p->peermd5secret;
17233    }
17234    if (ast_strlen_zero(username))   /* We have no authentication */
17235       return -1;
17236 
17237    /* Calculate SIP digest response */
17238    snprintf(a1, sizeof(a1), "%s:%s:%s", username, p->realm, secret);
17239    snprintf(a2, sizeof(a2), "%s:%s", sip_methods[method].text, uri);
17240    if (!ast_strlen_zero(md5secret))
17241       ast_copy_string(a1_hash, md5secret, sizeof(a1_hash));
17242    else
17243       ast_md5_hash(a1_hash, a1);
17244    ast_md5_hash(a2_hash, a2);
17245 
17246    p->noncecount++;
17247    if (!ast_strlen_zero(p->qop))
17248       snprintf(resp, sizeof(resp), "%s:%s:%08x:%s:%s:%s", a1_hash, p->nonce, p->noncecount, cnonce, "auth", a2_hash);
17249    else
17250       snprintf(resp, sizeof(resp), "%s:%s:%s", a1_hash, p->nonce, a2_hash);
17251    ast_md5_hash(resp_hash, resp);
17252 
17253    /* only include the opaque string if it's set */
17254    if (!ast_strlen_zero(p->opaque)) {
17255      snprintf(opaque, sizeof(opaque), ", opaque=\"%s\"", p->opaque);
17256    }
17257 
17258    /* XXX We hard code our qop to "auth" for now.  XXX */
17259    if (!ast_strlen_zero(p->qop))
17260       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);
17261    else
17262       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);
17263 
17264    append_history(p, "AuthResp", "Auth response sent for %s in realm %s - nc %d", username, p->realm, p->noncecount);
17265 
17266    return 0;
17267 }
17268    
17269 /*! \brief Read SIP header (dialplan function) */
17270 static int func_header_read(struct ast_channel *chan, const char *function, char *data, char *buf, size_t len) 
17271 {
17272    struct sip_pvt *p;
17273    const char *content = NULL;
17274    AST_DECLARE_APP_ARGS(args,
17275       AST_APP_ARG(header);
17276       AST_APP_ARG(number);
17277    );
17278    int i, number, start = 0;
17279 
17280    if (ast_strlen_zero(data)) {
17281       ast_log(LOG_WARNING, "This function requires a header name.\n");
17282       return -1;
17283    }
17284 
17285    ast_channel_lock(chan);
17286    if (!IS_SIP_TECH(chan->tech)) {
17287       ast_log(LOG_WARNING, "This function can only be used on SIP channels.\n");
17288       ast_channel_unlock(chan);
17289       return -1;
17290    }
17291 
17292    AST_STANDARD_APP_ARGS(args, data);
17293    if (!args.number) {
17294       number = 1;
17295    } else {
17296       sscanf(args.number, "%30d", &number);
17297       if (number < 1)
17298          number = 1;
17299    }
17300 
17301    p = chan->tech_pvt;
17302 
17303    /* If there is no private structure, this channel is no longer alive */
17304    if (!p) {
17305       ast_channel_unlock(chan);
17306       return -1;
17307    }
17308 
17309    for (i = 0; i < number; i++)
17310       content = __get_header(&p->initreq, args.header, &start);
17311 
17312    if (ast_strlen_zero(content)) {
17313       ast_channel_unlock(chan);
17314       return -1;
17315    }
17316 
17317    ast_copy_string(buf, content, len);
17318    ast_channel_unlock(chan);
17319 
17320    return 0;
17321 }
17322 
17323 static struct ast_custom_function sip_header_function = {
17324    .name = "SIP_HEADER",
17325    .read = func_header_read,
17326 };
17327 
17328 /*! \brief  Dial plan function to check if domain is local */
17329 static int func_check_sipdomain(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
17330 {
17331    if (ast_strlen_zero(data)) {
17332       ast_log(LOG_WARNING, "CHECKSIPDOMAIN requires an argument - A domain name\n");
17333       return -1;
17334    }
17335    if (check_sip_domain(data, NULL, 0))
17336       ast_copy_string(buf, data, len);
17337    else
17338       buf[0] = '\0';
17339    return 0;
17340 }
17341 
17342 static struct ast_custom_function checksipdomain_function = {
17343    .name = "CHECKSIPDOMAIN",
17344    .read = func_check_sipdomain,
17345 };
17346 
17347 /*! \brief  ${SIPPEER()} Dialplan function - reads peer data */
17348 static int function_sippeer(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
17349 {
17350    struct sip_peer *peer;
17351    char *colname;
17352 
17353    if ((colname = strchr(data, ':'))) {   /*! \todo Will be deprecated after 1.4 */
17354       static int deprecation_warning = 0;
17355       *colname++ = '\0';
17356       if (deprecation_warning++ % 10 == 0)
17357          ast_log(LOG_WARNING, "SIPPEER(): usage of ':' to separate arguments is deprecated.  Please use ',' instead.\n");
17358    } else if ((colname = strchr(data, ',')))
17359       *colname++ = '\0';
17360    else
17361       colname = "ip";
17362 
17363    if (!(peer = find_peer(data, NULL, TRUE, FINDPEERS, FALSE, 0)))
17364       return -1;
17365 
17366    if (!strcasecmp(colname, "ip")) {
17367       ast_copy_string(buf, peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "", len);
17368    } else  if (!strcasecmp(colname, "port")) {
17369       snprintf(buf, len, "%d", ntohs(peer->addr.sin_port));
17370    } else  if (!strcasecmp(colname, "status")) {
17371       peer_status(peer, buf, len);
17372    } else  if (!strcasecmp(colname, "language")) {
17373       ast_copy_string(buf, peer->language, len);
17374    } else  if (!strcasecmp(colname, "regexten")) {
17375       ast_copy_string(buf, peer->regexten, len);
17376    } else  if (!strcasecmp(colname, "limit")) {
17377       snprintf(buf, len, "%d", peer->call_limit);
17378    } else  if (!strcasecmp(colname, "busylevel")) {
17379       snprintf(buf, len, "%d", peer->busy_level);
17380    } else  if (!strcasecmp(colname, "curcalls")) {
17381       snprintf(buf, len, "%d", peer->inUse);
17382    } else  if (!strcasecmp(colname, "accountcode")) {
17383       ast_copy_string(buf, peer->accountcode, len);
17384    } else  if (!strcasecmp(colname, "callgroup")) {
17385       ast_print_group(buf, len, peer->callgroup);
17386    } else  if (!strcasecmp(colname, "pickupgroup")) {
17387       ast_print_group(buf, len, peer->pickupgroup);
17388    } else  if (!strcasecmp(colname, "useragent")) {
17389       ast_copy_string(buf, peer->useragent, len);
17390    } else  if (!strcasecmp(colname, "mailbox")) {
17391       struct ast_str *mailbox_str = ast_str_alloca(512);
17392       peer_mailboxes_to_str(&mailbox_str, peer);
17393       ast_copy_string(buf, mailbox_str->str, len);
17394    } else  if (!strcasecmp(colname, "context")) {
17395       ast_copy_string(buf, peer->context, len);
17396    } else  if (!strcasecmp(colname, "expire")) {
17397       snprintf(buf, len, "%d", peer->expire);
17398    } else  if (!strcasecmp(colname, "dynamic")) {
17399       ast_copy_string(buf, peer->host_dynamic ? "yes" : "no", len);
17400    } else  if (!strcasecmp(colname, "callerid_name")) {
17401       ast_copy_string(buf, peer->cid_name, len);
17402    } else  if (!strcasecmp(colname, "callerid_num")) {
17403       ast_copy_string(buf, peer->cid_num, len);
17404    } else  if (!strcasecmp(colname, "codecs")) {
17405       ast_getformatname_multiple(buf, len -1, peer->capability);
17406    } else  if (!strncasecmp(colname, "chanvar[", 8)) {
17407       char *chanvar=colname + 8;
17408       struct ast_variable *v;
17409    
17410       chanvar = strsep(&chanvar, "]");
17411       for (v = peer->chanvars ; v ; v = v->next) {
17412          if (!strcasecmp(v->name, chanvar)) {
17413             ast_copy_string(buf, v->value, len);
17414          }
17415       }
17416    } else  if (!strncasecmp(colname, "codec[", 6)) {
17417       char *codecnum;
17418       int codec = 0;
17419       
17420       codecnum = colname + 6; /* move past the '[' */
17421       codecnum = strsep(&codecnum, "]"); /* trim trailing ']' if any */
17422       if((codec = ast_codec_pref_index(&peer->prefs, atoi(codecnum)))) {
17423          ast_copy_string(buf, ast_getformatname(codec), len);
17424       } else {
17425          buf[0] = '\0';
17426       }
17427    } else {
17428       buf[0] = '\0';
17429    }
17430 
17431    unref_peer(peer, "unref_peer from function_sippeer, just before return");
17432 
17433    return 0;
17434 }
17435 
17436 /*! \brief Structure to declare a dialplan function: SIPPEER */
17437 static struct ast_custom_function sippeer_function = {
17438    .name = "SIPPEER",
17439    .read = function_sippeer,
17440 };
17441 
17442 /*! \brief ${SIPCHANINFO()} Dialplan function - reads sip channel data */
17443 static int function_sipchaninfo_read(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
17444 {
17445    struct sip_pvt *p;
17446    static int deprecated = 0;
17447 
17448    *buf = 0;
17449    
17450    if (!data) {
17451       ast_log(LOG_WARNING, "This function requires a parameter name.\n");
17452       return -1;
17453    }
17454 
17455    ast_channel_lock(chan);
17456    if (!IS_SIP_TECH(chan->tech)) {
17457       ast_log(LOG_WARNING, "This function can only be used on SIP channels.\n");
17458       ast_channel_unlock(chan);
17459       return -1;
17460    }
17461 
17462    if (deprecated++ % 20 == 0) {
17463       /* Deprecated in 1.6.1 */
17464       ast_log(LOG_WARNING, "SIPCHANINFO() is deprecated.  Please transition to using CHANNEL().\n");
17465    }
17466 
17467    p = chan->tech_pvt;
17468 
17469    /* If there is no private structure, this channel is no longer alive */
17470    if (!p) {
17471       ast_channel_unlock(chan);
17472       return -1;
17473    }
17474 
17475    if (!strcasecmp(data, "peerip")) {
17476       ast_copy_string(buf, p->sa.sin_addr.s_addr ? ast_inet_ntoa(p->sa.sin_addr) : "", len);
17477    } else  if (!strcasecmp(data, "recvip")) {
17478       ast_copy_string(buf, p->recv.sin_addr.s_addr ? ast_inet_ntoa(p->recv.sin_addr) : "", len);
17479    } else  if (!strcasecmp(data, "from")) {
17480       ast_copy_string(buf, p->from, len);
17481    } else  if (!strcasecmp(data, "uri")) {
17482       ast_copy_string(buf, p->uri, len);
17483    } else  if (!strcasecmp(data, "useragent")) {
17484       ast_copy_string(buf, p->useragent, len);
17485    } else  if (!strcasecmp(data, "peername")) {
17486       ast_copy_string(buf, p->peername, len);
17487    } else if (!strcasecmp(data, "t38passthrough")) {
17488       if (p->t38.state == T38_DISABLED) {
17489          ast_copy_string(buf, "0", len);
17490       } else { /* T38 is offered or enabled in this call */
17491          ast_copy_string(buf, "1", len);
17492       }
17493    } else {
17494       ast_channel_unlock(chan);
17495       return -1;
17496    }
17497    ast_channel_unlock(chan);
17498 
17499    return 0;
17500 }
17501 
17502 /*! \brief Structure to declare a dialplan function: SIPCHANINFO */
17503 static struct ast_custom_function sipchaninfo_function = {
17504    .name = "SIPCHANINFO",
17505    .read = function_sipchaninfo_read,
17506 };
17507 
17508 /*! \brief Parse 302 Moved temporalily response 
17509    \todo XXX Doesn't redirect over TLS on sips: uri's.
17510       If we get a redirect to a SIPS: uri, this needs to be going back to the
17511       dialplan (this is a request for a secure signalling path).
17512       Note that transport=tls is deprecated, but we need to support it on incoming requests.
17513 */
17514 static void parse_moved_contact(struct sip_pvt *p, struct sip_request *req)
17515 {
17516    char tmp[SIPBUFSIZE];
17517    char *s, *e, *t, *trans;
17518    char *domain;
17519    enum sip_transport transport = SIP_TRANSPORT_UDP;
17520 
17521    ast_copy_string(tmp, get_header(req, "Contact"), sizeof(tmp));
17522    if ((t = strchr(tmp, ',')))
17523       *t = '\0';
17524 
17525    s = get_in_brackets(tmp);
17526    if ((trans = strcasestr(s, ";transport="))) do {
17527       trans += 11;
17528 
17529       if ((e = strchr(trans, ';')))
17530          *e = '\0';
17531 
17532       if (!strncasecmp(trans, "tcp", 3))
17533          transport = SIP_TRANSPORT_TCP;
17534       else if (!strncasecmp(trans, "tls", 3))
17535          transport = SIP_TRANSPORT_TLS;
17536       else {
17537          if (strncasecmp(trans, "udp", 3))
17538             ast_debug(1, "received contact with an invalid transport, '%s'\n", s);
17539          /* This will assume UDP for all unknown transports */
17540          transport = SIP_TRANSPORT_UDP;
17541       }
17542    } while(0);
17543    s = remove_uri_parameters(s);
17544 
17545    if (p->socket.tcptls_session) {
17546       ao2_ref(p->socket.tcptls_session, -1);
17547       p->socket.tcptls_session = NULL;
17548    }
17549 
17550    set_socket_transport(&p->socket, transport);
17551 
17552    if (ast_test_flag(&p->flags[0], SIP_PROMISCREDIR)) {
17553       char *host = NULL;
17554       if (!strncasecmp(s, "sip:", 4))
17555          s += 4;
17556       else if (!strncasecmp(s, "sips:", 5))
17557          s += 5;
17558       e = strchr(s, '/');
17559       if (e)
17560          *e = '\0';
17561       if ((host = strchr(s, '@'))) {
17562          *host++ = '\0';
17563          ast_debug(2, "Found promiscuous redirection to 'SIP/%s::::%s@%s'\n", s, get_transport(transport), host);
17564          if (p->owner)
17565             ast_string_field_build(p->owner, call_forward, "SIP/%s::::%s@%s", s, get_transport(transport), host);
17566       } else {
17567          ast_debug(2, "Found promiscuous redirection to 'SIP/::::%s@%s'\n", get_transport(transport), s);
17568          if (p->owner)
17569             ast_string_field_build(p->owner, call_forward, "SIP/::::%s@%s", get_transport(transport), s);
17570       }
17571    } else {
17572       e = strchr(tmp, '@');
17573       if (e) {
17574          *e++ = '\0';
17575          domain = e;
17576       } else {
17577          /* No username part */
17578          domain = tmp;
17579       }
17580       e = strchr(tmp, '/');   /* WHEN do we hae a forward slash in the URI? */
17581       if (e)
17582          *e = '\0';
17583 
17584       if (!strncasecmp(s, "sip:", 4))
17585          s += 4;
17586       else if (!strncasecmp(s, "sips:", 5))
17587          s += 5;
17588       e = strchr(s, ';');  /* And username ; parameters? */
17589       if (e)
17590          *e = '\0';  
17591       ast_debug(2, "Received 302 Redirect to extension '%s' (domain %s)\n", s, domain);
17592       if (p->owner) {
17593          pbx_builtin_setvar_helper(p->owner, "SIPDOMAIN", domain);
17594          ast_string_field_set(p->owner, call_forward, s);
17595       }
17596    }
17597 }
17598 
17599 /*! \brief Check pending actions on SIP call */
17600 static void check_pendings(struct sip_pvt *p)
17601 {
17602    if (ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
17603       /* if we can't BYE, then this is really a pending CANCEL */
17604       if (p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA)
17605          transmit_request(p, SIP_CANCEL, p->lastinvite, XMIT_RELIABLE, FALSE);
17606          /* Actually don't destroy us yet, wait for the 487 on our original 
17607             INVITE, but do set an autodestruct just in case we never get it. */
17608       else {
17609          /* We have a pending outbound invite, don't send something
17610             new in-transaction */
17611          if (p->pendinginvite)
17612             return;
17613 
17614          /* Perhaps there is an SD change INVITE outstanding */
17615          transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, TRUE);
17616       }
17617       ast_clear_flag(&p->flags[0], SIP_PENDINGBYE);   
17618       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
17619    } else if (ast_test_flag(&p->flags[0], SIP_NEEDREINVITE)) {
17620       /* if we can't REINVITE, hold it for later */
17621       if (p->pendinginvite || p->invitestate == INV_CALLING || p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA || p->waitid > 0) {
17622          ast_debug(2, "NOT Sending pending reinvite (yet) on '%s'\n", p->callid);
17623       } else {
17624          ast_debug(2, "Sending pending reinvite on '%s'\n", p->callid);
17625          /* Didn't get to reinvite yet, so do it now */
17626          transmit_reinvite_with_sdp(p, (p->t38.state == T38_LOCAL_REINVITE ? TRUE : FALSE), FALSE);
17627          ast_clear_flag(&p->flags[0], SIP_NEEDREINVITE); 
17628       }
17629    }
17630 }
17631 
17632 /*! \brief Reset the NEEDREINVITE flag after waiting when we get 491 on a Re-invite
17633    to avoid race conditions between asterisk servers.
17634    Called from the scheduler.
17635 */
17636 static int sip_reinvite_retry(const void *data)
17637 {
17638    struct sip_pvt *p = (struct sip_pvt *) data;
17639 
17640    sip_pvt_lock(p); /* called from schedule thread which requires a lock */
17641    ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
17642    p->waitid = -1;
17643    check_pendings(p);
17644    sip_pvt_unlock(p);
17645    dialog_unref(p, "unref the dialog ptr from sip_reinvite_retry, because it held a dialog ptr");
17646    return 0;
17647 }
17648 
17649 
17650 /*! \brief Handle SIP response to INVITE dialogue */
17651 static void handle_response_invite(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
17652 {
17653    int outgoing = ast_test_flag(&p->flags[0], SIP_OUTGOING);
17654    int res = 0;
17655    int xmitres = 0;
17656    int reinvite = (p->owner && p->owner->_state == AST_STATE_UP);
17657    char *p_hdrval;
17658    int rtn;
17659 
17660    if (reinvite)
17661       ast_debug(4, "SIP response %d to RE-invite on %s call %s\n", resp, outgoing ? "outgoing" : "incoming", p->callid);
17662    else
17663       ast_debug(4, "SIP response %d to standard invite\n", resp);
17664 
17665    if (p->alreadygone) { /* This call is already gone */
17666       ast_debug(1, "Got response on call that is already terminated: %s (ignoring)\n", p->callid);
17667       return;
17668    }
17669 
17670    /* Acknowledge sequence number - This only happens on INVITE from SIP-call */
17671    /* Don't auto congest anymore since we've gotten something useful back */
17672    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"));
17673 
17674    /* RFC3261 says we must treat every 1xx response (but not 100)
17675       that we don't recognize as if it was 183.
17676    */
17677    if (resp > 100 && resp < 200 && resp!=101 && resp != 180 && resp != 182 && resp != 183)
17678       resp = 183;
17679 
17680    /* Any response between 100 and 199 is PROCEEDING */
17681    if (resp >= 100 && resp < 200 && p->invitestate == INV_CALLING)
17682       p->invitestate = INV_PROCEEDING;
17683  
17684    /* Final response, not 200 ? */
17685    if (resp >= 300 && (p->invitestate == INV_CALLING || p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA ))
17686       p->invitestate = INV_COMPLETED;
17687    
17688    /* Final response, clear out pending invite */
17689    if ((resp == 200 || resp >= 300) && p->pendinginvite && seqno == p->pendinginvite)
17690       p->pendinginvite = 0;
17691 
17692    switch (resp) {
17693    case 100:   /* Trying */
17694    case 101:   /* Dialog establishment */
17695       if (!req->ignore && p->invitestate != INV_CANCELLED && sip_cancel_destroy(p))
17696          ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
17697       check_pendings(p);
17698       break;
17699 
17700    case 180:   /* 180 Ringing */
17701    case 182:       /* 182 Queued */
17702       if (!req->ignore && p->invitestate != INV_CANCELLED && sip_cancel_destroy(p))
17703          ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
17704       if (!req->ignore && p->owner) {
17705          ast_queue_control(p->owner, AST_CONTROL_RINGING);
17706          if (p->owner->_state != AST_STATE_UP) {
17707             ast_setstate(p->owner, AST_STATE_RINGING);
17708          }
17709       }
17710       if (find_sdp(req)) {
17711          if (p->invitestate != INV_CANCELLED)
17712             p->invitestate = INV_EARLY_MEDIA;
17713          res = process_sdp(p, req, SDP_T38_NONE);
17714          if (!req->ignore && p->owner) {
17715             /* Queue a progress frame only if we have SDP in 180 or 182 */
17716             ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
17717          }
17718       }
17719       check_pendings(p);
17720       break;
17721 
17722    case 183:   /* Session progress */
17723       if (!req->ignore && (p->invitestate != INV_CANCELLED) && sip_cancel_destroy(p))
17724          ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
17725       if (find_sdp(req)) {
17726          if (p->invitestate != INV_CANCELLED)
17727             p->invitestate = INV_EARLY_MEDIA;
17728          res = process_sdp(p, req, SDP_T38_NONE);
17729          if (!req->ignore && p->owner) {
17730             /* Queue a progress frame */
17731             ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
17732          }
17733       } else {
17734          /* Alcatel PBXs are known to send 183s with no SDP after sending
17735           * a 100 Trying response. We're just going to treat this sort of thing
17736           * the same as we would treat a 180 Ringing
17737           */
17738          if (!req->ignore && p->owner) {
17739             ast_queue_control(p->owner, AST_CONTROL_RINGING);
17740          }
17741       }
17742       check_pendings(p);
17743       break;
17744 
17745    case 200:   /* 200 OK on invite - someone's answering our call */
17746       if (!req->ignore && (p->invitestate != INV_CANCELLED) && sip_cancel_destroy(p))
17747          ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
17748       p->authtries = 0;
17749       if (find_sdp(req)) {
17750          if ((res = process_sdp(p, req, SDP_T38_ACCEPT)) && !req->ignore)
17751             if (!reinvite)
17752                /* This 200 OK's SDP is not acceptable, so we need to ack, then hangup */
17753                /* For re-invites, we try to recover */
17754                ast_set_flag(&p->flags[0], SIP_PENDINGBYE);  
17755       }
17756 
17757       /* Parse contact header for continued conversation */
17758       /* When we get 200 OK, we know which device (and IP) to contact for this call */
17759       /* This is important when we have a SIP proxy between us and the phone */
17760       if (outgoing) {
17761          update_call_counter(p, DEC_CALL_RINGING);
17762          parse_ok_contact(p, req);
17763          /* Save Record-Route for any later requests we make on this dialogue */
17764          if (!reinvite)
17765             build_route(p, req, 1);
17766 
17767          if(set_address_from_contact(p)) {
17768             /* Bad contact - we don't know how to reach this device */
17769             /* We need to ACK, but then send a bye */
17770             if (!p->route && !req->ignore)
17771                ast_set_flag(&p->flags[0], SIP_PENDINGBYE);  
17772          } 
17773 
17774       }
17775 
17776       if (!req->ignore && p->owner) {
17777          if (!reinvite) {
17778             ast_queue_control(p->owner, AST_CONTROL_ANSWER);
17779             if (sip_cfg.callevents)
17780                manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
17781                   "Channel: %s\r\nChanneltype: %s\r\nUniqueid: %s\r\nSIPcallid: %s\r\nSIPfullcontact: %s\r\nPeername: %s\r\n",
17782                   p->owner->name, "SIP", p->owner->uniqueid, p->callid, p->fullcontact, p->peername);
17783          } else { /* RE-invite */
17784             ast_queue_frame(p->owner, &ast_null_frame);
17785          }
17786       } else {
17787           /* It's possible we're getting an 200 OK after we've tried to disconnect
17788               by sending CANCEL */
17789          /* First send ACK, then send bye */
17790          if (!req->ignore)
17791             ast_set_flag(&p->flags[0], SIP_PENDINGBYE);  
17792       }
17793 
17794       /* Check for Session-Timers related headers */
17795       if (st_get_mode(p) != SESSION_TIMER_MODE_REFUSE && p->outgoing_call == TRUE && !reinvite) {
17796          p_hdrval = (char*)get_header(req, "Session-Expires");
17797             if (!ast_strlen_zero(p_hdrval)) {
17798             /* UAS supports Session-Timers */
17799             enum st_refresher tmp_st_ref = SESSION_TIMER_REFRESHER_AUTO;
17800             int tmp_st_interval = 0;
17801             rtn = parse_session_expires(p_hdrval, &tmp_st_interval, &tmp_st_ref);
17802             if (rtn != 0) {
17803                ast_set_flag(&p->flags[0], SIP_PENDINGBYE);  
17804             }
17805             if (tmp_st_ref == SESSION_TIMER_REFRESHER_UAC || 
17806                tmp_st_ref == SESSION_TIMER_REFRESHER_UAS) {
17807                p->stimer->st_ref = tmp_st_ref;
17808             } 
17809             if (tmp_st_interval) {
17810                p->stimer->st_interval = tmp_st_interval;
17811             }
17812             p->stimer->st_active = TRUE;
17813             p->stimer->st_active_peer_ua = TRUE;
17814             start_session_timer(p);
17815          } else {
17816             /* UAS doesn't support Session-Timers */
17817             if (st_get_mode(p) == SESSION_TIMER_MODE_ORIGINATE) {
17818                p->stimer->st_ref = SESSION_TIMER_REFRESHER_UAC;
17819                p->stimer->st_active_peer_ua = FALSE;
17820                start_session_timer(p);
17821             }
17822          }
17823       }
17824 
17825 
17826       /* If I understand this right, the branch is different for a non-200 ACK only */
17827       p->invitestate = INV_TERMINATED;
17828       ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
17829       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, TRUE);
17830       check_pendings(p);
17831       break;
17832 
17833    case 407: /* Proxy authentication */
17834    case 401: /* Www auth */
17835       /* First we ACK */
17836       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
17837       if (p->options)
17838          p->options->auth_type = resp;
17839 
17840       /* Then we AUTH */
17841       ast_string_field_set(p, theirtag, NULL);  /* forget their old tag, so we don't match tags when getting response */
17842       if (!req->ignore) {
17843          if (p->authtries < MAX_AUTHTRIES)
17844             p->invitestate = INV_CALLING;
17845          if (p->authtries == MAX_AUTHTRIES || do_proxy_auth(p, req, resp, SIP_INVITE, 1)) {
17846             ast_log(LOG_NOTICE, "Failed to authenticate on INVITE to '%s'\n", get_header(&p->initreq, "From"));
17847             pvt_set_needdestroy(p, "failed to authenticate on INVITE");
17848             sip_alreadygone(p);
17849             if (p->owner)
17850                ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
17851          }
17852       }
17853       break;
17854 
17855    case 403: /* Forbidden */
17856       /* First we ACK */
17857       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
17858       ast_log(LOG_WARNING, "Received response: \"Forbidden\" from '%s'\n", get_header(&p->initreq, "From"));
17859       if (!req->ignore && p->owner)
17860          ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
17861       pvt_set_needdestroy(p, "received 403 response");
17862       sip_alreadygone(p);
17863       break;
17864 
17865    case 404: /* Not found */
17866       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
17867       if (p->owner && !req->ignore)
17868          ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
17869       sip_alreadygone(p);
17870       break;
17871 
17872    case 408: /* Request timeout */
17873    case 481: /* Call leg does not exist */
17874       /* Could be REFER caused INVITE with replaces */
17875       ast_log(LOG_WARNING, "Re-invite to non-existing call leg on other UA. SIP dialog '%s'. Giving up.\n", p->callid);
17876       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
17877       if (p->owner)
17878          ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
17879       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
17880       break;
17881 
17882    case 422: /* Session-Timers: Session interval too small */
17883       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
17884       ast_string_field_set(p, theirtag, NULL);
17885       proc_422_rsp(p, req);
17886       break;
17887 
17888    case 428: /* Use identity header - rfc 4474 - not supported by Asterisk yet */
17889       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
17890       append_history(p, "Identity", "SIP identity is required. Not supported by Asterisk.");
17891       ast_log(LOG_WARNING, "SIP identity required by proxy. SIP dialog '%s'. Giving up.\n", p->callid);
17892       if (p->owner)
17893          ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
17894       break;
17895 
17896       
17897 
17898    case 487: /* Cancelled transaction */
17899       /* We have sent CANCEL on an outbound INVITE 
17900          This transaction is already scheduled to be killed by sip_hangup().
17901       */
17902       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
17903       if (p->owner && !req->ignore) {
17904          ast_queue_hangup_with_cause(p->owner, AST_CAUSE_NORMAL_CLEARING);
17905          append_history(p, "Hangup", "Got 487 on CANCEL request from us. Queued AST hangup request");
17906       } else if (!req->ignore) {
17907          update_call_counter(p, DEC_CALL_LIMIT);
17908          append_history(p, "Hangup", "Got 487 on CANCEL request from us on call without owner. Killing this dialog.");
17909          pvt_set_needdestroy(p, "received 487 response");
17910          sip_alreadygone(p);
17911       }
17912       break;
17913    case 415: /* Unsupported media type */
17914    case 488: /* Not acceptable here */
17915    case 606: /* Not Acceptable */
17916       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
17917       if (p->udptl && p->t38.state == T38_LOCAL_REINVITE) {
17918          change_t38_state(p, T38_DISABLED);
17919          /* Try to reset RTP timers */
17920          ast_rtp_set_rtptimers_onhold(p->rtp);
17921 
17922          /* Trigger a reinvite back to audio */
17923          transmit_reinvite_with_sdp(p, FALSE, FALSE);
17924       } else {
17925          /* We can't set up this call, so give up */
17926          if (p->owner && !req->ignore)
17927             ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
17928          pvt_set_needdestroy(p, "received 488 response");
17929          /* If there's no dialog to end, then mark p as already gone */
17930          if (!reinvite)
17931             sip_alreadygone(p);
17932       }
17933       break;
17934    case 491: /* Pending */
17935       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
17936       if (p->owner && !req->ignore) {
17937          if (p->owner->_state != AST_STATE_UP) {
17938             ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
17939             pvt_set_needdestroy(p, "received 491 response");
17940          } else {
17941             /* This is a re-invite that failed. */
17942             /* Reset the flag after a while 
17943              */
17944             int wait;
17945             /* RFC 3261, if owner of call, wait between 2.1 to 4 seconds,
17946              * if not owner of call, wait 0 to 2 seconds */
17947             if (p->outgoing_call) {
17948                wait = 2100 + ast_random() % 2000;
17949             } else {
17950                wait = ast_random() % 2000;
17951             }
17952             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."));
17953             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);
17954             ast_debug(2, "Reinvite race. Waiting %d secs before retry\n", wait);
17955          }
17956       }
17957       break;
17958 
17959    case 501: /* Not implemented */
17960       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
17961       if (p->owner)
17962          ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
17963       break;
17964    }
17965    if (xmitres == XMIT_ERROR)
17966       ast_log(LOG_WARNING, "Could not transmit message in dialog %s\n", p->callid);
17967 }
17968 
17969 /* \brief Handle SIP response in NOTIFY transaction
17970        We've sent a NOTIFY, now handle responses to it
17971   */
17972 static void handle_response_notify(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
17973 {
17974    switch (resp) {
17975    case 200:   /* Notify accepted */
17976       /* They got the notify, this is the end */
17977       if (p->owner) {
17978          if (!p->refer) {
17979             ast_log(LOG_WARNING, "Notify answer on an owned channel? - %s\n", p->owner->name);
17980             ast_queue_hangup_with_cause(p->owner, AST_CAUSE_NORMAL_UNSPECIFIED);
17981          } else {
17982             ast_debug(4, "Got OK on REFER Notify message\n");
17983          }
17984       } else {
17985          if (p->subscribed == NONE) {
17986             ast_debug(4, "Got 200 accepted on NOTIFY\n");
17987             pvt_set_needdestroy(p, "received 200 response");
17988          }
17989          if (ast_test_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE)) {
17990             /* Ready to send the next state we have on queue */
17991             ast_clear_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE);
17992             cb_extensionstate((char *)p->context, (char *)p->exten, p->laststate, (void *) p);
17993          }
17994       }
17995       break;
17996    case 401:   /* Not www-authorized on SIP method */
17997    case 407:   /* Proxy auth */
17998       if (!p->notify_headers) {
17999          break; /* Only device notify can use NOTIFY auth */
18000       }
18001       ast_string_field_set(p, theirtag, NULL);
18002       if (ast_strlen_zero(p->authname)) {
18003          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));
18004          pvt_set_needdestroy(p, "unable to authenticate NOTIFY");
18005       }
18006       if (p->authtries > 1 || do_proxy_auth(p, req, resp, SIP_NOTIFY, 0)) {
18007          ast_log(LOG_NOTICE, "Failed to authenticate on NOTIFY to '%s'\n", get_header(&p->initreq, "From"));
18008          pvt_set_needdestroy(p, "failed to authenticate NOTIFY");
18009       }
18010       break;
18011    }
18012 }
18013 
18014 /* \brief Handle SIP response in SUBSCRIBE transaction */
18015 static void handle_response_subscribe(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
18016 {
18017    if (!p->mwi) {
18018       return;
18019    }
18020 
18021    switch (resp) {
18022    case 200: /* Subscription accepted */
18023       ast_debug(3, "Got 200 OK on subscription for MWI\n");
18024       if (p->options) {
18025          ast_free(p->options);
18026          p->options = NULL;
18027       }
18028       p->mwi->subscribed = 1;
18029       if ((p->mwi->resub = ast_sched_add(sched, mwi_expiry * 1000, sip_subscribe_mwi_do, ASTOBJ_REF(p->mwi))) < 0) {
18030          ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
18031       }
18032       break;
18033    case 401:
18034    case 407:
18035       ast_string_field_set(p, theirtag, NULL);
18036       if (p->authtries > 1 || do_proxy_auth(p, req, resp, SIP_SUBSCRIBE, 0)) {
18037          ast_log(LOG_NOTICE, "Failed to authenticate on SUBSCRIBE to '%s'\n", get_header(&p->initreq, "From"));
18038          p->mwi->call = NULL;
18039          ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
18040          pvt_set_needdestroy(p, "failed to authenticate SUBSCRIBE");
18041       }
18042       break;
18043    case 403:
18044       transmit_response_with_date(p, "200 OK", req);
18045       ast_log(LOG_WARNING, "Authentication failed while trying to subscribe for MWI.\n");
18046       p->mwi->call = NULL;
18047       ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
18048       pvt_set_needdestroy(p, "received 403 response");
18049       sip_alreadygone(p);
18050       break;
18051    case 404:
18052       ast_log(LOG_WARNING, "Subscription failed for MWI. The remote side said that a mailbox may not have been configured.\n");
18053       p->mwi->call = NULL;
18054       ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
18055       pvt_set_needdestroy(p, "received 404 response");
18056       break;
18057    case 481:
18058       ast_log(LOG_WARNING, "Subscription failed for MWI. The remote side said that our dialog did not exist.\n");
18059       p->mwi->call = NULL;
18060       ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
18061       pvt_set_needdestroy(p, "received 481 response");
18062       break;
18063    case 500:
18064    case 501:
18065       ast_log(LOG_WARNING, "Subscription failed for MWI. The remote side may have suffered a heart attack.\n");
18066       p->mwi->call = NULL;
18067       ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
18068       pvt_set_needdestroy(p, "received 500/501 response");
18069       break;
18070    }
18071 }
18072 
18073 /* \brief Handle SIP response in REFER transaction
18074    We've sent a REFER, now handle responses to it 
18075   */
18076 static void handle_response_refer(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
18077 {
18078    /* If no refer structure exists, then do nothing */
18079    if (!p->refer)
18080       return;
18081 
18082    switch (resp) {
18083    case 202:   /* Transfer accepted */
18084       /* We need  to do something here */
18085       /* The transferee is now sending INVITE to target */
18086       p->refer->status = REFER_ACCEPTED;
18087       /* Now wait for next message */
18088       ast_debug(3, "Got 202 accepted on transfer\n");
18089       /* We should hang along, waiting for NOTIFY's here */
18090       break;
18091 
18092    case 401:   /* Not www-authorized on SIP method */
18093    case 407:   /* Proxy auth */
18094       if (ast_strlen_zero(p->authname)) {
18095          ast_log(LOG_WARNING, "Asked to authenticate REFER to %s:%d but we have no matching peer or realm auth!\n",
18096             ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
18097          pvt_set_needdestroy(p, "unable to authenticate REFER");
18098       }
18099       if (p->authtries > 1 || do_proxy_auth(p, req, resp, SIP_REFER, 0)) {
18100          ast_log(LOG_NOTICE, "Failed to authenticate on REFER to '%s'\n", get_header(&p->initreq, "From"));
18101          p->refer->status = REFER_NOAUTH;
18102          pvt_set_needdestroy(p, "failed to authenticat REFER");
18103       }
18104       break;
18105    case 481: /* Call leg does not exist */
18106 
18107       /* A transfer with Replaces did not work */
18108       /* OEJ: We should Set flag, cancel the REFER, go back
18109       to original call - but right now we can't */
18110       ast_log(LOG_WARNING, "Remote host can't match REFER request to call '%s'. Giving up.\n", p->callid);
18111       if (p->owner)
18112          ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
18113       pvt_set_needdestroy(p, "received 481 response");
18114       break;
18115 
18116    case 500:   /* Server error */
18117    case 501:   /* Method not implemented */
18118       /* Return to the current call onhold */
18119       /* Status flag needed to be reset */
18120       ast_log(LOG_NOTICE, "SIP transfer to %s failed, call miserably fails. \n", p->refer->refer_to);
18121       pvt_set_needdestroy(p, "received 500/501 response");
18122       p->refer->status = REFER_FAILED;
18123       break;
18124    case 603:   /* Transfer declined */
18125       ast_log(LOG_NOTICE, "SIP transfer to %s declined, call miserably fails. \n", p->refer->refer_to);
18126       p->refer->status = REFER_FAILED;
18127       pvt_set_needdestroy(p, "received 603 response");
18128       break;
18129    }
18130 }
18131 
18132 /*! \brief Handle responses on REGISTER to services */
18133 static int handle_response_register(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
18134 {
18135    int expires, expires_ms;
18136    struct sip_registry *r;
18137    r=p->registry;
18138    
18139    switch (resp) {
18140    case 401:   /* Unauthorized */
18141       if (p->authtries == MAX_AUTHTRIES || do_register_auth(p, req, resp)) {
18142          ast_log(LOG_NOTICE, "Failed to authenticate on REGISTER to '%s@%s' (Tries %d)\n", p->registry->username, p->registry->hostname, p->authtries);
18143          pvt_set_needdestroy(p, "failed to authenticate REGISTER");
18144       }
18145       break;
18146    case 403:   /* Forbidden */
18147       ast_log(LOG_WARNING, "Forbidden - wrong password on authentication for REGISTER for '%s' to '%s'\n", p->registry->username, p->registry->hostname);
18148       AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 403"));
18149       r->regstate = REG_STATE_NOAUTH;
18150       pvt_set_needdestroy(p, "received 403 response");
18151       break;
18152    case 404:   /* Not found */
18153       ast_log(LOG_WARNING, "Got 404 Not found on SIP register to service %s@%s, giving up\n", p->registry->username, p->registry->hostname);
18154       pvt_set_needdestroy(p, "received 404 response");
18155       if (r->call)
18156          r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 404");
18157       r->regstate = REG_STATE_REJECTED;
18158       AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 404"));
18159       break;
18160    case 407:   /* Proxy auth */
18161       if (p->authtries == MAX_AUTHTRIES || do_register_auth(p, req, resp)) {
18162          ast_log(LOG_NOTICE, "Failed to authenticate on REGISTER to '%s' (tries '%d')\n", get_header(&p->initreq, "From"), p->authtries);
18163          pvt_set_needdestroy(p, "failed to authenticate REGISTER");
18164       }
18165       break;
18166    case 408:   /* Request timeout */
18167       /* Got a timeout response, so reset the counter of failed responses */
18168       if (r) {
18169          r->regattempts = 0;
18170       } else {
18171          ast_log(LOG_WARNING, "Got a 408 response to our REGISTER on call %s after we had destroyed the registry object\n", p->callid);
18172       }
18173       break;
18174    case 423:   /* Interval too brief */
18175       r->expiry = atoi(get_header(req, "Min-Expires"));
18176       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);
18177       AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 423"));
18178       if (r->call) {
18179          r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 423");
18180          pvt_set_needdestroy(p, "received 423 response");
18181       }
18182       if (r->expiry > max_expiry) {
18183          ast_log(LOG_WARNING, "Required expiration time from %s@%s is too high, giving up\n", p->registry->username, p->registry->hostname);
18184          r->expiry = r->configured_expiry;
18185          r->regstate = REG_STATE_REJECTED;
18186       } else {
18187          r->regstate = REG_STATE_UNREGISTERED;
18188          transmit_register(r, SIP_REGISTER, NULL, NULL);
18189       }
18190       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));
18191       break;
18192    case 479:   /* SER: Not able to process the URI - address is wrong in register*/
18193       ast_log(LOG_WARNING, "Got error 479 on register to %s@%s, giving up (check config)\n", p->registry->username, p->registry->hostname);
18194       pvt_set_needdestroy(p, "received 479 response");
18195       if (r->call)
18196          r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 479");
18197       r->regstate = REG_STATE_REJECTED;
18198       AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 479"));
18199       break;
18200    case 200:   /* 200 OK */
18201       if (!r) {
18202          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));
18203          pvt_set_needdestroy(p, "received erroneous 200 response");
18204          return 0;
18205       }
18206       
18207       r->regstate = REG_STATE_REGISTERED;
18208       r->regtime = ast_tvnow();     /* Reset time of last succesful registration */
18209       manager_event(EVENT_FLAG_SYSTEM, "Registry", "ChannelType: SIP\r\nDomain: %s\r\nStatus: %s\r\n", r->hostname, regstate2str(r->regstate));
18210       r->regattempts = 0;
18211       ast_debug(1, "Registration successful\n");
18212       if (r->timeout > -1) {
18213          ast_debug(1, "Cancelling timeout %d\n", r->timeout);
18214       }
18215       AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 200"));
18216       if (r->call)
18217          r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 200");
18218       p->registry = registry_unref(p->registry, "unref registry entry p->registry");
18219       /* Let this one hang around until we have all the responses */
18220       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
18221       /* p->needdestroy = 1; */
18222       
18223       /* set us up for re-registering
18224        * figure out how long we got registered for
18225        * according to section 6.13 of RFC, contact headers override
18226        * expires headers, so check those first */
18227       expires = 0;
18228 
18229       /* XXX todo: try to save the extra call */
18230       if (!ast_strlen_zero(get_header(req, "Contact"))) {
18231          const char *contact = NULL;
18232          const char *tmptmp = NULL;
18233          int start = 0;
18234          for(;;) {
18235             contact = __get_header(req, "Contact", &start);
18236             /* this loop ensures we get a contact header about our register request */
18237             if(!ast_strlen_zero(contact)) {
18238                if( (tmptmp=strstr(contact, p->our_contact))) {
18239                   contact=tmptmp;
18240                   break;
18241                }
18242             } else
18243                break;
18244          }
18245          tmptmp = strcasestr(contact, "expires=");
18246          if (tmptmp) {
18247             if (sscanf(tmptmp + 8, "%30d;", &expires) != 1)
18248                expires = 0;
18249          }
18250          
18251       }
18252       if (!expires) 
18253          expires=atoi(get_header(req, "expires"));
18254       if (!expires)
18255          expires=default_expiry;
18256       
18257       expires_ms = expires * 1000;
18258       if (expires <= EXPIRY_GUARD_LIMIT)
18259          expires_ms -= MAX((expires_ms * EXPIRY_GUARD_PCT), EXPIRY_GUARD_MIN);
18260       else
18261          expires_ms -= EXPIRY_GUARD_SECS * 1000;
18262       if (sipdebug)
18263          ast_log(LOG_NOTICE, "Outbound Registration: Expiry for %s is %d sec (Scheduling reregistration in %d s)\n", r->hostname, expires, expires_ms/1000); 
18264       
18265       r->refresh= (int) expires_ms / 1000;
18266       
18267       /* Schedule re-registration before we expire */
18268       AST_SCHED_REPLACE_UNREF(r->expire, sched, expires_ms, sip_reregister, r, 
18269                         registry_unref(_data,"unref in REPLACE del fail"), 
18270                         registry_unref(r,"unref in REPLACE add fail"), 
18271                         registry_addref(r,"The Addition side of REPLACE")); 
18272    }
18273    return 1;
18274 }
18275 
18276 /*! \brief Handle qualification responses (OPTIONS) */
18277 static void handle_response_peerpoke(struct sip_pvt *p, int resp, struct sip_request *req)
18278 {
18279    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! */
18280    int statechanged, is_reachable, was_reachable;
18281    int pingtime = ast_tvdiff_ms(ast_tvnow(), peer->ps);
18282 
18283    /*
18284     * Compute the response time to a ping (goes in peer->lastms.)
18285     * -1 means did not respond, 0 means unknown,
18286     * 1..maxms is a valid response, >maxms means late response.
18287     */
18288    if (pingtime < 1) /* zero = unknown, so round up to 1 */
18289       pingtime = 1;
18290 
18291    /* Now determine new state and whether it has changed.
18292     * Use some helper variables to simplify the writing
18293     * of the expressions.
18294     */
18295    was_reachable = peer->lastms > 0 && peer->lastms <= peer->maxms;
18296    is_reachable = pingtime <= peer->maxms;
18297    statechanged = peer->lastms == 0 /* yes, unknown before */
18298       || was_reachable != is_reachable;
18299 
18300    peer->lastms = pingtime;
18301    peer->call = dialog_unref(peer->call, "unref dialog peer->call");
18302    if (statechanged) {
18303       const char *s = is_reachable ? "Reachable" : "Lagged";
18304       char str_lastms[20];
18305       snprintf(str_lastms, sizeof(str_lastms), "%d", pingtime);
18306 
18307       ast_log(LOG_NOTICE, "Peer '%s' is now %s. (%dms / %dms)\n",
18308          peer->name, s, pingtime, peer->maxms);
18309       ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", peer->name);
18310       if (sip_cfg.peer_rtupdate) {
18311          ast_update_realtime(ast_check_realtime("sipregs") ? "sipregs" : "sippeers", "name", peer->name, "lastms", str_lastms, SENTINEL);
18312       }
18313       manager_event(EVENT_FLAG_SYSTEM, "PeerStatus",
18314          "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: %s\r\nTime: %d\r\n",
18315          peer->name, s, pingtime);
18316       if (is_reachable && sip_cfg.regextenonqualify)
18317          register_peer_exten(peer, TRUE);
18318    }
18319 
18320    pvt_set_needdestroy(p, "got OPTIONS response");
18321 
18322    /* Try again eventually */
18323    AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched,
18324          is_reachable ? peer->qualifyfreq : DEFAULT_FREQ_NOTOK,
18325          sip_poke_peer_s, peer,
18326          unref_peer(_data, "removing poke peer ref"),
18327          unref_peer(peer, "removing poke peer ref"),
18328          ref_peer(peer, "adding poke peer ref"));
18329 }
18330 
18331 /*! \brief Immediately stop RTP, VRTP and UDPTL as applicable */
18332 static void stop_media_flows(struct sip_pvt *p)
18333 {
18334    /* Immediately stop RTP, VRTP and UDPTL as applicable */
18335    if (p->rtp)
18336       ast_rtp_stop(p->rtp);
18337    if (p->vrtp)
18338       ast_rtp_stop(p->vrtp);
18339    if (p->trtp)
18340       ast_rtp_stop(p->trtp);
18341    if (p->udptl)
18342       ast_udptl_stop(p->udptl);
18343 }
18344 
18345 /*! \brief Handle SIP response in dialogue
18346    \note only called by handle_incoming */
18347 static void handle_response(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
18348 {
18349    struct ast_channel *owner;
18350    int sipmethod;
18351    int res = 1;
18352    const char *c = get_header(req, "Cseq");
18353    /* 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 */
18354    char *c_copy = ast_strdupa(c);
18355    /* Skip the Cseq and its subsequent spaces */
18356    const char *msg = ast_skip_blanks(ast_skip_nonblanks(c_copy));
18357 
18358    if (!msg)
18359       msg = "";
18360 
18361    sipmethod = find_sip_method(msg);
18362 
18363    owner = p->owner;
18364    if (owner) 
18365       owner->hangupcause = hangup_sip2cause(resp);
18366 
18367    if (p->socket.type == SIP_TRANSPORT_UDP) {
18368       int ack_res;
18369 
18370       /* Acknowledge whatever it is destined for */
18371       if ((resp >= 100) && (resp <= 199)) {
18372          ack_res = __sip_semi_ack(p, seqno, 0, sipmethod);
18373       } else {
18374          ack_res = __sip_ack(p, seqno, 0, sipmethod);
18375       }
18376 
18377       if (ack_res == FALSE) {
18378          append_history(p, "Ignore", "Ignoring this retransmit\n");
18379          return;
18380       }
18381    }
18382 
18383    /* If this is a NOTIFY for a subscription clear the flag that indicates that we have a NOTIFY pending */
18384    if (!p->owner && sipmethod == SIP_NOTIFY && p->pendinginvite) 
18385       p->pendinginvite = 0;
18386 
18387    /* Get their tag if we haven't already */
18388    if (ast_strlen_zero(p->theirtag) || (resp >= 200)) {
18389       char tag[128];
18390 
18391       gettag(req, "To", tag, sizeof(tag));
18392       ast_string_field_set(p, theirtag, tag);
18393    }
18394    /* This needs to be configurable on a channel/peer level,
18395       not mandatory for all communication. Sadly enough, NAT implementations
18396       are not so stable so we can always rely on these headers. 
18397       Temporarily disabled, while waiting for fix.
18398       Fix assigned to Rizzo :-)
18399    */
18400    /* check_via_response(p, req); */
18401 
18402    /* RFC 3261 Section 15 specifies that if we receive a 408 or 481
18403     * in response to a BYE, then we should end the current dialog
18404     * and session.  It is known that at least one phone manufacturer
18405     * potentially will send a 404 in response to a BYE, so we'll be
18406     * liberal in what we accept and end the dialog and session if we
18407     * receive any of those responses to a BYE.
18408     */
18409    if ((resp == 404 || resp == 408 || resp == 481) && sipmethod == SIP_BYE) {
18410       pvt_set_needdestroy(p, "received 4XX response to a BYE");
18411       return;
18412    }
18413 
18414    if (p->relatedpeer && p->method == SIP_OPTIONS) {
18415       /* We don't really care what the response is, just that it replied back. 
18416          Well, as long as it's not a 100 response...  since we might
18417          need to hang around for something more "definitive" */
18418       if (resp != 100)
18419          handle_response_peerpoke(p, resp, req);
18420    } else if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
18421       switch(resp) {
18422       case 100:   /* 100 Trying */
18423       case 101:   /* 101 Dialog establishment */
18424       case 183:   /* 183 Session Progress */
18425       case 180:   /* 180 Ringing */
18426       case 182:   /* 182 Queued */
18427          if (sipmethod == SIP_INVITE)
18428             handle_response_invite(p, resp, rest, req, seqno);
18429          break;
18430       case 200:   /* 200 OK */
18431          p->authtries = 0; /* Reset authentication counter */
18432          if (sipmethod == SIP_MESSAGE || sipmethod == SIP_INFO) {
18433             /* We successfully transmitted a message 
18434                or a video update request in INFO */
18435             /* Nothing happens here - the message is inside a dialog */
18436          } else if (sipmethod == SIP_INVITE) {
18437             handle_response_invite(p, resp, rest, req, seqno);
18438          } else if (sipmethod == SIP_NOTIFY) {
18439             handle_response_notify(p, resp, rest, req, seqno);
18440          } else if (sipmethod == SIP_REGISTER) {
18441             res = handle_response_register(p, resp, rest, req, seqno);
18442          } else if (sipmethod == SIP_SUBSCRIBE) {
18443             ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
18444             handle_response_subscribe(p, resp, rest, req, seqno);
18445          } else if (sipmethod == SIP_BYE) {     /* Ok, we're ready to go */
18446             pvt_set_needdestroy(p, "received 200 response");
18447             ast_clear_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
18448          }
18449          break;
18450       case 202:   /* Transfer accepted */
18451          if (sipmethod == SIP_REFER) 
18452             handle_response_refer(p, resp, rest, req, seqno);
18453          break;
18454       case 401: /* Not www-authorized on SIP method */
18455       case 407: /* Proxy auth required */
18456          if (sipmethod == SIP_INVITE)
18457             handle_response_invite(p, resp, rest, req, seqno);
18458          else if (sipmethod == SIP_NOTIFY)
18459             handle_response_notify(p, resp, rest, req, seqno);
18460          else if (sipmethod == SIP_REFER)
18461             handle_response_refer(p, resp, rest, req, seqno);
18462          else if (sipmethod == SIP_SUBSCRIBE)
18463             handle_response_subscribe(p, resp, rest, req, seqno);
18464          else if (p->registry && sipmethod == SIP_REGISTER)
18465             res = handle_response_register(p, resp, rest, req, seqno);
18466          else if (sipmethod == SIP_BYE) {
18467             if (p->options)
18468                p->options->auth_type = resp;
18469             if (ast_strlen_zero(p->authname)) {
18470                ast_log(LOG_WARNING, "Asked to authenticate %s, to %s:%d but we have no matching peer!\n",
18471                      msg, ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
18472                pvt_set_needdestroy(p, "unable to authenticate BYE");
18473             } else if ((p->authtries == MAX_AUTHTRIES) || do_proxy_auth(p, req, resp,  sipmethod, 0)) {
18474                ast_log(LOG_NOTICE, "Failed to authenticate on %s to '%s'\n", msg, get_header(&p->initreq, "From"));
18475                pvt_set_needdestroy(p, "failed to authenticate BYE");
18476             }
18477          } else {
18478             ast_log(LOG_WARNING, "Got authentication request (%d) on %s to '%s'\n", resp, sip_methods[sipmethod].text, get_header(req, "To"));
18479             pvt_set_needdestroy(p, "received 407 response");
18480          }
18481          break;
18482       case 403: /* Forbidden - we failed authentication */
18483          if (sipmethod == SIP_INVITE)
18484             handle_response_invite(p, resp, rest, req, seqno);
18485          else if (sipmethod == SIP_SUBSCRIBE)
18486             handle_response_subscribe(p, resp, rest, req, seqno);
18487          else if (p->registry && sipmethod == SIP_REGISTER) 
18488             res = handle_response_register(p, resp, rest, req, seqno);
18489          else {
18490             ast_log(LOG_WARNING, "Forbidden - maybe wrong password on authentication for %s\n", msg);
18491             pvt_set_needdestroy(p, "received 403 response");
18492          }
18493          break;
18494       case 404: /* Not found */
18495          if (p->registry && sipmethod == SIP_REGISTER)
18496             res = handle_response_register(p, resp, rest, req, seqno);
18497          else if (sipmethod == SIP_INVITE)
18498             handle_response_invite(p, resp, rest, req, seqno);
18499          else if (sipmethod == SIP_SUBSCRIBE)
18500             handle_response_subscribe(p, resp, rest, req, seqno);
18501          else if (owner)
18502             ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
18503          break;
18504       case 423: /* Interval too brief */
18505          if (sipmethod == SIP_REGISTER)
18506             res = handle_response_register(p, resp, rest, req, seqno);
18507          break;
18508       case 408: /* Request timeout - terminate dialog */
18509          if (sipmethod == SIP_INVITE)
18510             handle_response_invite(p, resp, rest, req, seqno);
18511          else if (sipmethod == SIP_REGISTER) 
18512             res = handle_response_register(p, resp, rest, req, seqno);
18513          else if (sipmethod == SIP_BYE) {
18514             pvt_set_needdestroy(p, "received 408 response");
18515             ast_debug(4, "Got timeout on bye. Thanks for the answer. Now, kill this call\n");
18516          } else {
18517             if (owner)
18518                ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
18519             pvt_set_needdestroy(p, "received 408 response");
18520          }
18521          break;
18522 
18523       case 422: /* Session-Timers: Session Interval Too Small */
18524          if (sipmethod == SIP_INVITE) {
18525             handle_response_invite(p, resp, rest, req, seqno);
18526          }
18527          break;
18528 
18529       case 481: /* Call leg does not exist */
18530          if (sipmethod == SIP_INVITE) {
18531             handle_response_invite(p, resp, rest, req, seqno);
18532          } else if (sipmethod == SIP_REFER) {
18533             handle_response_refer(p, resp, rest, req, seqno);
18534          } else if (sipmethod == SIP_SUBSCRIBE) {
18535             handle_response_subscribe(p, resp, rest, req, seqno);
18536          } else if (sipmethod == SIP_BYE) {
18537             /* The other side has no transaction to bye,
18538             just assume it's all right then */
18539             ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
18540          } else if (sipmethod == SIP_CANCEL) {
18541             /* The other side has no transaction to cancel,
18542             just assume it's all right then */
18543             ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
18544          } else {
18545             ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
18546             /* Guessing that this is not an important request */
18547          }
18548          break;
18549       case 487:
18550          if (sipmethod == SIP_INVITE)
18551             handle_response_invite(p, resp, rest, req, seqno);
18552          break;
18553       case 415: /* Unsupported media type */
18554       case 488: /* Not acceptable here - codec error */
18555       case 606: /* Not Acceptable */
18556          if (sipmethod == SIP_INVITE)
18557             handle_response_invite(p, resp, rest, req, seqno);
18558          break;
18559       case 491: /* Pending */
18560          if (sipmethod == SIP_INVITE)
18561             handle_response_invite(p, resp, rest, req, seqno);
18562          else {
18563             ast_debug(1, "Got 491 on %s, unsupported. Call ID %s\n", sip_methods[sipmethod].text, p->callid);
18564             pvt_set_needdestroy(p, "received 491 response");
18565          }
18566          break;
18567       case 501: /* Not Implemented */
18568          if (sipmethod == SIP_INVITE)
18569             handle_response_invite(p, resp, rest, req, seqno);
18570          else if (sipmethod == SIP_REFER)
18571             handle_response_refer(p, resp, rest, req, seqno);
18572          else
18573             ast_log(LOG_WARNING, "Host '%s' does not implement '%s'\n", ast_inet_ntoa(p->sa.sin_addr), msg);
18574          break;
18575       case 603:   /* Declined transfer */
18576          if (sipmethod == SIP_REFER) {
18577             handle_response_refer(p, resp, rest, req, seqno);
18578             break;
18579          }
18580          /* Fallthrough */
18581       default:
18582          if ((resp >= 300) && (resp < 700)) {
18583             /* Fatal response */
18584             if ((resp != 487))
18585                ast_verb(3, "Got SIP response %d \"%s\" back from %s\n", resp, rest, ast_inet_ntoa(p->sa.sin_addr));
18586    
18587             if (sipmethod == SIP_INVITE)
18588                stop_media_flows(p); /* Immediately stop RTP, VRTP and UDPTL as applicable */
18589 
18590             /* XXX Locking issues?? XXX */
18591             switch(resp) {
18592             case 300: /* Multiple Choices */
18593             case 301: /* Moved permanently */
18594             case 302: /* Moved temporarily */
18595             case 305: /* Use Proxy */
18596                parse_moved_contact(p, req);
18597                /* Fall through */
18598             case 486: /* Busy here */
18599             case 600: /* Busy everywhere */
18600             case 603: /* Decline */
18601                if (p->owner)
18602                   ast_queue_control(p->owner, AST_CONTROL_BUSY);
18603                break;
18604             case 482: /*!
18605                \note SIP is incapable of performing a hairpin call, which
18606                is yet another failure of not having a layer 2 (again, YAY
18607                 IETF for thinking ahead).  So we treat this as a call
18608                 forward and hope we end up at the right place... */
18609                ast_debug(1, "Hairpin detected, setting up call forward for what it's worth\n");
18610                if (p->owner)
18611                   ast_string_field_build(p->owner, call_forward,
18612                                "Local/%s@%s", p->username, p->context);
18613                /* Fall through */
18614             case 480: /* Temporarily Unavailable */
18615             case 404: /* Not Found */
18616             case 410: /* Gone */
18617             case 400: /* Bad Request */
18618             case 500: /* Server error */
18619                if (sipmethod == SIP_REFER) {
18620                   handle_response_refer(p, resp, rest, req, seqno);
18621                   break;
18622                } else if (sipmethod == SIP_SUBSCRIBE) {
18623                   handle_response_subscribe(p, resp, rest, req, seqno);
18624                   break;
18625                }
18626                /* Fall through */
18627             case 502: /* Bad gateway */
18628             case 503: /* Service Unavailable */
18629             case 504: /* Server Timeout */
18630                if (owner)
18631                   ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
18632                break;
18633             default:
18634                /* Send hangup */ 
18635                if (owner && sipmethod != SIP_MESSAGE && sipmethod != SIP_INFO && sipmethod != SIP_BYE)
18636                   ast_queue_hangup_with_cause(p->owner, AST_CAUSE_PROTOCOL_ERROR);
18637                break;
18638             }
18639             /* ACK on invite */
18640             if (sipmethod == SIP_INVITE) 
18641                transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
18642             if (sipmethod != SIP_MESSAGE && sipmethod != SIP_INFO) 
18643                sip_alreadygone(p);
18644             if (!p->owner) {
18645                pvt_set_needdestroy(p, "transaction completed");
18646             }
18647          } else if ((resp >= 100) && (resp < 200)) {
18648             if (sipmethod == SIP_INVITE) {
18649                if (!req->ignore && sip_cancel_destroy(p))
18650                   ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
18651                if (find_sdp(req))
18652                   process_sdp(p, req, SDP_T38_NONE);
18653                if (p->owner) {
18654                   /* Queue a progress frame */
18655                   ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
18656                }
18657             }
18658          } else
18659             ast_log(LOG_NOTICE, "Dont 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));
18660       }
18661    } else { 
18662       /* Responses to OUTGOING SIP requests on INCOMING calls 
18663          get handled here. As well as out-of-call message responses */
18664       if (req->debug)
18665          ast_verbose("SIP Response message for INCOMING dialog %s arrived\n", msg);
18666 
18667       if (sipmethod == SIP_INVITE && resp == 200) {
18668          /* Tags in early session is replaced by the tag in 200 OK, which is 
18669          the final reply to our INVITE */
18670          char tag[128];
18671 
18672          gettag(req, "To", tag, sizeof(tag));
18673          ast_string_field_set(p, theirtag, tag);
18674       }
18675 
18676       switch(resp) {
18677       case 200:
18678          if (sipmethod == SIP_INVITE) {
18679             handle_response_invite(p, resp, rest, req, seqno);
18680          } else if (sipmethod == SIP_CANCEL) {
18681             ast_debug(1, "Got 200 OK on CANCEL\n");
18682 
18683             /* Wait for 487, then destroy */
18684          } else if (sipmethod == SIP_NOTIFY) {
18685             /* They got the notify, this is the end */
18686             if (p->owner) {
18687                if (p->refer) {
18688                   ast_debug(1, "Got 200 OK on NOTIFY for transfer\n");
18689                } else
18690                   ast_log(LOG_WARNING, "Notify answer on an owned channel?\n");
18691                /* ast_queue_hangup(p->owner); Disabled */
18692             } else {
18693                if (!p->subscribed && !p->refer) {
18694                   pvt_set_needdestroy(p, "transaction completed");
18695                }
18696                if (ast_test_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE)) {
18697                   /* Ready to send the next state we have on queue */
18698                   ast_clear_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE);
18699                   cb_extensionstate((char *)p->context, (char *)p->exten, p->laststate, (void *) p);
18700                }
18701             }
18702          } else if (sipmethod == SIP_BYE) {
18703             pvt_set_needdestroy(p, "transaction completed");
18704          } else if (sipmethod == SIP_MESSAGE || sipmethod == SIP_INFO) {
18705             /* We successfully transmitted a message or
18706                a video update request in INFO */
18707             ;
18708          }
18709          break;
18710       case 202:   /* Transfer accepted */
18711          if (sipmethod == SIP_REFER) 
18712             handle_response_refer(p, resp, rest, req, seqno);
18713          break;
18714       case 401:   /* www-auth */
18715       case 407:
18716          if (sipmethod == SIP_REFER)
18717             handle_response_refer(p, resp, rest, req, seqno);
18718          else if (sipmethod == SIP_INVITE) 
18719             handle_response_invite(p, resp, rest, req, seqno);
18720          else if (sipmethod == SIP_BYE) {
18721             if (p->authtries == MAX_AUTHTRIES || do_proxy_auth(p, req, resp, sipmethod, 0)) {
18722                ast_log(LOG_NOTICE, "Failed to authenticate on %s to '%s'\n", msg, get_header(&p->initreq, "From"));
18723                pvt_set_needdestroy(p, "failed to authenticate BYE");
18724             }
18725          }
18726          break;
18727       case 481:   /* Call leg does not exist */
18728          if (sipmethod == SIP_INVITE) {
18729             /* Re-invite failed */
18730             handle_response_invite(p, resp, rest, req, seqno);
18731          } else if (sipmethod == SIP_BYE) {
18732             pvt_set_needdestroy(p, "received 481 response");
18733          } else if (sipdebug) {
18734             ast_debug(1, "Remote host can't match request %s to call '%s'. Giving up\n", sip_methods[sipmethod].text, p->callid);
18735          }
18736          break;
18737       case 501: /* Not Implemented */
18738          if (sipmethod == SIP_INVITE) 
18739             handle_response_invite(p, resp, rest, req, seqno);
18740          else if (sipmethod == SIP_REFER) 
18741             handle_response_refer(p, resp, rest, req, seqno);
18742          break;
18743       case 603:   /* Declined transfer */
18744          if (sipmethod == SIP_REFER) {
18745             handle_response_refer(p, resp, rest, req, seqno);
18746             break;
18747          }
18748          /* Fallthrough */
18749       default: /* Errors without handlers */
18750          if ((resp >= 100) && (resp < 200)) {
18751             if (sipmethod == SIP_INVITE) {   /* re-invite */
18752                if (!req->ignore && sip_cancel_destroy(p))
18753                   ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
18754             }
18755          }
18756          if ((resp >= 300) && (resp < 700)) {
18757             if ((resp != 487))
18758                ast_verb(3, "Incoming call: Got SIP response %d \"%s\" back from %s\n", resp, rest, ast_inet_ntoa(p->sa.sin_addr));
18759             switch(resp) {
18760             case 415: /* Unsupported media type */
18761             case 488: /* Not acceptable here - codec error */
18762             case 603: /* Decline */
18763             case 500: /* Server error */
18764             case 502: /* Bad gateway */
18765             case 503: /* Service Unavailable */
18766             case 504: /* Server timeout */
18767 
18768                /* re-invite failed */
18769                if (sipmethod == SIP_INVITE && sip_cancel_destroy(p))
18770                   ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
18771                break;
18772             }
18773          }
18774          break;
18775       }
18776    }
18777 }
18778 
18779 
18780 /*! \brief Park SIP call support function 
18781    Starts in a new thread, then parks the call
18782    XXX Should we add a wait period after streaming audio and before hangup?? Sometimes the
18783       audio can't be heard before hangup
18784 */
18785 static void *sip_park_thread(void *stuff)
18786 {
18787    struct ast_channel *transferee, *transferer; /* Chan1: The transferee, Chan2: The transferer */
18788    struct sip_dual *d;
18789    struct sip_request req = {0,};
18790    int ext;
18791    int res;
18792 
18793    d = stuff;
18794    transferee = d->chan1;
18795    transferer = d->chan2;
18796    copy_request(&req, &d->req);
18797 
18798    if (!transferee || !transferer) {
18799       ast_log(LOG_ERROR, "Missing channels for parking! Transferer %s Transferee %s\n", transferer ? "<available>" : "<missing>", transferee ? "<available>" : "<missing>" );
18800       if (d->req.data)
18801          ast_free(d->req.data);
18802       free(d);
18803       return NULL;
18804    }
18805    ast_debug(4, "SIP Park: Transferer channel %s, Transferee %s\n", transferer->name, transferee->name);
18806 
18807    ast_channel_lock(transferee);
18808    if (ast_do_masquerade(transferee)) {
18809       ast_log(LOG_WARNING, "Masquerade failed.\n");
18810       transmit_response(transferer->tech_pvt, "503 Internal error", &req);
18811       ast_channel_unlock(transferee);
18812       if (d->req.data)
18813          ast_free(d->req.data);
18814       free(d);
18815       return NULL;
18816    } 
18817    ast_channel_unlock(transferee);
18818 
18819    res = ast_park_call(transferee, transferer, 0, &ext);
18820    
18821 
18822 #ifdef WHEN_WE_KNOW_THAT_THE_CLIENT_SUPPORTS_MESSAGE
18823    if (!res) {
18824       transmit_message_with_text(transferer->tech_pvt, "Unable to park call.\n");
18825    } else {
18826       /* Then tell the transferer what happened */
18827       sprintf(buf, "Call parked on extension '%d'", ext);
18828       transmit_message_with_text(transferer->tech_pvt, buf);
18829    }
18830 #endif
18831 
18832    /* Any way back to the current call??? */
18833    /* Transmit response to the REFER request */
18834    transmit_response(transferer->tech_pvt, "202 Accepted", &req);
18835    if (!res)   {
18836       /* Transfer succeeded */
18837       append_history(transferer->tech_pvt, "SIPpark", "Parked call on %d", ext);
18838       transmit_notify_with_sipfrag(transferer->tech_pvt, d->seqno, "200 OK", TRUE);
18839       transferer->hangupcause = AST_CAUSE_NORMAL_CLEARING;
18840       ast_hangup(transferer); /* This will cause a BYE */
18841       ast_debug(1, "SIP Call parked on extension '%d'\n", ext);
18842    } else {
18843       transmit_notify_with_sipfrag(transferer->tech_pvt, d->seqno, "503 Service Unavailable", TRUE);
18844       append_history(transferer->tech_pvt, "SIPpark", "Parking failed\n");
18845       ast_debug(1, "SIP Call parked failed \n");
18846       /* Do not hangup call */
18847    }
18848    if (d->req.data)
18849       ast_free(d->req.data);
18850    free(d);
18851    return NULL;
18852 }
18853 
18854 /*! \brief Park a call using the subsystem in res_features.c 
18855    This is executed in a separate thread
18856 */
18857 static int sip_park(struct ast_channel *chan1, struct ast_channel *chan2, struct sip_request *req, int seqno)
18858 {
18859    struct sip_dual *d;
18860    struct ast_channel *transferee, *transferer;
18861       /* Chan2m: The transferer, chan1m: The transferee */
18862    pthread_t th;
18863 
18864    transferee = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, chan1->accountcode, chan1->exten, chan1->context, chan1->amaflags, "Parking/%s", chan1->name);
18865    transferer = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, chan2->accountcode, chan2->exten, chan2->context, chan2->amaflags, "SIPPeer/%s", chan2->name);
18866    if ((!transferer) || (!transferee)) {
18867       if (transferee) {
18868          transferee->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
18869          ast_hangup(transferee);
18870       }
18871       if (transferer) {
18872          transferer->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
18873          ast_hangup(transferer);
18874       }
18875       return -1;
18876    }
18877 
18878    /* Make formats okay */
18879    transferee->readformat = chan1->readformat;
18880    transferee->writeformat = chan1->writeformat;
18881 
18882    /* Prepare for taking over the channel */
18883    ast_channel_masquerade(transferee, chan1);
18884 
18885    /* Setup the extensions and such */
18886    ast_copy_string(transferee->context, chan1->context, sizeof(transferee->context));
18887    ast_copy_string(transferee->exten, chan1->exten, sizeof(transferee->exten));
18888    transferee->priority = chan1->priority;
18889       
18890    /* We make a clone of the peer channel too, so we can play
18891       back the announcement */
18892 
18893    /* Make formats okay */
18894    transferer->readformat = chan2->readformat;
18895    transferer->writeformat = chan2->writeformat;
18896    if (!ast_strlen_zero(chan2->parkinglot))
18897       ast_string_field_set(transferer, parkinglot, chan2->parkinglot);
18898 
18899    /* Prepare for taking over the channel.  Go ahead and grab this channel
18900     * lock here to avoid a deadlock with callbacks into the channel driver
18901     * that hold the channel lock and want the pvt lock.  */
18902    while (ast_channel_trylock(chan2)) {
18903       struct sip_pvt *pvt = chan2->tech_pvt;
18904       sip_pvt_unlock(pvt);
18905       usleep(1);
18906       sip_pvt_lock(pvt);
18907    }
18908    ast_channel_masquerade(transferer, chan2);
18909    ast_channel_unlock(chan2);
18910 
18911    /* Setup the extensions and such */
18912    ast_copy_string(transferer->context, chan2->context, sizeof(transferer->context));
18913    ast_copy_string(transferer->exten, chan2->exten, sizeof(transferer->exten));
18914    transferer->priority = chan2->priority;
18915 
18916    ast_channel_lock(transferer);
18917    if (ast_do_masquerade(transferer)) {
18918       ast_log(LOG_WARNING, "Masquerade failed :(\n");
18919       ast_channel_unlock(transferer);
18920       transferer->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
18921       ast_hangup(transferer);
18922       return -1;
18923    }
18924    ast_channel_unlock(transferer);
18925    if (!transferer || !transferee) {
18926       if (!transferer) { 
18927          ast_debug(1, "No transferer channel, giving up parking\n");
18928       }
18929       if (!transferee) {
18930          ast_debug(1, "No transferee channel, giving up parking\n");
18931       }
18932       return -1;
18933    }
18934    if ((d = ast_calloc(1, sizeof(*d)))) {
18935 
18936       /* Save original request for followup */
18937       copy_request(&d->req, req);
18938       d->chan1 = transferee;  /* Transferee */
18939       d->chan2 = transferer;  /* Transferer */
18940       d->seqno = seqno;
18941       if (ast_pthread_create_detached_background(&th, NULL, sip_park_thread, d) < 0) {
18942          /* Could not start thread */
18943          if (d->req.data)
18944             ast_free(d->req.data);
18945          ast_free(d);   /* We don't need it anymore. If thread is created, d will be free'd
18946                   by sip_park_thread() */
18947          return 0;
18948       }
18949    } 
18950    return -1;
18951 }
18952 
18953 /*! \brief Turn off generator data 
18954    XXX Does this function belong in the SIP channel?
18955 */
18956 static void ast_quiet_chan(struct ast_channel *chan) 
18957 {
18958    if (chan && chan->_state == AST_STATE_UP) {
18959       if (ast_test_flag(chan, AST_FLAG_MOH))
18960          ast_moh_stop(chan);
18961       else if (chan->generatordata)
18962          ast_deactivate_generator(chan);
18963    }
18964 }
18965 
18966 /*! \brief Attempt transfer of SIP call 
18967    This fix for attended transfers on a local PBX */
18968 static int attempt_transfer(struct sip_dual *transferer, struct sip_dual *target)
18969 {
18970    int res = 0;
18971    struct ast_channel *peera = NULL,   
18972       *peerb = NULL,
18973       *peerc = NULL,
18974       *peerd = NULL;
18975 
18976 
18977    /* We will try to connect the transferee with the target and hangup
18978       all channels to the transferer */   
18979    ast_debug(4, "Sip transfer:--------------------\n");
18980    if (transferer->chan1)
18981       ast_debug(4, "-- Transferer to PBX channel: %s State %s\n", transferer->chan1->name, ast_state2str(transferer->chan1->_state));
18982    else
18983       ast_debug(4, "-- No transferer first channel - odd??? \n");
18984    if (target->chan1)
18985       ast_debug(4, "-- Transferer to PBX second channel (target): %s State %s\n", target->chan1->name, ast_state2str(target->chan1->_state));
18986    else
18987       ast_debug(4, "-- No target first channel ---\n");
18988    if (transferer->chan2)
18989       ast_debug(4, "-- Bridged call to transferee: %s State %s\n", transferer->chan2->name, ast_state2str(transferer->chan2->_state));
18990    else
18991       ast_debug(4, "-- No bridged call to transferee\n");
18992    if (target->chan2)
18993       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)");
18994    else
18995       ast_debug(4, "-- No target second channel ---\n");
18996    ast_debug(4, "-- END Sip transfer:--------------------\n");
18997    if (transferer->chan2) { /* We have a bridge on the transferer's channel */
18998       peera = transferer->chan1; /* Transferer - PBX -> transferee channel * the one we hangup */
18999       peerb = target->chan1;     /* Transferer - PBX -> target channel - This will get lost in masq */
19000       peerc = transferer->chan2; /* Asterisk to Transferee */
19001       peerd = target->chan2;     /* Asterisk to Target */
19002       ast_debug(3, "SIP transfer: Four channels to handle\n");
19003    } else if (target->chan2) {   /* Transferer has no bridge (IVR), but transferee */
19004       peera = target->chan1;     /* Transferer to PBX -> target channel */
19005       peerb = transferer->chan1; /* Transferer to IVR*/
19006       peerc = target->chan2;     /* Asterisk to Target */
19007       peerd = transferer->chan2; /* Nothing */
19008       ast_debug(3, "SIP transfer: Three channels to handle\n");
19009    }
19010 
19011    if (peera && peerb && peerc && (peerb != peerc)) {
19012       ast_quiet_chan(peera);     /* Stop generators */
19013       ast_quiet_chan(peerb);  
19014       ast_quiet_chan(peerc);
19015       if (peerd)
19016          ast_quiet_chan(peerd);
19017 
19018       ast_debug(4, "SIP transfer: trying to masquerade %s into %s\n", peerc->name, peerb->name);
19019       if (ast_channel_masquerade(peerb, peerc)) {
19020          ast_log(LOG_WARNING, "Failed to masquerade %s into %s\n", peerb->name, peerc->name);
19021          res = -1;
19022       } else
19023          ast_debug(4, "SIP transfer: Succeeded to masquerade channels.\n");
19024       return res;
19025    } else {
19026       ast_log(LOG_NOTICE, "SIP Transfer attempted with no appropriate bridged calls to transfer\n");
19027       if (transferer->chan1)
19028          ast_softhangup_nolock(transferer->chan1, AST_SOFTHANGUP_DEV);
19029       if (target->chan1)
19030          ast_softhangup_nolock(target->chan1, AST_SOFTHANGUP_DEV);
19031       return -1;
19032    }
19033    return 0;
19034 }
19035 
19036 /*! \brief Get tag from packet 
19037  *
19038  * \return Returns the pointer to the provided tag buffer,
19039  *         or NULL if the tag was not found.
19040  */
19041 static const char *gettag(const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize)
19042 {
19043    const char *thetag;
19044 
19045    if (!tagbuf)
19046       return NULL;
19047    tagbuf[0] = '\0';    /* reset the buffer */
19048    thetag = get_header(req, header);
19049    thetag = strcasestr(thetag, ";tag=");
19050    if (thetag) {
19051       thetag += 5;
19052       ast_copy_string(tagbuf, thetag, tagbufsize);
19053       return strsep(&tagbuf, ";");
19054    }
19055    return NULL;
19056 }
19057 
19058 /*! \brief Handle incoming notifications */
19059 static int handle_request_notify(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e)
19060 {
19061    /* This is mostly a skeleton for future improvements */
19062    /* Mostly created to return proper answers on notifications on outbound REFER's */
19063    int res = 0;
19064    const char *event = get_header(req, "Event");
19065    char *eventid = NULL;
19066    char *sep;
19067 
19068    if( (sep = strchr(event, ';')) ) {  /* XXX bug here - overwriting string ? */
19069       *sep++ = '\0';
19070       eventid = sep;
19071    }
19072    
19073    if (sipdebug)
19074       ast_debug(2, "Got NOTIFY Event: %s\n", event);
19075 
19076    if (!strcmp(event, "refer")) {
19077       /* Save nesting depth for now, since there might be other events we will
19078          support in the future */
19079 
19080       /* Handle REFER notifications */
19081 
19082       char buf[1024];
19083       char *cmd, *code;
19084       int respcode;
19085       int success = TRUE;
19086 
19087       /* EventID for each transfer... EventID is basically the REFER cseq 
19088 
19089        We are getting notifications on a call that we transfered
19090        We should hangup when we are getting a 200 OK in a sipfrag
19091        Check if we have an owner of this event */
19092       
19093       /* Check the content type */
19094       if (strncasecmp(get_header(req, "Content-Type"), "message/sipfrag", strlen("message/sipfrag"))) {
19095          /* We need a sipfrag */
19096          transmit_response(p, "400 Bad request", req);
19097          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19098          return -1;
19099       }
19100 
19101       /* Get the text of the attachment */
19102       if (get_msg_text(buf, sizeof(buf), req, TRUE)) {
19103          ast_log(LOG_WARNING, "Unable to retrieve attachment from NOTIFY %s\n", p->callid);
19104          transmit_response(p, "400 Bad request", req);
19105          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19106          return -1;
19107       }
19108 
19109       /*
19110       From the RFC...
19111       A minimal, but complete, implementation can respond with a single
19112       NOTIFY containing either the body:
19113          SIP/2.0 100 Trying
19114       
19115       if the subscription is pending, the body:
19116          SIP/2.0 200 OK
19117       if the reference was successful, the body:
19118          SIP/2.0 503 Service Unavailable
19119       if the reference failed, or the body:
19120          SIP/2.0 603 Declined
19121 
19122       if the REFER request was accepted before approval to follow the
19123       reference could be obtained and that approval was subsequently denied
19124       (see Section 2.4.7).
19125       
19126       If there are several REFERs in the same dialog, we need to
19127       match the ID of the event header...
19128       */
19129       ast_debug(3, "* SIP Transfer NOTIFY Attachment: \n---%s\n---\n", buf);
19130       cmd = ast_skip_blanks(buf);
19131       code = cmd;
19132       /* We are at SIP/2.0 */
19133       while(*code && (*code > 32)) {   /* Search white space */
19134          code++;
19135       }
19136       *code++ = '\0';
19137       code = ast_skip_blanks(code);
19138       sep = code;
19139       sep++;
19140       while(*sep && (*sep > 32)) {  /* Search white space */
19141          sep++;
19142       }
19143       *sep++ = '\0';       /* Response string */
19144       respcode = atoi(code);
19145       switch (respcode) {
19146       case 100:   /* Trying: */
19147       case 101:   /* dialog establishment */
19148          /* Don't do anything yet */
19149          break;
19150       case 183:   /* Ringing: */
19151          /* Don't do anything yet */
19152          break;
19153       case 200:   /* OK: The new call is up, hangup this call */
19154          /* Hangup the call that we are replacing */
19155          break;
19156       case 301: /* Moved permenantly */
19157       case 302: /* Moved temporarily */
19158          /* Do we get the header in the packet in this case? */
19159          success = FALSE;
19160          break;
19161       case 503:   /* Service Unavailable: The new call failed */
19162             /* Cancel transfer, continue the call */
19163          success = FALSE;
19164          break;
19165       case 603:   /* Declined: Not accepted */
19166             /* Cancel transfer, continue the current call */
19167          success = FALSE;
19168          break;
19169       }
19170       if (!success) {
19171          ast_log(LOG_NOTICE, "Transfer failed. Sorry. Nothing further to do with this call\n");
19172       }
19173       
19174       /* Confirm that we received this packet */
19175       transmit_response(p, "200 OK", req);
19176    } else if (p->mwi && !strcmp(event, "message-summary")) {
19177       char *c = ast_strdupa(get_body(req, "Voice-Message", ':'));
19178 
19179       if (!ast_strlen_zero(c)) {
19180          char *old = strsep(&c, " ");
19181          char *new = strsep(&old, "/");
19182          struct ast_event *event;
19183 
19184          if ((event = ast_event_new(AST_EVENT_MWI,
19185                      AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, p->mwi->mailbox,
19186                      AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, "SIP_Remote",
19187                      AST_EVENT_IE_NEWMSGS, AST_EVENT_IE_PLTYPE_UINT, atoi(new),
19188                      AST_EVENT_IE_OLDMSGS, AST_EVENT_IE_PLTYPE_UINT, atoi(old),
19189                      AST_EVENT_IE_END))) {
19190             ast_event_queue_and_cache(event);
19191          }
19192       }
19193 
19194       transmit_response(p, "200 OK", req);
19195    } else if (!strcmp(event, "keep-alive")) {
19196        /* Used by Sipura/Linksys for NAT pinhole,
19197         * just confirm that we recieved the packet. */
19198       transmit_response(p, "200 OK", req);
19199    } else {
19200       /* We don't understand this event. */
19201       transmit_response(p, "489 Bad event", req);
19202       res = -1;
19203    }
19204 
19205    if (!p->lastinvite)
19206       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19207 
19208    return res;
19209 }
19210 
19211 /*! \brief Handle incoming OPTIONS request 
19212    An OPTIONS request should be answered like an INVITE from the same UA, including SDP
19213 */
19214 static int handle_request_options(struct sip_pvt *p, struct sip_request *req)
19215 {
19216    int res;
19217 
19218    /*! XXX get_destination assumes we're already authenticated. This means that a request from
19219       a known device (peer) will end up in the wrong context if this is out-of-dialog.
19220       However, we want to handle OPTIONS as light as possible, so we might want to have
19221       a configuration option whether we care or not. Some devices use this for testing
19222       capabilities, which means that we need to match device to answer with proper 
19223       capabilities (including SDP).
19224       \todo Fix handle_request_options device handling with optional authentication
19225          (this needs to be fixed in 1.4 as well)
19226    */
19227 
19228    if (p->lastinvite) {
19229       /* if this is a request in an active dialog, just confirm that the dialog exists. */
19230       transmit_response_with_allow(p, "200 OK", req, 0);
19231       return 0;
19232    }
19233 
19234    res = get_destination(p, req);
19235    build_contact(p);
19236 
19237    if (ast_strlen_zero(p->context))
19238       ast_string_field_set(p, context, sip_cfg.default_context);
19239 
19240    if (ast_shutting_down())
19241       transmit_response_with_allow(p, "503 Unavailable", req, 0);
19242    else if (res < 0)
19243       transmit_response_with_allow(p, "404 Not Found", req, 0);
19244    else 
19245       transmit_response_with_allow(p, "200 OK", req, 0);
19246 
19247    /* Destroy if this OPTIONS was the opening request, but not if
19248       it's in the middle of a normal call flow. */
19249    sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19250 
19251    return res;
19252 }
19253 
19254 /*! \brief Handle the transfer part of INVITE with a replaces: header, 
19255     meaning a target pickup or an attended transfer.
19256     Used only once.
19257    XXX 'ignore' is unused.
19258 
19259    \note this function is called by handle_request_invite(). Four locks
19260    held at the beginning of this function, p, p->owner, p->refer->refer_call->owner...
19261    only p's lock should remain at the end of this function.  p's lock is held by sipsock_read()
19262  */
19263 static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, struct sockaddr_in *sin, int *nounlock)
19264 {
19265    int earlyreplace = 0;
19266    int oneleggedreplace = 0;     /* Call with no bridge, propably IVR or voice message */
19267    struct ast_channel *c = p->owner;   /* Our incoming call */
19268    struct ast_channel *replacecall = p->refer->refer_call->owner; /* The channel we're about to take over */
19269    struct ast_channel *targetcall;     /* The bridge to the take-over target */
19270 
19271    struct ast_channel *test;
19272 
19273    /* Check if we're in ring state */
19274    if (replacecall->_state == AST_STATE_RING)
19275       earlyreplace = 1;
19276 
19277    /* Check if we have a bridge */
19278    if (!(targetcall = ast_bridged_channel(replacecall))) {
19279       /* We have no bridge */
19280       if (!earlyreplace) {
19281          ast_debug(2, " Attended transfer attempted to replace call with no bridge (maybe ringing). Channel %s!\n", replacecall->name);
19282          oneleggedreplace = 1;
19283       }
19284    } 
19285    if (targetcall && targetcall->_state == AST_STATE_RINGING)
19286       ast_debug(4, "SIP transfer: Target channel is in ringing state\n");
19287 
19288    if (targetcall) 
19289       ast_debug(4, "SIP transfer: Invite Replace incoming channel should bridge to channel %s while hanging up channel %s\n", targetcall->name, replacecall->name); 
19290    else
19291       ast_debug(4, "SIP transfer: Invite Replace incoming channel should replace and hang up channel %s (one call leg)\n", replacecall->name); 
19292 
19293    if (req->ignore) {
19294       ast_log(LOG_NOTICE, "Ignoring this INVITE with replaces in a stupid way.\n");
19295       /* We should answer something here. If we are here, the
19296          call we are replacing exists, so an accepted 
19297          can't harm */
19298       transmit_response_with_sdp(p, "200 OK", req, XMIT_RELIABLE, FALSE);
19299       /* Do something more clever here */
19300       if (c) {
19301          *nounlock = 1;
19302          ast_channel_unlock(c);
19303       }
19304       ast_channel_unlock(replacecall);
19305       sip_pvt_unlock(p->refer->refer_call);
19306       return 1;
19307    } 
19308    if (!c) {
19309       /* What to do if no channel ??? */
19310       ast_log(LOG_ERROR, "Unable to create new channel.  Invite/replace failed.\n");
19311       transmit_response_reliable(p, "503 Service Unavailable", req);
19312       append_history(p, "Xfer", "INVITE/Replace Failed. No new channel.");
19313       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19314       ast_channel_unlock(replacecall);
19315       sip_pvt_unlock(p->refer->refer_call);
19316       return 1;
19317    }
19318    append_history(p, "Xfer", "INVITE/Replace received");
19319    /* We have three channels to play with
19320       channel c: New incoming call
19321       targetcall: Call from PBX to target
19322       p->refer->refer_call: SIP pvt dialog from transferer to pbx.
19323       replacecall: The owner of the previous
19324       We need to masq C into refer_call to connect to 
19325       targetcall;
19326       If we are talking to internal audio stream, target call is null.
19327    */
19328 
19329    /* Fake call progress */
19330    transmit_response(p, "100 Trying", req);
19331    ast_setstate(c, AST_STATE_RING);
19332 
19333    /* Masquerade the new call into the referred call to connect to target call 
19334       Targetcall is not touched by the masq */
19335 
19336    /* Answer the incoming call and set channel to UP state */
19337    transmit_response_with_sdp(p, "200 OK", req, XMIT_RELIABLE, FALSE);
19338       
19339    ast_setstate(c, AST_STATE_UP);
19340    
19341    /* Stop music on hold and other generators */
19342    ast_quiet_chan(replacecall);
19343    ast_quiet_chan(targetcall);
19344    ast_debug(4, "Invite/Replaces: preparing to masquerade %s into %s\n", c->name, replacecall->name);
19345 
19346    /* Make sure that the masq does not free our PVT for the old call */
19347    if (! earlyreplace && ! oneleggedreplace )
19348       ast_set_flag(&p->refer->refer_call->flags[0], SIP_DEFER_BYE_ON_TRANSFER);  /* Delay hangup */
19349 
19350    /* Prepare the masquerade - if this does not happen, we will be gone */
19351    if(ast_channel_masquerade(replacecall, c))
19352       ast_log(LOG_ERROR, "Failed to masquerade C into Replacecall\n");
19353    else
19354       ast_debug(4, "Invite/Replaces: Going to masquerade %s into %s\n", c->name, replacecall->name);
19355 
19356    /* C should now be in place of replacecall */
19357    if (ast_do_masquerade(replacecall)) {
19358       ast_log(LOG_WARNING, "Failed to perform masquerade with INVITE replaces\n");
19359    }
19360 
19361    if (earlyreplace || oneleggedreplace ) {
19362       c->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
19363    }
19364 
19365    ast_setstate(c, AST_STATE_DOWN);
19366    ast_debug(4, "After transfer:----------------------------\n");
19367    ast_debug(4, " -- C:        %s State %s\n", c->name, ast_state2str(c->_state));
19368    if (replacecall)
19369       ast_debug(4, " -- replacecall:        %s State %s\n", replacecall->name, ast_state2str(replacecall->_state));
19370    if (p->owner) {
19371       ast_debug(4, " -- P->owner: %s State %s\n", p->owner->name, ast_state2str(p->owner->_state));
19372       test = ast_bridged_channel(p->owner);
19373       if (test)
19374          ast_debug(4, " -- Call bridged to P->owner: %s State %s\n", test->name, ast_state2str(test->_state));
19375       else
19376          ast_debug(4, " -- No call bridged to C->owner \n");
19377    } else 
19378       ast_debug(4, " -- No channel yet \n");
19379    ast_debug(4, "End After transfer:----------------------------\n");
19380 
19381    /* unlock sip pvt and owner so hangup can do its thing */
19382    ast_channel_unlock(replacecall);
19383    ast_channel_unlock(c);
19384    sip_pvt_unlock(p->refer->refer_call);
19385    sip_pvt_unlock(p);
19386    *nounlock = 1;
19387 
19388    /* The call should be down with no ast_channel, so hang it up */
19389    c->tech_pvt = dialog_unref(c->tech_pvt, "unref dialog c->tech_pvt");
19390    ast_hangup(c);
19391    sip_pvt_lock(p); /* lock PVT structure again after hangup */
19392 
19393    return 0;
19394 }
19395 
19396 /*! \brief helper routine for sip_uri_cmp
19397  *
19398  * This takes the parameters from two SIP URIs and determines
19399  * if the URIs match. The rules for parameters *suck*. Here's a breakdown
19400  * 1. If a parameter appears in both URIs, then they must have the same value
19401  *    in order for the URIs to match
19402  * 2. If one URI has a user, maddr, ttl, or method parameter, then the other
19403  *    URI must also have that parameter and must have the same value
19404  *    in order for the URIs to match
19405  * 3. All other headers appearing in only one URI are not considered when
19406  *    determining if URIs match
19407  *
19408  * \param input1 Parameters from URI 1
19409  * \param input2 Parameters from URI 2
19410  * \return Return 0 if the URIs' parameters match, 1 if they do not
19411  */
19412 static int sip_uri_params_cmp(const char *input1, const char *input2) 
19413 {
19414    char *params1 = NULL;
19415    char *params2 = NULL;
19416    char *pos1;
19417    char *pos2;
19418    int zerolength1 = 0;
19419    int zerolength2 = 0;
19420    int maddrmatch = 0;
19421    int ttlmatch = 0;
19422    int usermatch = 0;
19423    int methodmatch = 0;
19424 
19425    if (ast_strlen_zero(input1)) {
19426       zerolength1 = 1;
19427    } else {
19428       params1 = ast_strdupa(input1);
19429    }
19430    if (ast_strlen_zero(input2)) {
19431       zerolength2 = 1;
19432    } else {
19433       params2 = ast_strdupa(input2);
19434    }
19435 
19436    /*Quick optimization. If both params are zero-length, then
19437     * they match
19438     */
19439    if (zerolength1 && zerolength2) {
19440       return 0;
19441    }
19442 
19443    pos1 = params1;
19444    while (!ast_strlen_zero(pos1)) {
19445       char *name1 = pos1;
19446       char *value1 = strchr(pos1, '=');
19447       char *semicolon1 = strchr(pos1, ';');
19448       int matched = 0;
19449       if (semicolon1) {
19450          *semicolon1++ = '\0';
19451       }
19452       if (!value1) {
19453          goto fail;
19454       }
19455       *value1++ = '\0';
19456       /* Checkpoint reached. We have the name and value parsed for param1 
19457        * We have to duplicate params2 each time through the second loop
19458        * or else we can't search and replace the semicolons with \0 each
19459        * time
19460        */
19461       pos2 = ast_strdupa(params2);
19462       while (!ast_strlen_zero(pos2)) {
19463          char *name2 = pos2;
19464          char *value2 = strchr(pos2, '=');
19465          char *semicolon2 = strchr(pos2, ';');
19466          if (semicolon2) {
19467             *semicolon2++ = '\0';
19468          }
19469          if (!value2) {
19470             goto fail;
19471          }
19472          *value2++ = '\0';
19473          if (!strcasecmp(name1, name2)) {
19474             if (strcasecmp(value1, value2)) {
19475                goto fail;
19476             } else {
19477                matched = 1;
19478                break;
19479             }
19480          }
19481          pos2 = semicolon2;
19482       }
19483       /* Need to see if the parameter we're looking at is one of the 'must-match' parameters */
19484       if (!strcasecmp(name1, "maddr")) {
19485          if (matched) {
19486             maddrmatch = 1;
19487          } else {
19488             goto fail;
19489          }
19490       } else if (!strcasecmp(name1, "ttl")) {
19491          if (matched) {
19492             ttlmatch = 1;
19493          } else {
19494             goto fail;
19495          }
19496       } else if (!strcasecmp(name1, "user")) {
19497          if (matched) {
19498             usermatch = 1;
19499          } else {
19500             goto fail;
19501          }
19502       } else if (!strcasecmp(name1, "method")) {
19503          if (matched) {
19504             methodmatch = 1;
19505          } else {
19506             goto fail;
19507          }
19508       }
19509       pos1 = semicolon1;
19510    }
19511 
19512    /* We've made it out of that horrible O(m*n) construct and there are no
19513     * failures yet. We're not done yet, though, because params2 could have
19514     * an maddr, ttl, user, or method header and params1 did not.
19515     */
19516    pos2 = params2;
19517    while (!ast_strlen_zero(pos2)) {
19518       char *name2 = pos2;
19519       char *value2 = strchr(pos2, '=');
19520       char *semicolon2 = strchr(pos2, ';');
19521       if (semicolon2) {
19522          *semicolon2++ = '\0';
19523       }
19524       if (!value2) {
19525          goto fail;
19526       }
19527       *value2++ = '\0';
19528       if ((!strcasecmp(name2, "maddr") && !maddrmatch) ||
19529             (!strcasecmp(name2, "ttl") && !ttlmatch) ||
19530             (!strcasecmp(name2, "user") && !usermatch) ||
19531             (!strcasecmp(name2, "method") && !methodmatch)) {
19532          goto fail;
19533       }
19534    }
19535    return 0;
19536 
19537 fail:
19538    return 1;
19539 }
19540 
19541 /*! \brief helper routine for sip_uri_cmp
19542  *
19543  * This takes the "headers" from two SIP URIs and determines
19544  * if the URIs match. The rules for headers is simple. If a header
19545  * appears in one URI, then it must also appear in the other URI. The
19546  * order in which the headers appear does not matter.
19547  *
19548  * \param input1 Headers from URI 1
19549  * \param input2 Headers from URI 2
19550  * \return Return 0 if the URIs' headers match, 1 if they do not
19551  */
19552 static int sip_uri_headers_cmp(const char *input1, const char *input2)
19553 {
19554    char *headers1 = NULL;
19555    char *headers2 = NULL;
19556    int zerolength1 = 0;
19557    int zerolength2 = 0;
19558    int different = 0;
19559    char *header1;
19560 
19561    if (ast_strlen_zero(input1)) {
19562       zerolength1 = 1;
19563    } else {
19564       headers1 = ast_strdupa(input1);
19565    }
19566    
19567    if (ast_strlen_zero(input2)) {
19568       zerolength2 = 1;
19569    } else {
19570       headers2 = ast_strdupa(input2);
19571    }
19572 
19573    if ((zerolength1 && !zerolength2) ||
19574          (zerolength2 && !zerolength1))
19575       return 1;
19576 
19577    if (zerolength1 && zerolength2)
19578       return 0;
19579 
19580    /* At this point, we can definitively state that both inputs are
19581     * not zero-length. First, one more optimization. If the length
19582     * of the headers is not equal, then we definitely have no match
19583     */
19584    if (strlen(headers1) != strlen(headers2)) {
19585       return 1;
19586    }
19587 
19588    for (header1 = strsep(&headers1, "&"); header1; header1 = strsep(&headers1, "&")) {
19589       if (!strcasestr(headers2, header1)) {
19590          different = 1;
19591          break;
19592       }
19593    }
19594 
19595    return different;
19596 }
19597 
19598 static int sip_uri_cmp(const char *input1, const char *input2)
19599 {
19600    char *uri1 = ast_strdupa(input1);
19601    char *uri2 = ast_strdupa(input2);
19602    char *host1;
19603    char *host2;
19604    char *params1;
19605    char *params2;
19606    char *headers1;
19607    char *headers2;
19608 
19609    /* Strip off "sip:" from the URI. We know this is present
19610     * because it was checked back in parse_request()
19611     */
19612    strsep(&uri1, ":");
19613    strsep(&uri2, ":");
19614 
19615    if ((host1 = strchr(uri1, '@'))) {
19616       *host1++ = '\0';
19617    }
19618    if ((host2 = strchr(uri2, '@'))) {
19619       *host2++ = '\0';
19620    }
19621 
19622    /* Check for mismatched username and passwords. This is the
19623     * only case-sensitive comparison of a SIP URI
19624     */
19625    if ((host1 && !host2) ||
19626          (host2 && !host1) ||
19627          (host1 && host2 && strcmp(uri1, uri2))) {
19628       return 1;
19629    }
19630 
19631    if (!host1)
19632       host1 = uri1;
19633    if (!host2)
19634       host2 = uri2;
19635 
19636    /* Strip off the parameters and headers so we can compare
19637     * host and port
19638     */
19639 
19640    if ((params1 = strchr(host1, ';'))) {
19641       *params1++ = '\0';
19642    }
19643    if ((params2 = strchr(host2, ';'))) {
19644       *params2++ = '\0';
19645    }
19646 
19647    /* Headers come after parameters, but there may be headers without
19648     * parameters, thus the S_OR
19649     */
19650    if ((headers1 = strchr(S_OR(params1, host1), '?'))) {
19651       *headers1++ = '\0';
19652    }
19653    if ((headers2 = strchr(S_OR(params2, host2), '?'))) {
19654       *headers2++ = '\0';
19655    }
19656 
19657    /* Now the host/port are properly isolated. We can get by with a string comparison
19658     * because the SIP URI checking rules have some interesting exceptions that make
19659     * this possible. I will note 2 in particular
19660     * 1. hostnames which resolve to the same IP address as well as a hostname and its
19661     *    IP address are not considered a match with SIP URI's.
19662     * 2. If one URI specifies a port and the other does not, then the URIs do not match.
19663     *    This includes if one URI explicitly contains port 5060 and the other implies it
19664     *    by not having a port specified.
19665     */
19666 
19667    if (strcasecmp(host1, host2)) {
19668       return 1;
19669    }
19670 
19671    /* Headers have easier rules to follow, so do those first */
19672    if (sip_uri_headers_cmp(headers1, headers2)) {
19673       return 1;
19674    }
19675 
19676    /* And now the parameters. Ugh */
19677    return sip_uri_params_cmp(params1, params2);
19678 }
19679 
19680 static int do_magic_pickup(struct ast_channel *channel, const char *extension, const char *context)
19681 {
19682    struct ast_str *str = ast_str_alloca(AST_MAX_EXTENSION + AST_MAX_CONTEXT + 2);
19683    struct ast_app *pickup = pbx_findapp("Pickup");
19684 
19685    if (!pickup) {
19686       ast_log(LOG_ERROR, "Unable to perform pickup: Application 'Pickup' not loaded (app_directed_pickup.so).\n");
19687       return -1;
19688    }
19689 
19690    ast_str_set(&str, 0, "%s@%s", extension, sip_cfg.notifycid == IGNORE_CONTEXT ? "PICKUPMARK" : context);
19691 
19692    ast_debug(2, "About to call Pickup(%s)\n", str->str);
19693 
19694    /* There is no point in capturing the return value since pickup_exec
19695       doesn't return anything meaningful unless the passed data is an empty
19696       string (which in our case it will not be) */
19697    pbx_exec(channel, pickup, str->str);
19698 
19699    return 0;
19700 }
19701 
19702 /*! \brief Called to deny a T38 reinvite if the core does not respond to our request */
19703 static int sip_t38_abort(const void *data)
19704 {
19705    struct sip_pvt *p = (struct sip_pvt *) data;
19706 
19707    sip_pvt_lock(p);
19708    /* an application may have taken ownership of the T.38 negotiation on this
19709     * channel while we were waiting to grab the lock... if it did, the scheduler
19710     * id will have been reset to -1, which is our indication that we do *not*
19711     * want to abort the negotiation process
19712     */
19713    if (p->t38id != -1) {
19714       change_t38_state(p, T38_DISABLED);
19715       transmit_response_reliable(p, "488 Not acceptable here", &p->initreq);
19716       p->t38id = -1;
19717       dialog_unref(p, "unref the dialog ptr from sip_t38_abort, because it held a dialog ptr");
19718    }
19719    sip_pvt_unlock(p);
19720    return 0;
19721 }
19722 
19723 /*! \brief Handle incoming INVITE request
19724 \note    If the INVITE has a Replaces header, it is part of an
19725  * attended transfer. If so, we do not go through the dial
19726  * plan but tries to find the active call and masquerade
19727  * into it 
19728  */
19729 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)
19730 {
19731    int res = 1;
19732    int gotdest;
19733    const char *p_replaces;
19734    char *replace_id = NULL;
19735    int refer_locked = 0;
19736    const char *required;
19737    unsigned int required_profile = 0;
19738    struct ast_channel *c = NULL;    /* New channel */
19739    int reinvite = 0;
19740    int rtn;
19741 
19742    const char *p_uac_se_hdr;       /* UAC's Session-Expires header string                      */
19743    const char *p_uac_min_se;       /* UAC's requested Min-SE interval (char string)            */
19744    int uac_max_se = -1;            /* UAC's Session-Expires in integer format                  */
19745    int uac_min_se = -1;            /* UAC's Min-SE in integer format                           */
19746    int st_active = FALSE;          /* Session-Timer on/off boolean                             */
19747    int st_interval = 0;            /* Session-Timer negotiated refresh interval                */
19748    enum st_refresher st_ref;       /* Session-Timer session refresher                          */
19749    int dlg_min_se = -1;
19750    struct {
19751       char exten[AST_MAX_EXTENSION];
19752       char context[AST_MAX_CONTEXT];
19753    } pickup = {
19754       .exten = "",
19755    };
19756    st_ref = SESSION_TIMER_REFRESHER_AUTO;
19757 
19758    /* Find out what they support */
19759    if (!p->sipoptions) {
19760       const char *supported = get_header(req, "Supported");
19761       if (!ast_strlen_zero(supported))
19762          parse_sip_options(p, supported);
19763    }
19764 
19765    /* Find out what they require */
19766    required = get_header(req, "Require");
19767    if (!ast_strlen_zero(required)) {
19768       required_profile = parse_sip_options(NULL, required);
19769       if (required_profile && !(required_profile & (SIP_OPT_REPLACES | SIP_OPT_TIMER))) {
19770          /* At this point we only support REPLACES and Session-Timer */
19771          transmit_response_with_unsupported(p, "420 Bad extension (unsupported)", req, required);
19772          ast_log(LOG_WARNING, "Received SIP INVITE with unsupported required extension: %s\n", required);
19773          p->invitestate = INV_COMPLETED;
19774          if (!p->lastinvite)
19775             sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19776          res = -1;
19777          goto request_invite_cleanup;
19778       }
19779    }
19780 
19781    /* The option tags may be present in Supported: or Require: headers.
19782    Include the Require: option tags for further processing as well */
19783    p->sipoptions |= required_profile;
19784    p->reqsipoptions = required_profile;
19785 
19786    /* Check if this is a loop */
19787    if (ast_test_flag(&p->flags[0], SIP_OUTGOING) && p->owner && (p->invitestate != INV_TERMINATED && p->invitestate != INV_CONFIRMED)) {
19788       /* This is a call to ourself.  Send ourselves an error code and stop
19789          processing immediately, as SIP really has no good mechanism for
19790          being able to call yourself */
19791       /* If pedantic is on, we need to check the tags. If they're different, this is
19792          in fact a forked call through a SIP proxy somewhere. */
19793       int different;
19794       char *initial_rlPart2 = REQ_OFFSET_TO_STR(&p->initreq, rlPart2);
19795       char *this_rlPart2 = REQ_OFFSET_TO_STR(req, rlPart2);
19796       if (sip_cfg.pedanticsipchecking)
19797          different = sip_uri_cmp(initial_rlPart2, this_rlPart2);
19798       else
19799          different = strcmp(initial_rlPart2, this_rlPart2);
19800       if (!different) {
19801          transmit_response(p, "482 Loop Detected", req);
19802          p->invitestate = INV_COMPLETED;
19803          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19804          res = 0;
19805          goto request_invite_cleanup;
19806       } else {
19807          /*! This is a spiral. What we need to do is to just change the outgoing INVITE
19808           * so that it now routes to the new Request URI. Since we created the INVITE ourselves
19809           * that should be all we need to do.
19810           * 
19811           * \todo XXX This needs to be reviewed.  YOu don't change the request URI really, you route the packet
19812           * correctly instead...
19813           */
19814          char *uri = ast_strdupa(this_rlPart2);
19815          char *at = strchr(uri, '@');
19816          char *peerorhost;
19817          ast_debug(2, "Potential spiral detected. Original RURI was %s, new RURI is %s\n", initial_rlPart2, this_rlPart2);
19818          transmit_response(p, "100 Trying", req);
19819          if (at) {
19820             *at = '\0';
19821          }
19822          /* Parse out "sip:" */
19823          if ((peerorhost = strchr(uri, ':'))) {
19824             *peerorhost++ = '\0';
19825          }
19826          ast_string_field_set(p, theirtag, NULL);
19827          /* Treat this as if there were a call forward instead...
19828           */
19829          ast_string_field_set(p->owner, call_forward, peerorhost);
19830          ast_queue_control(p->owner, AST_CONTROL_BUSY);
19831          res = 0;
19832          goto request_invite_cleanup;
19833       }
19834    }
19835 
19836    if (!req->ignore && p->pendinginvite) {
19837       if (!ast_test_flag(&p->flags[0], SIP_OUTGOING) && (p->invitestate == INV_COMPLETED || p->invitestate == INV_TERMINATED)) {
19838          /* What do these circumstances mean? We have received an INVITE for an "incoming" dialog for which we
19839           * have sent a final response. We have not yet received an ACK, though (which is why p->pendinginvite is non-zero).
19840           * We also know that the INVITE is not a retransmission, because otherwise the "ignore" flag would be set.
19841           * This means that either we are receiving a reinvite for a terminated dialog, or we are receiving an INVITE with
19842           * credentials based on one we challenged earlier.
19843           *
19844           * The action to take in either case is to treat the INVITE as though it contains an implicit ACK for the previous
19845           * transaction. Calling __sip_ack will take care of this by clearing the p->pendinginvite and removing the response
19846           * from the previous transaction from the list of outstanding packets.
19847           */
19848          __sip_ack(p, p->pendinginvite, 1, 0);
19849       } else {
19850          /* We already have a pending invite. Sorry. You are on hold. */
19851          p->glareinvite = seqno;     /* must hold on to this seqno to process ack and retransmit correctly */
19852          if (p->rtp && find_sdp(req)) {
19853             struct sockaddr_in sin;
19854             if (get_ip_and_port_from_sdp(req, SDP_AUDIO, &sin)) {
19855                ast_log(LOG_WARNING, "Failed to set an alternate media source on glared reinvite. Audio may not work properly on this call.\n");
19856             } else {
19857                ast_rtp_set_alt_peer(p->rtp, &sin);
19858             }
19859             if (p->vrtp) {
19860                if (get_ip_and_port_from_sdp(req, SDP_VIDEO, &sin)) {
19861                   ast_log(LOG_WARNING, "Failed to set an alternate media source on glared reinvite. Video may not work properly on this call.\n");
19862                } else {
19863                   ast_rtp_set_alt_peer(p->vrtp, &sin);
19864                }
19865             }
19866          }
19867          transmit_response_reliable(p, "491 Request Pending", req);
19868          ast_debug(1, "Got INVITE on call where we already have pending INVITE, deferring that - %s\n", p->callid);
19869          /* Don't destroy dialog here */
19870          res = 0;
19871          goto request_invite_cleanup;
19872       }
19873    }
19874 
19875    p_replaces = get_header(req, "Replaces");
19876    if (!ast_strlen_zero(p_replaces)) {
19877       /* We have a replaces header */
19878       char *ptr;
19879       char *fromtag = NULL;
19880       char *totag = NULL;
19881       char *start, *to;
19882       int error = 0;
19883 
19884       if (p->owner) {
19885          ast_debug(3, "INVITE w Replaces on existing call? Refusing action. [%s]\n", p->callid);
19886          transmit_response_reliable(p, "400 Bad request", req);   /* The best way to not not accept the transfer */
19887          /* Do not destroy existing call */
19888          res = -1;
19889          goto request_invite_cleanup;
19890       }
19891 
19892       if (sipdebug)
19893          ast_debug(3, "INVITE part of call transfer. Replaces [%s]\n", p_replaces);
19894       /* Create a buffer we can manipulate */
19895       replace_id = ast_strdupa(p_replaces);
19896       ast_uri_decode(replace_id);
19897 
19898       if (!p->refer && !sip_refer_allocate(p)) {
19899          transmit_response_reliable(p, "500 Server Internal Error", req);
19900          append_history(p, "Xfer", "INVITE/Replace Failed. Out of memory.");
19901          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19902          p->invitestate = INV_COMPLETED;
19903          res = -1;
19904          goto request_invite_cleanup;
19905       }
19906 
19907       /*  Todo: (When we find phones that support this)
19908          if the replaces header contains ";early-only"
19909          we can only replace the call in early
19910          stage, not after it's up.
19911 
19912          If it's not in early mode, 486 Busy.
19913       */
19914 
19915       /* Skip leading whitespace */
19916       replace_id = ast_skip_blanks(replace_id);
19917 
19918       start = replace_id;
19919       while ( (ptr = strsep(&start, ";")) ) {
19920          ptr = ast_skip_blanks(ptr); /* XXX maybe unnecessary ? */
19921          if ( (to = strcasestr(ptr, "to-tag=") ) )
19922             totag = to + 7;   /* skip the keyword */
19923          else if ( (to = strcasestr(ptr, "from-tag=") ) ) {
19924             fromtag = to + 9; /* skip the keyword */
19925             fromtag = strsep(&fromtag, "&"); /* trim what ? */
19926          }
19927       }
19928 
19929       if (sipdebug)
19930          ast_debug(4, "Invite/replaces: Will use Replace-Call-ID : %s Fromtag: %s Totag: %s\n",
19931                  replace_id,
19932                  fromtag ? fromtag : "<no from tag>",
19933                  totag ? totag : "<no to tag>");
19934 
19935       /* Try to find call that we are replacing.
19936          If we have a Replaces header, we need to cancel that call if we succeed with this call.
19937          First we cheat a little and look for a magic call-id from phones that support
19938          dialog-info+xml so we can do technology independent pickup... */
19939       if (strncmp(replace_id, "pickup-", 7) == 0) {
19940          struct sip_pvt *subscription = NULL;
19941          replace_id += 7; /* Worst case we are looking at \0 */
19942 
19943          if ((subscription = get_sip_pvt_byid_locked(replace_id, NULL, NULL)) == NULL) {
19944             ast_log(LOG_NOTICE, "Unable to find subscription with call-id: %s\n", replace_id);
19945             transmit_response_reliable(p, "481 Call Leg Does Not Exist (Replaces)", req);
19946             error = 1;
19947          } else {
19948             ast_log(LOG_NOTICE, "Trying to pick up %s@%s\n", subscription->exten, subscription->context);
19949             ast_copy_string(pickup.exten, subscription->exten, sizeof(pickup.exten));
19950             ast_copy_string(pickup.context, subscription->context, sizeof(pickup.context));
19951             sip_pvt_unlock(subscription);
19952             if (subscription->owner) {
19953                ast_channel_unlock(subscription->owner);
19954             }
19955          }
19956       }
19957 
19958       /* This locks both refer_call pvt and refer_call pvt's owner!!!*/
19959       if (!error && ast_strlen_zero(pickup.exten) && (p->refer->refer_call = get_sip_pvt_byid_locked(replace_id, totag, fromtag)) == NULL) {
19960          ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-existent call id (%s)!\n", replace_id);
19961          transmit_response_reliable(p, "481 Call Leg Does Not Exist (Replaces)", req);
19962          error = 1;
19963       } else {
19964          refer_locked = 1;
19965       }
19966 
19967       /* The matched call is the call from the transferer to Asterisk .
19968          We want to bridge the bridged part of the call to the 
19969          incoming invite, thus taking over the refered call */
19970 
19971       if (p->refer->refer_call == p) {
19972          ast_log(LOG_NOTICE, "INVITE with replaces into it's own call id (%s == %s)!\n", replace_id, p->callid);
19973          p->refer->refer_call = dialog_unref(p->refer->refer_call, "unref dialog p->refer->refer_call");
19974          transmit_response_reliable(p, "400 Bad request", req);   /* The best way to not not accept the transfer */
19975          error = 1;
19976       }
19977 
19978       if (!error && ast_strlen_zero(pickup.exten) && !p->refer->refer_call->owner) {
19979          /* Oops, someting wrong anyway, no owner, no call */
19980          ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-existing call id (%s)!\n", replace_id);
19981          /* Check for better return code */
19982          transmit_response_reliable(p, "481 Call Leg Does Not Exist (Replace)", req);
19983          error = 1;
19984       }
19985 
19986       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) {
19987          ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-ringing or active call id (%s)!\n", replace_id);
19988          transmit_response_reliable(p, "603 Declined (Replaces)", req);
19989          error = 1;
19990       }
19991 
19992       if (error) {   /* Give up this dialog */
19993          append_history(p, "Xfer", "INVITE/Replace Failed.");
19994          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19995          sip_pvt_unlock(p);
19996          if (p->refer->refer_call) {
19997             sip_pvt_unlock(p->refer->refer_call);
19998             if (p->refer->refer_call->owner) {
19999                ast_channel_unlock(p->refer->refer_call->owner);
20000             }
20001          }
20002          refer_locked = 0;
20003          p->invitestate = INV_COMPLETED;
20004          res = -1;
20005          goto request_invite_cleanup;
20006       }
20007    }
20008 
20009    /* Check if this is an INVITE that sets up a new dialog or
20010       a re-invite in an existing dialog */
20011 
20012    if (!req->ignore) {
20013       int newcall = (p->initreq.headers ? TRUE : FALSE);
20014 
20015       if (sip_cancel_destroy(p))
20016          ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
20017       /* This also counts as a pending invite */
20018       p->pendinginvite = seqno;
20019       check_via(p, req);
20020 
20021       copy_request(&p->initreq, req);     /* Save this INVITE as the transaction basis */
20022       if (sipdebug)
20023          ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
20024       if (!p->owner) {  /* Not a re-invite */
20025          if (debug)
20026             ast_verbose("Using INVITE request as basis request - %s\n", p->callid);
20027          if (newcall)
20028             append_history(p, "Invite", "New call: %s", p->callid);
20029          parse_ok_contact(p, req);
20030       } else { /* Re-invite on existing call */
20031          ast_clear_flag(&p->flags[0], SIP_OUTGOING);  /* This is now an inbound dialog */
20032          /* Handle SDP here if we already have an owner */
20033          if (find_sdp(req)) {
20034             if (process_sdp(p, req, SDP_T38_INITIATE)) {
20035                transmit_response_reliable(p, "488 Not acceptable here", req);
20036                if (!p->lastinvite)
20037                   sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20038                res = -1;
20039                goto request_invite_cleanup;
20040             }
20041             ast_queue_control(p->owner, AST_CONTROL_SRCUPDATE);
20042          } else {
20043             p->jointcapability = p->capability;
20044             ast_debug(1, "Hm....  No sdp for the moment\n");
20045          }
20046          if (p->do_history) /* This is a response, note what it was for */
20047             append_history(p, "ReInv", "Re-invite received");
20048       }
20049    } else if (debug)
20050       ast_verbose("Ignoring this INVITE request\n");
20051 
20052    if (!p->lastinvite && !req->ignore && !p->owner) {
20053       /* This is a new invite */
20054       /* Handle authentication if this is our first invite */
20055       res = check_user(p, req, SIP_INVITE, e, XMIT_RELIABLE, sin);
20056       if (res == AUTH_CHALLENGE_SENT) {
20057          p->invitestate = INV_COMPLETED;     /* Needs to restart in another INVITE transaction */
20058          res = 0;
20059          goto request_invite_cleanup;
20060       }
20061       if (res < 0) { /* Something failed in authentication */
20062          if (res == AUTH_FAKE_AUTH) {
20063             ast_log(LOG_NOTICE, "Sending fake auth rejection for device %s\n", get_header(req, "From"));
20064             transmit_fake_auth_response(p, SIP_INVITE, req, XMIT_RELIABLE);
20065          } else {
20066             ast_log(LOG_NOTICE, "Failed to authenticate device %s\n", get_header(req, "From"));
20067             transmit_response_reliable(p, "403 Forbidden", req);
20068          }
20069          p->invitestate = INV_COMPLETED;
20070          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20071          ast_string_field_set(p, theirtag, NULL);
20072          res = 0;
20073          goto request_invite_cleanup;
20074       }
20075 
20076       /* If T38 is needed but not present, then make it magically appear */
20077       if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) && !p->udptl && (p->udptl = ast_udptl_new_with_bindaddr(sched, io, 0, bindaddr.sin_addr))) {
20078          p->t38_maxdatagram = global_t38_maxdatagram;
20079          set_t38_capabilities(p);
20080       }
20081 
20082       /* We have a succesful authentication, process the SDP portion if there is one */
20083       if (find_sdp(req)) {
20084          if (process_sdp(p, req, SDP_T38_INITIATE)) {
20085             /* Unacceptable codecs */
20086             transmit_response_reliable(p, "488 Not acceptable here", req);
20087             p->invitestate = INV_COMPLETED;
20088             sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20089             ast_debug(1, "No compatible codecs for this SIP call.\n");
20090             res = -1;
20091             goto request_invite_cleanup;
20092          }
20093       } else { /* No SDP in invite, call control session */
20094          p->jointcapability = p->capability;
20095          ast_debug(2, "No SDP in Invite, third party call control\n");
20096       }
20097 
20098       /* Queue NULL frame to prod ast_rtp_bridge if appropriate */
20099       /* This seems redundant ... see !p-owner above */
20100       if (p->owner)
20101          ast_queue_frame(p->owner, &ast_null_frame);
20102 
20103 
20104       /* Initialize the context if it hasn't been already */
20105       if (ast_strlen_zero(p->context))
20106          ast_string_field_set(p, context, sip_cfg.default_context);
20107 
20108 
20109       /* Check number of concurrent calls -vs- incoming limit HERE */
20110       ast_debug(1, "Checking SIP call limits for device %s\n", p->username);
20111       if ((res = update_call_counter(p, INC_CALL_LIMIT))) {
20112          if (res < 0) {
20113             ast_log(LOG_NOTICE, "Failed to place call for device %s, too many calls\n", p->username);
20114             transmit_response_reliable(p, "480 Temporarily Unavailable (Call limit) ", req);
20115             sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20116             p->invitestate = INV_COMPLETED;
20117          }
20118          res = 0;
20119          goto request_invite_cleanup;
20120       }
20121       gotdest = get_destination(p, NULL); /* Get destination right away */
20122       get_rdnis(p, NULL);        /* Get redirect information */
20123       extract_uri(p, req);       /* Get the Contact URI */
20124       build_contact(p);       /* Build our contact header */
20125 
20126       if (p->rtp) {
20127          ast_rtp_setdtmf(p->rtp, ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
20128          ast_rtp_setdtmfcompensate(p->rtp, ast_test_flag(&p->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
20129       }
20130 
20131       if (!replace_id && gotdest) { /* No matching extension found */
20132          if (gotdest == 1 && ast_test_flag(&p->flags[1], SIP_PAGE2_ALLOWOVERLAP))
20133             transmit_response_reliable(p, "484 Address Incomplete", req);
20134          else {
20135             char *decoded_exten = ast_strdupa(p->exten);
20136 
20137             transmit_response_reliable(p, "404 Not Found", req);
20138             ast_uri_decode(decoded_exten);
20139             ast_log(LOG_NOTICE, "Call from '%s' to extension"
20140                " '%s' rejected because extension not found.\n",
20141                S_OR(p->username, p->peername), decoded_exten);
20142          }
20143          p->invitestate = INV_COMPLETED;
20144          update_call_counter(p, DEC_CALL_LIMIT);
20145          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20146          res = 0;
20147          goto request_invite_cleanup;
20148       } else {
20149 
20150          /* If no extension was specified, use the s one */
20151          /* Basically for calling to IP/Host name only */
20152          if (ast_strlen_zero(p->exten))
20153             ast_string_field_set(p, exten, "s");
20154          /* Initialize our tag */
20155 
20156          make_our_tag(p->tag, sizeof(p->tag));
20157          /* First invitation - create the channel */
20158          c = sip_new(p, AST_STATE_DOWN, S_OR(p->peername, NULL));
20159          *recount = 1;
20160 
20161          /* Save Record-Route for any later requests we make on this dialogue */
20162          build_route(p, req, 0);
20163 
20164          if (c) {
20165             /* Pre-lock the call */
20166             ast_channel_lock(c);
20167          }
20168       }
20169    } else {
20170       if (sipdebug) {
20171          if (!req->ignore)
20172             ast_debug(2, "Got a SIP re-invite for call %s\n", p->callid);
20173          else
20174             ast_debug(2, "Got a SIP re-transmit of INVITE for call %s\n", p->callid);
20175       }
20176       if (!req->ignore)
20177          reinvite = 1;
20178       c = p->owner;
20179    }
20180 
20181    /* Session-Timers */
20182    if (p->sipoptions & SIP_OPT_TIMER) {
20183       /* The UAC has requested session-timers for this session. Negotiate
20184       the session refresh interval and who will be the refresher */
20185       ast_debug(2, "Incoming INVITE with 'timer' option enabled\n");
20186 
20187       /* Allocate Session-Timers struct w/in the dialog */
20188       if (!p->stimer)
20189          sip_st_alloc(p);
20190 
20191       /* Parse the Session-Expires header */
20192       p_uac_se_hdr = get_header(req, "Session-Expires");
20193       if (!ast_strlen_zero(p_uac_se_hdr)) {
20194          rtn = parse_session_expires(p_uac_se_hdr, &uac_max_se, &st_ref);
20195          if (rtn != 0) {
20196             transmit_response_reliable(p, "400 Session-Expires Invalid Syntax", req);
20197             p->invitestate = INV_COMPLETED;
20198             if (!p->lastinvite) {
20199                sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20200             }
20201             res = -1;
20202             goto request_invite_cleanup;
20203          }
20204       }
20205 
20206       /* Parse the Min-SE header */
20207       p_uac_min_se = get_header(req, "Min-SE");
20208       if (!ast_strlen_zero(p_uac_min_se)) {
20209          rtn = parse_minse(p_uac_min_se, &uac_min_se); 
20210          if (rtn != 0) {
20211             transmit_response_reliable(p, "400 Min-SE Invalid Syntax", req);
20212             p->invitestate = INV_COMPLETED;
20213             if (!p->lastinvite) {
20214                sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20215             }
20216             res = -1;
20217             goto request_invite_cleanup;
20218          }
20219       }
20220 
20221       dlg_min_se = st_get_se(p, FALSE);
20222       switch (st_get_mode(p)) {
20223       case SESSION_TIMER_MODE_ACCEPT:
20224       case SESSION_TIMER_MODE_ORIGINATE:
20225          if (uac_max_se > 0 && uac_max_se < dlg_min_se) {
20226             transmit_response_with_minse(p, "422 Session Interval Too Small", req, dlg_min_se);
20227             p->invitestate = INV_COMPLETED;
20228             if (!p->lastinvite) {
20229                sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20230             }
20231             res = -1;
20232             goto request_invite_cleanup;
20233          }
20234 
20235          p->stimer->st_active_peer_ua = TRUE;
20236          st_active = TRUE;
20237          if (st_ref == SESSION_TIMER_REFRESHER_AUTO) {
20238             st_ref = st_get_refresher(p);
20239          }
20240 
20241          if (uac_max_se > 0) {
20242             int dlg_max_se = st_get_se(p, TRUE);
20243             if (dlg_max_se >= uac_min_se) {
20244                st_interval = (uac_max_se < dlg_max_se) ? uac_max_se : dlg_max_se;
20245             } else {
20246                st_interval = uac_max_se;
20247             }
20248          } else {
20249             /* Set to default max value */
20250             st_interval = global_max_se;
20251          }
20252          break;
20253 
20254       case SESSION_TIMER_MODE_REFUSE:
20255          if (p->reqsipoptions & SIP_OPT_TIMER) {
20256             transmit_response_with_unsupported(p, "420 Option Disabled", req, required);
20257             ast_log(LOG_WARNING, "Received SIP INVITE with supported but disabled option: %s\n", required);
20258             p->invitestate = INV_COMPLETED;
20259             if (!p->lastinvite) {
20260                sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20261             }
20262             res = -1;
20263             goto request_invite_cleanup;
20264          }
20265          break;
20266 
20267       default:
20268          ast_log(LOG_ERROR, "Internal Error %d at %s:%d\n", st_get_mode(p), __FILE__, __LINE__);
20269          break;
20270       }
20271    } else {
20272       /* The UAC did not request session-timers.  Asterisk (UAS), will now decide
20273       (based on session-timer-mode in sip.conf) whether to run session-timers for
20274       this session or not. */
20275       switch (st_get_mode(p)) {
20276       case SESSION_TIMER_MODE_ORIGINATE:
20277          st_active = TRUE;
20278          st_interval = st_get_se(p, TRUE);
20279          st_ref = SESSION_TIMER_REFRESHER_UAS;
20280          p->stimer->st_active_peer_ua = FALSE;
20281          break;
20282 
20283       default:
20284          break;
20285       }
20286    }
20287 
20288    if (reinvite == 0) {
20289       /* Session-Timers: Start session refresh timer based on negotiation/config */
20290       if (st_active == TRUE) {
20291          p->stimer->st_active   = TRUE;
20292          p->stimer->st_interval = st_interval;
20293          p->stimer->st_ref      = st_ref;
20294          start_session_timer(p);
20295       }
20296    } else {
20297       if (p->stimer->st_active == TRUE) {
20298          /* Session-Timers:  A re-invite request sent within a dialog will serve as 
20299          a refresh request, no matter whether the re-invite was sent for refreshing 
20300          the session or modifying it.*/
20301          ast_debug (2, "Restarting session-timers on a refresh - %s\n", p->callid);
20302 
20303          /* The UAC may be adjusting the session-timers mid-session */
20304          if (st_interval > 0) {
20305             p->stimer->st_interval = st_interval;
20306             p->stimer->st_ref      = st_ref;
20307          }
20308 
20309          restart_session_timer(p);
20310          if (p->stimer->st_expirys > 0) {
20311             p->stimer->st_expirys--;
20312          }
20313       }
20314    }
20315 
20316    if (!req->ignore && p)
20317       p->lastinvite = seqno;
20318 
20319    if (replace_id) { /* Attended transfer or call pickup - we're the target */
20320       if (!ast_strlen_zero(pickup.exten)) {
20321          append_history(p, "Xfer", "INVITE/Replace received");
20322 
20323          /* Let the caller know we're giving it a shot */
20324          transmit_response(p, "100 Trying", req);
20325          ast_setstate(c, AST_STATE_RING);
20326 
20327          /* Do the pickup itself */
20328          ast_channel_unlock(c);
20329          *nounlock = 1;
20330          do_magic_pickup(c, pickup.exten, pickup.context);
20331 
20332          /* Now we're either masqueraded or we failed to pickup, in either case we... */
20333          sip_pvt_unlock(p);
20334          ast_hangup(c);
20335          sip_pvt_lock(p);
20336 
20337          res = 0;
20338          goto request_invite_cleanup;
20339       } else {
20340          /* Go and take over the target call */
20341          if (sipdebug)
20342             ast_debug(4, "Sending this call to the invite/replcaes handler %s\n", p->callid);
20343          res = handle_invite_replaces(p, req, debug, seqno, sin, nounlock);
20344          refer_locked = 0;
20345          goto request_invite_cleanup;
20346       }
20347    }
20348 
20349 
20350    if (c) { /* We have a call  -either a new call or an old one (RE-INVITE) */
20351       enum ast_channel_state c_state = c->_state;
20352 
20353       if (c_state != AST_STATE_UP && reinvite &&
20354          (p->invitestate == INV_TERMINATED || p->invitestate == INV_CONFIRMED)) {
20355          /* If these conditions are true, and the channel is still in the 'ringing'
20356           * state, then this likely means that we have a situation where the initial
20357           * INVITE transaction has completed *but* the channel's state has not yet been
20358           * changed to UP. The reason this could happen is if the reinvite is received
20359           * on the SIP socket prior to an application calling ast_read on this channel
20360           * to read the answer frame we earlier queued on it. In this case, the reinvite
20361           * is completely legitimate so we need to handle this the same as if the channel 
20362           * were already UP. Thus we are purposely falling through to the AST_STATE_UP case.
20363           */
20364          c_state = AST_STATE_UP;
20365       }
20366 
20367       switch(c_state) {
20368       case AST_STATE_DOWN:
20369          ast_debug(2, "%s: New call is still down.... Trying... \n", c->name);
20370          transmit_provisional_response(p, "100 Trying", req, 0);
20371          p->invitestate = INV_PROCEEDING;
20372          ast_setstate(c, AST_STATE_RING);
20373          if (strcmp(p->exten, ast_pickup_ext())) { /* Call to extension -start pbx on this call */
20374             enum ast_pbx_result result;
20375 
20376             result = ast_pbx_start(c);
20377 
20378             switch(result) {
20379             case AST_PBX_FAILED:
20380                ast_log(LOG_WARNING, "Failed to start PBX :(\n");
20381                p->invitestate = INV_COMPLETED;
20382                transmit_response_reliable(p, "503 Unavailable", req);
20383                break;
20384             case AST_PBX_CALL_LIMIT:
20385                ast_log(LOG_WARNING, "Failed to start PBX (call limit reached) \n");
20386                p->invitestate = INV_COMPLETED;
20387                transmit_response_reliable(p, "480 Temporarily Unavailable", req);
20388                break;
20389             case AST_PBX_SUCCESS:
20390                /* nothing to do */
20391                break;
20392             }
20393 
20394             if (result) {
20395 
20396                /* Unlock locks so ast_hangup can do its magic */
20397                ast_channel_unlock(c);
20398                sip_pvt_unlock(p);
20399                ast_hangup(c);
20400                sip_pvt_lock(p);
20401                c = NULL;
20402             }
20403          } else { /* Pickup call in call group */
20404             ast_channel_unlock(c);
20405             *nounlock = 1;
20406             if (ast_pickup_call(c)) {
20407                ast_log(LOG_NOTICE, "Nothing to pick up for %s\n", p->callid);
20408                transmit_response_reliable(p, "503 Unavailable", req);
20409                sip_alreadygone(p);
20410                /* Unlock locks so ast_hangup can do its magic */
20411                sip_pvt_unlock(p);
20412                c->hangupcause = AST_CAUSE_CALL_REJECTED;
20413             } else {
20414                sip_pvt_unlock(p);
20415                ast_setstate(c, AST_STATE_DOWN);
20416                c->hangupcause = AST_CAUSE_NORMAL_CLEARING;
20417             }
20418             p->invitestate = INV_COMPLETED;
20419             ast_hangup(c);
20420             sip_pvt_lock(p);
20421             c = NULL;
20422          }
20423          break;
20424       case AST_STATE_RING:
20425          transmit_provisional_response(p, "100 Trying", req, 0);
20426          p->invitestate = INV_PROCEEDING;
20427          break;
20428       case AST_STATE_RINGING:
20429          transmit_provisional_response(p, "180 Ringing", req, 0);
20430          p->invitestate = INV_PROCEEDING;
20431          break;
20432       case AST_STATE_UP:
20433          ast_debug(2, "%s: This call is UP.... \n", c->name);
20434 
20435          transmit_response(p, "100 Trying", req);
20436 
20437          if (p->t38.state == T38_PEER_REINVITE) {
20438             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."));
20439          } else if (p->t38.state == T38_ENABLED) {
20440             ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
20441             transmit_response_with_t38_sdp(p, "200 OK", req, (reinvite ? XMIT_RELIABLE : (req->ignore ?  XMIT_UNRELIABLE : XMIT_CRITICAL)));
20442          } else if (p->t38.state == T38_DISABLED) {
20443             /* If this is not a re-invite or something to ignore - it's critical */
20444             ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
20445             transmit_response_with_sdp(p, "200 OK", req, (reinvite ? XMIT_RELIABLE : (req->ignore ?  XMIT_UNRELIABLE : XMIT_CRITICAL)), p->session_modify == TRUE ? FALSE:TRUE); 
20446          }
20447 
20448          p->invitestate = INV_TERMINATED;
20449          break;
20450       default:
20451          ast_log(LOG_WARNING, "Don't know how to handle INVITE in state %d\n", c->_state);
20452          transmit_response(p, "100 Trying", req);
20453          break;
20454       }
20455    } else {
20456       if (p && (p->autokillid == -1)) {
20457          const char *msg;
20458 
20459          if (!p->jointcapability)
20460             msg = "488 Not Acceptable Here (codec error)";
20461          else {
20462             ast_log(LOG_NOTICE, "Unable to create/find SIP channel for this INVITE\n");
20463             msg = "503 Unavailable";
20464          }
20465          transmit_response_reliable(p, msg, req);
20466          p->invitestate = INV_COMPLETED;
20467          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20468       }
20469    }
20470 
20471 request_invite_cleanup:
20472 
20473    if (refer_locked && p->refer && p->refer->refer_call) {
20474       sip_pvt_unlock(p->refer->refer_call);
20475       if (p->refer->refer_call->owner) {
20476          ast_channel_unlock(p->refer->refer_call->owner);
20477       }
20478    }
20479 
20480    return res;
20481 }
20482 
20483 /*! \brief  Find all call legs and bridge transferee with target 
20484  * called from handle_request_refer */
20485 static int local_attended_transfer(struct sip_pvt *transferer, struct sip_dual *current, struct sip_request *req, int seqno)
20486 {
20487    struct sip_dual target;    /* Chan 1: Call from tranferer to Asterisk */
20488                /* Chan 2: Call from Asterisk to target */
20489    int res = 0;
20490    struct sip_pvt *targetcall_pvt;
20491 
20492    /* Check if the call ID of the replaces header does exist locally */
20493    if (!(targetcall_pvt = get_sip_pvt_byid_locked(transferer->refer->replaces_callid, transferer->refer->replaces_callid_totag, 
20494       transferer->refer->replaces_callid_fromtag))) {
20495       if (transferer->refer->localtransfer) {
20496          /* We did not find the refered call. Sorry, can't accept then */
20497          transmit_response(transferer, "202 Accepted", req);
20498          /* Let's fake a response from someone else in order
20499             to follow the standard */
20500          transmit_notify_with_sipfrag(transferer, seqno, "481 Call leg/transaction does not exist", TRUE);
20501          append_history(transferer, "Xfer", "Refer failed");
20502          ast_clear_flag(&transferer->flags[0], SIP_GOTREFER);  
20503          transferer->refer->status = REFER_FAILED;
20504          return -1;
20505       }
20506       /* Fall through for remote transfers that we did not find locally */
20507       ast_debug(3, "SIP attended transfer: Not our call - generating INVITE with replaces\n");
20508       return 0;
20509    }
20510 
20511    /* Ok, we can accept this transfer */
20512    transmit_response(transferer, "202 Accepted", req);
20513    append_history(transferer, "Xfer", "Refer accepted");
20514    if (!targetcall_pvt->owner) { /* No active channel */
20515       ast_debug(4, "SIP attended transfer: Error: No owner of target call\n");
20516       /* Cancel transfer */
20517       transmit_notify_with_sipfrag(transferer, seqno, "503 Service Unavailable", TRUE);
20518       append_history(transferer, "Xfer", "Refer failed");
20519       ast_clear_flag(&transferer->flags[0], SIP_GOTREFER);
20520       transferer->refer->status = REFER_FAILED;
20521       sip_pvt_unlock(targetcall_pvt);
20522       if (targetcall_pvt)
20523          ao2_t_ref(targetcall_pvt, -1, "Drop targetcall_pvt pointer");
20524       return -1;
20525    }
20526 
20527    /* We have a channel, find the bridge */
20528    target.chan1 = targetcall_pvt->owner;           /* Transferer to Asterisk */
20529    target.chan2 = ast_bridged_channel(targetcall_pvt->owner);  /* Asterisk to target */
20530 
20531    if (!target.chan2 || !(target.chan2->_state == AST_STATE_UP || target.chan2->_state == AST_STATE_RINGING) ) {
20532       /* Wrong state of new channel */
20533       if (target.chan2) 
20534          ast_debug(4, "SIP attended transfer: Error: Wrong state of target call: %s\n", ast_state2str(target.chan2->_state));
20535       else if (target.chan1->_state != AST_STATE_RING)
20536          ast_debug(4, "SIP attended transfer: Error: No target channel\n");
20537       else
20538          ast_debug(4, "SIP attended transfer: Attempting transfer in ringing state\n");
20539    }
20540 
20541    /* Transfer */
20542    if (sipdebug) {
20543       if (current->chan2)  /* We have two bridges */
20544          ast_debug(4, "SIP attended transfer: trying to bridge %s and %s\n", target.chan1->name, current->chan2->name);
20545       else        /* One bridge, propably transfer of IVR/voicemail etc */
20546          ast_debug(4, "SIP attended transfer: trying to make %s take over (masq) %s\n", target.chan1->name, current->chan1->name);
20547    }
20548 
20549    ast_set_flag(&transferer->flags[0], SIP_DEFER_BYE_ON_TRANSFER);   /* Delay hangup */
20550 
20551    /* Perform the transfer */
20552    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",
20553       transferer->owner->name,
20554       transferer->owner->uniqueid,
20555       transferer->callid,
20556       target.chan1->name,
20557       target.chan1->uniqueid);
20558    res = attempt_transfer(current, &target);
20559    sip_pvt_unlock(targetcall_pvt);
20560    if (res) {
20561       /* Failed transfer */
20562       transmit_notify_with_sipfrag(transferer, seqno, "486 Busy Here", TRUE);
20563       append_history(transferer, "Xfer", "Refer failed");
20564       if (targetcall_pvt->owner)
20565          ast_channel_unlock(targetcall_pvt->owner);
20566       ast_clear_flag(&transferer->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
20567    } else {
20568       /* Transfer succeeded! */
20569       const char *xfersound = pbx_builtin_getvar_helper(target.chan1, "ATTENDED_TRANSFER_COMPLETE_SOUND");
20570 
20571       /* Tell transferer that we're done. */
20572       transmit_notify_with_sipfrag(transferer, seqno, "200 OK", TRUE);
20573       append_history(transferer, "Xfer", "Refer succeeded");
20574       transferer->refer->status = REFER_200OK;
20575       if (target.chan2 && !ast_strlen_zero(xfersound) && ast_streamfile(target.chan2, xfersound, target.chan2->language) >= 0) {
20576          ast_waitstream(target.chan2, "");
20577       }
20578       if (targetcall_pvt->owner) {
20579          ast_debug(1, "SIP attended transfer: Unlocking channel %s\n", targetcall_pvt->owner->name);
20580          ast_channel_unlock(targetcall_pvt->owner);
20581       }
20582    }
20583    if (targetcall_pvt)
20584       ao2_t_ref(targetcall_pvt, -1, "drop targetcall_pvt");
20585    return 1;
20586 }
20587 
20588 
20589 /*! \brief Handle incoming REFER request */
20590 /*! \page SIP_REFER SIP transfer Support (REFER)
20591 
20592    REFER is used for call transfer in SIP. We get a REFER
20593    to place a new call with an INVITE somwhere and then
20594    keep the transferor up-to-date of the transfer. If the
20595    transfer fails, get back on line with the orginal call. 
20596 
20597    - REFER can be sent outside or inside of a dialog.
20598      Asterisk only accepts REFER inside of a dialog.
20599 
20600    - If we get a replaces header, it is an attended transfer
20601 
20602    \par Blind transfers
20603    The transferor provides the transferee
20604    with the transfer targets contact. The signalling between
20605    transferer or transferee should not be cancelled, so the
20606    call is recoverable if the transfer target can not be reached 
20607    by the transferee.
20608 
20609    In this case, Asterisk receives a TRANSFER from
20610    the transferor, thus is the transferee. We should
20611    try to set up a call to the contact provided
20612    and if that fails, re-connect the current session.
20613    If the new call is set up, we issue a hangup.
20614    In this scenario, we are following section 5.2
20615    in the SIP CC Transfer draft. (Transfer without
20616    a GRUU)
20617 
20618    \par Transfer with consultation hold
20619    In this case, the transferor
20620    talks to the transfer target before the transfer takes place.
20621    This is implemented with SIP hold and transfer.
20622    Note: The invite From: string could indicate a transfer.
20623    (Section 6. Transfer with consultation hold)
20624    The transferor places the transferee on hold, starts a call
20625    with the transfer target to alert them to the impending
20626    transfer, terminates the connection with the target, then
20627    proceeds with the transfer (as in Blind transfer above)
20628 
20629    \par Attended transfer
20630    The transferor places the transferee
20631    on hold, calls the transfer target to alert them,
20632    places the target on hold, then proceeds with the transfer
20633    using a Replaces header field in the Refer-to header. This
20634    will force the transfee to send an Invite to the target,
20635    with a replaces header that instructs the target to
20636    hangup the call between the transferor and the target.
20637    In this case, the Refer/to: uses the AOR address. (The same
20638    URI that the transferee used to establish the session with
20639    the transfer target (To: ). The Require: replaces header should
20640    be in the INVITE to avoid the wrong UA in a forked SIP proxy
20641    scenario to answer and have no call to replace with.
20642 
20643    The referred-by header is *NOT* required, but if we get it,
20644    can be copied into the INVITE to the transfer target to 
20645    inform the target about the transferor
20646 
20647    "Any REFER request has to be appropriately authenticated.".
20648    
20649    We can't destroy dialogs, since we want the call to continue.
20650    
20651    */
20652 static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, int *nounlock)
20653 {
20654    struct sip_dual current;   /* Chan1: Call between asterisk and transferer */
20655                /* Chan2: Call between asterisk and transferee */
20656 
20657    int res = 0;
20658    current.req.data = NULL;
20659 
20660    if (req->debug)
20661       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");
20662 
20663    if (!p->owner) {
20664       /* This is a REFER outside of an existing SIP dialog */
20665       /* We can't handle that, so decline it */
20666       ast_debug(3, "Call %s: Declined REFER, outside of dialog...\n", p->callid);
20667       transmit_response(p, "603 Declined (No dialog)", req);
20668       if (!req->ignore) {
20669          append_history(p, "Xfer", "Refer failed. Outside of dialog.");
20670          sip_alreadygone(p);
20671          pvt_set_needdestroy(p, "outside of dialog");
20672       }
20673       return 0;
20674    }
20675 
20676 
20677    /* Check if transfer is allowed from this device */
20678    if (p->allowtransfer == TRANSFER_CLOSED ) {
20679       /* Transfer not allowed, decline */
20680       transmit_response(p, "603 Declined (policy)", req);
20681       append_history(p, "Xfer", "Refer failed. Allowtransfer == closed.");
20682       /* Do not destroy SIP session */
20683       return 0;
20684    }
20685 
20686    if (!req->ignore && ast_test_flag(&p->flags[0], SIP_GOTREFER)) {
20687       /* Already have a pending REFER */
20688       transmit_response(p, "491 Request pending", req);
20689       append_history(p, "Xfer", "Refer failed. Request pending.");
20690       return 0;
20691    }
20692 
20693    /* Allocate memory for call transfer data */
20694    if (!p->refer && !sip_refer_allocate(p)) {
20695       transmit_response(p, "500 Internal Server Error", req);
20696       append_history(p, "Xfer", "Refer failed. Memory allocation error.");
20697       return -3;
20698    }
20699 
20700    res = get_refer_info(p, req); /* Extract headers */
20701 
20702    p->refer->status = REFER_SENT;
20703 
20704    if (res != 0) {
20705       switch (res) {
20706       case -2: /* Syntax error */
20707          transmit_response(p, "400 Bad Request (Refer-to missing)", req);
20708          append_history(p, "Xfer", "Refer failed. Refer-to missing.");
20709          if (req->debug)
20710             ast_debug(1, "SIP transfer to black hole can't be handled (no refer-to: )\n");
20711          break;
20712       case -3:
20713          transmit_response(p, "603 Declined (Non sip: uri)", req);
20714          append_history(p, "Xfer", "Refer failed. Non SIP uri");
20715          if (req->debug)
20716             ast_debug(1, "SIP transfer to non-SIP uri denied\n");
20717          break;
20718       default:
20719          /* Refer-to extension not found, fake a failed transfer */
20720          transmit_response(p, "202 Accepted", req);
20721          append_history(p, "Xfer", "Refer failed. Bad extension.");
20722          transmit_notify_with_sipfrag(p, seqno, "404 Not found", TRUE);
20723          ast_clear_flag(&p->flags[0], SIP_GOTREFER);  
20724          if (req->debug)
20725             ast_debug(1, "SIP transfer to bad extension: %s\n", p->refer->refer_to);
20726          break;
20727       } 
20728       return 0;
20729    }
20730    if (ast_strlen_zero(p->context))
20731       ast_string_field_set(p, context, sip_cfg.default_context);
20732 
20733    /* If we do not support SIP domains, all transfers are local */
20734    if (sip_cfg.allow_external_domains && check_sip_domain(p->refer->refer_to_domain, NULL, 0)) {
20735       p->refer->localtransfer = 1;
20736       if (sipdebug)
20737          ast_debug(3, "This SIP transfer is local : %s\n", p->refer->refer_to_domain);
20738    } else if (AST_LIST_EMPTY(&domain_list) || check_sip_domain(p->refer->refer_to_domain, NULL, 0)) {
20739       /* This PBX doesn't bother with SIP domains or domain is local, so this transfer is local */
20740       p->refer->localtransfer = 1;
20741    } else if (sipdebug)
20742          ast_debug(3, "This SIP transfer is to a remote SIP extension (remote domain %s)\n", p->refer->refer_to_domain);
20743 
20744    /* Is this a repeat of a current request? Ignore it */
20745    /* Don't know what else to do right now. */
20746    if (req->ignore) 
20747       return res;
20748 
20749    /* If this is a blind transfer, we have the following
20750    channels to work with:
20751    - chan1, chan2: The current call between transferer and transferee (2 channels)
20752    - target_channel: A new call from the transferee to the target (1 channel)
20753    We need to stay tuned to what happens in order to be able
20754    to bring back the call to the transferer */
20755 
20756    /* If this is a attended transfer, we should have all call legs within reach:
20757    - chan1, chan2: The call between the transferer and transferee (2 channels)
20758    - target_channel, targetcall_pvt: The call between the transferer and the target (2 channels)
20759    We want to bridge chan2 with targetcall_pvt!
20760    
20761    The replaces call id in the refer message points
20762    to the call leg between Asterisk and the transferer.
20763    So we need to connect the target and the transferee channel
20764    and hangup the two other channels silently 
20765    
20766    If the target is non-local, the call ID could be on a remote
20767    machine and we need to send an INVITE with replaces to the
20768    target. We basically handle this as a blind transfer
20769    and let the sip_call function catch that we need replaces
20770    header in the INVITE.
20771    */
20772 
20773 
20774    /* Get the transferer's channel */
20775    current.chan1 = p->owner;
20776 
20777    /* Find the other part of the bridge (2) - transferee */
20778    current.chan2 = ast_bridged_channel(current.chan1);
20779    
20780    if (sipdebug)
20781       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>");
20782 
20783    if (!current.chan2 && !p->refer->attendedtransfer) {
20784       /* No bridged channel, propably IVR or echo or similar... */
20785       /* Guess we should masquerade or something here */
20786       /* Until we figure it out, refuse transfer of such calls */
20787       if (sipdebug)
20788          ast_debug(3, "Refused SIP transfer on non-bridged channel.\n");
20789       p->refer->status = REFER_FAILED;
20790       append_history(p, "Xfer", "Refer failed. Non-bridged channel.");
20791       transmit_response(p, "603 Declined", req);
20792       return -1;
20793    }
20794 
20795    if (current.chan2) {
20796       if (sipdebug)
20797          ast_debug(4, "Got SIP transfer, applying to bridged peer '%s'\n", current.chan2->name);
20798 
20799       ast_queue_control(current.chan1, AST_CONTROL_UNHOLD);
20800    }
20801 
20802    ast_set_flag(&p->flags[0], SIP_GOTREFER);
20803 
20804    /* Attended transfer: Find all call legs and bridge transferee with target*/
20805    if (p->refer->attendedtransfer) {
20806       if ((res = local_attended_transfer(p, &current, req, seqno)))
20807          return res; /* We're done with the transfer */
20808       /* Fall through for remote transfers that we did not find locally */
20809       if (sipdebug)
20810          ast_debug(4, "SIP attended transfer: Still not our call - generating INVITE with replaces\n");
20811       /* Fallthrough if we can't find the call leg internally */
20812    }
20813 
20814 
20815    /* Parking a call */
20816    if (p->refer->localtransfer && !strcmp(p->refer->refer_to, ast_parking_ext())) {
20817       /* Must release c's lock now, because it will not longer be accessible after the transfer! */
20818       *nounlock = 1;
20819       ast_channel_unlock(current.chan1);
20820       copy_request(&current.req, req);
20821       ast_clear_flag(&p->flags[0], SIP_GOTREFER);
20822       p->refer->status = REFER_200OK;
20823       append_history(p, "Xfer", "REFER to call parking.");
20824       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",
20825          current.chan1->name,
20826          current.chan1->uniqueid,
20827          p->callid,
20828          current.chan2->name,
20829          current.chan2->uniqueid,
20830          p->refer->refer_to);
20831       if (sipdebug)
20832          ast_debug(4, "SIP transfer to parking: trying to park %s. Parked by %s\n", current.chan2->name, current.chan1->name);
20833       sip_park(current.chan2, current.chan1, req, seqno);
20834       return res;
20835    } 
20836 
20837    /* Blind transfers and remote attended xfers */
20838    transmit_response(p, "202 Accepted", req);
20839 
20840    if (current.chan1 && current.chan2) {
20841       ast_debug(3, "chan1->name: %s\n", current.chan1->name);
20842       pbx_builtin_setvar_helper(current.chan1, "BLINDTRANSFER", current.chan2->name);
20843    }
20844    if (current.chan2) {
20845       pbx_builtin_setvar_helper(current.chan2, "BLINDTRANSFER", current.chan1->name);
20846       pbx_builtin_setvar_helper(current.chan2, "SIPDOMAIN", p->refer->refer_to_domain);
20847       pbx_builtin_setvar_helper(current.chan2, "SIPTRANSFER", "yes");
20848       /* One for the new channel */
20849       pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER", "yes");
20850       /* Attended transfer to remote host, prepare headers for the INVITE */
20851       if (p->refer->referred_by) 
20852          pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER_REFERER", p->refer->referred_by);
20853    }
20854    /* Generate a Replaces string to be used in the INVITE during attended transfer */
20855    if (!ast_strlen_zero(p->refer->replaces_callid)) {
20856       char tempheader[SIPBUFSIZE];
20857       snprintf(tempheader, sizeof(tempheader), "%s%s%s%s%s", p->refer->replaces_callid, 
20858             p->refer->replaces_callid_totag ? ";to-tag=" : "", 
20859             p->refer->replaces_callid_totag, 
20860             p->refer->replaces_callid_fromtag ? ";from-tag=" : "",
20861             p->refer->replaces_callid_fromtag);
20862       if (current.chan2)
20863          pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER_REPLACES", tempheader);
20864    }
20865    /* Must release lock now, because it will not longer
20866       be accessible after the transfer! */
20867    *nounlock = 1;
20868    ast_channel_unlock(current.chan1);
20869 
20870    /* Connect the call */
20871 
20872    /* FAKE ringing if not attended transfer */
20873    if (!p->refer->attendedtransfer)
20874       transmit_notify_with_sipfrag(p, seqno, "183 Ringing", FALSE); 
20875 
20876    /* For blind transfer, this will lead to a new call */
20877    /* For attended transfer to remote host, this will lead to
20878       a new SIP call with a replaces header, if the dial plan allows it 
20879    */
20880    if (!current.chan2) {
20881       /* We have no bridge, so we're talking with Asterisk somehow */
20882       /* We need to masquerade this call */
20883       /* What to do to fix this situation:
20884          * Set up the new call in a new channel 
20885          * Let the new channel masq into this channel
20886          Please add that code here :-)
20887       */
20888       p->refer->status = REFER_FAILED;
20889       transmit_notify_with_sipfrag(p, seqno, "503 Service Unavailable (can't handle one-legged xfers)", TRUE);
20890       ast_clear_flag(&p->flags[0], SIP_GOTREFER);  
20891       append_history(p, "Xfer", "Refer failed (only bridged calls).");
20892       return -1;
20893    }
20894    ast_set_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER);   /* Delay hangup */
20895 
20896 
20897    /* For blind transfers, move the call to the new extensions. For attended transfers on multiple
20898       servers - generate an INVITE with Replaces. Either way, let the dial plan decided  */
20899    res = ast_async_goto(current.chan2, p->refer->refer_to_context, p->refer->refer_to, 1);
20900 
20901    if (!res) {
20902       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",
20903          current.chan1->name,
20904          current.chan1->uniqueid,
20905          p->callid,
20906          current.chan2->name,
20907          current.chan2->uniqueid,
20908          p->refer->refer_to, p->refer->refer_to_context);
20909       /* Success  - we have a new channel */
20910       ast_debug(3, "%s transfer succeeded. Telling transferer.\n", p->refer->attendedtransfer? "Attended" : "Blind");
20911       transmit_notify_with_sipfrag(p, seqno, "200 Ok", TRUE);
20912       if (p->refer->localtransfer)
20913          p->refer->status = REFER_200OK;
20914       if (p->owner)
20915          p->owner->hangupcause = AST_CAUSE_NORMAL_CLEARING;
20916       append_history(p, "Xfer", "Refer succeeded.");
20917       ast_clear_flag(&p->flags[0], SIP_GOTREFER);  
20918       /* Do not hangup call, the other side do that when we say 200 OK */
20919       /* We could possibly implement a timer here, auto congestion */
20920       res = 0;
20921    } else {
20922       ast_clear_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER); /* Don't delay hangup */
20923       ast_debug(3, "%s transfer failed. Resuming original call.\n", p->refer->attendedtransfer? "Attended" : "Blind");
20924       append_history(p, "Xfer", "Refer failed.");
20925       /* Failure of some kind */
20926       p->refer->status = REFER_FAILED;
20927       transmit_notify_with_sipfrag(p, seqno, "503 Service Unavailable", TRUE);
20928       ast_clear_flag(&p->flags[0], SIP_GOTREFER);  
20929       res = -1;
20930    }
20931    return res;
20932 }
20933 
20934 /*! \brief Handle incoming CANCEL request */
20935 static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req)
20936 {
20937       
20938    check_via(p, req);
20939    sip_alreadygone(p);
20940 
20941    /* At this point, we could have cancelled the invite at the same time
20942       as the other side sends a CANCEL. Our final reply with error code
20943       might not have been received by the other side before the CANCEL
20944       was sent, so let's just give up retransmissions and waiting for
20945       ACK on our error code. The call is hanging up any way. */
20946    if (p->invitestate == INV_TERMINATED)
20947       __sip_pretend_ack(p);
20948    else
20949       p->invitestate = INV_CANCELLED;
20950    
20951    if (p->owner && p->owner->_state == AST_STATE_UP) {
20952       /* This call is up, cancel is ignored, we need a bye */
20953       transmit_response(p, "200 OK", req);
20954       ast_debug(1, "Got CANCEL on an answered call. Ignoring... \n");
20955       return 0;
20956    }
20957 
20958    if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) 
20959       update_call_counter(p, DEC_CALL_LIMIT);
20960 
20961    stop_media_flows(p); /* Immediately stop RTP, VRTP and UDPTL as applicable */
20962    if (p->owner)
20963       ast_queue_hangup(p->owner);
20964    else
20965       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20966    if (p->initreq.len > 0) {
20967       struct sip_pkt *pkt, *prev_pkt;
20968       /* If the CANCEL we are receiving is a retransmission, and we already have scheduled
20969        * a reliable 487, then we don't want to schedule another one on top of the previous
20970        * one.
20971        *
20972        * As odd as this may sound, we can't rely on the previously-transmitted "reliable" 
20973        * response in this situation. What if we've sent all of our reliable responses 
20974        * already and now all of a sudden, we get this second CANCEL?
20975        *
20976        * The only way to do this correctly is to cancel our previously-scheduled reliably-
20977        * transmitted response and send a new one in its place.
20978        */
20979       for (pkt = p->packets, prev_pkt = NULL; pkt; prev_pkt = pkt, pkt = pkt->next) {
20980          if (pkt->seqno == p->lastinvite && pkt->response_code == 487) {
20981             AST_SCHED_DEL(sched, pkt->retransid);
20982             UNLINK(pkt, p->packets, prev_pkt);
20983             ast_free(pkt);
20984             break;
20985          }
20986       }
20987       transmit_response_reliable(p, "487 Request Terminated", &p->initreq);
20988       transmit_response(p, "200 OK", req);
20989       return 1;
20990    } else {
20991       transmit_response(p, "481 Call Leg Does Not Exist", req);
20992       return 0;
20993    }
20994 }
20995 
20996 static int acf_channel_read(struct ast_channel *chan, const char *funcname, char *preparse, char *buf, size_t buflen)
20997 {
20998    struct sip_pvt *p = chan->tech_pvt;
20999    char *all = "", *parse = ast_strdupa(preparse);
21000    int res = 0;
21001    AST_DECLARE_APP_ARGS(args,
21002       AST_APP_ARG(param);
21003       AST_APP_ARG(type);
21004       AST_APP_ARG(field);
21005    );
21006    AST_STANDARD_APP_ARGS(args, parse);
21007 
21008    /* Sanity check */
21009    if (!IS_SIP_TECH(chan->tech)) {
21010       ast_log(LOG_ERROR, "Cannot call %s on a non-SIP channel\n", funcname);
21011       return 0;
21012    }
21013 
21014    memset(buf, 0, buflen);
21015 
21016    if (p == NULL) {
21017       return -1;
21018    }
21019 
21020    if (!strcasecmp(args.param, "peerip")) {
21021       ast_copy_string(buf, p->sa.sin_addr.s_addr ? ast_inet_ntoa(p->sa.sin_addr) : "", buflen);
21022    } else if (!strcasecmp(args.param, "recvip")) {
21023       ast_copy_string(buf, p->recv.sin_addr.s_addr ? ast_inet_ntoa(p->recv.sin_addr) : "", buflen);
21024    } else if (!strcasecmp(args.param, "from")) {
21025       ast_copy_string(buf, p->from, buflen);
21026    } else if (!strcasecmp(args.param, "uri")) {
21027       ast_copy_string(buf, p->uri, buflen);
21028    } else if (!strcasecmp(args.param, "useragent")) {
21029       ast_copy_string(buf, p->useragent, buflen);
21030    } else if (!strcasecmp(args.param, "peername")) {
21031       ast_copy_string(buf, p->peername, buflen);
21032    } else if (!strcasecmp(args.param, "t38passthrough")) {
21033       ast_copy_string(buf, (p->t38.state == T38_DISABLED) ? "0" : "1", buflen);
21034    } else if (!strcasecmp(args.param, "rtpdest")) {
21035       struct sockaddr_in sin;
21036       struct ast_rtp *stream = NULL;
21037 
21038       if (ast_strlen_zero(args.type))
21039          args.type = "audio";
21040 
21041       if (!strcasecmp(args.type, "audio")) {
21042          stream = p->rtp;
21043       } else if (!strcasecmp(args.type, "video")) {
21044          stream = p->vrtp;
21045       } else if (!strcasecmp(args.type, "text")) {
21046          stream = p->trtp;
21047       } else {
21048          return -1;
21049       }
21050 
21051       if (!stream) {
21052          return -1;
21053       }
21054 
21055       ast_rtp_get_peer(stream, &sin);
21056       snprintf(buf, buflen, "%s:%d", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
21057    } else if (!strcasecmp(args.param, "rtpqos")) {
21058       struct ast_rtp_quality qos;
21059       struct ast_rtp *rtp = p->rtp;
21060       
21061       memset(&qos, 0, sizeof(qos));
21062 
21063       if (ast_strlen_zero(args.type))
21064          args.type = "audio";
21065       if (ast_strlen_zero(args.field))
21066          args.field = "all";
21067       
21068       if (!strcasecmp(args.type, "AUDIO")) {
21069          all = ast_rtp_get_quality(rtp = p->rtp, &qos, RTPQOS_SUMMARY);
21070       } else if (!strcasecmp(args.type, "VIDEO")) {
21071          all = ast_rtp_get_quality(rtp = p->vrtp, &qos, RTPQOS_SUMMARY);
21072       } else if (!strcasecmp(args.type, "TEXT")) {
21073          all = ast_rtp_get_quality(rtp = p->trtp, &qos, RTPQOS_SUMMARY);
21074       } else {
21075          return -1;
21076       }
21077       
21078       if (!strcasecmp(args.field, "local_ssrc"))
21079          snprintf(buf, buflen, "%u", qos.local_ssrc);
21080       else if (!strcasecmp(args.field, "local_lostpackets"))
21081          snprintf(buf, buflen, "%u", qos.local_lostpackets);
21082       else if (!strcasecmp(args.field, "local_jitter"))
21083          snprintf(buf, buflen, "%.0f", qos.local_jitter * 1000.0);
21084       else if (!strcasecmp(args.field, "local_count"))
21085          snprintf(buf, buflen, "%u", qos.local_count);
21086       else if (!strcasecmp(args.field, "remote_ssrc"))
21087          snprintf(buf, buflen, "%u", qos.remote_ssrc);
21088       else if (!strcasecmp(args.field, "remote_lostpackets"))
21089          snprintf(buf, buflen, "%u", qos.remote_lostpackets);
21090       else if (!strcasecmp(args.field, "remote_jitter"))
21091          snprintf(buf, buflen, "%.0f", qos.remote_jitter * 1000.0);
21092       else if (!strcasecmp(args.field, "remote_count"))
21093          snprintf(buf, buflen, "%u", qos.remote_count);
21094       else if (!strcasecmp(args.field, "rtt"))
21095          snprintf(buf, buflen, "%.0f", qos.rtt * 1000.0);
21096       else if (!strcasecmp(args.field, "all"))
21097          ast_copy_string(buf, all, buflen);
21098       else if (!ast_rtp_get_qos(rtp, args.field, buf, buflen))
21099           ;
21100       else {
21101          ast_log(LOG_WARNING, "Unrecognized argument '%s' to %s\n", preparse, funcname);
21102          return -1;
21103       }
21104    } else {
21105       res = -1;
21106    }
21107    return res;
21108 }
21109 
21110 /*! \brief Handle incoming BYE request */
21111 static int handle_request_bye(struct sip_pvt *p, struct sip_request *req)
21112 {
21113    struct ast_channel *c=NULL;
21114    int res;
21115    struct ast_channel *bridged_to;
21116    
21117    /* If we have an INCOMING invite that we haven't answered, terminate that transaction */
21118    if (p->pendinginvite && !ast_test_flag(&p->flags[0], SIP_OUTGOING) && !req->ignore) {
21119       transmit_response_reliable(p, "487 Request Terminated", &p->initreq);
21120    }
21121 
21122    __sip_pretend_ack(p);
21123 
21124    p->invitestate = INV_TERMINATED;
21125 
21126    copy_request(&p->initreq, req);
21127    if (sipdebug)
21128       ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
21129    check_via(p, req);
21130    sip_alreadygone(p);
21131 
21132    /* Get RTCP quality before end of call */
21133    if (p->do_history || p->owner) {
21134       struct ast_channel *bridge = p->owner ? ast_bridged_channel(p->owner) : NULL;
21135       char *videoqos, *textqos;
21136 
21137       /* We need to get the lock on bridge because ast_rtp_set_vars will attempt
21138        * to lock the bridge. This may get hairy...
21139        */
21140       while (bridge && ast_channel_trylock(bridge)) {
21141          ast_channel_unlock(p->owner);
21142          do {
21143             /* Can't use DEADLOCK_AVOIDANCE since p is an ao2 object */
21144             sip_pvt_unlock(p);
21145             usleep(1);
21146             sip_pvt_lock(p);
21147          } while (p->owner && ast_channel_trylock(p->owner));
21148          bridge = p->owner ? ast_bridged_channel(p->owner) : NULL;
21149       }
21150 
21151       if (p->rtp) {  
21152          if (p->do_history) {
21153             char *audioqos,
21154                  *audioqos_jitter,
21155                  *audioqos_loss,
21156                  *audioqos_rtt;
21157 
21158             audioqos        = ast_rtp_get_quality(p->rtp, NULL, RTPQOS_SUMMARY);
21159             audioqos_jitter = ast_rtp_get_quality(p->rtp, NULL, RTPQOS_JITTER);
21160             audioqos_loss   = ast_rtp_get_quality(p->rtp, NULL, RTPQOS_LOSS);
21161             audioqos_rtt    = ast_rtp_get_quality(p->rtp, NULL, RTPQOS_RTT);
21162 
21163             append_history(p, "RTCPaudio", "Quality:%s", audioqos);
21164             append_history(p, "RTCPaudioJitter", "Quality:%s", audioqos_jitter);
21165             append_history(p, "RTCPaudioLoss", "Quality:%s", audioqos_loss);
21166             append_history(p, "RTCPaudioRTT", "Quality:%s", audioqos_rtt);
21167          }
21168          
21169          if (p->owner) {
21170             ast_rtp_set_vars(p->owner, p->rtp);
21171          }
21172       }
21173 
21174       if (bridge) {
21175          struct sip_pvt *q = bridge->tech_pvt;
21176 
21177          if (IS_SIP_TECH(bridge->tech) && q && q->rtp)
21178             ast_rtp_set_vars(bridge, q->rtp);
21179          ast_channel_unlock(bridge);
21180       }
21181 
21182       if (p->vrtp) {
21183          videoqos = ast_rtp_get_quality(p->vrtp, NULL, RTPQOS_SUMMARY);
21184          if (p->do_history)
21185             append_history(p, "RTCPvideo", "Quality:%s", videoqos);
21186          if (p->owner)
21187             pbx_builtin_setvar_helper(p->owner, "RTPVIDEOQOS", videoqos);
21188       }
21189 
21190       if (p->trtp) {
21191          textqos = ast_rtp_get_quality(p->trtp, NULL, RTPQOS_SUMMARY);
21192          if (p->do_history)
21193             append_history(p, "RTCPtext", "Quality:%s", textqos);
21194          if (p->owner)
21195             pbx_builtin_setvar_helper(p->owner, "RTPTEXTQOS", textqos);
21196       }
21197    }
21198 
21199    stop_media_flows(p); /* Immediately stop RTP, VRTP and UDPTL as applicable */
21200    stop_session_timer(p); /* Stop Session-Timer */
21201 
21202    if (!ast_strlen_zero(get_header(req, "Also"))) {
21203       ast_log(LOG_NOTICE, "Client '%s' using deprecated BYE/Also transfer method.  Ask vendor to support REFER instead\n",
21204          ast_inet_ntoa(p->recv.sin_addr));
21205       if (ast_strlen_zero(p->context))
21206          ast_string_field_set(p, context, sip_cfg.default_context);
21207       res = get_also_info(p, req);
21208       if (!res) {
21209          c = p->owner;
21210          if (c) {
21211             bridged_to = ast_bridged_channel(c);
21212             if (bridged_to) {
21213                /* Don't actually hangup here... */
21214                ast_queue_control(c, AST_CONTROL_UNHOLD);
21215                ast_async_goto(bridged_to, p->context, p->refer->refer_to, 1);
21216             } else
21217                ast_queue_hangup(p->owner);
21218          }
21219       } else {
21220          ast_log(LOG_WARNING, "Invalid transfer information from '%s'\n", ast_inet_ntoa(p->recv.sin_addr));
21221          if (p->owner)
21222             ast_queue_hangup_with_cause(p->owner, AST_CAUSE_PROTOCOL_ERROR);
21223       }
21224    } else if (p->owner) {
21225       ast_queue_hangup(p->owner);
21226       ast_debug(3, "Received bye, issuing owner hangup\n");
21227    } else {
21228       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
21229       ast_debug(3, "Received bye, no owner, selfdestruct soon.\n");
21230    }
21231    ast_clear_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
21232    transmit_response(p, "200 OK", req);
21233 
21234    return 1;
21235 }
21236 
21237 /*! \brief Handle incoming MESSAGE request */
21238 static int handle_request_message(struct sip_pvt *p, struct sip_request *req)
21239 {
21240    if (!req->ignore) {
21241       if (req->debug)
21242          ast_verbose("Receiving message!\n");
21243       receive_message(p, req);
21244    } else
21245       transmit_response(p, "202 Accepted", req);
21246    return 1;
21247 }
21248 
21249 static void add_peer_mwi_subs(struct sip_peer *peer)
21250 {
21251    struct sip_mailbox *mailbox;
21252 
21253    AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
21254       mailbox->event_sub = ast_event_subscribe(AST_EVENT_MWI, mwi_event_cb, peer,
21255          AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, mailbox->mailbox,
21256          AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, S_OR(mailbox->context, "default"),
21257          AST_EVENT_IE_END);
21258    }
21259 }
21260 
21261 /*! \brief  Handle incoming SUBSCRIBE request */
21262 static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e)
21263 {
21264    int gotdest = 0;
21265    int res = 0;
21266    int firststate = AST_EXTENSION_REMOVED;
21267    struct sip_peer *authpeer = NULL;
21268    const char *eventheader = get_header(req, "Event");   /* Get Event package name */
21269    const char *acceptheader = get_header(req, "Accept");
21270    int resubscribe = (p->subscribed != NONE);
21271    char *temp, *event;
21272    struct ao2_iterator i;
21273 
21274    if (p->initreq.headers) {  
21275       /* We already have a dialog */
21276       if (p->initreq.method != SIP_SUBSCRIBE) {
21277          /* This is a SUBSCRIBE within another SIP dialog, which we do not support */
21278          /* For transfers, this could happen, but since we haven't seen it happening, let us just refuse this */
21279          transmit_response(p, "403 Forbidden (within dialog)", req);
21280          /* Do not destroy session, since we will break the call if we do */
21281          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);
21282          return 0;
21283       } else if (req->debug) {
21284          if (resubscribe)
21285             ast_debug(1, "Got a re-subscribe on existing subscription %s\n", p->callid);
21286          else
21287             ast_debug(1, "Got a new subscription %s (possibly with auth)\n", p->callid);
21288       }
21289    }
21290 
21291    /* Check if we have a global disallow setting on subscriptions. 
21292       if so, we don't have to check peer settings after auth, which saves a lot of processing
21293    */
21294    if (!sip_cfg.allowsubscribe) {
21295       transmit_response(p, "403 Forbidden (policy)", req);
21296       pvt_set_needdestroy(p, "forbidden");
21297       return 0;
21298    }
21299 
21300    if (!req->ignore && !resubscribe) { /* Set up dialog, new subscription */
21301       const char *to = get_header(req, "To");
21302       char totag[128];
21303 
21304       /* Check to see if a tag was provided, if so this is actually a resubscription of a dialog we no longer know about */
21305       if (!ast_strlen_zero(to) && gettag(req, "To", totag, sizeof(totag))) {
21306          if (req->debug)
21307             ast_verbose("Received resubscription for a dialog we no longer know about. Telling remote side to subscribe again.\n");
21308          transmit_response(p, "481 Subscription does not exist", req);
21309          pvt_set_needdestroy(p, "subscription does not exist");
21310          return 0;
21311       }
21312 
21313       /* Use this as the basis */
21314       if (req->debug)
21315          ast_verbose("Creating new subscription\n");
21316 
21317       copy_request(&p->initreq, req);
21318       if (sipdebug)
21319          ast_debug(4, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
21320       check_via(p, req);
21321       build_route(p, req, 0);
21322    } else if (req->debug && req->ignore)
21323       ast_verbose("Ignoring this SUBSCRIBE request\n");
21324 
21325    /* Find parameters to Event: header value and remove them for now */
21326    if (ast_strlen_zero(eventheader)) {
21327       transmit_response(p, "489 Bad Event", req);
21328       ast_debug(2, "Received SIP subscribe for unknown event package: <none>\n");
21329       pvt_set_needdestroy(p, "unknown event package in subscribe");
21330       return 0;
21331    }
21332 
21333    if ( (strchr(eventheader, ';'))) {
21334       event = ast_strdupa(eventheader);   /* Since eventheader is a const, we can't change it */
21335       temp = strchr(event, ';');       
21336       *temp = '\0';           /* Remove any options for now */
21337                      /* We might need to use them later :-) */
21338    } else
21339       event = (char *) eventheader;    /* XXX is this legal ? */
21340 
21341    /* Handle authentication */
21342    res = check_user_full(p, req, SIP_SUBSCRIBE, e, 0, sin, &authpeer);
21343    /* if an authentication response was sent, we are done here */
21344    if (res == AUTH_CHALLENGE_SENT)  /* authpeer = NULL here */
21345       return 0;
21346    if (res < 0) {
21347       if (res == AUTH_FAKE_AUTH) {
21348          ast_log(LOG_NOTICE, "Sending fake auth rejection for device %s\n", get_header(req, "From"));
21349          transmit_fake_auth_response(p, SIP_SUBSCRIBE, req, XMIT_UNRELIABLE);
21350       } else {
21351          ast_log(LOG_NOTICE, "Failed to authenticate device %s for SUBSCRIBE\n", get_header(req, "From"));
21352          transmit_response_reliable(p, "403 Forbidden", req);
21353       }
21354       pvt_set_needdestroy(p, "authentication failed");
21355       return 0;
21356    }
21357 
21358    /* At this point, authpeer cannot be NULL. Remember we hold a reference,
21359     * so we must release it when done.
21360     * XXX must remove all the checks for authpeer == NULL.
21361     */
21362 
21363    /* Check if this device  is allowed to subscribe at all */
21364    if (!ast_test_flag(&p->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)) {
21365       transmit_response(p, "403 Forbidden (policy)", req);
21366       pvt_set_needdestroy(p, "subscription not allowed");
21367       if (authpeer)
21368          unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 1)");
21369       return 0;
21370    }
21371 
21372    if (strcmp(event, "message-summary")) {
21373       /* Get destination right away */
21374       gotdest = get_destination(p, NULL);
21375    }
21376 
21377    /* Get full contact header - this needs to be used as a request URI in NOTIFY's */
21378    parse_ok_contact(p, req);
21379 
21380    build_contact(p);
21381    if (gotdest) {
21382       transmit_response(p, "404 Not Found", req);
21383       pvt_set_needdestroy(p, "subscription target not found");
21384       if (authpeer)
21385          unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 2)");
21386       return 0;
21387    }
21388 
21389    /* Initialize tag for new subscriptions */   
21390    if (ast_strlen_zero(p->tag))
21391       make_our_tag(p->tag, sizeof(p->tag));
21392 
21393    if (!strcmp(event, "presence") || !strcmp(event, "dialog")) { /* Presence, RFC 3842 */
21394       unsigned int pidf_xml;
21395 
21396       if (authpeer)  /* We do not need the authpeer any more */
21397          unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 2)");
21398 
21399       /* Header from Xten Eye-beam Accept: multipart/related, application/rlmi+xml, application/pidf+xml, application/xpidf+xml */
21400 
21401       pidf_xml = strstr(acceptheader, "application/pidf+xml") ? 1 : 0;
21402 
21403       /* Older versions of Polycom firmware will claim pidf+xml, but really
21404        * they only support xpidf+xml. */
21405       if (pidf_xml && strstr(p->useragent, "Polycom")) {
21406          p->subscribed = XPIDF_XML;
21407       } else if (pidf_xml) {
21408          p->subscribed = PIDF_XML;         /* RFC 3863 format */
21409       } else if (strstr(acceptheader, "application/dialog-info+xml")) {
21410          p->subscribed = DIALOG_INFO_XML;
21411          /* IETF draft: draft-ietf-sipping-dialog-package-05.txt */
21412       } else if (strstr(acceptheader, "application/cpim-pidf+xml")) {
21413          p->subscribed = CPIM_PIDF_XML;    /* RFC 3863 format */
21414       } else if (strstr(acceptheader, "application/xpidf+xml")) {
21415          p->subscribed = XPIDF_XML;        /* Early pre-RFC 3863 format with MSN additions (Microsoft Messenger) */
21416       } else if (ast_strlen_zero(acceptheader)) {
21417          if (p->subscribed == NONE) { /* if the subscribed field is not already set, and there is no accept header... */
21418             transmit_response(p, "489 Bad Event", req);
21419   
21420             ast_log(LOG_WARNING, "SUBSCRIBE failure: no Accept header: pvt: stateid: %d, laststate: %d, dialogver: %d, subscribecont: '%s', subscribeuri: '%s'\n",
21421                p->stateid, p->laststate, p->dialogver, p->subscribecontext, p->subscribeuri);
21422             pvt_set_needdestroy(p, "no Accept header");
21423             return 0;
21424          }
21425          /* if p->subscribed is non-zero, then accept is not obligatory; according to rfc 3265 section 3.1.3, at least.
21426             so, we'll just let it ride, keeping the value from a previous subscription, and not abort the subscription */
21427       } else {
21428          /* Can't find a format for events that we know about */
21429          char mybuf[200];
21430          snprintf(mybuf, sizeof(mybuf), "489 Bad Event (format %s)", acceptheader);
21431          transmit_response(p, mybuf, req);
21432  
21433          ast_log(LOG_WARNING, "SUBSCRIBE failure: unrecognized format: '%s' pvt: subscribed: %d, stateid: %d, laststate: %d, dialogver: %d, subscribecont: '%s', subscribeuri: '%s'\n",
21434             acceptheader, (int)p->subscribed, p->stateid, p->laststate, p->dialogver, p->subscribecontext, p->subscribeuri);
21435          pvt_set_needdestroy(p, "unrecognized format");
21436          return 0;
21437       }
21438    } else if (!strcmp(event, "message-summary")) { 
21439       if (!ast_strlen_zero(acceptheader) && strcmp(acceptheader, "application/simple-message-summary")) {
21440          /* Format requested that we do not support */
21441          transmit_response(p, "406 Not Acceptable", req);
21442          ast_debug(2, "Received SIP mailbox subscription for unknown format: %s\n", acceptheader);
21443          pvt_set_needdestroy(p, "unknown format");
21444          if (authpeer)
21445             unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 3)");
21446          return 0;
21447       }
21448       /* Looks like they actually want a mailbox status 
21449         This version of Asterisk supports mailbox subscriptions
21450         The subscribed URI needs to exist in the dial plan
21451         In most devices, this is configurable to the voicemailmain extension you use
21452       */
21453       if (!authpeer || AST_LIST_EMPTY(&authpeer->mailboxes)) {
21454          transmit_response(p, "404 Not found (no mailbox)", req);
21455          pvt_set_needdestroy(p, "received 404 response");
21456          ast_log(LOG_NOTICE, "Received SIP subscribe for peer without mailbox: %s\n", authpeer->name);
21457          if (authpeer)
21458             unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 4)");
21459          return 0;
21460       }
21461 
21462       p->subscribed = MWI_NOTIFICATION;
21463       if (ast_test_flag(&authpeer->flags[1], SIP_PAGE2_SUBSCRIBEMWIONLY)) {
21464          add_peer_mwi_subs(authpeer);
21465       }
21466       if (authpeer->mwipvt && authpeer->mwipvt != p) {   /* Destroy old PVT if this is a new one */
21467          /* We only allow one subscription per peer */
21468          dialog_unlink_all(authpeer->mwipvt, TRUE, TRUE);
21469          authpeer->mwipvt = dialog_unref(authpeer->mwipvt, "unref dialog authpeer->mwipvt");
21470          /* sip_destroy(authpeer->mwipvt); */
21471       }
21472       if (authpeer->mwipvt)
21473          dialog_unref(authpeer->mwipvt, "Unref previously stored mwipvt dialog pointer");
21474       authpeer->mwipvt = dialog_ref(p, "setting peers' mwipvt to p");      /* Link from peer to pvt UH- should this be dialog_ref()? */
21475       if (p->relatedpeer)
21476          unref_peer(p->relatedpeer, "Unref previously stored relatedpeer ptr");
21477       p->relatedpeer = ref_peer(authpeer, "setting dialog's relatedpeer pointer");  /* already refcounted...Link from pvt to peer UH- should this be dialog_ref()? */
21478       /* Do not release authpeer here */
21479    } else { /* At this point, Asterisk does not understand the specified event */
21480       transmit_response(p, "489 Bad Event", req);
21481       ast_debug(2, "Received SIP subscribe for unknown event package: %s\n", event);
21482       pvt_set_needdestroy(p, "unknown event package");
21483       if (authpeer)
21484          unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 5)");
21485       return 0;
21486    }
21487 
21488    /* Add subscription for extension state from the PBX core */
21489    if (p->subscribed != MWI_NOTIFICATION && !resubscribe) {
21490       if (p->stateid > -1) {
21491          ast_extension_state_del(p->stateid, cb_extensionstate);
21492          /* we need to dec the refcount, now that the extensionstate is removed */
21493          dialog_unref(p, "the extensionstate containing this dialog ptr was deleted");
21494       }
21495       p->stateid = ast_extension_state_add(p->context, p->exten, cb_extensionstate, dialog_ref(p,"copying dialog ptr into extension state struct"));
21496    }
21497 
21498    if (!req->ignore && p)
21499       p->lastinvite = seqno;
21500    if (p && !p->needdestroy) {
21501       p->expiry = atoi(get_header(req, "Expires"));
21502 
21503       /* check if the requested expiry-time is within the approved limits from sip.conf */
21504       if (p->expiry > max_expiry)
21505          p->expiry = max_expiry;
21506       if (p->expiry < min_expiry && p->expiry > 0)
21507          p->expiry = min_expiry;
21508 
21509       if (sipdebug) {
21510          if (p->subscribed == MWI_NOTIFICATION && p->relatedpeer)
21511             ast_debug(2, "Adding subscription for mailbox notification - peer %s\n", p->relatedpeer->name);
21512          else
21513             ast_debug(2, "Adding subscription for extension %s context %s for peer %s\n", p->exten, p->context, p->username);
21514       }
21515       if (p->autokillid > -1 && sip_cancel_destroy(p))   /* Remove subscription expiry for renewals */
21516          ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
21517       if (p->expiry > 0)
21518          sip_scheddestroy(p, (p->expiry + 10) * 1000);   /* Set timer for destruction of call at expiration */
21519 
21520       if (p->subscribed == MWI_NOTIFICATION) {
21521          ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
21522          transmit_response(p, "200 OK", req);
21523          if (p->relatedpeer) {   /* Send first notification */
21524             ao2_lock(p->relatedpeer); /* was WRLOCK */
21525             sip_send_mwi_to_peer(p->relatedpeer, NULL, 0);
21526             ao2_unlock(p->relatedpeer);
21527          }
21528       } else {
21529          struct sip_pvt *p_old;
21530 
21531          if ((firststate = ast_extension_state(NULL, p->context, p->exten)) < 0) {
21532 
21533             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));
21534             transmit_response(p, "404 Not found", req);
21535             pvt_set_needdestroy(p, "no extension for SUBSCRIBE");
21536             return 0;
21537          }
21538          ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
21539          transmit_response(p, "200 OK", req);
21540          transmit_state_notify(p, firststate, 1, FALSE); /* Send first notification */
21541          append_history(p, "Subscribestatus", "%s", ast_extension_state2str(firststate));
21542          /* hide the 'complete' exten/context in the refer_to field for later display */
21543          ast_string_field_build(p, subscribeuri, "%s@%s", p->exten, p->context);
21544 
21545          /* remove any old subscription from this peer for the same exten/context,
21546          as the peer has obviously forgotten about it and it's wasteful to wait
21547          for it to expire and send NOTIFY messages to the peer only to have them
21548          ignored (or generate errors)
21549          */
21550          i = ao2_iterator_init(dialogs, 0);
21551          while ((p_old = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
21552             if (p_old == p) {
21553                ao2_t_ref(p_old, -1, "toss dialog ptr from iterator_next before continue");
21554                continue;
21555             }
21556             if (p_old->initreq.method != SIP_SUBSCRIBE) {
21557                ao2_t_ref(p_old, -1, "toss dialog ptr from iterator_next before continue");
21558                continue;
21559             }
21560             if (p_old->subscribed == NONE) {
21561                ao2_t_ref(p_old, -1, "toss dialog ptr from iterator_next before continue");
21562                continue;
21563             }
21564             sip_pvt_lock(p_old);
21565             if (!strcmp(p_old->username, p->username)) {
21566                if (!strcmp(p_old->exten, p->exten) &&
21567                    !strcmp(p_old->context, p->context)) {
21568                   pvt_set_needdestroy(p_old, "replacing subscription");
21569                   sip_pvt_unlock(p_old);
21570                   ao2_t_ref(p_old, -1, "toss dialog ptr from iterator_next before break");
21571                   break;
21572                }
21573             }
21574             sip_pvt_unlock(p_old);
21575             ao2_t_ref(p_old, -1, "toss dialog ptr from iterator_next");
21576          }
21577          ao2_iterator_destroy(&i);
21578       }
21579       if (!p->expiry) {
21580          pvt_set_needdestroy(p, "forcing expiration");
21581       }
21582    }
21583    return 1;
21584 }
21585 
21586 /*! \brief Handle incoming REGISTER request */
21587 static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, char *e)
21588 {
21589    enum check_auth_result res;
21590 
21591    /* Use this as the basis */
21592    copy_request(&p->initreq, req);
21593    if (sipdebug)
21594       ast_debug(4, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
21595    check_via(p, req);
21596    if ((res = register_verify(p, sin, req, e)) < 0) {
21597       const char *reason;
21598 
21599       switch (res) {
21600       case AUTH_SECRET_FAILED:
21601          reason = "Wrong password";
21602          break;
21603       case AUTH_USERNAME_MISMATCH:
21604          reason = "Username/auth name mismatch";
21605          break;
21606       case AUTH_NOT_FOUND:
21607          reason = "No matching peer found";
21608          break;
21609       case AUTH_UNKNOWN_DOMAIN:
21610          reason = "Not a local domain";
21611          break;
21612       case AUTH_PEER_NOT_DYNAMIC:
21613          reason = "Peer is not supposed to register";
21614          break;
21615       case AUTH_ACL_FAILED:
21616          reason = "Device does not match ACL";
21617          break;
21618       case AUTH_BAD_TRANSPORT:
21619          reason = "Device not configured to use this transport type";
21620          break;
21621       default:
21622          reason = "Unknown failure";
21623          break;
21624       }
21625       ast_log(LOG_NOTICE, "Registration from '%s' failed for '%s' - %s\n",
21626          get_header(req, "To"), ast_inet_ntoa(sin->sin_addr),
21627          reason);
21628       append_history(p, "RegRequest", "Failed : Account %s : %s", get_header(req, "To"), reason);
21629    } else
21630       append_history(p, "RegRequest", "Succeeded : Account %s", get_header(req, "To"));
21631 
21632    if (res < 1) {
21633       /* Destroy the session, but keep us around for just a bit in case they don't
21634          get our 200 OK */
21635       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
21636    }
21637    return res;
21638 }
21639 
21640 /*! \brief Handle incoming SIP requests (methods) 
21641 \note This is where all incoming requests go first   */
21642 /* called with p and p->owner locked */
21643 static int handle_incoming(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int *recount, int *nounlock)
21644 {
21645    /* Called with p->lock held, as well as p->owner->lock if appropriate, keeping things
21646       relatively static */
21647    const char *cmd;
21648    const char *cseq;
21649    const char *useragent;
21650    int seqno;
21651    int len;
21652    int respid;
21653    int res = 0;
21654    int debug = sip_debug_test_pvt(p);
21655    char *e;
21656    int error = 0;
21657    int oldmethod = p->method;
21658    int acked = 0;
21659 
21660    /* Get Method and Cseq */
21661    cseq = get_header(req, "Cseq");
21662    cmd = REQ_OFFSET_TO_STR(req, header[0]);
21663 
21664    /* Must have Cseq */
21665    if (ast_strlen_zero(cmd) || ast_strlen_zero(cseq)) {
21666       ast_log(LOG_ERROR, "Missing Cseq. Dropping this SIP message, it's incomplete.\n");
21667       error = 1;
21668    }
21669    if (!error && sscanf(cseq, "%30d%n", &seqno, &len) != 1) {
21670       ast_log(LOG_ERROR, "No seqno in '%s'. Dropping incomplete message.\n", cmd);
21671       error = 1;
21672    }
21673    if (error) {
21674       if (!p->initreq.headers) { /* New call */
21675          pvt_set_needdestroy(p, "no headers");
21676       }
21677       return -1;
21678    }
21679    /* Get the command XXX */
21680 
21681    cmd = REQ_OFFSET_TO_STR(req, rlPart1);
21682    e = ast_skip_blanks(REQ_OFFSET_TO_STR(req, rlPart2));
21683 
21684    /* Save useragent of the client */
21685    useragent = get_header(req, "User-Agent");
21686    if (!ast_strlen_zero(useragent))
21687       ast_string_field_set(p, useragent, useragent);
21688 
21689    /* Find out SIP method for incoming request */
21690    if (req->method == SIP_RESPONSE) {  /* Response to our request */
21691       /* ignore means "don't do anything with it" but still have to 
21692        * respond appropriately.
21693        * But in this case this is a response already, so we really
21694        * have nothing to do with this message, and even setting the
21695        * ignore flag is pointless.
21696        */
21697       if (ast_strlen_zero(e)) {
21698          return 0;
21699       }
21700       if (sscanf(e, "%30d %n", &respid, &len) != 1) {
21701          ast_log(LOG_WARNING, "Invalid response: '%s'\n", e);
21702          return 0;
21703       }
21704       if (respid <= 0) {
21705          ast_log(LOG_WARNING, "Invalid SIP response code: '%d'\n", respid);
21706          return 0;
21707       }
21708       if (p->ocseq && (p->ocseq < seqno)) {
21709          if (option_debug)
21710             ast_log(LOG_DEBUG, "Ignoring out of order response %d (expecting %d)\n", seqno, p->ocseq);
21711          return -1;
21712       } else {
21713          if ((respid == 200) || ((respid >= 300) && (respid <= 399))) {
21714             extract_uri(p, req);
21715          }
21716          handle_response(p, respid, e + len, req, seqno);
21717       }
21718       return 0;
21719    }
21720 
21721    /* New SIP request coming in 
21722       (could be new request in existing SIP dialog as well...) 
21723     */         
21724    
21725    p->method = req->method;   /* Find out which SIP method they are using */
21726    ast_debug(4, "**** Received %s (%d) - Command in SIP %s\n", sip_methods[p->method].text, sip_methods[p->method].id, cmd); 
21727 
21728    if (p->icseq && (p->icseq > seqno) ) {
21729       if (p->pendinginvite && seqno == p->pendinginvite && (req->method == SIP_ACK || req->method == SIP_CANCEL)) {
21730          ast_debug(2, "Got CANCEL or ACK on INVITE with transactions in between.\n");
21731       }  else {
21732          ast_debug(1, "Ignoring too old SIP packet packet %d (expecting >= %d)\n", seqno, p->icseq);
21733          if (req->method != SIP_ACK)
21734             transmit_response(p, "503 Server error", req);  /* We must respond according to RFC 3261 sec 12.2 */
21735          return -1;
21736       }
21737    } else if (p->icseq &&
21738          p->icseq == seqno &&
21739          req->method != SIP_ACK &&
21740          (p->method != SIP_CANCEL || p->alreadygone)) {
21741       /* ignore means "don't do anything with it" but still have to 
21742          respond appropriately.  We do this if we receive a repeat of
21743          the last sequence number  */
21744       req->ignore = 1;
21745       ast_debug(3, "Ignoring SIP message because of retransmit (%s Seqno %d, ours %d)\n", sip_methods[p->method].text, p->icseq, seqno);
21746    }
21747       
21748    if (seqno >= p->icseq)
21749       /* Next should follow monotonically (but not necessarily 
21750          incrementally -- thanks again to the genius authors of SIP --
21751          increasing */
21752       p->icseq = seqno;
21753 
21754    /* Find their tag if we haven't got it */
21755    if (ast_strlen_zero(p->theirtag)) {
21756       char tag[128];
21757 
21758       gettag(req, "From", tag, sizeof(tag));
21759       ast_string_field_set(p, theirtag, tag);
21760    }
21761    snprintf(p->lastmsg, sizeof(p->lastmsg), "Rx: %s", cmd);
21762 
21763    if (sip_cfg.pedanticsipchecking) {
21764       /* If this is a request packet without a from tag, it's not
21765          correct according to RFC 3261  */
21766       /* Check if this a new request in a new dialog with a totag already attached to it,
21767          RFC 3261 - section 12.2 - and we don't want to mess with recovery  */
21768       if (!p->initreq.headers && req->has_to_tag) {
21769          /* If this is a first request and it got a to-tag, it is not for us */
21770          if (!req->ignore && req->method == SIP_INVITE) {
21771             transmit_response_reliable(p, "481 Call/Transaction Does Not Exist", req);
21772             /* Will cease to exist after ACK */
21773          } else if (req->method != SIP_ACK) {
21774             transmit_response(p, "481 Call/Transaction Does Not Exist", req);
21775             sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
21776          } else {
21777             ast_debug(1, "Got ACK for unknown dialog... strange.\n");
21778          }
21779          return res;
21780       }
21781    }
21782 
21783    if (!e && (p->method == SIP_INVITE || p->method == SIP_SUBSCRIBE || p->method == SIP_REGISTER || p->method == SIP_NOTIFY)) {
21784       transmit_response(p, "400 Bad request", req);
21785       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
21786       return -1;
21787    }
21788 
21789    /* Handle various incoming SIP methods in requests */
21790    switch (p->method) {
21791    case SIP_OPTIONS:
21792       res = handle_request_options(p, req);
21793       break;
21794    case SIP_INVITE:
21795       res = handle_request_invite(p, req, debug, seqno, sin, recount, e, nounlock);
21796       break;
21797    case SIP_REFER:
21798       res = handle_request_refer(p, req, debug, seqno, nounlock);
21799       break;
21800    case SIP_CANCEL:
21801       res = handle_request_cancel(p, req);
21802       break;
21803    case SIP_BYE:
21804       res = handle_request_bye(p, req);
21805       break;
21806    case SIP_MESSAGE:
21807       res = handle_request_message(p, req);
21808       break;
21809    case SIP_SUBSCRIBE:
21810       res = handle_request_subscribe(p, req, sin, seqno, e);
21811       break;
21812    case SIP_REGISTER:
21813       res = handle_request_register(p, req, sin, e);
21814       break;
21815    case SIP_INFO:
21816       if (req->debug)
21817          ast_verbose("Receiving INFO!\n");
21818       if (!req->ignore) 
21819          handle_request_info(p, req);
21820       else  /* if ignoring, transmit response */
21821          transmit_response(p, "200 OK", req);
21822       break;
21823    case SIP_NOTIFY:
21824       res = handle_request_notify(p, req, sin, seqno, e);
21825       break;
21826    case SIP_ACK:
21827       /* Make sure we don't ignore this */
21828       if (seqno == p->pendinginvite) {
21829          p->invitestate = INV_TERMINATED;
21830          p->pendinginvite = 0;
21831          acked = __sip_ack(p, seqno, 1 /* response */, 0);
21832          if (find_sdp(req)) {
21833             if (process_sdp(p, req, SDP_T38_NONE))
21834                return -1;
21835          }
21836          check_pendings(p);
21837       } else if (p->glareinvite == seqno) {
21838          /* handle ack for the 491 pending sent for glareinvite */
21839          p->glareinvite = 0;
21840          acked = __sip_ack(p, seqno, 1, 0);
21841       }
21842       if (!acked) {
21843          /* Got an ACK that did not match anything. Ignore
21844           * silently and restore previous method */
21845          p->method = oldmethod;
21846       }
21847       if (!p->lastinvite && ast_strlen_zero(p->randdata)) {
21848          pvt_set_needdestroy(p, "unmatched ACK");
21849       }
21850       break;
21851    default:
21852       transmit_response_with_allow(p, "501 Method Not Implemented", req, 0);
21853       ast_log(LOG_NOTICE, "Unknown SIP command '%s' from '%s'\n", 
21854          cmd, ast_inet_ntoa(p->sa.sin_addr));
21855       /* If this is some new method, and we don't have a call, destroy it now */
21856       if (!p->initreq.headers) {
21857          pvt_set_needdestroy(p, "unimplemented method");
21858       }
21859       break;
21860    }
21861    return res;
21862 }
21863 
21864 static void process_request_queue(struct sip_pvt *p, int *recount, int *nounlock)
21865 {
21866    struct sip_request *req;
21867 
21868    while ((req = AST_LIST_REMOVE_HEAD(&p->request_queue, next))) {
21869       if (handle_incoming(p, req, &p->recv, recount, nounlock) == -1) {
21870          /* Request failed */
21871          if (option_debug) {
21872             ast_log(LOG_DEBUG, "SIP message could not be handled, bad request: %-70.70s\n", p->callid[0] ? p->callid : "<no callid>");
21873          }
21874       }
21875       ast_free(req);
21876    }
21877 }
21878 
21879 static int scheduler_process_request_queue(const void *data)
21880 {
21881    struct sip_pvt *p = (struct sip_pvt *) data;
21882    int recount = 0;
21883    int nounlock = 0;
21884    int lockretry;
21885 
21886    for (lockretry = 10; lockretry > 0; lockretry--) {
21887       sip_pvt_lock(p);
21888 
21889       /* lock the owner if it has one -- we may need it */
21890       /* because this is deadlock-prone, we need to try and unlock if failed */
21891       if (!p->owner || !ast_channel_trylock(p->owner)) {
21892          break;   /* locking succeeded */
21893       }
21894 
21895       if (lockretry != 1) {
21896          sip_pvt_unlock(p);
21897          /* Sleep for a very short amount of time */
21898          usleep(1);
21899       }
21900    }
21901 
21902    if (!lockretry) {
21903       int retry = !AST_LIST_EMPTY(&p->request_queue);
21904 
21905       /* we couldn't get the owner lock, which is needed to process
21906          the queued requests, so return a non-zero value, which will
21907          cause the scheduler to run this request again later if there
21908          still requests to be processed
21909       */
21910       sip_pvt_unlock(p);
21911       if (!retry) {
21912          dialog_unref(p, "The ref to a dialog passed to this sched callback is going out of scope; unref it.");
21913       }
21914       return retry;
21915    };
21916 
21917    process_request_queue(p, &recount, &nounlock);
21918    p->request_queue_sched_id = -1;
21919 
21920    if (p->owner && !nounlock) {
21921       ast_channel_unlock(p->owner);
21922    }
21923    sip_pvt_unlock(p);
21924 
21925    if (recount) {
21926       ast_update_use_count();
21927    }
21928 
21929    dialog_unref(p, "The ref to a dialog passed to this sched callback is going out of scope; unref it.");
21930 
21931    return 0;
21932 }
21933 
21934 static int queue_request(struct sip_pvt *p, const struct sip_request *req)
21935 {
21936    struct sip_request *newreq;
21937 
21938    if (!(newreq = ast_calloc(1, sizeof(*newreq)))) {
21939       return -1;
21940    }
21941 
21942    copy_request(newreq, req);
21943    AST_LIST_INSERT_TAIL(&p->request_queue, newreq, next);
21944    if (p->request_queue_sched_id == -1) {
21945       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) {
21946          dialog_unref(p, "Decrement refcount due to sched_add failure");
21947       }
21948    }
21949 
21950    return 0;
21951 }
21952 
21953 /*! \brief Read data from SIP UDP socket
21954 \note sipsock_read locks the owner channel while we are processing the SIP message
21955 \return 1 on error, 0 on success
21956 \note Successful messages is connected to SIP call and forwarded to handle_incoming() 
21957 */
21958 static int sipsock_read(int *id, int fd, short events, void *ignore)
21959 {
21960    struct sip_request req;
21961    struct sockaddr_in sin = { 0, };
21962    int res;
21963    socklen_t len = sizeof(sin);
21964    static char readbuf[65535];
21965 
21966    memset(&req, 0, sizeof(req));
21967    res = recvfrom(fd, readbuf, sizeof(readbuf) - 1, 0, (struct sockaddr *)&sin, &len);
21968    if (res < 0) {
21969 #if !defined(__FreeBSD__)
21970       if (errno == EAGAIN)
21971          ast_log(LOG_NOTICE, "SIP: Received packet with bad UDP checksum\n");
21972       else 
21973 #endif
21974       if (errno != ECONNREFUSED)
21975          ast_log(LOG_WARNING, "Recv error: %s\n", strerror(errno));
21976       return 1;
21977    }
21978 
21979    readbuf[res] = '\0';
21980 
21981    if (!(req.data = ast_str_create(SIP_MIN_PACKET))) {
21982       return 1;
21983    }
21984 
21985    if (ast_str_set(&req.data, 0, "%s", readbuf) == AST_DYNSTR_BUILD_FAILED) {
21986       return -1;
21987    }
21988 
21989    req.len = res;
21990    req.socket.fd = sipsock;
21991    set_socket_transport(&req.socket, SIP_TRANSPORT_UDP);
21992    req.socket.tcptls_session  = NULL;
21993    req.socket.port = bindaddr.sin_port;
21994 
21995    handle_request_do(&req, &sin);
21996    if (req.data) {
21997       ast_free(req.data);
21998       req.data = NULL;
21999    }
22000 
22001    return 1;
22002 }
22003 
22004 /*! \brief Handle incoming SIP message - request or response 
22005 
22006    This is used for all transports (udp, tcp and tcp/tls)
22007 */
22008 static int handle_request_do(struct sip_request *req, struct sockaddr_in *sin) 
22009 {
22010    struct sip_pvt *p;
22011    int recount = 0;
22012    int nounlock = 0;
22013    int lockretry;
22014 
22015    if (sip_debug_test_addr(sin)) /* Set the debug flag early on packet level */
22016       req->debug = 1;
22017    if (sip_cfg.pedanticsipchecking)
22018       req->len = lws2sws(req->data->str, req->len);   /* Fix multiline headers */
22019    if (req->debug) {
22020       ast_verbose("\n<--- SIP read from %s:%s:%d --->\n%s\n<------------->\n", 
22021          get_transport(req->socket.type), ast_inet_ntoa(sin->sin_addr), 
22022          ntohs(sin->sin_port), req->data->str);
22023    }
22024 
22025    if (parse_request(req) == -1) { /* Bad packet, can't parse */
22026       ast_str_reset(req->data); /* nulling this out is NOT a good idea here. */
22027       return 1;
22028    }
22029    req->method = find_sip_method(REQ_OFFSET_TO_STR(req, rlPart1));
22030 
22031    if (req->debug)
22032       ast_verbose("--- (%d headers %d lines)%s ---\n", req->headers, req->lines, (req->headers + req->lines == 0) ? " Nat keepalive" : "");
22033 
22034    if (req->headers < 2) { /* Must have at least two headers */
22035       ast_str_reset(req->data); /* nulling this out is NOT a good idea here. */
22036       return 1;
22037    }
22038 
22039    /* Process request, with netlock held, and with usual deadlock avoidance */
22040    for (lockretry = 10; lockretry > 0; lockretry--) {
22041       ast_mutex_lock(&netlock);
22042 
22043       /* Find the active SIP dialog or create a new one */
22044       p = find_call(req, sin, req->method);  /* returns p locked */
22045       if (p == NULL) {
22046          ast_debug(1, "Invalid SIP message - rejected , no callid, len %d\n", req->len);
22047          ast_mutex_unlock(&netlock);
22048          return 1;
22049       }
22050 
22051       copy_socket_data(&p->socket, &req->socket);
22052 
22053       /* Go ahead and lock the owner if it has one -- we may need it */
22054       /* becaues this is deadlock-prone, we need to try and unlock if failed */
22055       if (!p->owner || !ast_channel_trylock(p->owner))
22056          break;   /* locking succeeded */
22057 
22058       if (lockretry != 1) {
22059          sip_pvt_unlock(p);
22060          ao2_t_ref(p, -1, "release p (from find_call) inside lockretry loop"); /* we'll look for it again, but p is dead now */
22061          ast_mutex_unlock(&netlock);
22062          /* Sleep for a very short amount of time */
22063          usleep(1);
22064       }
22065    }
22066    p->recv = *sin;
22067 
22068    if (p->do_history) /* This is a request or response, note what it was for */
22069       append_history(p, "Rx", "%s / %s / %s", req->data->str, get_header(req, "CSeq"), REQ_OFFSET_TO_STR(req, rlPart2));
22070 
22071    if (!lockretry) {
22072       if (!queue_request(p, req)) {
22073          /* the request has been queued for later handling */
22074          sip_pvt_unlock(p);
22075          ao2_t_ref(p, -1, "release p (from find_call) after queueing request");
22076          ast_mutex_unlock(&netlock);
22077          return 1;
22078       }
22079 
22080       if (p->owner)
22081          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 ??? - "));
22082       ast_log(LOG_ERROR, "SIP transaction failed: %s \n", p->callid);
22083       if (req->method != SIP_ACK)
22084          transmit_response(p, "503 Server error", req);  /* We must respond according to RFC 3261 sec 12.2 */
22085       /* XXX We could add retry-after to make sure they come back */
22086       append_history(p, "LockFail", "Owner lock failed, transaction failed.");
22087       sip_pvt_unlock(p);
22088       ao2_t_ref(p, -1, "release p (from find_call) at end of lockretry"); /* p is gone after the return */
22089       ast_mutex_unlock(&netlock);
22090       return 1;
22091    }
22092 
22093    /* if there are queued requests on this sip_pvt, process them first, so that everything is
22094       handled in order
22095    */
22096    if (!AST_LIST_EMPTY(&p->request_queue)) {
22097       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"));
22098       process_request_queue(p, &recount, &nounlock);
22099    }
22100 
22101    if (handle_incoming(p, req, sin, &recount, &nounlock) == -1) {
22102       /* Request failed */
22103       ast_debug(1, "SIP message could not be handled, bad request: %-70.70s\n", p->callid[0] ? p->callid : "<no callid>");
22104    }
22105       
22106    if (recount)
22107       ast_update_use_count();
22108 
22109    if (p->owner && !nounlock)
22110       ast_channel_unlock(p->owner);
22111    sip_pvt_unlock(p);
22112    ast_mutex_unlock(&netlock);
22113    ao2_t_ref(p, -1, "throw away dialog ptr from find_call at end of routine"); /* p is gone after the return */
22114    return 1;
22115 }
22116 
22117 /*! \brief Returns the port to use for this socket
22118  *
22119  * \param type The type of transport used
22120  * \param port Port we are checking to see if it's the standard port.
22121  * \note port is expected in host byte order
22122  */
22123 static int sip_standard_port(enum sip_transport type, int port)
22124 {
22125    if (type & SIP_TRANSPORT_TLS)
22126       return port == STANDARD_TLS_PORT;
22127    else
22128       return port == STANDARD_SIP_PORT;
22129 }
22130 
22131 static int threadinfo_locate_cb(void *obj, void *arg, int flags)
22132 {
22133    struct sip_threadinfo *th = obj;
22134    struct sockaddr_in *s = arg;
22135 
22136    if (!inaddrcmp(&th->tcptls_session->remote_address, s)) {
22137       return CMP_MATCH | CMP_STOP;
22138    }
22139 
22140    return 0;
22141 }
22142 
22143 /*! 
22144  * \brief Find thread for TCP/TLS session (based on IP/Port 
22145  *
22146  * \note This function returns an astobj2 reference
22147  */
22148 static struct ast_tcptls_session_instance *sip_tcp_locate(struct sockaddr_in *s)
22149 {
22150    struct sip_threadinfo *th;
22151    struct ast_tcptls_session_instance *tcptls_instance = NULL;
22152 
22153    if ((th = ao2_callback(threadt, 0, threadinfo_locate_cb, s))) {
22154       tcptls_instance = (ao2_ref(th->tcptls_session, +1), th->tcptls_session);
22155       ao2_t_ref(th, -1, "decrement ref from callback");
22156    }
22157    return tcptls_instance;
22158 }
22159 
22160 /*! \todo Get socket for dialog, prepare if needed, and return file handle  */
22161 static int sip_prepare_socket(struct sip_pvt *p) 
22162 {
22163    struct sip_socket *s = &p->socket;
22164    static const char name[] = "SIP socket";
22165    struct sip_threadinfo *th = NULL;
22166    struct ast_tcptls_session_instance *tcptls_session;
22167    struct ast_tcptls_session_args tmp_ca = {
22168       .name = name,
22169       .accept_fd = -1,
22170    };
22171    struct ast_tcptls_session_args *ca;
22172 
22173    /* check to see if a socket is already active */
22174    if ((s->fd != -1) && (s->type == SIP_TRANSPORT_UDP)) {
22175       return s->fd;
22176    }
22177    if ((s->type & (SIP_TRANSPORT_TCP | SIP_TRANSPORT_TLS)) &&
22178          (s->tcptls_session) &&
22179          (s->tcptls_session->fd != -1)) {
22180       return s->tcptls_session->fd;
22181    }
22182 
22183    /*! \todo Check this... This might be wrong, depending on the proxy configuration
22184       If proxy is in "force" mode its correct.
22185     */
22186    if (p->outboundproxy && p->outboundproxy->transport) {
22187       s->type = p->outboundproxy->transport;
22188    }
22189 
22190    if (s->type == SIP_TRANSPORT_UDP) {
22191       s->fd = sipsock;
22192       return s->fd;
22193    }
22194 
22195    /* At this point we are dealing with a TCP/TLS connection
22196     * 1. We need to check to see if a connectin thread exists
22197     *    for this address, if so use that.
22198     * 2. If a thread does not exist for this address, but the tcptls_session
22199     *    exists on the socket, the connection was closed.
22200     * 3. If no tcptls_session thread exists for the address, and no tcptls_session
22201     *    already exists on the socket, create a new one and launch a new thread.
22202     */
22203 
22204    /* 1.  check for existing threads */
22205    tmp_ca.remote_address = *(sip_real_dst(p));
22206    if ((tcptls_session = sip_tcp_locate(&tmp_ca.remote_address))) {
22207       s->fd = tcptls_session->fd;
22208       if (s->tcptls_session) {
22209          ao2_ref(s->tcptls_session, -1);
22210          s->tcptls_session = NULL;
22211       }
22212       s->tcptls_session = tcptls_session;
22213       return s->fd;
22214    /* 2.  Thread not found, if tcptls_session already exists, it once had a thread and is now terminated */
22215    } else if (s->tcptls_session) {
22216       return s->fd; /* XXX whether reconnection is ever necessary here needs to be investigated further */
22217    }
22218 
22219    /* 3.  Create a new TCP/TLS client connection */
22220    /* create new session arguments for the client connection */
22221    if (!(ca = ao2_alloc(sizeof(*ca), sip_tcptls_client_args_destructor)) ||
22222       !(ca->name = ast_strdup(name))) {
22223       goto create_tcptls_session_fail;
22224    }
22225    ca->accept_fd = -1;
22226    ca->remote_address = *(sip_real_dst(p));
22227    /* if type is TLS, we need to create a tls cfg for this session arg */
22228    if (s->type == SIP_TRANSPORT_TLS) {
22229       if (!(ca->tls_cfg = ast_calloc(1, sizeof(*ca->tls_cfg)))) {
22230          goto create_tcptls_session_fail;
22231       }
22232       memcpy(ca->tls_cfg, &default_tls_cfg, sizeof(*ca->tls_cfg));
22233 
22234       if (!(ca->tls_cfg->certfile = ast_strdup(default_tls_cfg.certfile)) ||
22235          !(ca->tls_cfg->cipher = ast_strdup(default_tls_cfg.cipher)) ||
22236          !(ca->tls_cfg->cafile = ast_strdup(default_tls_cfg.cafile)) ||
22237          !(ca->tls_cfg->capath = ast_strdup(default_tls_cfg.capath))) {
22238 
22239          goto create_tcptls_session_fail;
22240       }
22241 
22242       /* this host is used as the common name in ssl/tls */
22243       if (!ast_strlen_zero(p->tohost)) {
22244          ast_copy_string(ca->hostname, p->tohost, sizeof(ca->hostname));
22245       }
22246    }
22247    /* Create a client connection for address, this does not start the connection, just sets it up. */
22248    if (!(s->tcptls_session = ast_tcptls_client_create(ca))) {
22249       goto create_tcptls_session_fail;
22250    }
22251 
22252    s->fd = s->tcptls_session->fd;
22253 
22254    /* client connections need to have the sip_threadinfo object created before
22255     * the thread is detached.  This ensures the alert_pipe is up before it will
22256     * be used.  Note that this function links the new threadinfo object into the
22257     * threadt container. */
22258    if (!(th = sip_threadinfo_create(s->tcptls_session, s->type))) {
22259       goto create_tcptls_session_fail;
22260 
22261    }
22262 
22263    /* Give the new thread a reference to the tcptls_session */
22264    ao2_ref(s->tcptls_session, +1);
22265 
22266    if (ast_pthread_create_background(&ca->master, NULL, sip_tcp_worker_fn, s->tcptls_session)) {
22267       ast_debug(1, "Unable to launch '%s'.", ca->name);
22268       ao2_ref(s->tcptls_session, -1); /* take away the thread ref we just gave it */
22269       goto create_tcptls_session_fail;
22270    }
22271 
22272    return s->fd;
22273 
22274 create_tcptls_session_fail:
22275    if (ca) {
22276       ao2_t_ref(ca, -1, "failed to create client, getting rid of client tcptls_session arguments");
22277    }
22278    if (s->tcptls_session) {
22279       close(tcptls_session->fd);
22280       s->fd = tcptls_session->fd = -1;
22281       ao2_ref(s->tcptls_session, -1);
22282       s->tcptls_session = NULL;
22283    }
22284    if (th) {
22285       ao2_t_unlink(threadt, th, "Removing tcptls thread info object, thread failed to open");
22286    }
22287 
22288    return -1;
22289 }
22290 
22291 /*!
22292  * \brief Small function to parse a config line for a host with a transport
22293  *        i.e. tls://www.google.com:8056
22294  */
22295 static int sip_parse_host(char *line, int lineno, char **hostname, int *portnum, enum sip_transport *transport)
22296 {
22297    char *port;
22298 
22299    if ((*hostname = strstr(line, "://"))) {
22300       *hostname += 3;
22301 
22302       if (!strncasecmp(line, "tcp", 3))
22303          *transport = SIP_TRANSPORT_TCP;
22304       else if (!strncasecmp(line, "tls", 3))
22305          *transport = SIP_TRANSPORT_TLS;
22306       else if (!strncasecmp(line, "udp", 3))
22307          *transport = SIP_TRANSPORT_UDP;
22308       else
22309          ast_log(LOG_NOTICE, "'%.3s' is not a valid transport type on line %d of sip.conf. defaulting to udp.\n", line, lineno);
22310    } else {
22311       *hostname = line;
22312       *transport = SIP_TRANSPORT_UDP;
22313    }
22314 
22315    if ((line = strrchr(*hostname, '@')))
22316       line++;
22317    else
22318       line = *hostname;
22319 
22320    if ((port = strrchr(line, ':'))) {
22321       *port++ = '\0';
22322 
22323       if (!sscanf(port, "%5u", portnum)) {
22324          ast_log(LOG_NOTICE, "'%s' is not a valid port number on line %d of sip.conf. using default.\n", port, lineno);
22325          port = NULL;
22326       }
22327    }
22328 
22329    if (!port) {
22330       if (*transport & SIP_TRANSPORT_TLS) {
22331          *portnum = STANDARD_TLS_PORT;
22332       } else {
22333          *portnum = STANDARD_SIP_PORT;
22334       }
22335    }
22336 
22337    return 0;
22338 }
22339 
22340 /*!
22341  * \brief Get cached MWI info
22342  * \retval 0 At least one message is waiting
22343  * \retval 1 no messages waiting
22344  */
22345 static int get_cached_mwi(struct sip_peer *peer, int *new, int *old)
22346 {
22347    struct sip_mailbox *mailbox;
22348 
22349    AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
22350       struct ast_event *event;
22351       event = ast_event_get_cached(AST_EVENT_MWI,
22352          AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, mailbox->mailbox,
22353          AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, S_OR(mailbox->context, "default"),
22354          AST_EVENT_IE_END);
22355       if (!event)
22356          continue;
22357       *new += ast_event_get_ie_uint(event, AST_EVENT_IE_NEWMSGS);
22358       *old += ast_event_get_ie_uint(event, AST_EVENT_IE_OLDMSGS);
22359       ast_event_destroy(event);
22360    }
22361 
22362    return (*new || *old) ? 0 : 1;
22363 }
22364 
22365 /*! \brief Send message waiting indication to alert peer that they've got voicemail */
22366 static int sip_send_mwi_to_peer(struct sip_peer *peer, const struct ast_event *event, int cache_only)
22367 {
22368    /* Called with peerl lock, but releases it */
22369    struct sip_pvt *p;
22370    int newmsgs = 0, oldmsgs = 0;
22371 
22372    if (ast_test_flag((&peer->flags[1]), SIP_PAGE2_SUBSCRIBEMWIONLY) && !peer->mwipvt)
22373       return 0;
22374 
22375    /* Do we have an IP address? If not, skip this peer */
22376    if (!peer->addr.sin_addr.s_addr && !peer->defaddr.sin_addr.s_addr) 
22377       return 0;
22378 
22379    if (event) {
22380       newmsgs = ast_event_get_ie_uint(event, AST_EVENT_IE_NEWMSGS);
22381       oldmsgs = ast_event_get_ie_uint(event, AST_EVENT_IE_OLDMSGS);
22382    } else if (!get_cached_mwi(peer, &newmsgs, &oldmsgs)) {
22383       /* got it!  Don't keep looking. */
22384    } else if (cache_only) {
22385       return 0;
22386    } else { /* Fall back to manually checking the mailbox */
22387       struct ast_str *mailbox_str = ast_str_alloca(512);
22388       peer_mailboxes_to_str(&mailbox_str, peer);
22389       ast_app_inboxcount(mailbox_str->str, &newmsgs, &oldmsgs);
22390    }
22391    
22392    if (peer->mwipvt) {
22393       /* Base message on subscription */
22394       p = dialog_ref(peer->mwipvt, "sip_send_mwi_to_peer: Setting dialog ptr p from peer->mwipvt-- should this be done?");
22395    } else {
22396       /* Build temporary dialog for this message */
22397       if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY, NULL))) 
22398          return -1;
22399       /* If we don't set the socket type to 0, then create_addr_from_peer will fail immediately if the peer
22400        * uses any transport other than UDP. We set the type to 0 here and then let create_addr_from_peer copy 
22401        * the peer's socket information to the sip_pvt we just allocated
22402        */
22403       set_socket_transport(&p->socket, 0);
22404       if (create_addr_from_peer(p, peer)) {
22405          /* Maybe they're not registered, etc. */
22406          dialog_unlink_all(p, TRUE, TRUE);
22407          dialog_unref(p, "unref dialog p just created via sip_alloc");
22408          /* sip_destroy(p); */
22409          return 0;
22410       }
22411       /* Recalculate our side, and recalculate Call ID */
22412       ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
22413       build_via(p);
22414       ao2_t_unlink(dialogs, p, "About to change the callid -- remove the old name");
22415       build_callid_pvt(p);
22416       ao2_t_link(dialogs, p, "Linking in under new name");
22417       /* Destroy this session after 32 secs */
22418       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
22419    }
22420 
22421    /* Send MWI */
22422    ast_set_flag(&p->flags[0], SIP_OUTGOING);
22423    /* the following will decrement the refcount on p as it finishes */
22424    transmit_notify_with_mwi(p, newmsgs, oldmsgs, peer->vmexten);
22425    dialog_unref(p, "unref dialog ptr p just before it goes out of scope at the end of sip_send_mwi_to_peer.");
22426    return 0;
22427 }
22428 
22429 /*! \brief helper function for the monitoring thread -- seems to be called with the assumption that the dialog is locked */
22430 static void check_rtp_timeout(struct sip_pvt *dialog, time_t t)
22431 {
22432    /* If we have no RTP or no active owner, no need to check timers */
22433    if (!dialog->rtp || !dialog->owner)
22434       return;
22435    /* If the call is not in UP state or redirected outside Asterisk, no need to check timers */
22436 
22437    if (dialog->owner->_state != AST_STATE_UP || dialog->redirip.sin_addr.s_addr)
22438       return;
22439 
22440    /* If the call is involved in a T38 fax session do not check RTP timeout */
22441    if (dialog->t38.state == T38_ENABLED)
22442       return;
22443 
22444    /* If we have no timers set, return now */
22445    if ((ast_rtp_get_rtpkeepalive(dialog->rtp) == 0) && (ast_rtp_get_rtptimeout(dialog->rtp) == 0) && (ast_rtp_get_rtpholdtimeout(dialog->rtp) == 0))
22446       return;
22447 
22448    /* Check AUDIO RTP keepalives */
22449    if (dialog->lastrtptx && ast_rtp_get_rtpkeepalive(dialog->rtp) &&
22450           (t > dialog->lastrtptx + ast_rtp_get_rtpkeepalive(dialog->rtp))) {
22451       /* Need to send an empty RTP packet */
22452       dialog->lastrtptx = time(NULL);
22453       ast_rtp_sendcng(dialog->rtp, 0);
22454    }
22455 
22456    /*! \todo Check video RTP keepalives
22457 
22458       Do we need to move the lastrtptx to the RTP structure to have one for audio and one
22459       for video? It really does belong to the RTP structure.
22460    */
22461 
22462    /* Check AUDIO RTP timers */
22463    if (dialog->lastrtprx && (ast_rtp_get_rtptimeout(dialog->rtp) || ast_rtp_get_rtpholdtimeout(dialog->rtp)) &&
22464           (t > dialog->lastrtprx + ast_rtp_get_rtptimeout(dialog->rtp))) {
22465 
22466       /* Might be a timeout now -- see if we're on hold */
22467       struct sockaddr_in sin;
22468       ast_rtp_get_peer(dialog->rtp, &sin);
22469       if (!ast_test_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD) || (ast_rtp_get_rtpholdtimeout(dialog->rtp) &&
22470            (t > dialog->lastrtprx + ast_rtp_get_rtpholdtimeout(dialog->rtp)))) {
22471          /* Needs a hangup */
22472          if (ast_rtp_get_rtptimeout(dialog->rtp)) {
22473             while (dialog->owner && ast_channel_trylock(dialog->owner)) {
22474                sip_pvt_unlock(dialog);
22475                usleep(1);
22476                sip_pvt_lock(dialog);
22477             }
22478             ast_log(LOG_NOTICE, "Disconnecting call '%s' for lack of RTP activity in %ld seconds\n",
22479                dialog->owner->name, (long) (t - dialog->lastrtprx));
22480             /* Issue a softhangup */
22481             ast_softhangup_nolock(dialog->owner, AST_SOFTHANGUP_DEV);
22482             ast_channel_unlock(dialog->owner);
22483             /* forget the timeouts for this call, since a hangup
22484                has already been requested and we don't want to
22485                repeatedly request hangups
22486             */
22487             ast_rtp_set_rtptimeout(dialog->rtp, 0);
22488             ast_rtp_set_rtpholdtimeout(dialog->rtp, 0);
22489             if (dialog->vrtp) {
22490                ast_rtp_set_rtptimeout(dialog->vrtp, 0);
22491                ast_rtp_set_rtpholdtimeout(dialog->vrtp, 0);
22492             }
22493          }
22494       }
22495    }
22496 }
22497 
22498 /*! \brief The SIP monitoring thread 
22499 \note This thread monitors all the SIP sessions and peers that needs notification of mwi
22500    (and thus do not have a separate thread) indefinitely 
22501 */
22502 static void *do_monitor(void *data)
22503 {
22504    int res;
22505    time_t t;
22506    int reloading;
22507 
22508    /* Add an I/O event to our SIP UDP socket */
22509    if (sipsock > -1) 
22510       sipsock_read_id = ast_io_add(io, sipsock, sipsock_read, AST_IO_IN, NULL);
22511 
22512    /* From here on out, we die whenever asked */
22513    for(;;) {
22514       /* Check for a reload request */
22515       ast_mutex_lock(&sip_reload_lock);
22516       reloading = sip_reloading;
22517       sip_reloading = FALSE;
22518       ast_mutex_unlock(&sip_reload_lock);
22519       if (reloading) {
22520          ast_verb(1, "Reloading SIP\n");
22521          sip_do_reload(sip_reloadreason);
22522 
22523          /* Change the I/O fd of our UDP socket */
22524          if (sipsock > -1) {
22525             if (sipsock_read_id)
22526                sipsock_read_id = ast_io_change(io, sipsock_read_id, sipsock, NULL, 0, NULL);
22527             else
22528                sipsock_read_id = ast_io_add(io, sipsock, sipsock_read, AST_IO_IN, NULL);
22529          } else if (sipsock_read_id) {
22530             ast_io_remove(io, sipsock_read_id);
22531             sipsock_read_id = NULL;
22532          }
22533       }
22534 
22535       /* Check for dialogs needing to be killed */
22536       t = time(NULL);
22537       /* don't scan the dialogs list if it hasn't been a reasonable period
22538          of time since the last time we did it (when MWI is being sent, we can
22539          get back to this point every millisecond or less)
22540       */
22541       ao2_t_callback(dialogs, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, dialog_needdestroy, &t,
22542             "callback to remove dialogs w/needdestroy");
22543 
22544       /* the old methodology would be to restart the search for dialogs to delete with every 
22545          dialog that was found and destroyed, probably because the list contents would change,
22546          so we'd need to restart. This isn't the best thing to do with callbacks. */
22547 
22548       /* XXX TODO The scheduler usage in this module does not have sufficient 
22549        * synchronization being done between running the scheduler and places 
22550        * scheduling tasks.  As it is written, any scheduled item may not run 
22551        * any sooner than about  1 second, regardless of whether a sooner time 
22552        * was asked for. */
22553 
22554       pthread_testcancel();
22555       /* Wait for sched or io */
22556       res = ast_sched_wait(sched);
22557       if ((res < 0) || (res > 1000))
22558          res = 1000;
22559       res = ast_io_wait(io, res);
22560       if (res > 20)
22561          ast_debug(1, "chan_sip: ast_io_wait ran %d all at once\n", res);
22562       ast_mutex_lock(&monlock);
22563       res = ast_sched_runq(sched);
22564       if (res >= 20)
22565          ast_debug(1, "chan_sip: ast_sched_runq ran %d all at once\n", res);
22566       ast_mutex_unlock(&monlock);
22567    }
22568 
22569    /* Never reached */
22570    return NULL;
22571 }
22572 
22573 /*! \brief Start the channel monitor thread */
22574 static int restart_monitor(void)
22575 {
22576    /* If we're supposed to be stopped -- stay stopped */
22577    if (monitor_thread == AST_PTHREADT_STOP)
22578       return 0;
22579    ast_mutex_lock(&monlock);
22580    if (monitor_thread == pthread_self()) {
22581       ast_mutex_unlock(&monlock);
22582       ast_log(LOG_WARNING, "Cannot kill myself\n");
22583       return -1;
22584    }
22585    if (monitor_thread != AST_PTHREADT_NULL) {
22586       /* Wake up the thread */
22587       pthread_kill(monitor_thread, SIGURG);
22588    } else {
22589       /* Start a new monitor */
22590       if (ast_pthread_create_background(&monitor_thread, NULL, do_monitor, NULL) < 0) {
22591          ast_mutex_unlock(&monlock);
22592          ast_log(LOG_ERROR, "Unable to start monitor thread.\n");
22593          return -1;
22594       }
22595    }
22596    ast_mutex_unlock(&monlock);
22597    return 0;
22598 }
22599 
22600 
22601 /*! \brief Session-Timers: Restart session timer */
22602 static void restart_session_timer(struct sip_pvt *p)
22603 {
22604    if (!p->stimer) {
22605       ast_log(LOG_WARNING, "Null stimer in restart_session_timer - %s\n", p->callid);
22606       return;
22607    }
22608 
22609    if (p->stimer->st_active == TRUE) {
22610       AST_SCHED_DEL_UNREF(sched, p->stimer->st_schedid,
22611             dialog_unref(p, "Removing session timer ref"));
22612       ast_debug(2, "Session timer stopped: %d - %s\n", p->stimer->st_schedid, p->callid);
22613       start_session_timer(p);
22614    }
22615 }
22616 
22617 
22618 /*! \brief Session-Timers: Stop session timer */
22619 static void stop_session_timer(struct sip_pvt *p)
22620 {
22621    if (!p->stimer) {
22622       ast_log(LOG_WARNING, "Null stimer in stop_session_timer - %s\n", p->callid);
22623       return;
22624    }
22625 
22626    if (p->stimer->st_active == TRUE) {
22627       p->stimer->st_active = FALSE;
22628       AST_SCHED_DEL_UNREF(sched, p->stimer->st_schedid,
22629             dialog_unref(p, "removing session timer ref"));
22630       ast_debug(2, "Session timer stopped: %d - %s\n", p->stimer->st_schedid, p->callid);
22631    }
22632 }
22633 
22634 
22635 /*! \brief Session-Timers: Start session timer */
22636 static void start_session_timer(struct sip_pvt *p)
22637 {
22638    if (!p->stimer) {
22639       ast_log(LOG_WARNING, "Null stimer in start_session_timer - %s\n", p->callid);
22640       return;
22641    }
22642 
22643    p->stimer->st_schedid  = ast_sched_add(sched, p->stimer->st_interval * 1000 / 2, proc_session_timer, 
22644          dialog_ref(p, "adding session timer ref"));
22645    if (p->stimer->st_schedid < 0) {
22646       dialog_unref(p, "removing session timer ref");
22647       ast_log(LOG_ERROR, "ast_sched_add failed.\n");
22648    }
22649    ast_debug(2, "Session timer started: %d - %s\n", p->stimer->st_schedid, p->callid);
22650 }
22651 
22652 
22653 /*! \brief Session-Timers: Process session refresh timeout event */
22654 static int proc_session_timer(const void *vp)
22655 {
22656    struct sip_pvt *p = (struct sip_pvt *) vp;
22657    int sendreinv = FALSE;
22658    int res = 0;
22659 
22660    if (!p->stimer) {
22661       ast_log(LOG_WARNING, "Null stimer in proc_session_timer - %s\n", p->callid);
22662       goto return_unref;
22663    }
22664 
22665    ast_debug(2, "Session timer expired: %d - %s\n", p->stimer->st_schedid, p->callid);
22666 
22667    if (!p->owner) {
22668       goto return_unref;
22669    }
22670 
22671    if ((p->stimer->st_active != TRUE) || (p->owner->_state != AST_STATE_UP)) {
22672       goto return_unref;
22673    }
22674 
22675    switch (p->stimer->st_ref) {
22676    case SESSION_TIMER_REFRESHER_UAC:
22677       if (p->outgoing_call == TRUE) {
22678          sendreinv = TRUE;
22679       }
22680       break;
22681    case SESSION_TIMER_REFRESHER_UAS:
22682       if (p->outgoing_call != TRUE) {
22683          sendreinv = TRUE;
22684       }
22685       break;
22686    default:
22687       ast_log(LOG_ERROR, "Unknown session refresher %d\n", p->stimer->st_ref);
22688       goto return_unref;
22689    }
22690 
22691    if (sendreinv == TRUE) {
22692       res = 1;
22693       transmit_reinvite_with_sdp(p, FALSE, TRUE);
22694    } else {
22695       p->stimer->st_expirys++;
22696       if (p->stimer->st_expirys >= 2) {
22697          if (p->stimer->quit_flag) {
22698             goto return_unref;
22699          }
22700          ast_log(LOG_WARNING, "Session-Timer expired - %s\n", p->callid);
22701          sip_pvt_lock(p);
22702          while (p->owner && ast_channel_trylock(p->owner)) {
22703             sip_pvt_unlock(p);
22704             usleep(1);
22705             if (p->stimer && p->stimer->quit_flag) {
22706                goto return_unref;
22707             }
22708             sip_pvt_lock(p);
22709          }
22710 
22711          ast_softhangup_nolock(p->owner, AST_SOFTHANGUP_DEV);
22712          ast_channel_unlock(p->owner);
22713          sip_pvt_unlock(p);
22714       }
22715    }
22716 
22717 return_unref:
22718    if (!res) {
22719       /* An error occurred.  Stop session timer processing */
22720       if (p->stimer) {
22721          p->stimer->st_schedid = -1;
22722          stop_session_timer(p);
22723       }
22724 
22725       /* If we are not asking to be rescheduled, then we need to release our
22726        * reference to the dialog. */
22727       dialog_unref(p, "removing session timer ref");
22728    }
22729 
22730    return res;
22731 }
22732 
22733 
22734 /*! \brief Session-Timers: Function for parsing Min-SE header */
22735 int parse_minse (const char *p_hdrval, int *const p_interval)
22736 {
22737    if (ast_strlen_zero(p_hdrval)) {
22738       ast_log(LOG_WARNING, "Null Min-SE header\n");
22739       return -1;
22740    }
22741 
22742    *p_interval = 0;
22743    p_hdrval = ast_skip_blanks(p_hdrval);
22744    if (!sscanf(p_hdrval, "%30d", p_interval)) {
22745       ast_log(LOG_WARNING, "Parsing of Min-SE header failed %s\n", p_hdrval);
22746       return -1;
22747    }
22748 
22749    ast_debug(2, "Received Min-SE: %d\n", *p_interval);
22750    return 0;
22751 }
22752 
22753 
22754 /*! \brief Session-Timers: Function for parsing Session-Expires header */
22755 int parse_session_expires(const char *p_hdrval, int *const p_interval, enum st_refresher *const p_ref)
22756 {
22757    char *p_token;
22758    int  ref_idx;
22759    char *p_se_hdr;
22760 
22761    if (ast_strlen_zero(p_hdrval)) {
22762       ast_log(LOG_WARNING, "Null Session-Expires header\n");
22763       return -1;
22764    }
22765 
22766    *p_ref = SESSION_TIMER_REFRESHER_AUTO;
22767    *p_interval = 0;
22768 
22769    p_se_hdr = ast_strdupa(p_hdrval);
22770    p_se_hdr = ast_skip_blanks(p_se_hdr);
22771 
22772    while ((p_token = strsep(&p_se_hdr, ";"))) {
22773       p_token = ast_skip_blanks(p_token);
22774       if (!sscanf(p_token, "%30d", p_interval)) {
22775          ast_log(LOG_WARNING, "Parsing of Session-Expires failed\n");
22776          return -1;
22777       }
22778 
22779       ast_debug(2, "Session-Expires: %d\n", *p_interval);
22780 
22781       if (!p_se_hdr)
22782          continue;
22783 
22784       p_se_hdr = ast_skip_blanks(p_se_hdr);
22785       ref_idx = strlen("refresher=");
22786       if (!strncasecmp(p_se_hdr, "refresher=", ref_idx)) {
22787          p_se_hdr += ref_idx;
22788          p_se_hdr = ast_skip_blanks(p_se_hdr);
22789 
22790          if (!strncasecmp(p_se_hdr, "uac", strlen("uac"))) {
22791             *p_ref = SESSION_TIMER_REFRESHER_UAC;
22792             ast_debug(2, "Refresher: UAC\n");
22793          } else if (!strncasecmp(p_se_hdr, "uas", strlen("uas"))) {
22794             *p_ref = SESSION_TIMER_REFRESHER_UAS;
22795             ast_debug(2, "Refresher: UAS\n");
22796          } else {
22797             ast_log(LOG_WARNING, "Invalid refresher value %s\n", p_se_hdr);
22798             return -1;
22799          }
22800          break;
22801       }
22802    }
22803    return 0;
22804 }
22805 
22806 
22807 /*! \brief Handle 422 response to INVITE with session-timer requested
22808 
22809    Session-Timers:   An INVITE originated by Asterisk that asks for session-timers support
22810    from the UAS can result into a 422 response. This is how a UAS or an intermediary proxy 
22811    server tells Asterisk that the session refresh interval offered by Asterisk is too low 
22812    for them.  The proc_422_rsp() function handles a 422 response.  It extracts the Min-SE 
22813    header that comes back in 422 and sends a new INVITE accordingly. */
22814 static void proc_422_rsp(struct sip_pvt *p, struct sip_request *rsp)
22815 {
22816    int rtn;
22817    const char *p_hdrval;
22818    int minse;
22819 
22820    p_hdrval = get_header(rsp, "Min-SE");
22821    if (ast_strlen_zero(p_hdrval)) {
22822       ast_log(LOG_WARNING, "422 response without a Min-SE header %s\n", p_hdrval);
22823       return;
22824    }
22825    rtn = parse_minse(p_hdrval, &minse);
22826    if (rtn != 0) {
22827       ast_log(LOG_WARNING, "Parsing of Min-SE header failed %s\n", p_hdrval);
22828       return;
22829    }
22830    p->stimer->st_interval = minse;
22831    transmit_invite(p, SIP_INVITE, 1, 2); 
22832 }
22833 
22834 
22835 /*! \brief Get Max or Min SE (session timer expiry)
22836  * \param p pointer to the SIP dialog 
22837  * \param max if true, get max se, otherwise min se
22838 */
22839 int st_get_se(struct sip_pvt *p, int max)
22840 {
22841    if (max == TRUE) {
22842       if (p->stimer->st_cached_max_se) {
22843          return p->stimer->st_cached_max_se;
22844       } else if (p->peername) {
22845          struct sip_peer *pp = find_peer(p->peername, NULL, TRUE, FINDPEERS, FALSE, 0);
22846          if (pp) {
22847             p->stimer->st_cached_max_se = pp->stimer.st_max_se;
22848             unref_peer(pp, "unref peer pointer from find_peer call in st_get_se");
22849             return (p->stimer->st_cached_max_se);
22850          }
22851       }
22852       p->stimer->st_cached_max_se = global_max_se;
22853       return (p->stimer->st_cached_max_se);
22854    } else {
22855       if (p->stimer->st_cached_min_se) {
22856          return p->stimer->st_cached_min_se;
22857       } else if (p->peername) {
22858          struct sip_peer *pp = find_peer(p->peername, NULL, TRUE, FINDPEERS, FALSE, 0);
22859          if (pp) {
22860             p->stimer->st_cached_min_se = pp->stimer.st_min_se;
22861             unref_peer(pp, "unref peer pointer from find_peer call in st_get_se (2)");
22862             return (p->stimer->st_cached_min_se);
22863          }
22864       }
22865       p->stimer->st_cached_min_se = global_min_se;
22866       return (p->stimer->st_cached_min_se);
22867    }
22868 }
22869 
22870 
22871 /*! \brief Get the entity (UAC or UAS) that's acting as the session-timer refresher 
22872  * \param p pointer to the SIP dialog 
22873 */
22874 enum st_refresher st_get_refresher(struct sip_pvt *p)
22875 {
22876    if (p->stimer->st_cached_ref != SESSION_TIMER_REFRESHER_AUTO) 
22877       return p->stimer->st_cached_ref;
22878 
22879    if (p->peername) {
22880       struct sip_peer *pp = find_peer(p->peername, NULL, TRUE, FINDPEERS, FALSE, 0);
22881       if (pp) {
22882          p->stimer->st_cached_ref = pp->stimer.st_ref;
22883          unref_peer(pp, "unref peer pointer from find_peer call in st_get_refresher");
22884          return pp->stimer.st_ref;
22885       }
22886    }
22887    
22888    p->stimer->st_cached_ref = global_st_refresher;
22889    return global_st_refresher;
22890 }
22891 
22892 
22893 /*! \brief Get the session-timer mode 
22894  * \param p pointer to the SIP dialog 
22895 */
22896 enum st_mode st_get_mode(struct sip_pvt *p)
22897 {
22898    if (!p->stimer) 
22899       sip_st_alloc(p);
22900 
22901    if (p->stimer->st_cached_mode != SESSION_TIMER_MODE_INVALID) 
22902       return p->stimer->st_cached_mode;
22903 
22904    if (p->peername) {
22905       struct sip_peer *pp = find_peer(p->peername, NULL, TRUE, FINDPEERS, FALSE, 0);
22906       if (pp) {
22907          p->stimer->st_cached_mode = pp->stimer.st_mode_oper;
22908          unref_peer(pp, "unref peer pointer from find_peer call in st_get_mode");
22909          return pp->stimer.st_mode_oper;
22910       }
22911    }
22912 
22913    p->stimer->st_cached_mode = global_st_mode;
22914    return global_st_mode;
22915 }
22916 
22917 
22918 /*! \brief React to lack of answer to Qualify poke */
22919 static int sip_poke_noanswer(const void *data)
22920 {
22921    struct sip_peer *peer = (struct sip_peer *)data;
22922    
22923    peer->pokeexpire = -1;
22924 
22925    if (peer->lastms > -1) {
22926       ast_log(LOG_NOTICE, "Peer '%s' is now UNREACHABLE!  Last qualify: %d\n", peer->name, peer->lastms);
22927       if (sip_cfg.peer_rtupdate) {
22928          ast_update_realtime(ast_check_realtime("sipregs") ? "sipregs" : "sippeers", "name", peer->name, "lastms", "-1", SENTINEL);
22929       }
22930       manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: Unreachable\r\nTime: %d\r\n", peer->name, -1);
22931       if (sip_cfg.regextenonqualify) {
22932          register_peer_exten(peer, FALSE);
22933       }
22934    }
22935 
22936    if (peer->call) {
22937       dialog_unlink_all(peer->call, TRUE, TRUE);
22938       peer->call = dialog_unref(peer->call, "unref dialog peer->call");
22939       /* peer->call = sip_destroy(peer->call);*/
22940    }
22941    
22942    peer->lastms = -1;
22943    ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", peer->name);
22944 
22945    /* Try again quickly */
22946    AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched, 
22947          DEFAULT_FREQ_NOTOK, sip_poke_peer_s, peer,
22948          unref_peer(_data, "removing poke peer ref"),
22949          unref_peer(peer, "removing poke peer ref"),
22950          ref_peer(peer, "adding poke peer ref"));
22951 
22952    /* Release the ref held by the running scheduler entry */
22953    unref_peer(peer, "release peer poke noanswer ref");
22954 
22955    return 0;
22956 }
22957 
22958 /*! \brief Check availability of peer, also keep NAT open
22959 \note This is done with 60 seconds between each ping,
22960    unless forced by cli or manager. If peer is unreachable,
22961    we check every 10th second by default. 
22962 */
22963 static int sip_poke_peer(struct sip_peer *peer, int force)
22964 {
22965    struct sip_pvt *p;
22966    int xmitres = 0;
22967    
22968    if ((!peer->maxms && !force) || !peer->addr.sin_addr.s_addr) {
22969       /* IF we have no IP, or this isn't to be monitored, return
22970         immediately after clearing things out */
22971       AST_SCHED_DEL_UNREF(sched, peer->pokeexpire,
22972             unref_peer(peer, "removing poke peer ref"));
22973       
22974       peer->lastms = 0;
22975       if (peer->call) {
22976          peer->call = dialog_unref(peer->call, "unref dialog peer->call");
22977       }
22978       return 0;
22979    }
22980    if (peer->call) {
22981       if (sipdebug) {
22982          ast_log(LOG_NOTICE, "Still have a QUALIFY dialog active, deleting\n");
22983       }
22984       dialog_unlink_all(peer->call, TRUE, TRUE);
22985       peer->call = dialog_unref(peer->call, "unref dialog peer->call");
22986       /* peer->call = sip_destroy(peer->call); */
22987    }
22988    if (!(p = sip_alloc(NULL, NULL, 0, SIP_OPTIONS, NULL))) {
22989       return -1;
22990    }
22991    peer->call = dialog_ref(p, "copy sip alloc from p to peer->call");
22992    
22993    p->sa = peer->addr;
22994    p->recv = peer->addr;
22995    copy_socket_data(&p->socket, &peer->socket);
22996    ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
22997    ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
22998 
22999    /* Send OPTIONs to peer's fullcontact */
23000    if (!ast_strlen_zero(peer->fullcontact))
23001       ast_string_field_set(p, fullcontact, peer->fullcontact);
23002 
23003    if (!ast_strlen_zero(peer->tohost))
23004       ast_string_field_set(p, tohost, peer->tohost);
23005    else
23006       ast_string_field_set(p, tohost, ast_inet_ntoa(peer->addr.sin_addr));
23007 
23008    /* Recalculate our side, and recalculate Call ID */
23009    ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
23010    build_via(p);
23011    ao2_t_unlink(dialogs, p, "About to change the callid -- remove the old name");
23012    build_callid_pvt(p);
23013    ao2_t_link(dialogs, p, "Linking in under new name");
23014 
23015    AST_SCHED_DEL_UNREF(sched, peer->pokeexpire,
23016          unref_peer(peer, "removing poke peer ref"));
23017    
23018    if (p->relatedpeer)
23019       p->relatedpeer = unref_peer(p->relatedpeer,"unsetting the relatedpeer field in the dialog, before it is set to something else.");
23020    p->relatedpeer = ref_peer(peer, "setting the relatedpeer field in the dialog");
23021    ast_set_flag(&p->flags[0], SIP_OUTGOING);
23022 #ifdef VOCAL_DATA_HACK
23023    ast_copy_string(p->username, "__VOCAL_DATA_SHOULD_READ_THE_SIP_SPEC__", sizeof(p->username));
23024    xmitres = transmit_invite(p, SIP_INVITE, 0, 2); /* sinks the p refcount */
23025 #else
23026    xmitres = transmit_invite(p, SIP_OPTIONS, 0, 2); /* sinks the p refcount */
23027 #endif
23028    peer->ps = ast_tvnow();
23029    if (xmitres == XMIT_ERROR) {
23030       sip_poke_noanswer(peer);   /* Immediately unreachable, network problems */
23031    } else if (!force) {
23032       AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched, peer->maxms * 2, sip_poke_noanswer, peer,
23033             unref_peer(_data, "removing poke peer ref"),
23034             unref_peer(peer, "removing poke peer ref"),
23035             ref_peer(peer, "adding poke peer ref"));
23036    }
23037    dialog_unref(p, "unref dialog at end of sip_poke_peer, obtained from sip_alloc, just before it goes out of scope");
23038    return 0;
23039 }
23040 
23041 /*! \brief Part of PBX channel interface
23042 \note
23043 \par  Return values:---
23044 
23045    If we have qualify on and the device is not reachable, regardless of registration
23046    state we return AST_DEVICE_UNAVAILABLE
23047 
23048    For peers with call limit:
23049       - not registered        AST_DEVICE_UNAVAILABLE
23050       - registered, no call         AST_DEVICE_NOT_INUSE
23051       - registered, active calls    AST_DEVICE_INUSE
23052       - registered, call limit reached AST_DEVICE_BUSY
23053       - registered, onhold       AST_DEVICE_ONHOLD
23054       - registered, ringing         AST_DEVICE_RINGING
23055 
23056    For peers without call limit:
23057       - not registered        AST_DEVICE_UNAVAILABLE
23058       - registered            AST_DEVICE_NOT_INUSE
23059       - fixed IP (!dynamic)         AST_DEVICE_NOT_INUSE
23060    
23061    Peers that does not have a known call and can't be reached by OPTIONS
23062       - unreachable           AST_DEVICE_UNAVAILABLE
23063 
23064    If we return AST_DEVICE_UNKNOWN, the device state engine will try to find
23065    out a state by walking the channel list.
23066 
23067    The queue system (\ref app_queue.c) treats a member as "active"
23068    if devicestate is != AST_DEVICE_UNAVAILBALE && != AST_DEVICE_INVALID
23069 
23070    When placing a call to the queue member, queue system sets a member to busy if
23071    != AST_DEVICE_NOT_INUSE and != AST_DEVICE_UNKNOWN
23072 
23073 */
23074 static int sip_devicestate(void *data)
23075 {
23076    char *host;
23077    char *tmp;
23078    struct sip_peer *p;
23079 
23080    int res = AST_DEVICE_INVALID;
23081 
23082    /* make sure data is not null. Maybe unnecessary, but better be safe */
23083    host = ast_strdupa(data ? data : "");
23084    if ((tmp = strchr(host, '@')))
23085       host = tmp + 1;
23086 
23087    ast_debug(3, "Checking device state for peer %s\n", host);
23088 
23089    /* If find_peer asks for a realtime peer, then this breaks rtautoclear.  This
23090     * is because when a peer tries to autoexpire, the last thing it does is to
23091     * queue up an event telling the system that the devicestate has changed
23092     * (presumably to unavailable).  If we ask for a realtime peer here, this would
23093     * load it BACK into memory, thus defeating the point of trying to clear dead
23094     * hosts out of memory.
23095     */
23096    if ((p = find_peer(host, NULL, FALSE, FINDALLDEVICES, TRUE, 0))) {
23097       if (p->addr.sin_addr.s_addr || p->defaddr.sin_addr.s_addr) {
23098          /* we have an address for the peer */
23099       
23100          /* Check status in this order
23101             - Hold
23102             - Ringing
23103             - Busy (enforced only by call limit)
23104             - Inuse (we have a call)
23105             - Unreachable (qualify)
23106             If we don't find any of these state, report AST_DEVICE_NOT_INUSE
23107             for registered devices */
23108 
23109          if (p->onHold)
23110             /* First check for hold or ring states */
23111             res = AST_DEVICE_ONHOLD;
23112          else if (p->inRinging) {
23113             if (p->inRinging == p->inUse)
23114                res = AST_DEVICE_RINGING;
23115             else
23116                res = AST_DEVICE_RINGINUSE;
23117          } else if (p->call_limit && (p->inUse == p->call_limit))
23118             /* check call limit */
23119             res = AST_DEVICE_BUSY;
23120          else if (p->call_limit && p->busy_level && p->inUse >= p->busy_level)
23121             /* We're forcing busy before we've reached the call limit */
23122             res = AST_DEVICE_BUSY;
23123          else if (p->call_limit && p->inUse)
23124             /* Not busy, but we do have a call */
23125             res = AST_DEVICE_INUSE;
23126          else if (p->maxms && ((p->lastms > p->maxms) || (p->lastms < 0))) 
23127             /* We don't have a call. Are we reachable at all? Requires qualify= */
23128             res = AST_DEVICE_UNAVAILABLE;
23129          else  /* Default reply if we're registered and have no other data */
23130             res = AST_DEVICE_NOT_INUSE;
23131       } else {
23132          /* there is no address, it's unavailable */
23133          res = AST_DEVICE_UNAVAILABLE;
23134       }
23135       unref_peer(p, "unref_peer, from sip_devicestate, release ref from find_peer");
23136    } else {
23137       res = AST_DEVICE_UNKNOWN;
23138    }
23139 
23140    return res;
23141 }
23142 
23143 /*! \brief PBX interface function -build SIP pvt structure 
23144  * SIP calls initiated by the PBX arrive here. 
23145  *
23146  * \verbatim   
23147  *    SIP Dial string syntax
23148  *    SIP/exten@host!dnid
23149  * or SIP/host/exten!dnid
23150  * or SIP/host!dnid
23151  * \endverbatim
23152 */
23153 static struct ast_channel *sip_request_call(const char *type, int format, void *data, int *cause)
23154 {
23155    struct sip_pvt *p;
23156    struct ast_channel *tmpc = NULL;
23157    char *ext = NULL, *host;
23158    char tmp[256];
23159    char *dest = data;
23160    char *dnid;
23161    char *secret = NULL;
23162    char *md5secret = NULL;
23163    char *authname = NULL;
23164    char *trans = NULL;
23165    enum sip_transport transport = 0;
23166    int oldformat = format;
23167 
23168    /* mask request with some set of allowed formats.
23169     * XXX this needs to be fixed.
23170     * The original code uses AST_FORMAT_AUDIO_MASK, but it is
23171     * unclear what to use here. We have global_capabilities, which is
23172     * configured from sip.conf, and sip_tech.capabilities, which is
23173     * hardwired to all audio formats.
23174     */
23175    format &= AST_FORMAT_AUDIO_MASK;
23176    if (!format) {
23177       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));
23178       *cause = AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;   /* Can't find codec to connect to host */
23179       return NULL;
23180    }
23181    ast_debug(1, "Asked to create a SIP channel with formats: %s\n", ast_getformatname_multiple(tmp, sizeof(tmp), oldformat));
23182 
23183    if (!(p = sip_alloc(NULL, NULL, 0, SIP_INVITE, NULL))) {
23184       ast_log(LOG_ERROR, "Unable to build sip pvt data for '%s' (Out of memory or socket error)\n", dest);
23185       *cause = AST_CAUSE_SWITCH_CONGESTION;
23186       return NULL;
23187    }
23188 
23189    p->outgoing_call = TRUE;
23190 
23191    if (!(p->options = ast_calloc(1, sizeof(*p->options)))) {
23192       dialog_unlink_all(p, TRUE, TRUE);
23193       dialog_unref(p, "unref dialog p from mem fail");
23194       /* sip_destroy(p); */
23195       ast_log(LOG_ERROR, "Unable to build option SIP data structure - Out of memory\n");
23196       *cause = AST_CAUSE_SWITCH_CONGESTION;
23197       return NULL;
23198    }
23199 
23200    /* Save the destination, the SIP dial string */
23201    ast_copy_string(tmp, dest, sizeof(tmp));
23202 
23203 
23204    /* Find DNID and take it away */
23205    dnid = strchr(tmp, '!');
23206    if (dnid != NULL) {
23207       *dnid++ = '\0';
23208       ast_string_field_set(p, todnid, dnid);
23209    }
23210 
23211    /* Find at sign - @ */
23212    host = strchr(tmp, '@');
23213    if (host) {
23214       *host++ = '\0';
23215       ext = tmp;
23216       secret = strchr(ext, ':');
23217    }
23218    if (secret) {
23219       *secret++ = '\0';
23220       md5secret = strchr(secret, ':');
23221    }
23222    if (md5secret) {
23223       *md5secret++ = '\0';
23224       authname = strchr(md5secret, ':');
23225    }
23226    if (authname) {
23227       *authname++ = '\0';
23228       trans = strchr(authname, ':');
23229    }
23230    if (trans) {
23231       *trans++ = '\0';
23232       if (!strcasecmp(trans, "tcp"))
23233          transport = SIP_TRANSPORT_TCP;
23234       else if (!strcasecmp(trans, "tls"))
23235          transport = SIP_TRANSPORT_TLS;
23236       else {
23237          if (strcasecmp(trans, "udp"))
23238             ast_log(LOG_WARNING, "'%s' is not a valid transport option to Dial() for SIP calls, using udp by default.\n", trans);
23239          transport = SIP_TRANSPORT_UDP;
23240       }
23241    } else { /* use default */
23242       transport = SIP_TRANSPORT_UDP;
23243    }
23244 
23245    if (!host) {
23246       ext = strchr(tmp, '/');
23247       if (ext) 
23248          *ext++ = '\0';
23249       host = tmp;
23250    }
23251 
23252    set_socket_transport(&p->socket, transport);
23253 
23254    /* We now have 
23255       host = peer name, DNS host name or DNS domain (for SRV) 
23256       ext = extension (user part of URI)
23257       dnid = destination of the call (applies to the To: header)
23258    */
23259    if (create_addr(p, host, NULL, 1)) {
23260       *cause = AST_CAUSE_UNREGISTERED;
23261       ast_debug(3, "Cant create SIP call - target device not registered\n");
23262       dialog_unlink_all(p, TRUE, TRUE);
23263       dialog_unref(p, "unref dialog p UNREGISTERED");
23264       /* sip_destroy(p); */
23265       return NULL;
23266    }
23267    if (ast_strlen_zero(p->peername) && ext)
23268       ast_string_field_set(p, peername, ext);
23269    /* Recalculate our side, and recalculate Call ID */
23270    ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
23271    build_via(p);
23272    ao2_t_unlink(dialogs, p, "About to change the callid -- remove the old name");
23273    build_callid_pvt(p);
23274    ao2_t_link(dialogs, p, "Linking in under new name");
23275    
23276    /* We have an extension to call, don't use the full contact here */
23277    /* This to enable dialing registered peers with extension dialling,
23278       like SIP/peername/extension   
23279       SIP/peername will still use the full contact 
23280     */
23281    if (ext) {
23282       ast_string_field_set(p, username, ext);
23283       ast_string_field_set(p, fullcontact, NULL);
23284    }
23285    if (secret && !ast_strlen_zero(secret))
23286       ast_string_field_set(p, peersecret, secret);
23287 
23288    if (md5secret && !ast_strlen_zero(md5secret))
23289       ast_string_field_set(p, peermd5secret, md5secret);
23290 
23291    if (authname && !ast_strlen_zero(authname))
23292       ast_string_field_set(p, authname, authname);
23293 #if 0
23294    printf("Setting up to call extension '%s' at '%s'\n", ext ? ext : "<none>", host);
23295 #endif
23296    p->prefcodec = oldformat;           /* Format for this call */
23297    p->jointcapability = oldformat;
23298    sip_pvt_lock(p);
23299    tmpc = sip_new(p, AST_STATE_DOWN, host);  /* Place the call */
23300    if (sip_cfg.callevents)
23301       manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
23302          "Channel: %s\r\nChanneltype: %s\r\nSIPcallid: %s\r\nSIPfullcontact: %s\r\nPeername: %s\r\n",
23303          p->owner? p->owner->name : "", "SIP", p->callid, p->fullcontact, p->peername);
23304    sip_pvt_unlock(p);
23305    if (!tmpc) {
23306       dialog_unlink_all(p, TRUE, TRUE);
23307       /* sip_destroy(p); */
23308    }
23309    dialog_unref(p, "toss pvt ptr at end of sip_request_call");
23310    ast_update_use_count();
23311    restart_monitor();
23312    return tmpc;
23313 }
23314 
23315 /*! \brief Parse insecure= setting in sip.conf and set flags according to setting */
23316 static void set_insecure_flags (struct ast_flags *flags, const char *value, int lineno)
23317 {
23318    if (ast_strlen_zero(value))
23319       return;
23320 
23321    if (!ast_false(value)) {
23322       char buf[64];
23323       char *word, *next;
23324 
23325       ast_copy_string(buf, value, sizeof(buf));
23326       next = buf;
23327       while ((word = strsep(&next, ","))) {
23328          if (!strcasecmp(word, "port"))
23329             ast_set_flag(&flags[0], SIP_INSECURE_PORT);
23330          else if (!strcasecmp(word, "invite"))
23331             ast_set_flag(&flags[0], SIP_INSECURE_INVITE);
23332          else
23333             ast_log(LOG_WARNING, "Unknown insecure mode '%s' on line %d\n", value, lineno);
23334       }
23335    }
23336 }
23337 
23338 /*!
23339   \brief Handle T.38 configuration options common to users and peers
23340   \returns non-zero if any config options were handled, zero otherwise
23341 */
23342 static int handle_t38_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v,
23343                int *maxdatagram)
23344 {
23345    int res = 1;
23346 
23347    if (!strcasecmp(v->name, "t38pt_udptl")) {
23348       char *buf = ast_strdupa(v->value);
23349       char *word, *next = buf;
23350 
23351       ast_set_flag(&mask[1], SIP_PAGE2_T38SUPPORT);
23352 
23353       while ((word = strsep(&next, ","))) {
23354          if (ast_true(word) || !strcasecmp(word, "fec")) {
23355             ast_clear_flag(&flags[1], SIP_PAGE2_T38SUPPORT);
23356             ast_set_flag(&flags[1], SIP_PAGE2_T38SUPPORT_UDPTL_FEC);
23357          } else if (!strcasecmp(word, "redundancy")) {
23358             ast_clear_flag(&flags[1], SIP_PAGE2_T38SUPPORT);
23359             ast_set_flag(&flags[1], SIP_PAGE2_T38SUPPORT_UDPTL_REDUNDANCY);
23360          } else if (!strcasecmp(word, "none")) {
23361             ast_clear_flag(&flags[1], SIP_PAGE2_T38SUPPORT);
23362             ast_set_flag(&flags[1], SIP_PAGE2_T38SUPPORT_UDPTL);
23363          } else if (!strncasecmp(word, "maxdatagram=", 12)) {
23364             if (sscanf(&word[12], "%30u", maxdatagram) != 1) {
23365                ast_log(LOG_WARNING, "Invalid maxdatagram '%s' at line %d of %s\n", v->value, v->lineno, config);
23366                *maxdatagram = global_t38_maxdatagram;
23367             }
23368          }
23369       }
23370    } else if (!strcasecmp(v->name, "t38pt_usertpsource")) {
23371       ast_set_flag(&mask[1], SIP_PAGE2_UDPTL_DESTINATION);
23372       ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_UDPTL_DESTINATION);
23373    } else {
23374       res = 0;
23375    }
23376 
23377    return res;
23378 }
23379 
23380 /*!
23381   \brief Handle flag-type options common to configuration of devices - peers
23382   \param flags array of two struct ast_flags
23383   \param mask array of two struct ast_flags
23384   \param v linked list of config variables to process
23385   \returns non-zero if any config options were handled, zero otherwise
23386 */
23387 static int handle_common_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v)
23388 {
23389    int res = 1;
23390 
23391    if (!strcasecmp(v->name, "trustrpid")) {
23392       ast_set_flag(&mask[0], SIP_TRUSTRPID);
23393       ast_set2_flag(&flags[0], ast_true(v->value), SIP_TRUSTRPID);
23394    } else if (!strcasecmp(v->name, "sendrpid")) {
23395       ast_set_flag(&mask[0], SIP_SENDRPID);
23396       ast_set2_flag(&flags[0], ast_true(v->value), SIP_SENDRPID);
23397    } else if (!strcasecmp(v->name, "g726nonstandard")) {
23398       ast_set_flag(&mask[0], SIP_G726_NONSTANDARD);
23399       ast_set2_flag(&flags[0], ast_true(v->value), SIP_G726_NONSTANDARD);
23400    } else if (!strcasecmp(v->name, "useclientcode")) {
23401       ast_set_flag(&mask[0], SIP_USECLIENTCODE);
23402       ast_set2_flag(&flags[0], ast_true(v->value), SIP_USECLIENTCODE);
23403    } else if (!strcasecmp(v->name, "dtmfmode")) {
23404       ast_set_flag(&mask[0], SIP_DTMF);
23405       ast_clear_flag(&flags[0], SIP_DTMF);
23406       if (!strcasecmp(v->value, "inband"))
23407          ast_set_flag(&flags[0], SIP_DTMF_INBAND);
23408       else if (!strcasecmp(v->value, "rfc2833"))
23409          ast_set_flag(&flags[0], SIP_DTMF_RFC2833);
23410       else if (!strcasecmp(v->value, "info"))
23411          ast_set_flag(&flags[0], SIP_DTMF_INFO);
23412       else if (!strcasecmp(v->value, "shortinfo"))
23413          ast_set_flag(&flags[0], SIP_DTMF_SHORTINFO);
23414       else if (!strcasecmp(v->value, "auto"))
23415          ast_set_flag(&flags[0], SIP_DTMF_AUTO);
23416       else {
23417          ast_log(LOG_WARNING, "Unknown dtmf mode '%s' on line %d, using rfc2833\n", v->value, v->lineno);
23418          ast_set_flag(&flags[0], SIP_DTMF_RFC2833);
23419       }
23420    } else if (!strcasecmp(v->name, "nat")) {
23421       ast_set_flag(&mask[0], SIP_NAT);
23422       ast_clear_flag(&flags[0], SIP_NAT);
23423       if (!strcasecmp(v->value, "never"))
23424          ast_set_flag(&flags[0], SIP_NAT_NEVER);
23425       else if (!strcasecmp(v->value, "route"))
23426          ast_set_flag(&flags[0], SIP_NAT_ROUTE);
23427       else if (ast_true(v->value))
23428          ast_set_flag(&flags[0], SIP_NAT_ALWAYS);
23429       else
23430          ast_set_flag(&flags[0], SIP_NAT_RFC3581);
23431    } else if (!strcasecmp(v->name, "directmedia") || !strcasecmp(v->name, "canreinvite")) {
23432       ast_set_flag(&mask[0], SIP_REINVITE);
23433       ast_clear_flag(&flags[0], SIP_REINVITE);
23434       if (ast_true(v->value)) {
23435          ast_set_flag(&flags[0], SIP_DIRECT_MEDIA | SIP_DIRECT_MEDIA_NAT);
23436       } else if (!ast_false(v->value)) {
23437          char buf[64];
23438          char *word, *next = buf;
23439 
23440          ast_copy_string(buf, v->value, sizeof(buf));
23441          while ((word = strsep(&next, ","))) {
23442             if (!strcasecmp(word, "update")) {
23443                ast_set_flag(&flags[0], SIP_REINVITE_UPDATE | SIP_DIRECT_MEDIA);
23444             } else if (!strcasecmp(word, "nonat")) {
23445                ast_set_flag(&flags[0], SIP_DIRECT_MEDIA);
23446                ast_clear_flag(&flags[0], SIP_DIRECT_MEDIA_NAT);
23447             } else {
23448                ast_log(LOG_WARNING, "Unknown directmedia mode '%s' on line %d\n", v->value, v->lineno);
23449             }
23450          }
23451       }
23452    } else if (!strcasecmp(v->name, "insecure")) {
23453       ast_set_flag(&mask[0], SIP_INSECURE);
23454       ast_clear_flag(&flags[0], SIP_INSECURE);
23455       set_insecure_flags(&flags[0], v->value, v->lineno);   
23456    } else if (!strcasecmp(v->name, "progressinband")) {
23457       ast_set_flag(&mask[0], SIP_PROG_INBAND);
23458       ast_clear_flag(&flags[0], SIP_PROG_INBAND);
23459       if (ast_true(v->value))
23460          ast_set_flag(&flags[0], SIP_PROG_INBAND_YES);
23461       else if (strcasecmp(v->value, "never"))
23462          ast_set_flag(&flags[0], SIP_PROG_INBAND_NO);
23463    } else if (!strcasecmp(v->name, "promiscredir")) {
23464       ast_set_flag(&mask[0], SIP_PROMISCREDIR);
23465       ast_set2_flag(&flags[0], ast_true(v->value), SIP_PROMISCREDIR);
23466    } else if (!strcasecmp(v->name, "videosupport")) {
23467       if (!strcasecmp(v->value, "always")) {
23468          ast_set_flag(&mask[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS);
23469          ast_set_flag(&flags[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS);
23470       } else {
23471          ast_set_flag(&mask[1], SIP_PAGE2_VIDEOSUPPORT);
23472          ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_VIDEOSUPPORT);
23473       }
23474    } else if (!strcasecmp(v->name, "textsupport")) {
23475       ast_set_flag(&mask[1], SIP_PAGE2_TEXTSUPPORT);
23476       ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_TEXTSUPPORT);
23477       res = 1;
23478    } else if (!strcasecmp(v->name, "allowoverlap")) {
23479       ast_set_flag(&mask[1], SIP_PAGE2_ALLOWOVERLAP);
23480       ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_ALLOWOVERLAP);
23481    } else if (!strcasecmp(v->name, "allowsubscribe")) {
23482       ast_set_flag(&mask[1], SIP_PAGE2_ALLOWSUBSCRIBE);
23483       ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_ALLOWSUBSCRIBE);
23484    } else if (!strcasecmp(v->name, "ignoresdpversion")) {
23485       ast_set_flag(&mask[1], SIP_PAGE2_IGNORESDPVERSION);
23486       ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_IGNORESDPVERSION);
23487    } else if (!strcasecmp(v->name, "faxdetect")) {
23488       ast_set_flag(&mask[1], SIP_PAGE2_FAX_DETECT);
23489       if (ast_true(v->value)) {
23490          ast_set_flag(&flags[1], SIP_PAGE2_FAX_DETECT_BOTH);
23491       } else if (ast_false(v->value)) {
23492          ast_clear_flag(&flags[1], SIP_PAGE2_FAX_DETECT_BOTH);
23493       } else {
23494          char *buf = ast_strdupa(v->value);
23495          char *word, *next = buf;
23496 
23497          while ((word = strsep(&next, ","))) {
23498             if (!strcasecmp(word, "cng")) {
23499                ast_set_flag(&flags[1], SIP_PAGE2_FAX_DETECT_CNG);
23500             } else if (!strcasecmp(word, "t38")) {
23501                ast_set_flag(&flags[1], SIP_PAGE2_FAX_DETECT_T38);
23502             } else {
23503                ast_log(LOG_WARNING, "Unknown faxdetect mode '%s' on line %d.\n", word, v->lineno);
23504             }
23505          }
23506       }
23507    } else if (!strcasecmp(v->name, "rfc2833compensate")) {
23508       ast_set_flag(&mask[1], SIP_PAGE2_RFC2833_COMPENSATE);
23509       ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_RFC2833_COMPENSATE);
23510    } else if (!strcasecmp(v->name, "buggymwi")) {
23511       ast_set_flag(&mask[1], SIP_PAGE2_BUGGY_MWI);
23512       ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_BUGGY_MWI);
23513    } else
23514       res = 0;
23515 
23516    return res;
23517 }
23518 
23519 /*! \brief Add SIP domain to list of domains we are responsible for */
23520 static int add_sip_domain(const char *domain, const enum domain_mode mode, const char *context)
23521 {
23522    struct domain *d;
23523 
23524    if (ast_strlen_zero(domain)) {
23525       ast_log(LOG_WARNING, "Zero length domain.\n");
23526       return 1;
23527    }
23528 
23529    if (!(d = ast_calloc(1, sizeof(*d))))
23530       return 0;
23531 
23532    ast_copy_string(d->domain, domain, sizeof(d->domain));
23533 
23534    if (!ast_strlen_zero(context))
23535       ast_copy_string(d->context, context, sizeof(d->context));
23536 
23537    d->mode = mode;
23538 
23539    AST_LIST_LOCK(&domain_list);
23540    AST_LIST_INSERT_TAIL(&domain_list, d, list);
23541    AST_LIST_UNLOCK(&domain_list);
23542 
23543    if (sipdebug)  
23544       ast_debug(1, "Added local SIP domain '%s'\n", domain);
23545 
23546    return 1;
23547 }
23548 
23549 /*! \brief  check_sip_domain: Check if domain part of uri is local to our server */
23550 static int check_sip_domain(const char *domain, char *context, size_t len)
23551 {
23552    struct domain *d;
23553    int result = 0;
23554 
23555    AST_LIST_LOCK(&domain_list);
23556    AST_LIST_TRAVERSE(&domain_list, d, list) {
23557       if (strcasecmp(d->domain, domain))
23558          continue;
23559 
23560       if (len && !ast_strlen_zero(d->context))
23561          ast_copy_string(context, d->context, len);
23562       
23563       result = 1;
23564       break;
23565    }
23566    AST_LIST_UNLOCK(&domain_list);
23567 
23568    return result;
23569 }
23570 
23571 /*! \brief Clear our domain list (at reload) */
23572 static void clear_sip_domains(void)
23573 {
23574    struct domain *d;
23575 
23576    AST_LIST_LOCK(&domain_list);
23577    while ((d = AST_LIST_REMOVE_HEAD(&domain_list, list)))
23578       ast_free(d);
23579    AST_LIST_UNLOCK(&domain_list);
23580 }
23581 
23582 
23583 /*! \brief Add realm authentication in list */
23584 static struct sip_auth *add_realm_authentication(struct sip_auth *authlist, const char *configuration, int lineno)
23585 {
23586    char authcopy[256];
23587    char *username=NULL, *realm=NULL, *secret=NULL, *md5secret=NULL;
23588    struct sip_auth *a, *b, *auth;
23589 
23590    if (ast_strlen_zero(configuration))
23591       return authlist;
23592 
23593    ast_debug(1, "Auth config ::  %s\n", configuration);
23594 
23595    ast_copy_string(authcopy, configuration, sizeof(authcopy));
23596    username = authcopy;
23597 
23598    /* split user[:secret] and relm */
23599    realm = strrchr(username, '@');
23600    if (realm)
23601       *realm++ = '\0';
23602    if (ast_strlen_zero(username) || ast_strlen_zero(realm)) {
23603       ast_log(LOG_WARNING, "Format for authentication entry is user[:secret]@realm at line %d\n", lineno);
23604       return authlist;
23605    }
23606 
23607    /* parse username at ':' for secret, or '#" for md5secret */
23608    if ((secret = strchr(username, ':'))) {
23609       *secret++ = '\0';
23610    } else if ((md5secret = strchr(username, '#'))) {
23611       *md5secret++ = '\0';
23612    }
23613 
23614    if (!(auth = ast_calloc(1, sizeof(*auth))))
23615       return authlist;
23616 
23617    ast_copy_string(auth->realm, realm, sizeof(auth->realm));
23618    ast_copy_string(auth->username, username, sizeof(auth->username));
23619    if (secret)
23620       ast_copy_string(auth->secret, secret, sizeof(auth->secret));
23621    if (md5secret)
23622       ast_copy_string(auth->md5secret, md5secret, sizeof(auth->md5secret));
23623 
23624    /* find the end of the list */
23625    for (b = NULL, a = authlist; a ; b = a, a = a->next)
23626       ;
23627    if (b)
23628       b->next = auth;   /* Add structure add end of list */
23629    else
23630       authlist = auth;
23631 
23632    ast_verb(3, "Added authentication for realm %s\n", realm);
23633 
23634    return authlist;
23635 
23636 }
23637 
23638 /*! \brief Clear realm authentication list (at reload) */
23639 static int clear_realm_authentication(struct sip_auth *authlist)
23640 {
23641    struct sip_auth *a = authlist;
23642    struct sip_auth *b;
23643 
23644    while (a) {
23645       b = a;
23646       a = a->next;
23647       ast_free(b);
23648    }
23649 
23650    return 1;
23651 }
23652 
23653 /*! \brief Find authentication for a specific realm */
23654 static struct sip_auth *find_realm_authentication(struct sip_auth *authlist, const char *realm)
23655 {
23656    struct sip_auth *a;
23657 
23658    for (a = authlist; a; a = a->next) {
23659       if (!strcasecmp(a->realm, realm))
23660          break;
23661    }
23662 
23663    return a;
23664 }
23665 
23666 /*! \brief
23667  * implement the setvar config line
23668  */
23669 static struct ast_variable *add_var(const char *buf, struct ast_variable *list)
23670 {
23671    struct ast_variable *tmpvar = NULL;
23672    char *varname = ast_strdupa(buf), *varval = NULL;
23673    
23674    if ((varval = strchr(varname, '='))) {
23675       *varval++ = '\0';
23676       if ((tmpvar = ast_variable_new(varname, varval, ""))) {
23677          tmpvar->next = list;
23678          list = tmpvar;
23679       }
23680    }
23681    return list;
23682 }
23683 
23684 /*! \brief Set peer defaults before configuring specific configurations */
23685 static void set_peer_defaults(struct sip_peer *peer)
23686 {
23687    if (peer->expire == 0) {
23688       /* Don't reset expire or port time during reload 
23689          if we have an active registration 
23690       */
23691       peer->expire = -1;
23692       peer->pokeexpire = -1;
23693       peer->addr.sin_port = htons(STANDARD_SIP_PORT);
23694       set_socket_transport(&peer->socket, SIP_TRANSPORT_UDP);
23695    }
23696    peer->type = SIP_TYPE_PEER;
23697    ast_copy_flags(&peer->flags[0], &global_flags[0], SIP_FLAGS_TO_COPY);
23698    ast_copy_flags(&peer->flags[1], &global_flags[1], SIP_PAGE2_FLAGS_TO_COPY);
23699    ast_string_field_set(peer, context, sip_cfg.default_context);
23700    ast_string_field_set(peer, subscribecontext, sip_cfg.default_subscribecontext);
23701    ast_string_field_set(peer, language, default_language);
23702    ast_string_field_set(peer, mohinterpret, default_mohinterpret);
23703    ast_string_field_set(peer, mohsuggest, default_mohsuggest);
23704    peer->addr.sin_family = AF_INET;
23705    peer->defaddr.sin_family = AF_INET;
23706    peer->capability = global_capability;
23707    peer->maxcallbitrate = default_maxcallbitrate;
23708    peer->rtptimeout = global_rtptimeout;
23709    peer->rtpholdtimeout = global_rtpholdtimeout;
23710    peer->rtpkeepalive = global_rtpkeepalive;
23711    peer->allowtransfer = sip_cfg.allowtransfer;
23712    peer->autoframing = global_autoframing;
23713    peer->t38_maxdatagram = global_t38_maxdatagram;
23714    peer->qualifyfreq = global_qualifyfreq;
23715    if (global_callcounter)
23716       peer->call_limit=INT_MAX;
23717    ast_string_field_set(peer, vmexten, default_vmexten);
23718    ast_string_field_set(peer, secret, "");
23719    ast_string_field_set(peer, remotesecret, "");
23720    ast_string_field_set(peer, md5secret, "");
23721    ast_string_field_set(peer, cid_num, "");
23722    ast_string_field_set(peer, cid_name, "");
23723    ast_string_field_set(peer, fromdomain, "");
23724    ast_string_field_set(peer, fromuser, "");
23725    ast_string_field_set(peer, regexten, "");
23726    peer->callgroup = 0;
23727    peer->pickupgroup = 0;
23728    peer->maxms = default_qualify;
23729    peer->prefs = default_prefs;
23730    peer->stimer.st_mode_oper = global_st_mode;  /* Session-Timers */
23731    peer->stimer.st_ref = global_st_refresher;
23732    peer->stimer.st_min_se = global_min_se;
23733    peer->stimer.st_max_se = global_max_se;
23734    peer->timer_t1 = global_t1;
23735    peer->timer_b = global_timer_b;
23736    clear_peer_mailboxes(peer);
23737 }
23738 
23739 /*! \brief Create temporary peer (used in autocreatepeer mode) */
23740 static struct sip_peer *temp_peer(const char *name)
23741 {
23742    struct sip_peer *peer;
23743 
23744    if (!(peer = ao2_t_alloc(sizeof(*peer), sip_destroy_peer_fn, "allocate a peer struct")))
23745       return NULL;
23746 
23747    if (ast_string_field_init(peer, 512)) {
23748       ao2_t_ref(peer, -1, "failed to string_field_init, drop peer");
23749       return NULL;
23750    }
23751 
23752    ast_atomic_fetchadd_int(&apeerobjs, 1);
23753    set_peer_defaults(peer);
23754 
23755    ast_copy_string(peer->name, name, sizeof(peer->name));
23756 
23757    peer->selfdestruct = TRUE;
23758    peer->host_dynamic = TRUE;
23759    peer->prefs = default_prefs;
23760    reg_source_db(peer);
23761 
23762    return peer;
23763 }
23764 
23765 /*! \todo document this function */
23766 static void add_peer_mailboxes(struct sip_peer *peer, const char *value)
23767 {
23768    char *next, *mbox, *context;
23769 
23770    next = ast_strdupa(value);
23771 
23772    while ((mbox = context = strsep(&next, ","))) {
23773       struct sip_mailbox *mailbox;
23774 
23775       if (!(mailbox = ast_calloc(1, sizeof(*mailbox))))
23776          continue;
23777 
23778       strsep(&context, "@");
23779       if (ast_strlen_zero(mbox)) {
23780          ast_free(mailbox);
23781          continue;
23782       }
23783       mailbox->mailbox = ast_strdup(mbox);
23784       mailbox->context = ast_strdup(context);
23785 
23786       AST_LIST_INSERT_TAIL(&peer->mailboxes, mailbox, entry);
23787    }
23788 }
23789 
23790 /*! \brief Build peer from configuration (file or realtime static/dynamic) */
23791 static struct sip_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime, int devstate_only)
23792 {
23793    struct sip_peer *peer = NULL;
23794    struct ast_ha *oldha = NULL;
23795    int found = 0;
23796    int firstpass = 1;
23797    uint16_t port = 0;
23798    int format = 0;      /* Ama flags */
23799    time_t regseconds = 0;
23800    struct ast_flags peerflags[2] = {{(0)}};
23801    struct ast_flags mask[2] = {{(0)}};
23802    char callback[256] = "";
23803    struct sip_peer tmp_peer;
23804    const char *srvlookup = NULL;
23805    static int deprecation_warning = 1;
23806    int alt_fullcontact = alt ? 1 : 0;
23807    struct ast_str *fullcontact = ast_str_alloca(512);
23808 
23809    if (!realtime || ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
23810       /* Note we do NOT use find_peer here, to avoid realtime recursion */
23811       /* We also use a case-sensitive comparison (unlike find_peer) so
23812          that case changes made to the peer name will be properly handled
23813          during reload
23814       */
23815       ast_copy_string(tmp_peer.name, name, sizeof(tmp_peer.name));
23816       peer = ao2_t_find(peers, &tmp_peer, OBJ_POINTER | OBJ_UNLINK, "find and unlink peer from peers table");
23817    }
23818 
23819    if (peer) {
23820       /* Already in the list, remove it and it will be added back (or FREE'd)  */
23821       found++;
23822       if (!(peer->the_mark))
23823          firstpass = 0;
23824    } else {
23825       if (!(peer = ao2_t_alloc(sizeof(*peer), sip_destroy_peer_fn, "allocate a peer struct")))
23826          return NULL;
23827 
23828       if (ast_string_field_init(peer, 512)) {
23829          ao2_t_ref(peer, -1, "failed to string_field_init, drop peer");
23830          return NULL;
23831       }
23832 
23833       if (realtime && !ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
23834          ast_atomic_fetchadd_int(&rpeerobjs, 1);
23835          ast_debug(3, "-REALTIME- peer built. Name: %s. Peer objects: %d\n", name, rpeerobjs);
23836       } else
23837          ast_atomic_fetchadd_int(&speerobjs, 1);
23838    }
23839 
23840    /* Note that our peer HAS had its reference count increased */
23841    if (firstpass) {
23842       peer->lastmsgssent = -1;
23843       oldha = peer->ha;
23844       peer->ha = NULL;
23845       set_peer_defaults(peer);   /* Set peer defaults */
23846       peer->type = 0;
23847    }
23848    if (!found && name)
23849       ast_copy_string(peer->name, name, sizeof(peer->name));
23850 
23851    /* If we have channel variables, remove them (reload) */
23852    if (peer->chanvars) {
23853       ast_variables_destroy(peer->chanvars);
23854       peer->chanvars = NULL;
23855       /* XXX should unregister ? */
23856    }
23857 
23858    if (found)
23859       peer->portinuri = 0;
23860 
23861    /* If we have realm authentication information, remove them (reload) */
23862    clear_realm_authentication(peer->auth);
23863    peer->auth = NULL;
23864    peer->default_outbound_transport = 0;
23865    peer->transports = 0;
23866 
23867    for (; v || ((v = alt) && !(alt=NULL)); v = v->next) {
23868       if (!devstate_only) {
23869          if (handle_common_options(&peerflags[0], &mask[0], v)) {
23870             continue;
23871          }
23872          if (handle_t38_options(&peerflags[0], &mask[0], v, &peer->t38_maxdatagram)) {
23873             continue;
23874          }
23875          if (!strcasecmp(v->name, "transport") && !ast_strlen_zero(v->value)) {
23876             char *val = ast_strdupa(v->value);
23877             char *trans;
23878 
23879             while ((trans = strsep(&val, ","))) {
23880                trans = ast_skip_blanks(trans);
23881 
23882                if (!strncasecmp(trans, "udp", 3)) {
23883                   peer->transports |= SIP_TRANSPORT_UDP;
23884                } else if (!strncasecmp(trans, "tcp", 3)) {
23885                   peer->transports |= SIP_TRANSPORT_TCP;
23886                } else if (!strncasecmp(trans, "tls", 3)) {
23887                   peer->transports |= SIP_TRANSPORT_TLS;
23888                } else {
23889                   ast_log(LOG_NOTICE, "'%s' is not a valid transport type. if no other is specified, udp will be used.\n", trans);
23890                }
23891 
23892                if (!peer->default_outbound_transport) { /*!< The first transport listed should be default outbound */
23893                   peer->default_outbound_transport = peer->transports;
23894                }
23895             }
23896          } else if (realtime && !strcasecmp(v->name, "regseconds")) {
23897             ast_get_time_t(v->value, &regseconds, 0, NULL);
23898          } else if (realtime && !strcasecmp(v->name, "name")) {
23899             ast_copy_string(peer->name, v->value, sizeof(peer->name));
23900          } else if (!strcasecmp(v->name, "type")) {
23901             if (!strcasecmp(v->value, "peer")) {
23902                peer->type |= SIP_TYPE_PEER;
23903             } else if (!strcasecmp(v->value, "user")) {
23904                peer->type |= SIP_TYPE_USER;
23905             } else if (!strcasecmp(v->value, "friend")) {
23906                peer->type = SIP_TYPE_USER | SIP_TYPE_PEER;
23907             }
23908          } else if (!strcasecmp(v->name, "remotesecret")) {
23909             ast_string_field_set(peer, remotesecret, v->value);
23910          } else if (!strcasecmp(v->name, "secret")) {
23911             ast_string_field_set(peer, secret, v->value);
23912          } else if (!strcasecmp(v->name, "md5secret")) {
23913             ast_string_field_set(peer, md5secret, v->value);
23914          } else if (!strcasecmp(v->name, "auth")) {
23915             peer->auth = add_realm_authentication(peer->auth, v->value, v->lineno);
23916          } else if (!strcasecmp(v->name, "callerid")) {
23917             char cid_name[80] = { '\0' }, cid_num[80] = { '\0' };
23918 
23919             ast_callerid_split(v->value, cid_name, sizeof(cid_name), cid_num, sizeof(cid_num));
23920             ast_string_field_set(peer, cid_name, cid_name);
23921             ast_string_field_set(peer, cid_num, cid_num);
23922          } else if (!strcasecmp(v->name, "fullname")) {
23923             ast_string_field_set(peer, cid_name, v->value);
23924          } else if (!strcasecmp(v->name, "trunkname")) {
23925             /* This is actually for a trunk, so we don't want to override callerid */
23926             ast_string_field_set(peer, cid_name, "");
23927          } else if (!strcasecmp(v->name, "cid_number")) {
23928             ast_string_field_set(peer, cid_num, v->value);
23929          } else if (!strcasecmp(v->name, "context")) {
23930             ast_string_field_set(peer, context, v->value);
23931             ast_set_flag(&peer->flags[1], SIP_PAGE2_HAVEPEERCONTEXT);
23932          } else if (!strcasecmp(v->name, "subscribecontext")) {
23933             ast_string_field_set(peer, subscribecontext, v->value);
23934          } else if (!strcasecmp(v->name, "fromdomain")) {
23935             ast_string_field_set(peer, fromdomain, v->value);
23936          } else if (!strcasecmp(v->name, "usereqphone")) {
23937             ast_set2_flag(&peer->flags[0], ast_true(v->value), SIP_USEREQPHONE);
23938          } else if (!strcasecmp(v->name, "fromuser")) {
23939             ast_string_field_set(peer, fromuser, v->value);
23940          } else if (!strcasecmp(v->name, "outboundproxy")) {
23941             char *port, *next, *force, *proxyname;
23942             int forceopt = FALSE;
23943             /* Set peer channel variable */
23944             next = proxyname = ast_strdupa(v->value);
23945             if ((port = strchr(proxyname, ':'))) {
23946                *port++ = '\0';
23947                next = port;
23948             }
23949             if ((force = strchr(next, ','))) {
23950                *force++ = '\0';
23951                forceopt = strcmp(force, "force");
23952             }
23953             /* Allocate proxy object */
23954             peer->outboundproxy = proxy_allocate(proxyname, port, forceopt);
23955          } else if (!strcasecmp(v->name, "host")) {
23956             if (!strcasecmp(v->value, "dynamic")) {
23957                /* They'll register with us */
23958                if (!found || !peer->host_dynamic) {
23959                   /* Initialize stuff if this is a new peer, or if it used to
23960                    * not be dynamic before the reload. */
23961                   memset(&peer->addr.sin_addr, 0, 4);
23962                   peer->addr.sin_port = 0;
23963                }
23964                peer->host_dynamic = TRUE;
23965             } else {
23966                /* Non-dynamic.  Make sure we become that way if we're not */
23967                AST_SCHED_DEL_UNREF(sched, peer->expire,
23968                      unref_peer(peer, "removing register expire ref"));
23969                /* the port will either be set to a default value or a config specified value once all option parsing is complete */
23970                peer->addr.sin_port = 0;
23971                peer->host_dynamic = FALSE;
23972                srvlookup = v->value;
23973                if (global_dynamic_exclude_static) {
23974                   int err = 0;
23975                   global_contact_ha = ast_append_ha("deny", (char *)ast_inet_ntoa(peer->addr.sin_addr), global_contact_ha, &err);
23976                   if (err) {
23977                      ast_log(LOG_ERROR, "Bad ACL entry in configuration line %d : %s\n", v->lineno, v->value);
23978                   }
23979                }
23980             }
23981          } else if (!strcasecmp(v->name, "defaultip")) {
23982             if (!ast_strlen_zero(v->value) && ast_get_ip(&peer->defaddr, v->value)) {
23983                unref_peer(peer, "unref_peer: from build_peer defaultip");
23984                return NULL;
23985             }
23986          } else if (!strcasecmp(v->name, "permit") || !strcasecmp(v->name, "deny")) {
23987             int ha_error = 0;
23988             if (!ast_strlen_zero(v->value)) {
23989                peer->ha = ast_append_ha(v->name, v->value, peer->ha, &ha_error);
23990             }
23991             if (ha_error) {
23992                ast_log(LOG_ERROR, "Bad ACL entry in configuration line %d : %s\n", v->lineno, v->value);
23993             }
23994          } else if (!strcasecmp(v->name, "contactpermit") || !strcasecmp(v->name, "contactdeny")) {
23995             int ha_error = 0;
23996             if (!ast_strlen_zero(v->value)) {
23997                peer->contactha = ast_append_ha(v->name + 7, v->value, peer->contactha, &ha_error);
23998             }
23999             if (ha_error) {
24000                ast_log(LOG_ERROR, "Bad ACL entry in configuration line %d : %s\n", v->lineno, v->value);
24001             }
24002          } else if (!strcasecmp(v->name, "port")) {
24003             peer->portinuri = 1;
24004             if (!(port = port_str2int(v->value, 0))) {
24005                if (realtime) {
24006                   /* If stored as integer, could be 0 for some DBs (notably MySQL) */
24007                   peer->portinuri = 0;
24008                } else {
24009                   ast_log(LOG_WARNING, "Invalid peer port configuration at line %d : %s\n", v->lineno, v->value);
24010                }
24011             }
24012          } else if (!strcasecmp(v->name, "callingpres")) {
24013             peer->callingpres = ast_parse_caller_presentation(v->value);
24014             if (peer->callingpres == -1) {
24015                peer->callingpres = atoi(v->value);
24016             }
24017          } else if (!strcasecmp(v->name, "username") || !strcmp(v->name, "defaultuser")) {   /* "username" is deprecated */
24018             ast_string_field_set(peer, username, v->value);
24019             if (!strcasecmp(v->name, "username")) {
24020                if (deprecation_warning) {
24021                   ast_log(LOG_NOTICE, "The 'username' field for sip peers has been deprecated in favor of the term 'defaultuser'\n");
24022                   deprecation_warning = 0;
24023                }
24024                peer->deprecated_username = 1;
24025             }
24026          } else if (!strcasecmp(v->name, "language")) {
24027             ast_string_field_set(peer, language, v->value);
24028          } else if (!strcasecmp(v->name, "regexten")) {
24029             ast_string_field_set(peer, regexten, v->value);
24030          } else if (!strcasecmp(v->name, "callbackextension")) {
24031             ast_copy_string(callback, v->value, sizeof(callback));
24032          } else if (!strcasecmp(v->name, "amaflags")) {
24033             format = ast_cdr_amaflags2int(v->value);
24034             if (format < 0) {
24035                ast_log(LOG_WARNING, "Invalid AMA Flags for peer: %s at line %d\n", v->value, v->lineno);
24036             } else {
24037                peer->amaflags = format;
24038             }
24039          } else if (!strcasecmp(v->name, "accountcode")) {
24040             ast_string_field_set(peer, accountcode, v->value);
24041          } else if (!strcasecmp(v->name, "mohinterpret")) {
24042             ast_string_field_set(peer, mohinterpret, v->value);
24043          } else if (!strcasecmp(v->name, "mohsuggest")) {
24044             ast_string_field_set(peer, mohsuggest, v->value);
24045          } else if (!strcasecmp(v->name, "parkinglot")) {
24046             ast_string_field_set(peer, parkinglot, v->value);
24047          } else if (!strcasecmp(v->name, "mailbox")) {
24048             add_peer_mailboxes(peer, v->value);
24049          } else if (!strcasecmp(v->name, "hasvoicemail")) {
24050             /* People expect that if 'hasvoicemail' is set, that the mailbox will
24051              * be also set, even if not explicitly specified. */
24052             if (ast_true(v->value) && AST_LIST_EMPTY(&peer->mailboxes)) {
24053                add_peer_mailboxes(peer, name);
24054             }
24055          } else if (!strcasecmp(v->name, "subscribemwi")) {
24056             ast_set2_flag(&peer->flags[1], ast_true(v->value), SIP_PAGE2_SUBSCRIBEMWIONLY);
24057          } else if (!strcasecmp(v->name, "vmexten")) {
24058             ast_string_field_set(peer, vmexten, v->value);
24059          } else if (!strcasecmp(v->name, "callgroup")) {
24060             peer->callgroup = ast_get_group(v->value);
24061          } else if (!strcasecmp(v->name, "allowtransfer")) {
24062             peer->allowtransfer = ast_true(v->value) ? TRANSFER_OPENFORALL : TRANSFER_CLOSED;
24063          } else if (!strcasecmp(v->name, "pickupgroup")) {
24064             peer->pickupgroup = ast_get_group(v->value);
24065          } else if (!strcasecmp(v->name, "allow")) {
24066             int error =  ast_parse_allow_disallow(&peer->prefs, &peer->capability, v->value, TRUE);
24067             if (error) {
24068                ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
24069             }
24070          } else if (!strcasecmp(v->name, "disallow")) {
24071             int error =  ast_parse_allow_disallow(&peer->prefs, &peer->capability, v->value, FALSE);
24072             if (error) {
24073                ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
24074             }
24075          } else if (!strcasecmp(v->name, "registertrying")) {
24076             ast_set2_flag(&peer->flags[1], ast_true(v->value), SIP_PAGE2_REGISTERTRYING);
24077          } else if (!strcasecmp(v->name, "autoframing")) {
24078             peer->autoframing = ast_true(v->value);
24079          } else if (!strcasecmp(v->name, "rtptimeout")) {
24080             if ((sscanf(v->value, "%30d", &peer->rtptimeout) != 1) || (peer->rtptimeout < 0)) {
24081                ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d.  Using default.\n", v->value, v->lineno);
24082                peer->rtptimeout = global_rtptimeout;
24083             }
24084          } else if (!strcasecmp(v->name, "rtpholdtimeout")) {
24085             if ((sscanf(v->value, "%30d", &peer->rtpholdtimeout) != 1) || (peer->rtpholdtimeout < 0)) {
24086                ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d.  Using default.\n", v->value, v->lineno);
24087                peer->rtpholdtimeout = global_rtpholdtimeout;
24088             }
24089          } else if (!strcasecmp(v->name, "rtpkeepalive")) {
24090             if ((sscanf(v->value, "%30d", &peer->rtpkeepalive) != 1) || (peer->rtpkeepalive < 0)) {
24091                ast_log(LOG_WARNING, "'%s' is not a valid RTP keepalive time at line %d.  Using default.\n", v->value, v->lineno);
24092                peer->rtpkeepalive = global_rtpkeepalive;
24093             }
24094          } else if (!strcasecmp(v->name, "timert1")) {
24095             if ((sscanf(v->value, "%30d", &peer->timer_t1) != 1) || (peer->timer_t1 < 0)) {
24096                ast_log(LOG_WARNING, "'%s' is not a valid T1 time at line %d.  Using default.\n", v->value, v->lineno);
24097                peer->timer_t1 = global_t1;
24098             }
24099             /* Note that Timer B is dependent upon T1 and MUST NOT be lower
24100              * than T1 * 64, according to RFC 3261, Section 17.1.1.2 */
24101             if (peer->timer_b < peer->timer_t1 * 64) {
24102                peer->timer_b = peer->timer_t1 * 64;
24103             }
24104          } else if (!strcasecmp(v->name, "timerb")) {
24105             if ((sscanf(v->value, "%30d", &peer->timer_b) != 1) || (peer->timer_b < 0)) {
24106                ast_log(LOG_WARNING, "'%s' is not a valid Timer B time at line %d.  Using default.\n", v->value, v->lineno);
24107                peer->timer_b = global_timer_b;
24108             }
24109             if (peer->timer_b < peer->timer_t1 * 64) {
24110                static int warning = 0;
24111                if (warning++ % 20 == 0) {
24112                   ast_log(LOG_WARNING, "Timer B has been set lower than recommended. (RFC 3261, 17.1.1.2)\n");
24113                }
24114             }
24115          } else if (!strcasecmp(v->name, "setvar")) {
24116             peer->chanvars = add_var(v->value, peer->chanvars);
24117          } else if (!strcasecmp(v->name, "qualifyfreq")) {
24118             int i;
24119             if (sscanf(v->value, "%30d", &i) == 1) {
24120                peer->qualifyfreq = i * 1000;
24121             } else {
24122                ast_log(LOG_WARNING, "Invalid qualifyfreq number '%s' at line %d of %s\n", v->value, v->lineno, config);
24123                peer->qualifyfreq = global_qualifyfreq;
24124             }
24125          } else if (!strcasecmp(v->name, "maxcallbitrate")) {
24126             peer->maxcallbitrate = atoi(v->value);
24127             if (peer->maxcallbitrate < 0) {
24128                peer->maxcallbitrate = default_maxcallbitrate;
24129             }
24130          } else if (!strcasecmp(v->name, "session-timers")) {
24131             int i = (int) str2stmode(v->value);
24132             if (i < 0) {
24133                ast_log(LOG_WARNING, "Invalid session-timers '%s' at line %d of %s\n", v->value, v->lineno, config);
24134                peer->stimer.st_mode_oper = global_st_mode;
24135             } else {
24136                peer->stimer.st_mode_oper = i;
24137             }
24138          } else if (!strcasecmp(v->name, "session-expires")) {
24139             if (sscanf(v->value, "%30d", &peer->stimer.st_max_se) != 1) {
24140                ast_log(LOG_WARNING, "Invalid session-expires '%s' at line %d of %s\n", v->value, v->lineno, config);
24141                peer->stimer.st_max_se = global_max_se;
24142             }
24143          } else if (!strcasecmp(v->name, "session-minse")) {
24144             if (sscanf(v->value, "%30d", &peer->stimer.st_min_se) != 1) {
24145                ast_log(LOG_WARNING, "Invalid session-minse '%s' at line %d of %s\n", v->value, v->lineno, config);
24146                peer->stimer.st_min_se = global_min_se;
24147             }
24148             if (peer->stimer.st_min_se < 90) {
24149                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);
24150                peer->stimer.st_min_se = global_min_se;
24151             }
24152          } else if (!strcasecmp(v->name, "session-refresher")) {
24153             int i = (int) str2strefresher(v->value);
24154             if (i < 0) {
24155                ast_log(LOG_WARNING, "Invalid session-refresher '%s' at line %d of %s\n", v->value, v->lineno, config);
24156                peer->stimer.st_ref = global_st_refresher;
24157             } else {
24158                peer->stimer.st_ref = i;
24159             }
24160          }
24161       }
24162 
24163       /* These apply to devstate lookups */
24164       if (realtime && !strcasecmp(v->name, "lastms")) {
24165          sscanf(v->value, "%30d", &peer->lastms);
24166       } else if (realtime && !strcasecmp(v->name, "ipaddr") && !ast_strlen_zero(v->value) ) {
24167          inet_aton(v->value, &(peer->addr.sin_addr));
24168       } else if (realtime && !strcasecmp(v->name, "fullcontact")) {
24169          if (alt_fullcontact && !alt) {
24170             /* Reset, because the alternate also has a fullcontact and we
24171              * do NOT want the field value to be doubled. It might be
24172              * tempting to skip this, but the first table might not have
24173              * fullcontact and since we're here, we know that the alternate
24174              * absolutely does. */
24175             alt_fullcontact = 0;
24176             ast_str_reset(fullcontact);
24177          }
24178          /* Reconstruct field, because realtime separates our value at the ';' */
24179          if (fullcontact->used > 0) {
24180             ast_str_append(&fullcontact, 0, ";%s", v->value);
24181          } else {
24182             ast_str_set(&fullcontact, 0, "%s", v->value);
24183          }
24184       } else if (!strcasecmp(v->name, "qualify")) {
24185          if (!strcasecmp(v->value, "no")) {
24186             peer->maxms = 0;
24187          } else if (!strcasecmp(v->value, "yes")) {
24188             peer->maxms = default_qualify ? default_qualify : DEFAULT_MAXMS;
24189          } else if (sscanf(v->value, "%30d", &peer->maxms) != 1) {
24190             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);
24191             peer->maxms = 0;
24192          }
24193          if (realtime && !ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) && peer->maxms > 0) {
24194             /* This would otherwise cause a network storm, where the
24195              * qualify response refreshes the peer from the database,
24196              * which in turn causes another qualify to be sent, ad
24197              * infinitum. */
24198             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);
24199             peer->maxms = 0;
24200          }
24201       } else if (!strcasecmp(v->name, "callcounter")) {
24202          peer->call_limit = ast_true(v->value) ? INT_MAX : 0;
24203       } else if (!strcasecmp(v->name, "call-limit")) {
24204          peer->call_limit = atoi(v->value);
24205          if (peer->call_limit < 0) {
24206             peer->call_limit = 0;
24207          }
24208       } else if (!strcasecmp(v->name, "busylevel")) {
24209          peer->busy_level = atoi(v->value);
24210          if (peer->busy_level < 0) {
24211             peer->busy_level = 0;
24212          }
24213       }
24214    }
24215 
24216    if (!peer->default_outbound_transport) {
24217       /* Set default set of transports */
24218       peer->transports = default_transports;
24219       /* Set default primary transport */
24220       peer->default_outbound_transport = default_primary_transport;
24221    }
24222 
24223    /* The default transport type set during build_peer should only replace the socket.type when...
24224     * 1. Registration is not present and the socket.type and default transport types are different.
24225     * 2. The socket.type is not an acceptable transport type after rebuilding peer.
24226     * 3. The socket.type is not set yet. */
24227    if (((peer->socket.type != peer->default_outbound_transport) && (peer->expire == -1)) ||
24228       !(peer->socket.type & peer->transports) || !(peer->socket.type)) {
24229 
24230       set_socket_transport(&peer->socket, peer->default_outbound_transport);
24231    }
24232 
24233    if (port && !realtime && peer->host_dynamic) {
24234       peer->defaddr.sin_port = htons(port);
24235    } else if (port) {
24236       peer->addr.sin_port = htons(port);
24237    }
24238 
24239    if (ast_str_strlen(fullcontact)) {
24240       ast_string_field_set(peer, fullcontact, ast_str_buffer(fullcontact));
24241       peer->rt_fromcontact = TRUE;
24242       /* We have a hostname in the fullcontact, but if we don't have an
24243        * address listed on the entry (or if it's 'dynamic'), then we need to
24244        * parse the entry to obtain the IP address, so a dynamic host can be
24245        * contacted immediately after reload (as opposed to waiting for it to
24246        * register once again). But if we have an address for this peer and NAT was
24247        * specified, use that address instead. */
24248       /* XXX May need to revisit the final argument; does the realtime DB store whether
24249        * the original contact was over TLS or not? XXX */
24250       if (!ast_test_flag(&peer->flags[0], SIP_NAT_ROUTE) || !peer->addr.sin_addr.s_addr) {
24251          __set_address_from_contact(fullcontact->str, &peer->addr, 0);
24252       }
24253    }
24254 
24255    if (srvlookup && peer->dnsmgr == NULL) {
24256       char transport[MAXHOSTNAMELEN];
24257       char _srvlookup[MAXHOSTNAMELEN];
24258       char *params;
24259 
24260       ast_copy_string(_srvlookup, srvlookup, sizeof(_srvlookup));
24261       if ((params = strchr(_srvlookup, ';'))) {
24262          *params++ = '\0';
24263       }
24264 
24265       snprintf(transport, sizeof(transport), "_sip._%s", get_transport(peer->socket.type));
24266 
24267       if (ast_dnsmgr_lookup(_srvlookup, &peer->addr, &peer->dnsmgr, sip_cfg.srvlookup && !peer->portinuri ? transport : NULL)) {
24268          ast_log(LOG_ERROR, "srvlookup failed for host: %s, on peer %s, removing peer\n", _srvlookup, peer->name);
24269          unref_peer(peer, "getting rid of a peer pointer");
24270          return NULL;
24271       }
24272 
24273       ast_string_field_set(peer, tohost, srvlookup);
24274    }
24275 
24276    if (!peer->addr.sin_port) {
24277       peer->addr.sin_port = htons(((peer->socket.type & SIP_TRANSPORT_TLS) ? STANDARD_TLS_PORT : STANDARD_SIP_PORT));
24278    }
24279    if (!peer->defaddr.sin_port) {
24280       peer->defaddr.sin_port = htons(((peer->socket.type & SIP_TRANSPORT_TLS) ? STANDARD_TLS_PORT : STANDARD_SIP_PORT));
24281    }
24282    if (!peer->socket.port) {
24283       peer->socket.port = htons(((peer->socket.type & SIP_TRANSPORT_TLS) ? STANDARD_TLS_PORT : STANDARD_SIP_PORT));
24284    }
24285 
24286    if (!sip_cfg.ignore_regexpire && peer->host_dynamic && realtime) {
24287       time_t nowtime = time(NULL);
24288 
24289       if ((nowtime - regseconds) > 0) {
24290          destroy_association(peer);
24291          memset(&peer->addr, 0, sizeof(peer->addr));
24292          peer->lastms = -1;
24293          ast_debug(1, "Bah, we're expired (%d/%d/%d)!\n", (int)(nowtime - regseconds), (int)regseconds, (int)nowtime);
24294       }
24295    }
24296 
24297    /* Startup regular pokes */
24298    if (!devstate_only && realtime && peer->lastms > 0) {
24299       ref_peer(peer, "schedule qualify");
24300       sip_poke_peer(peer, 0);
24301    }
24302 
24303    ast_copy_flags(&peer->flags[0], &peerflags[0], mask[0].flags);
24304    ast_copy_flags(&peer->flags[1], &peerflags[1], mask[1].flags);
24305    if (ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)) {
24306       sip_cfg.allowsubscribe = TRUE;   /* No global ban any more */
24307    }
24308    if (!found && peer->host_dynamic && !peer->is_realtime) {
24309       reg_source_db(peer);
24310    }
24311 
24312    /* If they didn't request that MWI is sent *only* on subscribe, go ahead and
24313     * subscribe to it now. */
24314    if (!devstate_only && !ast_test_flag(&peer->flags[1], SIP_PAGE2_SUBSCRIBEMWIONLY) &&
24315       !AST_LIST_EMPTY(&peer->mailboxes)) {
24316       add_peer_mwi_subs(peer);
24317       /* Send MWI from the event cache only.  This is so we can send initial
24318        * MWI if app_voicemail got loaded before chan_sip.  If it is the other
24319        * way, then we will get events when app_voicemail gets loaded. */
24320       sip_send_mwi_to_peer(peer, NULL, 1);
24321    }
24322 
24323    peer->the_mark = 0;
24324 
24325    ast_free_ha(oldha);
24326    if (!ast_strlen_zero(callback)) { /* build string from peer info */
24327       char *reg_string;
24328       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) {
24329          ast_log(LOG_WARNING, "asprintf() failed: %s\n", strerror(errno));
24330       } else if (reg_string) {
24331          sip_register(reg_string, 0); /* XXX TODO: count in registry_count */
24332          ast_free(reg_string);
24333       }
24334    }
24335    return peer;
24336 }
24337 
24338 static int peer_markall_func(void *device, void *arg, int flags)
24339 {
24340    struct sip_peer *peer = device;
24341    peer->the_mark = 1;
24342    return 0;
24343 }
24344 
24345 /*! \brief Re-read SIP.conf config file
24346 \note This function reloads all config data, except for
24347    active peers (with registrations). They will only
24348    change configuration data at restart, not at reload.
24349    SIP debug and recordhistory state will not change
24350  */
24351 static int reload_config(enum channelreloadreason reason)
24352 {
24353    struct ast_config *cfg, *ucfg;
24354    struct ast_variable *v;
24355    struct sip_peer *peer;
24356    char *cat, *stringp, *context, *oldregcontext;
24357    char newcontexts[AST_MAX_CONTEXT], oldcontexts[AST_MAX_CONTEXT];
24358    struct ast_flags dummy[2];
24359    struct ast_flags config_flags = { reason == CHANNEL_MODULE_LOAD ? 0 : ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) ? 0 : CONFIG_FLAG_FILEUNCHANGED };
24360    int auto_sip_domains = FALSE;
24361    struct sockaddr_in old_bindaddr = bindaddr;
24362    int registry_count = 0, peer_count = 0;
24363    time_t run_start, run_end;
24364    
24365    run_start = time(0);
24366    ast_unload_realtime("sipregs");     
24367    ast_unload_realtime("sippeers");
24368    cfg = ast_config_load(config, config_flags);
24369 
24370    /* We *must* have a config file otherwise stop immediately */
24371    if (!cfg) {
24372       ast_log(LOG_NOTICE, "Unable to load config %s\n", config);
24373       return -1;
24374    } else if (cfg == CONFIG_STATUS_FILEUNCHANGED) {
24375       ucfg = ast_config_load("users.conf", config_flags);
24376       if (ucfg == CONFIG_STATUS_FILEUNCHANGED) {
24377          return 1;
24378       } else if (ucfg == CONFIG_STATUS_FILEINVALID) {
24379          ast_log(LOG_ERROR, "Contents of users.conf are invalid and cannot be parsed\n");
24380          return 1;
24381       }
24382       /* Must reread both files, because one changed */
24383       ast_clear_flag(&config_flags, CONFIG_FLAG_FILEUNCHANGED);
24384       if ((cfg = ast_config_load(config, config_flags)) == CONFIG_STATUS_FILEINVALID) {
24385          ast_log(LOG_ERROR, "Contents of %s are invalid and cannot be parsed\n", config);
24386          ast_config_destroy(ucfg);
24387          return 1;
24388       }
24389    } else if (cfg == CONFIG_STATUS_FILEINVALID) {
24390       ast_log(LOG_ERROR, "Contents of %s are invalid and cannot be parsed\n", config);
24391       return 1;
24392    } else {
24393       ast_clear_flag(&config_flags, CONFIG_FLAG_FILEUNCHANGED);
24394       if ((ucfg = ast_config_load("users.conf", config_flags)) == CONFIG_STATUS_FILEINVALID) {
24395          ast_log(LOG_ERROR, "Contents of users.conf are invalid and cannot be parsed\n");
24396          ast_config_destroy(cfg);
24397          return 1;
24398       }
24399    }
24400 
24401    /* Initialize tcp sockets */
24402    memset(&sip_tcp_desc.local_address, 0, sizeof(sip_tcp_desc.local_address));
24403    memset(&sip_tls_desc.local_address, 0, sizeof(sip_tls_desc.local_address));
24404 
24405    ast_free_ha(global_contact_ha);
24406    global_contact_ha = NULL;
24407 
24408    default_tls_cfg.enabled = FALSE;    /* Default: Disable TLS */
24409 
24410    sip_tcp_desc.local_address.sin_port = htons(STANDARD_SIP_PORT);
24411    sip_tls_desc.local_address.sin_port = htons(STANDARD_TLS_PORT);
24412 
24413    if (reason != CHANNEL_MODULE_LOAD) {
24414       ast_debug(4, "--------------- SIP reload started\n");
24415 
24416       clear_realm_authentication(authl);
24417       clear_sip_domains();
24418       authl = NULL;
24419 
24420       /* First, destroy all outstanding registry calls */
24421       /* This is needed, since otherwise active registry entries will not be destroyed */
24422       ASTOBJ_CONTAINER_TRAVERSE(&regl, 1, do {  /* regl is locked */
24423 
24424             ASTOBJ_RDLOCK(iterator); /* now regl is locked, and the object is also locked */
24425             if (iterator->call) {
24426                ast_debug(3, "Destroying active SIP dialog for registry %s@%s\n", iterator->username, iterator->hostname);
24427                /* This will also remove references to the registry */
24428                dialog_unlink_all(iterator->call, TRUE, TRUE);
24429                iterator->call = dialog_unref(iterator->call, "remove iterator->call from registry traversal");
24430             }
24431             if (iterator->expire > -1) {
24432                AST_SCHED_DEL_UNREF(sched, iterator->expire, registry_unref(iterator, "reg ptr unref from reload config"));
24433             }
24434             if (iterator->timeout > -1) {
24435                AST_SCHED_DEL_UNREF(sched, iterator->timeout, registry_unref(iterator, "reg ptr unref from reload config"));
24436             }
24437             ASTOBJ_UNLOCK(iterator);
24438             
24439       } while(0));
24440 
24441       /* Then, actually destroy users and registry */
24442       ASTOBJ_CONTAINER_DESTROYALL(&regl, sip_registry_destroy);
24443       ast_debug(4, "--------------- Done destroying registry list\n");
24444       ao2_t_callback(peers, OBJ_NODATA, peer_markall_func, NULL, "callback to mark all peers");
24445    }
24446    
24447    /* Reset certificate handling for TLS sessions */
24448    if (reason != CHANNEL_MODULE_LOAD) {
24449       ast_free(default_tls_cfg.certfile);
24450       ast_free(default_tls_cfg.cipher);
24451       ast_free(default_tls_cfg.cafile);
24452       ast_free(default_tls_cfg.capath);
24453    }
24454    default_tls_cfg.certfile = ast_strdup(AST_CERTFILE); /*XXX Not sure if this is useful */
24455    default_tls_cfg.cipher = ast_strdup("");
24456    default_tls_cfg.cafile = ast_strdup("");
24457    default_tls_cfg.capath = ast_strdup("");
24458 
24459    
24460    /* Initialize copy of current global_regcontext for later use in removing stale contexts */
24461    ast_copy_string(oldcontexts, global_regcontext, sizeof(oldcontexts));
24462    oldregcontext = oldcontexts;
24463 
24464    /* Clear all flags before setting default values */
24465    /* Preserve debugging settings for console */
24466    sipdebug &= sip_debug_console;
24467    ast_clear_flag(&global_flags[0], AST_FLAGS_ALL);
24468    ast_clear_flag(&global_flags[1], AST_FLAGS_ALL);
24469 
24470    /* Reset IP addresses  */
24471    memset(&bindaddr, 0, sizeof(bindaddr));
24472    memset(&stunaddr, 0, sizeof(stunaddr));
24473    memset(&internip, 0, sizeof(internip));
24474 
24475    /* Free memory for local network address mask */
24476    ast_free_ha(localaddr);
24477    memset(&localaddr, 0, sizeof(localaddr));
24478    memset(&externip, 0, sizeof(externip));
24479    memset(&default_prefs, 0 , sizeof(default_prefs));
24480    memset(&sip_cfg.outboundproxy, 0, sizeof(struct sip_proxy));
24481    sip_cfg.outboundproxy.ip.sin_port = htons(STANDARD_SIP_PORT);
24482    sip_cfg.outboundproxy.ip.sin_family = AF_INET;  /*!< Type of address: IPv4 */
24483    sip_cfg.outboundproxy.force = FALSE;      /*!< Don't force proxy usage, use route: headers */
24484    default_transports = 0;          /*!< Reset default transport to zero here, default value later on */
24485    default_primary_transport = 0;         /*!< Reset default primary transport to zero here, default value later on */
24486    ourport_tcp = STANDARD_SIP_PORT;
24487    ourport_tls = STANDARD_TLS_PORT;
24488    bindaddr.sin_port = htons(STANDARD_SIP_PORT);
24489    sip_cfg.srvlookup = DEFAULT_SRVLOOKUP;
24490    global_tos_sip = DEFAULT_TOS_SIP;
24491    global_tos_audio = DEFAULT_TOS_AUDIO;
24492    global_tos_video = DEFAULT_TOS_VIDEO;
24493    global_tos_text = DEFAULT_TOS_TEXT;
24494    global_cos_sip = DEFAULT_COS_SIP;
24495    global_cos_audio = DEFAULT_COS_AUDIO;
24496    global_cos_video = DEFAULT_COS_VIDEO;
24497    global_cos_text = DEFAULT_COS_TEXT;
24498 
24499    externhost[0] = '\0';         /* External host name (for behind NAT DynDNS support) */
24500    externexpire = 0;       /* Expiration for DNS re-issuing */
24501    externrefresh = 10;
24502 
24503    /* Reset channel settings to default before re-configuring */
24504    sip_cfg.allow_external_domains = DEFAULT_ALLOW_EXT_DOM;           /* Allow external invites */
24505    global_regcontext[0] = '\0';
24506    sip_cfg.regextenonqualify = DEFAULT_REGEXTENONQUALIFY;
24507    sip_cfg.notifyringing = DEFAULT_NOTIFYRINGING;
24508    sip_cfg.notifycid = DEFAULT_NOTIFYCID;
24509    sip_cfg.notifyhold = FALSE;      /*!< Keep track of hold status for a peer */
24510    sip_cfg.directrtpsetup = FALSE;     /* Experimental feature, disabled by default */
24511    sip_cfg.alwaysauthreject = DEFAULT_ALWAYSAUTHREJECT;
24512    sip_cfg.allowsubscribe = FALSE;
24513    snprintf(global_useragent, sizeof(global_useragent), "%s %s", DEFAULT_USERAGENT, ast_get_version());
24514    snprintf(global_sdpsession, sizeof(global_sdpsession), "%s %s", DEFAULT_SDPSESSION, ast_get_version());
24515    snprintf(global_sdpowner, sizeof(global_sdpowner), "%s", DEFAULT_SDPOWNER);
24516    global_prematuremediafilter = TRUE;
24517    ast_copy_string(default_notifymime, DEFAULT_NOTIFYMIME, sizeof(default_notifymime));
24518    ast_copy_string(sip_cfg.realm, S_OR(ast_config_AST_SYSTEM_NAME, DEFAULT_REALM), sizeof(sip_cfg.realm));
24519    ast_copy_string(default_callerid, DEFAULT_CALLERID, sizeof(default_callerid));
24520    sip_cfg.compactheaders = DEFAULT_COMPACTHEADERS;
24521    global_reg_timeout = DEFAULT_REGISTRATION_TIMEOUT;
24522    global_regattempts_max = 0;
24523    sip_cfg.pedanticsipchecking = DEFAULT_PEDANTIC;
24524    sip_cfg.autocreatepeer = DEFAULT_AUTOCREATEPEER;
24525    global_autoframing = 0;
24526    sip_cfg.allowguest = DEFAULT_ALLOWGUEST;
24527    global_callcounter = DEFAULT_CALLCOUNTER;
24528    global_match_auth_username = FALSE;    /*!< Match auth username if available instead of From: Default off. */
24529    global_rtptimeout = 0;
24530    global_rtpholdtimeout = 0;
24531    global_rtpkeepalive = DEFAULT_RTPKEEPALIVE;
24532    sip_cfg.allowtransfer = TRANSFER_OPENFORALL; /* Merrily accept all transfers by default */
24533    sip_cfg.rtautoclear = 120;
24534    ast_set_flag(&global_flags[1], SIP_PAGE2_ALLOWSUBSCRIBE);   /* Default for all devices: TRUE */
24535    ast_set_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP);     /* Default for all devices: TRUE */
24536    sip_cfg.peer_rtupdate = TRUE;
24537    global_dynamic_exclude_static = 0;  /* Exclude static peers */
24538 
24539    /* Session-Timers */
24540    global_st_mode = SESSION_TIMER_MODE_ACCEPT;    
24541    global_st_refresher = SESSION_TIMER_REFRESHER_UAS;
24542    global_min_se  = DEFAULT_MIN_SE;
24543    global_max_se  = DEFAULT_MAX_SE;
24544 
24545    /* Peer poking settings */
24546    global_qualify_gap = DEFAULT_QUALIFY_GAP;
24547    global_qualify_peers = DEFAULT_QUALIFY_PEERS;
24548 
24549    /* Initialize some reasonable defaults at SIP reload (used both for channel and as default for devices */
24550    ast_copy_string(sip_cfg.default_context, DEFAULT_CONTEXT, sizeof(sip_cfg.default_context));
24551    sip_cfg.default_subscribecontext[0] = '\0';
24552    default_language[0] = '\0';
24553    default_fromdomain[0] = '\0';
24554    default_qualify = DEFAULT_QUALIFY;
24555    default_maxcallbitrate = DEFAULT_MAX_CALL_BITRATE;
24556    ast_copy_string(default_mohinterpret, DEFAULT_MOHINTERPRET, sizeof(default_mohinterpret));
24557    ast_copy_string(default_mohsuggest, DEFAULT_MOHSUGGEST, sizeof(default_mohsuggest));
24558    ast_copy_string(default_vmexten, DEFAULT_VMEXTEN, sizeof(default_vmexten));
24559    ast_set_flag(&global_flags[0], SIP_DTMF_RFC2833);        /*!< Default DTMF setting: RFC2833 */
24560    ast_set_flag(&global_flags[0], SIP_NAT_RFC3581);         /*!< NAT support if requested by device with rport */
24561    ast_set_flag(&global_flags[0], SIP_DIRECT_MEDIA);        /*!< Allow re-invites */
24562 
24563    /* Debugging settings, always default to off */
24564    dumphistory = FALSE;
24565    recordhistory = FALSE;
24566    sipdebug &= ~sip_debug_config;
24567 
24568    /* Misc settings for the channel */
24569    global_relaxdtmf = FALSE;
24570    sip_cfg.callevents = DEFAULT_CALLEVENTS;
24571    global_authfailureevents = FALSE;
24572    global_t1 = DEFAULT_TIMER_T1;
24573    global_timer_b = 64 * DEFAULT_TIMER_T1;
24574    global_t1min = DEFAULT_T1MIN;
24575    global_qualifyfreq = DEFAULT_QUALIFYFREQ;
24576    global_t38_maxdatagram = -1;
24577    global_shrinkcallerid = 1;
24578 
24579    sip_cfg.matchexterniplocally = DEFAULT_MATCHEXTERNIPLOCALLY;
24580 
24581    /* Copy the default jb config over global_jbconf */
24582    memcpy(&global_jbconf, &default_jbconf, sizeof(struct ast_jb_conf));
24583 
24584    ast_clear_flag(&global_flags[1], SIP_PAGE2_FAX_DETECT);
24585    ast_clear_flag(&global_flags[1], SIP_PAGE2_VIDEOSUPPORT | SIP_PAGE2_VIDEOSUPPORT_ALWAYS);
24586    ast_clear_flag(&global_flags[1], SIP_PAGE2_TEXTSUPPORT);
24587    ast_clear_flag(&global_flags[1], SIP_PAGE2_IGNORESDPVERSION);
24588 
24589 
24590    /* Read the [general] config section of sip.conf (or from realtime config) */
24591    for (v = ast_variable_browse(cfg, "general"); v; v = v->next) {
24592       if (handle_common_options(&global_flags[0], &dummy[0], v))
24593          continue;
24594       if (handle_t38_options(&global_flags[0], &dummy[0], v, &global_t38_maxdatagram)) {
24595          continue;
24596       }
24597       /* handle jb conf */
24598       if (!ast_jb_read_conf(&global_jbconf, v->name, v->value))
24599          continue;
24600 
24601       if (!strcasecmp(v->name, "context")) {
24602          ast_copy_string(sip_cfg.default_context, v->value, sizeof(sip_cfg.default_context));
24603       } else if (!strcasecmp(v->name, "subscribecontext")) {
24604          ast_copy_string(sip_cfg.default_subscribecontext, v->value, sizeof(sip_cfg.default_subscribecontext));
24605       } else if (!strcasecmp(v->name, "callcounter")) {
24606          global_callcounter = ast_true(v->value) ? 1 : 0;
24607       } else if (!strcasecmp(v->name, "allowguest")) {
24608          sip_cfg.allowguest = ast_true(v->value) ? 1 : 0;
24609       } else if (!strcasecmp(v->name, "realm")) {
24610          ast_copy_string(sip_cfg.realm, v->value, sizeof(sip_cfg.realm));
24611       } else if (!strcasecmp(v->name, "useragent")) {
24612          ast_copy_string(global_useragent, v->value, sizeof(global_useragent));
24613          ast_debug(1, "Setting SIP channel User-Agent Name to %s\n", global_useragent);
24614       } else if (!strcasecmp(v->name, "sdpsession")) {
24615          ast_copy_string(global_sdpsession, v->value, sizeof(global_sdpsession));
24616       } else if (!strcasecmp(v->name, "sdpowner")) {
24617          /* Field cannot contain spaces */
24618          if (!strstr(v->value, " "))
24619             ast_copy_string(global_sdpowner, v->value, sizeof(global_sdpowner));
24620          else
24621             ast_log(LOG_WARNING, "'%s' must not contain spaces at line %d.  Using default.\n", v->value, v->lineno);
24622       } else if (!strcasecmp(v->name, "allowtransfer")) {
24623          sip_cfg.allowtransfer = ast_true(v->value) ? TRANSFER_OPENFORALL : TRANSFER_CLOSED;
24624       } else if (!strcasecmp(v->name, "rtcachefriends")) {
24625          ast_set2_flag(&global_flags[1], ast_true(v->value), SIP_PAGE2_RTCACHEFRIENDS);   
24626       } else if (!strcasecmp(v->name, "rtsavesysname")) {
24627          sip_cfg.rtsave_sysname = ast_true(v->value);
24628       } else if (!strcasecmp(v->name, "rtupdate")) {
24629          sip_cfg.peer_rtupdate = ast_true(v->value);
24630       } else if (!strcasecmp(v->name, "ignoreregexpire")) {
24631          sip_cfg.ignore_regexpire = ast_true(v->value);
24632       } else if (!strcasecmp(v->name, "timert1")) {
24633          /* Defaults to 500ms, but RFC 3261 states that it is recommended
24634           * for the value to be set higher, though a lower value is only
24635           * allowed on private networks unconnected to the Internet. */
24636          global_t1 = atoi(v->value);
24637          /* Note that timer B is dependent on the value of T1 */
24638          global_timer_b = global_t1 * 64;
24639       } else if (!strcasecmp(v->name, "t1min")) {
24640          global_t1min = atoi(v->value);
24641       } else if (!strcasecmp(v->name, "transport") && !ast_strlen_zero(v->value)) {
24642          char *val = ast_strdupa(v->value);
24643          char *trans;
24644 
24645          while ((trans = strsep(&val, ","))) {
24646             trans = ast_skip_blanks(trans);
24647 
24648             if (!strncasecmp(trans, "udp", 3)) 
24649                default_transports |= SIP_TRANSPORT_UDP;
24650             else if (!strncasecmp(trans, "tcp", 3))
24651                default_transports |= SIP_TRANSPORT_TCP;
24652             else if (!strncasecmp(trans, "tls", 3))
24653                default_transports |= SIP_TRANSPORT_TLS;
24654             else
24655                ast_log(LOG_NOTICE, "'%s' is not a valid transport type. if no other is specified, udp will be used.\n", trans);
24656             if (default_primary_transport == 0) {
24657                default_primary_transport = default_transports;
24658             }
24659          }
24660       } else if (!strcasecmp(v->name, "tcpenable")) {
24661          sip_tcp_desc.local_address.sin_family = ast_false(v->value) ? 0 : AF_INET;
24662          ast_debug(2, "Enabling TCP socket for listening\n");
24663       } else if (!strcasecmp(v->name, "tcpbindaddr")) {
24664          int family = sip_tcp_desc.local_address.sin_family;
24665          if (ast_parse_arg(v->value, PARSE_INADDR, &sip_tcp_desc.local_address))
24666             ast_log(LOG_WARNING, "Invalid %s '%s' at line %d of %s\n", v->name, v->value, v->lineno, config);
24667          sip_tcp_desc.local_address.sin_family = family;
24668          ast_debug(2, "Setting TCP socket address to %s\n", v->value);
24669       } else if (!strcasecmp(v->name, "tlsenable")) {
24670          default_tls_cfg.enabled = ast_true(v->value) ? TRUE : FALSE;
24671          sip_tls_desc.local_address.sin_family = AF_INET;
24672       } else if (!strcasecmp(v->name, "tlscertfile")) {
24673          ast_free(default_tls_cfg.certfile);
24674          default_tls_cfg.certfile = ast_strdup(v->value);
24675       } else if (!strcasecmp(v->name, "tlscipher")) {
24676          ast_free(default_tls_cfg.cipher);
24677          default_tls_cfg.cipher = ast_strdup(v->value);
24678       } else if (!strcasecmp(v->name, "tlscafile")) {
24679          ast_free(default_tls_cfg.cafile);
24680          default_tls_cfg.cafile = ast_strdup(v->value);
24681       } else if (!strcasecmp(v->name, "tlscapath")) {
24682          ast_free(default_tls_cfg.capath);
24683          default_tls_cfg.capath = ast_strdup(v->value);
24684       } else if (!strcasecmp(v->name, "tlsverifyclient")) {
24685          ast_set2_flag(&default_tls_cfg.flags, ast_true(v->value), AST_SSL_VERIFY_CLIENT);   
24686       } else if (!strcasecmp(v->name, "tlsdontverifyserver")) {
24687          ast_set2_flag(&default_tls_cfg.flags, ast_true(v->value), AST_SSL_DONT_VERIFY_SERVER); 
24688       } else if (!strcasecmp(v->name, "tlsbindaddr")) {
24689          if (ast_parse_arg(v->value, PARSE_INADDR, &sip_tls_desc.local_address))
24690             ast_log(LOG_WARNING, "Invalid %s '%s' at line %d of %s\n", v->name, v->value, v->lineno, config);
24691       } else if (!strcasecmp(v->name, "dynamic_exclude_static") || !strcasecmp(v->name, "dynamic_excludes_static")) {
24692          global_dynamic_exclude_static = ast_true(v->value);
24693       } else if (!strcasecmp(v->name, "contactpermit") || !strcasecmp(v->name, "contactdeny")) {
24694          int ha_error = 0;
24695          global_contact_ha = ast_append_ha(v->name + 7, v->value, global_contact_ha, &ha_error);
24696          if (ha_error) {
24697             ast_log(LOG_ERROR, "Bad ACL entry in configuration line %d : %s\n", v->lineno, v->value);
24698          }
24699       } else if (!strcasecmp(v->name, "rtautoclear")) {
24700          int i = atoi(v->value);
24701          if (i > 0)
24702             sip_cfg.rtautoclear = i;
24703          else
24704             i = 0;
24705          ast_set2_flag(&global_flags[1], i || ast_true(v->value), SIP_PAGE2_RTAUTOCLEAR);
24706       } else if (!strcasecmp(v->name, "usereqphone")) {
24707          ast_set2_flag(&global_flags[0], ast_true(v->value), SIP_USEREQPHONE);   
24708       } else if (!strcasecmp(v->name, "prematuremedia")) {
24709          global_prematuremediafilter = ast_true(v->value);
24710       } else if (!strcasecmp(v->name, "relaxdtmf")) {
24711          global_relaxdtmf = ast_true(v->value);
24712       } else if (!strcasecmp(v->name, "vmexten")) {
24713          ast_copy_string(default_vmexten, v->value, sizeof(default_vmexten));
24714       } else if (!strcasecmp(v->name, "rtptimeout")) {
24715          if ((sscanf(v->value, "%30d", &global_rtptimeout) != 1) || (global_rtptimeout < 0)) {
24716             ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d.  Using default.\n", v->value, v->lineno);
24717             global_rtptimeout = 0;
24718          }
24719       } else if (!strcasecmp(v->name, "rtpholdtimeout")) {
24720          if ((sscanf(v->value, "%30d", &global_rtpholdtimeout) != 1) || (global_rtpholdtimeout < 0)) {
24721             ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d.  Using default.\n", v->value, v->lineno);
24722             global_rtpholdtimeout = 0;
24723          }
24724       } else if (!strcasecmp(v->name, "rtpkeepalive")) {
24725          if ((sscanf(v->value, "%30d", &global_rtpkeepalive) != 1) || (global_rtpkeepalive < 0)) {
24726             ast_log(LOG_WARNING, "'%s' is not a valid RTP keepalive time at line %d.  Using default.\n", v->value, v->lineno);
24727             global_rtpkeepalive = DEFAULT_RTPKEEPALIVE;
24728          }
24729       } else if (!strcasecmp(v->name, "compactheaders")) {
24730          sip_cfg.compactheaders = ast_true(v->value);
24731       } else if (!strcasecmp(v->name, "notifymimetype")) {
24732          ast_copy_string(default_notifymime, v->value, sizeof(default_notifymime));
24733       } else if (!strcasecmp(v->name, "directrtpsetup")) {
24734          sip_cfg.directrtpsetup = ast_true(v->value);
24735       } else if (!strcasecmp(v->name, "notifyringing")) {
24736          sip_cfg.notifyringing = ast_true(v->value);
24737       } else if (!strcasecmp(v->name, "notifyhold")) {
24738          sip_cfg.notifyhold = ast_true(v->value);
24739       } else if (!strcasecmp(v->name, "notifycid")) {
24740          if (!strcasecmp(v->value, "ignore-context")) {
24741             sip_cfg.notifycid = IGNORE_CONTEXT;
24742          } else {
24743             sip_cfg.notifycid = ast_true(v->value);
24744          }
24745       } else if (!strcasecmp(v->name, "alwaysauthreject")) {
24746          sip_cfg.alwaysauthreject = ast_true(v->value);
24747       } else if (!strcasecmp(v->name, "mohinterpret")) {
24748          ast_copy_string(default_mohinterpret, v->value, sizeof(default_mohinterpret));
24749       } else if (!strcasecmp(v->name, "mohsuggest")) {
24750          ast_copy_string(default_mohsuggest, v->value, sizeof(default_mohsuggest));
24751       } else if (!strcasecmp(v->name, "language")) {
24752          ast_copy_string(default_language, v->value, sizeof(default_language));
24753       } else if (!strcasecmp(v->name, "regcontext")) {
24754          ast_copy_string(newcontexts, v->value, sizeof(newcontexts));
24755          stringp = newcontexts;
24756          /* Let's remove any contexts that are no longer defined in regcontext */
24757          cleanup_stale_contexts(stringp, oldregcontext);
24758          /* Create contexts if they don't exist already */
24759          while ((context = strsep(&stringp, "&"))) {
24760             ast_copy_string(used_context, context, sizeof(used_context));
24761             ast_context_find_or_create(NULL, NULL, context, "SIP");
24762          }
24763          ast_copy_string(global_regcontext, v->value, sizeof(global_regcontext));
24764       } else if (!strcasecmp(v->name, "regextenonqualify")) {
24765          sip_cfg.regextenonqualify = ast_true(v->value);
24766       } else if (!strcasecmp(v->name, "callerid")) {
24767          ast_copy_string(default_callerid, v->value, sizeof(default_callerid));
24768       } else if (!strcasecmp(v->name, "fromdomain")) {
24769          ast_copy_string(default_fromdomain, v->value, sizeof(default_fromdomain));
24770       } else if (!strcasecmp(v->name, "outboundproxy")) {
24771          int portnum;
24772          char *tok, *proxyname;
24773 
24774          if (ast_strlen_zero(v->value)) {
24775             ast_log(LOG_WARNING, "no value given for outbound proxy on line %d of sip.conf.", v->lineno);
24776             continue;
24777          }
24778 
24779          tok = ast_skip_blanks(strtok(ast_strdupa(v->value), ","));
24780 
24781          sip_parse_host(tok, v->lineno, &proxyname, &portnum, &sip_cfg.outboundproxy.transport);
24782 
24783          sip_cfg.outboundproxy.ip.sin_port = htons(portnum);
24784    
24785          if ((tok = strtok(NULL, ","))) {
24786             sip_cfg.outboundproxy.force = !strncasecmp(ast_skip_blanks(tok), "force", 5);
24787          } else {
24788             sip_cfg.outboundproxy.force = FALSE;
24789          }
24790 
24791          if (ast_strlen_zero(proxyname)) {
24792             ast_log(LOG_WARNING, "you must specify a name for the outboundproxy on line %d of sip.conf.", v->lineno);
24793             sip_cfg.outboundproxy.name[0] = '\0';
24794             continue;
24795          }
24796 
24797          ast_copy_string(sip_cfg.outboundproxy.name, proxyname, sizeof(sip_cfg.outboundproxy.name));
24798 
24799          proxy_update(&sip_cfg.outboundproxy);
24800       } else if (!strcasecmp(v->name, "autocreatepeer")) {
24801          sip_cfg.autocreatepeer = ast_true(v->value);
24802       } else if (!strcasecmp(v->name, "match_auth_username")) {
24803          global_match_auth_username = ast_true(v->value);
24804       } else if (!strcasecmp(v->name, "srvlookup")) {
24805          sip_cfg.srvlookup = ast_true(v->value);
24806       } else if (!strcasecmp(v->name, "pedantic")) {
24807          sip_cfg.pedanticsipchecking = ast_true(v->value);
24808       } else if (!strcasecmp(v->name, "maxexpirey") || !strcasecmp(v->name, "maxexpiry")) {
24809          max_expiry = atoi(v->value);
24810          if (max_expiry < 1)
24811             max_expiry = DEFAULT_MAX_EXPIRY;
24812       } else if (!strcasecmp(v->name, "minexpirey") || !strcasecmp(v->name, "minexpiry")) {
24813          min_expiry = atoi(v->value);
24814          if (min_expiry < 1)
24815             min_expiry = DEFAULT_MIN_EXPIRY;
24816       } else if (!strcasecmp(v->name, "defaultexpiry") || !strcasecmp(v->name, "defaultexpirey")) {
24817          default_expiry = atoi(v->value);
24818          if (default_expiry < 1)
24819             default_expiry = DEFAULT_DEFAULT_EXPIRY;
24820       } else if (!strcasecmp(v->name, "mwiexpiry") || !strcasecmp(v->name, "mwiexpirey")) {
24821          mwi_expiry = atoi(v->value);
24822          if (mwi_expiry < 1)
24823             mwi_expiry = DEFAULT_MWI_EXPIRY;
24824       } else if (!strcasecmp(v->name, "sipdebug")) {
24825          if (ast_true(v->value))
24826             sipdebug |= sip_debug_config;
24827       } else if (!strcasecmp(v->name, "dumphistory")) {
24828          dumphistory = ast_true(v->value);
24829       } else if (!strcasecmp(v->name, "recordhistory")) {
24830          recordhistory = ast_true(v->value);
24831       } else if (!strcasecmp(v->name, "registertimeout")) {
24832          global_reg_timeout = atoi(v->value);
24833          if (global_reg_timeout < 1)
24834             global_reg_timeout = DEFAULT_REGISTRATION_TIMEOUT;
24835       } else if (!strcasecmp(v->name, "registerattempts")) {
24836          global_regattempts_max = atoi(v->value);
24837       } else if (!strcasecmp(v->name, "stunaddr")) {
24838          stunaddr.sin_port = htons(3478);
24839          if (ast_parse_arg(v->value, PARSE_INADDR, &stunaddr))
24840             ast_log(LOG_WARNING, "Invalid STUN server address: %s\n", v->value);
24841          externexpire = time(NULL);
24842       } else if (!strcasecmp(v->name, "bindaddr") || !strcasecmp(v->name, "udpbindaddr")) {
24843          if (ast_parse_arg(v->value, PARSE_INADDR, &bindaddr))
24844             ast_log(LOG_WARNING, "Invalid address: %s\n", v->value);
24845       } else if (!strcasecmp(v->name, "localnet")) {
24846          struct ast_ha *na;
24847          int ha_error = 0;
24848 
24849          if (!(na = ast_append_ha("d", v->value, localaddr, &ha_error)))
24850             ast_log(LOG_WARNING, "Invalid localnet value: %s\n", v->value);
24851          else
24852             localaddr = na;
24853          if (ha_error)
24854             ast_log(LOG_ERROR, "Bad localnet configuration value line %d : %s\n", v->lineno, v->value);
24855       } else if (!strcasecmp(v->name, "externip")) {
24856          if (ast_parse_arg(v->value, PARSE_INADDR, &externip))
24857             ast_log(LOG_WARNING, "Invalid address for externip keyword: %s\n", v->value);
24858          externexpire = 0;
24859          /* If no port was specified use the value of bindport */
24860          if (!externip.sin_port)
24861             externip.sin_port = bindaddr.sin_port;
24862       } else if (!strcasecmp(v->name, "externhost")) {
24863          ast_copy_string(externhost, v->value, sizeof(externhost));
24864          if (ast_parse_arg(externhost, PARSE_INADDR, &externip))
24865             ast_log(LOG_WARNING, "Invalid address for externhost keyword: %s\n", externhost);
24866          externexpire = time(NULL);
24867          /* If no port was specified use the value of bindport */
24868          if (!externip.sin_port)
24869             externip.sin_port = bindaddr.sin_port;
24870       } else if (!strcasecmp(v->name, "externrefresh")) {
24871          if (sscanf(v->value, "%30d", &externrefresh) != 1) {
24872             ast_log(LOG_WARNING, "Invalid externrefresh value '%s', must be an integer >0 at line %d\n", v->value, v->lineno);
24873             externrefresh = 10;
24874          }
24875       } else if (!strcasecmp(v->name, "allow")) {
24876          int error =  ast_parse_allow_disallow(&default_prefs, &global_capability, v->value, TRUE);
24877          if (error)
24878             ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
24879       } else if (!strcasecmp(v->name, "disallow")) {
24880          int error =  ast_parse_allow_disallow(&default_prefs, &global_capability, v->value, FALSE);
24881          if (error)
24882             ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
24883       } else if (!strcasecmp(v->name, "autoframing")) {
24884          global_autoframing = ast_true(v->value);
24885       } else if (!strcasecmp(v->name, "allowexternaldomains")) {
24886          sip_cfg.allow_external_domains = ast_true(v->value);
24887       } else if (!strcasecmp(v->name, "autodomain")) {
24888          auto_sip_domains = ast_true(v->value);
24889       } else if (!strcasecmp(v->name, "domain")) {
24890          char *domain = ast_strdupa(v->value);
24891          char *cntx = strchr(domain, ',');
24892 
24893          if (cntx)
24894             *cntx++ = '\0';
24895 
24896          if (ast_strlen_zero(cntx))
24897             ast_debug(1, "No context specified at line %d for domain '%s'\n", v->lineno, domain);
24898          if (ast_strlen_zero(domain))
24899             ast_log(LOG_WARNING, "Empty domain specified at line %d\n", v->lineno);
24900          else
24901             add_sip_domain(ast_strip(domain), SIP_DOMAIN_CONFIG, cntx ? ast_strip(cntx) : "");
24902       } else if (!strcasecmp(v->name, "register")) {
24903          if (sip_register(v->value, v->lineno) == 0)
24904             registry_count++;
24905       } else if (!strcasecmp(v->name, "mwi")) {
24906          sip_subscribe_mwi(v->value, v->lineno);
24907       } else if (!strcasecmp(v->name, "tos_sip")) {
24908          if (ast_str2tos(v->value, &global_tos_sip))
24909             ast_log(LOG_WARNING, "Invalid tos_sip value at line %d, refer to QoS documentation\n", v->lineno);
24910       } else if (!strcasecmp(v->name, "tos_audio")) {
24911          if (ast_str2tos(v->value, &global_tos_audio))
24912             ast_log(LOG_WARNING, "Invalid tos_audio value at line %d, refer to QoS documentation\n", v->lineno);
24913       } else if (!strcasecmp(v->name, "tos_video")) {
24914          if (ast_str2tos(v->value, &global_tos_video))
24915             ast_log(LOG_WARNING, "Invalid tos_video value at line %d, refer to QoS documentation\n", v->lineno);
24916       } else if (!strcasecmp(v->name, "tos_text")) {
24917          if (ast_str2tos(v->value, &global_tos_text))
24918             ast_log(LOG_WARNING, "Invalid tos_text value at line %d, refer to QoS documentation\n", v->lineno);
24919       } else if (!strcasecmp(v->name, "cos_sip")) {
24920          if (ast_str2cos(v->value, &global_cos_sip))
24921             ast_log(LOG_WARNING, "Invalid cos_sip value at line %d, refer to QoS documentation\n", v->lineno);
24922       } else if (!strcasecmp(v->name, "cos_audio")) {
24923          if (ast_str2cos(v->value, &global_cos_audio))
24924             ast_log(LOG_WARNING, "Invalid cos_audio value at line %d, refer to QoS documentation\n", v->lineno);
24925       } else if (!strcasecmp(v->name, "cos_video")) {
24926          if (ast_str2cos(v->value, &global_cos_video))
24927             ast_log(LOG_WARNING, "Invalid cos_video value at line %d, refer to QoS documentation\n", v->lineno);
24928       } else if (!strcasecmp(v->name, "cos_text")) {
24929          if (ast_str2cos(v->value, &global_cos_text))
24930             ast_log(LOG_WARNING, "Invalid cos_text value at line %d, refer to QoS documentation\n", v->lineno);
24931       } else if (!strcasecmp(v->name, "bindport")) {
24932          int i;
24933          if (sscanf(v->value, "%5d", &i) == 1) {
24934             bindaddr.sin_port = htons(i);
24935          } else {
24936             ast_log(LOG_WARNING, "Invalid port number '%s' at line %d of %s\n", v->value, v->lineno, config);
24937          }
24938       } else if (!strcasecmp(v->name, "hash_user")) {
24939          int i;
24940          if (sscanf(v->value, "%30d", &i) == 1 && i > 2) {
24941             hash_user_size = i;
24942          } else {
24943             ast_log(LOG_WARNING, "Invalid hash_user size '%s' at line %d of %s -- should be much larger than 2\n", v->value, v->lineno, config);
24944          }
24945       } else if (!strcasecmp(v->name, "hash_peer")) {
24946          int i;
24947          if (sscanf(v->value, "%30d", &i) == 1 && i > 2) {
24948             hash_peer_size = i;
24949          } else {
24950             ast_log(LOG_WARNING, "Invalid hash_peer size '%s' at line %d of %s -- should be much larger than 2\n", v->value, v->lineno, config);
24951          }
24952       } else if (!strcasecmp(v->name, "hash_dialog")) {
24953          int i;
24954          if (sscanf(v->value, "%30d", &i) == 1 && i > 2) {
24955             hash_dialog_size = i;
24956          } else {
24957             ast_log(LOG_WARNING, "Invalid hash_dialog size '%s' at line %d of %s -- should be much larger than 2\n", v->value, v->lineno, config);
24958          }
24959       } else if (!strcasecmp(v->name, "qualify")) {
24960          if (!strcasecmp(v->value, "no")) {
24961             default_qualify = 0;
24962          } else if (!strcasecmp(v->value, "yes")) {
24963             default_qualify = DEFAULT_MAXMS;
24964          } else if (sscanf(v->value, "%30d", &default_qualify) != 1) {
24965             ast_log(LOG_WARNING, "Qualification default should be 'yes', 'no', or a number of milliseconds at line %d of sip.conf\n", v->lineno);
24966             default_qualify = 0;
24967          }
24968       } else if (!strcasecmp(v->name, "qualifyfreq")) {
24969          int i;
24970          if (sscanf(v->value, "%30d", &i) == 1)
24971             global_qualifyfreq = i * 1000;
24972          else {
24973             ast_log(LOG_WARNING, "Invalid qualifyfreq number '%s' at line %d of %s\n", v->value, v->lineno, config);
24974             global_qualifyfreq = DEFAULT_QUALIFYFREQ;
24975          }
24976       } else if (!strcasecmp(v->name, "callevents")) {
24977          sip_cfg.callevents = ast_true(v->value);
24978       } else if (!strcasecmp(v->name, "authfailureevents")) {
24979          global_authfailureevents = ast_true(v->value);
24980       } else if (!strcasecmp(v->name, "maxcallbitrate")) {
24981          default_maxcallbitrate = atoi(v->value);
24982          if (default_maxcallbitrate < 0)
24983             default_maxcallbitrate = DEFAULT_MAX_CALL_BITRATE;
24984       } else if (!strcasecmp(v->name, "matchexterniplocally")) {
24985          sip_cfg.matchexterniplocally = ast_true(v->value);
24986       } else if (!strcasecmp(v->name, "session-timers")) {
24987          int i = (int) str2stmode(v->value); 
24988          if (i < 0) {
24989             ast_log(LOG_WARNING, "Invalid session-timers '%s' at line %d of %s\n", v->value, v->lineno, config);
24990             global_st_mode = SESSION_TIMER_MODE_ACCEPT;
24991          } else {
24992             global_st_mode = i;
24993          }
24994       } else if (!strcasecmp(v->name, "session-expires")) {
24995          if (sscanf(v->value, "%30d", &global_max_se) != 1) {
24996             ast_log(LOG_WARNING, "Invalid session-expires '%s' at line %d of %s\n", v->value, v->lineno, config);
24997             global_max_se = DEFAULT_MAX_SE;
24998          } 
24999       } else if (!strcasecmp(v->name, "session-minse")) {
25000          if (sscanf(v->value, "%30d", &global_min_se) != 1) {
25001             ast_log(LOG_WARNING, "Invalid session-minse '%s' at line %d of %s\n", v->value, v->lineno, config);
25002             global_min_se = DEFAULT_MIN_SE;
25003          } 
25004          if (global_min_se < 90) {
25005             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);
25006             global_min_se = DEFAULT_MIN_SE;
25007          } 
25008       } else if (!strcasecmp(v->name, "session-refresher")) {
25009          int i = (int) str2strefresher(v->value); 
25010          if (i < 0) {
25011             ast_log(LOG_WARNING, "Invalid session-refresher '%s' at line %d of %s\n", v->value, v->lineno, config);
25012             global_st_refresher = SESSION_TIMER_REFRESHER_UAS;
25013          } else {
25014             global_st_refresher = i;
25015          }
25016       } else if (!strcasecmp(v->name, "qualifygap")) {
25017          if (sscanf(v->value, "%30d", &global_qualify_gap) != 1) {
25018             ast_log(LOG_WARNING, "Invalid qualifygap '%s' at line %d of %s\n", v->value, v->lineno, config);
25019             global_qualify_gap = DEFAULT_QUALIFY_GAP;
25020          }
25021       } else if (!strcasecmp(v->name, "qualifypeers")) {
25022          if (sscanf(v->value, "%30d", &global_qualify_peers) != 1) {
25023             ast_log(LOG_WARNING, "Invalid pokepeers '%s' at line %d of %s\n", v->value, v->lineno, config);
25024             global_qualify_peers = DEFAULT_QUALIFY_PEERS;
25025          }
25026       } else if (!strcasecmp(v->name, "shrinkcallerid")) {
25027          if (ast_true(v->value)) {
25028             global_shrinkcallerid = 1;
25029          } else if (ast_false(v->value)) {
25030             global_shrinkcallerid = 0;
25031          } else {
25032             ast_log(LOG_WARNING, "shrinkcallerid value %s is not valid at line %d.\n", v->value, v->lineno);
25033          }
25034       }
25035    }
25036 
25037    if (!sip_cfg.allow_external_domains && AST_LIST_EMPTY(&domain_list)) {
25038       ast_log(LOG_WARNING, "To disallow external domains, you need to configure local SIP domains.\n");
25039       sip_cfg.allow_external_domains = 1;
25040    }
25041    /* If not configured, set default transports */
25042    if (default_transports == 0) {
25043       default_transports = default_primary_transport = SIP_TRANSPORT_UDP;
25044    }
25045    
25046    /* Build list of authentication to various SIP realms, i.e. service providers */
25047    for (v = ast_variable_browse(cfg, "authentication"); v ; v = v->next) {
25048       /* Format for authentication is auth = username:password@realm */
25049       if (!strcasecmp(v->name, "auth"))
25050          authl = add_realm_authentication(authl, v->value, v->lineno);
25051    }
25052    
25053    if (ucfg) {
25054       struct ast_variable *gen;
25055       int genhassip, genregistersip;
25056       const char *hassip, *registersip;
25057       
25058       genhassip = ast_true(ast_variable_retrieve(ucfg, "general", "hassip"));
25059       genregistersip = ast_true(ast_variable_retrieve(ucfg, "general", "registersip"));
25060       gen = ast_variable_browse(ucfg, "general");
25061       cat = ast_category_browse(ucfg, NULL);
25062       while (cat) {
25063          if (strcasecmp(cat, "general")) {
25064             hassip = ast_variable_retrieve(ucfg, cat, "hassip");
25065             registersip = ast_variable_retrieve(ucfg, cat, "registersip");
25066             if (ast_true(hassip) || (!hassip && genhassip)) {
25067                peer = build_peer(cat, gen, ast_variable_browse(ucfg, cat), 0, 0);
25068                if (peer) {
25069                   /* user.conf entries are always of type friend */
25070                   peer->type = SIP_TYPE_USER | SIP_TYPE_PEER;
25071                   ao2_t_link(peers, peer, "link peer into peer table");
25072                   if ((peer->type & SIP_TYPE_PEER) && peer->addr.sin_addr.s_addr) {
25073                      ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
25074                   }
25075                   
25076                   unref_peer(peer, "unref_peer: from reload_config");
25077                   peer_count++;
25078                }
25079             }
25080             if (ast_true(registersip) || (!registersip && genregistersip)) {
25081                char tmp[256];
25082                const char *host = ast_variable_retrieve(ucfg, cat, "host");
25083                const char *username = ast_variable_retrieve(ucfg, cat, "username");
25084                const char *secret = ast_variable_retrieve(ucfg, cat, "secret");
25085                const char *contact = ast_variable_retrieve(ucfg, cat, "contact");
25086                const char *authuser = ast_variable_retrieve(ucfg, cat, "authuser");
25087                if (!host)
25088                   host = ast_variable_retrieve(ucfg, "general", "host");
25089                if (!username)
25090                   username = ast_variable_retrieve(ucfg, "general", "username");
25091                if (!secret)
25092                   secret = ast_variable_retrieve(ucfg, "general", "secret");
25093                if (!contact)
25094                   contact = "s";
25095                if (!ast_strlen_zero(username) && !ast_strlen_zero(host)) {
25096                   if (!ast_strlen_zero(secret)) {
25097                      if (!ast_strlen_zero(authuser)) {
25098                         snprintf(tmp, sizeof(tmp), "%s:%s:%s@%s/%s", username, secret, authuser, host, contact);
25099                      } else {
25100                         snprintf(tmp, sizeof(tmp), "%s:%s@%s/%s", username, secret, host, contact);
25101                      }
25102                   } else if (!ast_strlen_zero(authuser)) {
25103                      snprintf(tmp, sizeof(tmp), "%s::%s@%s/%s", username, authuser, host, contact);
25104                   } else {
25105                      snprintf(tmp, sizeof(tmp), "%s@%s/%s", username, host, contact);
25106                   }
25107                   if (sip_register(tmp, 0) == 0)
25108                      registry_count++;
25109                }
25110             }
25111          }
25112          cat = ast_category_browse(ucfg, cat);
25113       }
25114       ast_config_destroy(ucfg);
25115    }
25116    
25117 
25118    /* Load peers, users and friends */
25119    cat = NULL;
25120    while ( (cat = ast_category_browse(cfg, cat)) ) {
25121       const char *utype;
25122       if (!strcasecmp(cat, "general") || !strcasecmp(cat, "authentication"))
25123          continue;
25124       utype = ast_variable_retrieve(cfg, cat, "type");
25125       if (!utype) {
25126          ast_log(LOG_WARNING, "Section '%s' lacks type\n", cat);
25127          continue;
25128       } else {
25129          if (!strcasecmp(utype, "user")) {
25130             ;
25131          } else if (!strcasecmp(utype, "friend")) {
25132             ;
25133          } else if (!strcasecmp(utype, "peer")) {
25134             ;
25135          } else {
25136             ast_log(LOG_WARNING, "Unknown type '%s' for '%s' in %s\n", utype, cat, "sip.conf");
25137             continue;
25138          }
25139          peer = build_peer(cat, ast_variable_browse(cfg, cat), NULL, 0, 0);
25140          if (peer) {
25141             ao2_t_link(peers, peer, "link peer into peers table");
25142             if ((peer->type & SIP_TYPE_PEER) && peer->addr.sin_addr.s_addr) {
25143                ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
25144             }
25145             unref_peer(peer, "unref the result of the build_peer call. Now, the links from the tables are the only ones left.");
25146             peer_count++;
25147          }
25148       }
25149    }
25150    
25151    /* Set UDP address and open socket */
25152    bindaddr.sin_family = AF_INET;
25153    internip = bindaddr;
25154    if (ast_find_ourip(&internip.sin_addr, bindaddr)) {
25155       ast_log(LOG_WARNING, "Unable to get own IP address, SIP disabled\n");
25156       ast_config_destroy(cfg);
25157       return 0;
25158    }
25159    ast_mutex_lock(&netlock);
25160    if ((sipsock > -1) && (memcmp(&old_bindaddr, &bindaddr, sizeof(struct sockaddr_in)))) {
25161       close(sipsock);
25162       sipsock = -1;
25163    }
25164    if (sipsock < 0) {
25165       sipsock = socket(AF_INET, SOCK_DGRAM, 0);
25166       if (sipsock < 0) {
25167          ast_log(LOG_WARNING, "Unable to create SIP socket: %s\n", strerror(errno));
25168          ast_config_destroy(cfg);
25169          return -1;
25170       } else {
25171          /* Allow SIP clients on the same host to access us: */
25172          const int reuseFlag = 1;
25173 
25174          setsockopt(sipsock, SOL_SOCKET, SO_REUSEADDR,
25175                (const char*)&reuseFlag,
25176                sizeof reuseFlag);
25177 
25178          ast_enable_packet_fragmentation(sipsock);
25179 
25180          if (bind(sipsock, (struct sockaddr *)&bindaddr, sizeof(bindaddr)) < 0) {
25181             ast_log(LOG_WARNING, "Failed to bind to %s:%d: %s\n",
25182             ast_inet_ntoa(bindaddr.sin_addr), ntohs(bindaddr.sin_port),
25183             strerror(errno));
25184             close(sipsock);
25185             sipsock = -1;
25186          } else {
25187             ast_verb(2, "SIP Listening on %s:%d\n",
25188                   ast_inet_ntoa(bindaddr.sin_addr), ntohs(bindaddr.sin_port));
25189             ast_netsock_set_qos(sipsock, global_tos_sip, global_cos_sip, "SIP");
25190          }
25191       }
25192    }
25193    if (stunaddr.sin_addr.s_addr != 0) {
25194       ast_debug(1, "stun to %s:%d\n",
25195          ast_inet_ntoa(stunaddr.sin_addr) , ntohs(stunaddr.sin_port));
25196       ast_stun_request(sipsock, &stunaddr,
25197          NULL, &externip);
25198       ast_debug(1, "STUN sees us at %s:%d\n", 
25199          ast_inet_ntoa(externip.sin_addr) , ntohs(externip.sin_port));
25200    }
25201    ast_mutex_unlock(&netlock);
25202 
25203    /* Start TCP server */
25204    ast_tcptls_server_start(&sip_tcp_desc);
25205    if (sip_tcp_desc.accept_fd == -1 &&  sip_tcp_desc.local_address.sin_family == AF_INET) {
25206       /* TCP server start failed. Tell the admin */
25207       ast_log(LOG_ERROR, "SIP TCP Server start failed. Not listening on TCP socket.\n");
25208       sip_tcp_desc.local_address.sin_family = 0;
25209    } else {
25210       ast_debug(2, "SIP TCP server started\n");
25211    }
25212 
25213    /* Start TLS server if needed */
25214    memcpy(sip_tls_desc.tls_cfg, &default_tls_cfg, sizeof(default_tls_cfg));
25215 
25216    if (ast_ssl_setup(sip_tls_desc.tls_cfg)) {
25217       ast_tcptls_server_start(&sip_tls_desc);
25218       if (default_tls_cfg.enabled && sip_tls_desc.accept_fd == -1) {
25219          ast_log(LOG_ERROR, "TLS Server start failed. Not listening on TLS socket.\n");
25220          sip_tls_desc.tls_cfg = NULL;
25221       }
25222    } else if (sip_tls_desc.tls_cfg->enabled) {
25223       sip_tls_desc.tls_cfg = NULL;
25224       ast_log(LOG_WARNING, "SIP TLS server did not load because of errors.\n");
25225    }
25226 
25227 
25228    /* Add default domains - host name, IP address and IP:port
25229     * Only do this if user added any sip domain with "localdomains" 
25230     * In order to *not* break backwards compatibility 
25231     *    Some phones address us at IP only, some with additional port number 
25232     */
25233    if (auto_sip_domains) {
25234       char temp[MAXHOSTNAMELEN];
25235 
25236       /* First our default IP address */
25237       if (bindaddr.sin_addr.s_addr) {
25238          add_sip_domain(ast_inet_ntoa(bindaddr.sin_addr), SIP_DOMAIN_AUTO, NULL);
25239       } else if (internip.sin_addr.s_addr) {
25240       /* Our internal IP address, if configured */
25241          add_sip_domain(ast_inet_ntoa(internip.sin_addr), SIP_DOMAIN_AUTO, NULL);
25242       } else {
25243          ast_log(LOG_NOTICE, "Can't add wildcard IP address to domain list, please add IP address to domain manually.\n");
25244       }
25245 
25246       /* If TCP is running on a different IP than UDP, then add it too */
25247       if (sip_tcp_desc.local_address.sin_addr.s_addr && !inaddrcmp(&bindaddr, &sip_tcp_desc.local_address))
25248          add_sip_domain(ast_inet_ntoa(sip_tcp_desc.local_address.sin_addr), SIP_DOMAIN_AUTO, NULL);
25249 
25250       /* If TLS is running on a differen IP than UDP and TCP, then add that too */
25251       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))
25252          add_sip_domain(ast_inet_ntoa(sip_tls_desc.local_address.sin_addr), SIP_DOMAIN_AUTO, NULL);
25253 
25254       /* Our extern IP address, if configured */
25255       if (externip.sin_addr.s_addr)
25256          add_sip_domain(ast_inet_ntoa(externip.sin_addr), SIP_DOMAIN_AUTO, NULL);
25257 
25258       /* Extern host name (NAT traversal support) */
25259       if (!ast_strlen_zero(externhost))
25260          add_sip_domain(externhost, SIP_DOMAIN_AUTO, NULL);
25261       
25262       /* Our host name */
25263       if (!gethostname(temp, sizeof(temp)))
25264          add_sip_domain(temp, SIP_DOMAIN_AUTO, NULL);
25265    }
25266 
25267    /* Release configuration from memory */
25268    ast_config_destroy(cfg);
25269 
25270    /* Load the list of manual NOTIFY types to support */
25271    if (notify_types)
25272       ast_config_destroy(notify_types);
25273    if ((notify_types = ast_config_load(notify_config, config_flags)) == CONFIG_STATUS_FILEINVALID) {
25274       ast_log(LOG_ERROR, "Contents of %s are invalid and cannot be parsed.\n", notify_config);
25275       notify_types = NULL;
25276    }
25277 
25278    /* Done, tell the manager */
25279    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);
25280    run_end = time(0);
25281    ast_debug(4, "SIP reload_config done...Runtime= %d sec\n", (int)(run_end-run_start));
25282 
25283    return 0;
25284 }
25285 
25286 static struct ast_udptl *sip_get_udptl_peer(struct ast_channel *chan)
25287 {
25288    struct sip_pvt *p;
25289    struct ast_udptl *udptl = NULL;
25290    
25291    p = chan->tech_pvt;
25292    if (!p)
25293       return NULL;
25294    
25295    sip_pvt_lock(p);
25296    if (p->udptl && ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA))
25297       udptl = p->udptl;
25298    sip_pvt_unlock(p);
25299    return udptl;
25300 }
25301 
25302 static int sip_set_udptl_peer(struct ast_channel *chan, struct ast_udptl *udptl)
25303 {
25304    struct sip_pvt *p;
25305    
25306    p = chan->tech_pvt;
25307    if (!p)
25308       return -1;
25309    sip_pvt_lock(p);
25310    if (udptl)
25311       ast_udptl_get_peer(udptl, &p->udptlredirip);
25312    else
25313       memset(&p->udptlredirip, 0, sizeof(p->udptlredirip));
25314    if (!ast_test_flag(&p->flags[0], SIP_GOTREFER)) {
25315       if (!p->pendinginvite) {
25316          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);
25317          transmit_reinvite_with_sdp(p, TRUE, FALSE);
25318       } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
25319          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);
25320          ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
25321       }
25322    }
25323    /* Reset lastrtprx timer */
25324    p->lastrtprx = p->lastrtptx = time(NULL);
25325    sip_pvt_unlock(p);
25326    return 0;
25327 }
25328 
25329 /*! \brief Returns null if we can't reinvite audio (part of RTP interface) */
25330 static enum ast_rtp_get_result sip_get_rtp_peer(struct ast_channel *chan, struct ast_rtp **rtp)
25331 {
25332    struct sip_pvt *p = NULL;
25333    enum ast_rtp_get_result res = AST_RTP_TRY_PARTIAL;
25334 
25335    if (!(p = chan->tech_pvt))
25336       return AST_RTP_GET_FAILED;
25337 
25338    sip_pvt_lock(p);
25339    if (!(p->rtp)) {
25340       sip_pvt_unlock(p);
25341       return AST_RTP_GET_FAILED;
25342    }
25343 
25344    *rtp = p->rtp;
25345 
25346    if (ast_rtp_getnat(*rtp) && !ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA_NAT))
25347       res = AST_RTP_TRY_PARTIAL;
25348    else if (ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA))
25349       res = AST_RTP_TRY_NATIVE;
25350    else if (ast_test_flag(&global_jbconf, AST_JB_FORCED))
25351       res = AST_RTP_GET_FAILED;
25352 
25353    sip_pvt_unlock(p);
25354 
25355    return res;
25356 }
25357 
25358 /*! \brief Returns null if we can't reinvite video (part of RTP interface) */
25359 static enum ast_rtp_get_result sip_get_vrtp_peer(struct ast_channel *chan, struct ast_rtp **rtp)
25360 {
25361    struct sip_pvt *p = NULL;
25362    enum ast_rtp_get_result res = AST_RTP_TRY_PARTIAL;
25363    
25364    if (!(p = chan->tech_pvt))
25365       return AST_RTP_GET_FAILED;
25366 
25367    sip_pvt_lock(p);
25368    if (!(p->vrtp)) {
25369       sip_pvt_unlock(p);
25370       return AST_RTP_GET_FAILED;
25371    }
25372 
25373    *rtp = p->vrtp;
25374 
25375    if (ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA))
25376       res = AST_RTP_TRY_NATIVE;
25377 
25378    sip_pvt_unlock(p);
25379 
25380    return res;
25381 }
25382 
25383 /*! \brief Returns null if we can't reinvite text (part of RTP interface) */
25384 static enum ast_rtp_get_result sip_get_trtp_peer(struct ast_channel *chan, struct ast_rtp **rtp)
25385 {
25386    struct sip_pvt *p = NULL;
25387    enum ast_rtp_get_result res = AST_RTP_TRY_PARTIAL;
25388    
25389    if (!(p = chan->tech_pvt))
25390       return AST_RTP_GET_FAILED;
25391 
25392    sip_pvt_lock(p);
25393    if (!(p->trtp)) {
25394       sip_pvt_unlock(p);
25395       return AST_RTP_GET_FAILED;
25396    }
25397 
25398    *rtp = p->trtp;
25399 
25400    if (ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA))
25401       res = AST_RTP_TRY_NATIVE;
25402 
25403    sip_pvt_unlock(p);
25404 
25405    return res;
25406 }
25407 
25408 /*! \brief Set the RTP peer for this call */
25409 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)
25410 {
25411    struct sip_pvt *p;
25412    int changed = 0;
25413 
25414    p = chan->tech_pvt;
25415    if (!p) 
25416       return -1;
25417 
25418    /* Disable early RTP bridge  */
25419    if (!ast_bridged_channel(chan) && !sip_cfg.directrtpsetup)  /* We are in early state */
25420       return 0;
25421 
25422    sip_pvt_lock(p);
25423    if (p->alreadygone) {
25424       /* If we're destroyed, don't bother */
25425       sip_pvt_unlock(p);
25426       return 0;
25427    }
25428 
25429    /* if this peer cannot handle reinvites of the media stream to devices
25430       that are known to be behind a NAT, then stop the process now
25431    */
25432         if (nat_active && !ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA_NAT)) {
25433                 sip_pvt_unlock(p);
25434                 return 0;
25435         }
25436 
25437    if (rtp) {
25438       changed |= ast_rtp_get_peer(rtp, &p->redirip);
25439    } else if (p->redirip.sin_addr.s_addr || ntohs(p->redirip.sin_port) != 0) {
25440       memset(&p->redirip, 0, sizeof(p->redirip));
25441       changed = 1;
25442    }
25443    if (vrtp) {
25444       changed |= ast_rtp_get_peer(vrtp, &p->vredirip);
25445    } else if (p->vredirip.sin_addr.s_addr || ntohs(p->vredirip.sin_port) != 0) {
25446       memset(&p->vredirip, 0, sizeof(p->vredirip));
25447       changed = 1;
25448    }
25449    if (trtp) {
25450       changed |= ast_rtp_get_peer(trtp, &p->tredirip);
25451    } else if (p->tredirip.sin_addr.s_addr || ntohs(p->tredirip.sin_port) != 0) {
25452       memset(&p->tredirip, 0, sizeof(p->tredirip));
25453       changed = 1;
25454    }
25455    if (codecs && (p->redircodecs != codecs)) {
25456       p->redircodecs = codecs;
25457       changed = 1;
25458    }
25459    if (changed && !ast_test_flag(&p->flags[0], SIP_GOTREFER) && !ast_test_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER)) {
25460       if (chan->_state != AST_STATE_UP) { /* We are in early state */
25461          if (p->do_history)
25462             append_history(p, "ExtInv", "Initial invite sent with remote bridge proposal.");
25463          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));
25464       } else if (!p->pendinginvite) {     /* We are up, and have no outstanding invite */
25465          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));
25466          transmit_reinvite_with_sdp(p, FALSE, FALSE);
25467       } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
25468          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));
25469          /* We have a pending Invite. Send re-invite when we're done with the invite */
25470          ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);   
25471       }
25472    }
25473    /* Reset lastrtprx timer */
25474    p->lastrtprx = p->lastrtptx = time(NULL);
25475    sip_pvt_unlock(p);
25476    return 0;
25477 }
25478 
25479 static char *app_dtmfmode = "SIPDtmfMode";
25480 static char *app_sipaddheader = "SIPAddHeader";
25481 static char *app_sipremoveheader = "SIPRemoveHeader";
25482 
25483 /*! \brief Set the DTMFmode for an outbound SIP call (application) */
25484 static int sip_dtmfmode(struct ast_channel *chan, void *data)
25485 {
25486    struct sip_pvt *p;
25487    char *mode = data;
25488 
25489    if (!data) {
25490       ast_log(LOG_WARNING, "This application requires the argument: info, inband, rfc2833\n");
25491       return 0;
25492    }
25493    ast_channel_lock(chan);
25494    if (!IS_SIP_TECH(chan->tech)) {
25495       ast_log(LOG_WARNING, "Call this application only on SIP incoming calls\n");
25496       ast_channel_unlock(chan);
25497       return 0;
25498    }
25499    p = chan->tech_pvt;
25500    if (!p) {
25501       ast_channel_unlock(chan);
25502       return 0;
25503    }
25504    sip_pvt_lock(p);
25505    if (!strcasecmp(mode, "info")) {
25506       ast_clear_flag(&p->flags[0], SIP_DTMF);
25507       ast_set_flag(&p->flags[0], SIP_DTMF_INFO);
25508       p->jointnoncodeccapability &= ~AST_RTP_DTMF;
25509    } else if (!strcasecmp(mode, "shortinfo")) {
25510       ast_clear_flag(&p->flags[0], SIP_DTMF);
25511       ast_set_flag(&p->flags[0], SIP_DTMF_SHORTINFO);
25512       p->jointnoncodeccapability &= ~AST_RTP_DTMF;
25513    } else if (!strcasecmp(mode, "rfc2833")) {
25514       ast_clear_flag(&p->flags[0], SIP_DTMF);
25515       ast_set_flag(&p->flags[0], SIP_DTMF_RFC2833);
25516       p->jointnoncodeccapability |= AST_RTP_DTMF;
25517    } else if (!strcasecmp(mode, "inband")) { 
25518       ast_clear_flag(&p->flags[0], SIP_DTMF);
25519       ast_set_flag(&p->flags[0], SIP_DTMF_INBAND);
25520       p->jointnoncodeccapability &= ~AST_RTP_DTMF;
25521    } else
25522       ast_log(LOG_WARNING, "I don't know about this dtmf mode: %s\n", mode);
25523    if (p->rtp)
25524       ast_rtp_setdtmf(p->rtp, ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
25525    if (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) {
25526       if (!p->dsp) {
25527          p->dsp = ast_dsp_new();
25528          ast_dsp_set_features(p->dsp, DSP_FEATURE_DIGIT_DETECT);
25529       }
25530    } else {
25531       if (p->dsp) {
25532          ast_dsp_free(p->dsp);
25533          p->dsp = NULL;
25534       }
25535    }
25536    sip_pvt_unlock(p);
25537    ast_channel_unlock(chan);
25538    return 0;
25539 }
25540 
25541 /*! \brief Add a SIP header to an outbound INVITE */
25542 static int sip_addheader(struct ast_channel *chan, void *data)
25543 {
25544    int no = 0;
25545    int ok = FALSE;
25546    char varbuf[30];
25547    char *inbuf = data, *subbuf;
25548    
25549    if (ast_strlen_zero(inbuf)) {
25550       ast_log(LOG_WARNING, "This application requires the argument: Header\n");
25551       return 0;
25552    }
25553    ast_channel_lock(chan);
25554 
25555    /* Check for headers */
25556    while (!ok && no <= 50) {
25557       no++;
25558       snprintf(varbuf, sizeof(varbuf), "__SIPADDHEADER%.2d", no);
25559 
25560       /* Compare without the leading underscores */
25561       if ((pbx_builtin_getvar_helper(chan, (const char *) varbuf + 2) == (const char *) NULL)) {
25562          ok = TRUE;
25563       }
25564    }
25565    if (ok) {
25566       size_t len = strlen(inbuf);
25567       subbuf = alloca(len + 1);
25568       ast_get_encoded_str(inbuf, subbuf, len + 1);
25569       pbx_builtin_setvar_helper(chan, varbuf, subbuf);
25570       if (sipdebug) {
25571          ast_debug(1, "SIP Header added \"%s\" as %s\n", inbuf, varbuf);
25572       }
25573    } else {
25574       ast_log(LOG_WARNING, "Too many SIP headers added, max 50\n");
25575    }
25576    ast_channel_unlock(chan);
25577    return 0;
25578 }
25579 
25580 /*! \brief Remove SIP headers added previously with SipAddHeader application */
25581 static int sip_removeheader(struct ast_channel *chan, void *data)
25582 {
25583    struct ast_var_t *newvariable;
25584    struct varshead *headp;
25585    int removeall = 0;
25586    char *inbuf = (char *) data;
25587 
25588    if (ast_strlen_zero(inbuf)) {
25589       removeall = 1;
25590    }
25591    ast_channel_lock(chan);
25592  
25593    headp=&chan->varshead;
25594    AST_LIST_TRAVERSE_SAFE_BEGIN (headp, newvariable, entries) {
25595       if (strncasecmp(ast_var_name(newvariable), "SIPADDHEADER", strlen("SIPADDHEADER")) == 0) {
25596          if (removeall || (!strncasecmp(ast_var_value(newvariable),inbuf,strlen(inbuf)))) {
25597             if (sipdebug)
25598                ast_log(LOG_DEBUG,"removing SIP Header \"%s\" as %s\n",
25599                   ast_var_value(newvariable),
25600                   ast_var_name(newvariable));
25601             AST_LIST_REMOVE_CURRENT(entries);
25602             ast_var_delete(newvariable);
25603          }
25604       }
25605    }
25606    AST_LIST_TRAVERSE_SAFE_END;
25607  
25608    ast_channel_unlock(chan);
25609    return 0;
25610 }
25611 
25612 /*! \brief Transfer call before connect with a 302 redirect
25613 \note Called by the transfer() dialplan application through the sip_transfer()
25614    pbx interface function if the call is in ringing state 
25615 \todo Fix this function so that we wait for reply to the REFER and
25616    react to errors, denials or other issues the other end might have.
25617  */
25618 static int sip_sipredirect(struct sip_pvt *p, const char *dest)
25619 {
25620    char *cdest;
25621    char *extension, *host, *port;
25622    char tmp[80];
25623 
25624    cdest = ast_strdupa(dest);
25625    
25626    extension = strsep(&cdest, "@");
25627    host = strsep(&cdest, ":");
25628    port = strsep(&cdest, ":");
25629    if (ast_strlen_zero(extension)) {
25630       ast_log(LOG_ERROR, "Missing mandatory argument: extension\n");
25631       return 0;
25632    }
25633 
25634    /* we'll issue the redirect message here */
25635    if (!host) {
25636       char *localtmp;
25637 
25638       ast_copy_string(tmp, get_header(&p->initreq, "To"), sizeof(tmp));
25639       if (ast_strlen_zero(tmp)) {
25640          ast_log(LOG_ERROR, "Cannot retrieve the 'To' header from the original SIP request!\n");
25641          return 0;
25642       }
25643       if ( ( (localtmp = strcasestr(tmp, "sip:")) || (localtmp = strcasestr(tmp, "sips:")) ) 
25644          && (localtmp = strchr(localtmp, '@'))) {
25645          char lhost[80], lport[80];
25646 
25647          memset(lhost, 0, sizeof(lhost));
25648          memset(lport, 0, sizeof(lport));
25649          localtmp++;
25650          /* This is okey because lhost and lport are as big as tmp */
25651          sscanf(localtmp, "%80[^<>:; ]:%80[^<>:; ]", lhost, lport);
25652          if (ast_strlen_zero(lhost)) {
25653             ast_log(LOG_ERROR, "Can't find the host address\n");
25654             return 0;
25655          }
25656          host = ast_strdupa(lhost);
25657          if (!ast_strlen_zero(lport)) {
25658             port = ast_strdupa(lport);
25659          }
25660       }
25661    }
25662 
25663    ast_string_field_build(p, our_contact, "Transfer <sip:%s@%s%s%s>", extension, host, port ? ":" : "", port ? port : "");
25664    transmit_response_reliable(p, "302 Moved Temporarily", &p->initreq);
25665 
25666    sip_scheddestroy(p, SIP_TRANS_TIMEOUT);   /* Make sure we stop send this reply. */
25667    sip_alreadygone(p);
25668    /* hangup here */
25669    return 0;
25670 }
25671 
25672 /*! \brief Return SIP UA's codec (part of the RTP interface) */
25673 static int sip_get_codec(struct ast_channel *chan)
25674 {
25675    struct sip_pvt *p = chan->tech_pvt;
25676    return p->jointcapability ? p->jointcapability : p->capability;   
25677 }
25678 
25679 /*! \brief Send a poke to all known peers */
25680 static void sip_poke_all_peers(void)
25681 {
25682    int ms = 0, num = 0;
25683    struct ao2_iterator i;
25684    struct sip_peer *peer;
25685 
25686    if (!speerobjs)   /* No peers, just give up */
25687       return;
25688 
25689    i = ao2_iterator_init(peers, 0);
25690    while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
25691       ao2_lock(peer);
25692       if (num == global_qualify_peers) {
25693          ms += global_qualify_gap;
25694          num = 0;
25695       } else {
25696          num++;
25697       }
25698       AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched, ms, sip_poke_peer_s, peer,
25699             unref_peer(_data, "removing poke peer ref"),
25700             unref_peer(peer, "removing poke peer ref"),
25701             ref_peer(peer, "adding poke peer ref"));
25702       ao2_unlock(peer);
25703       unref_peer(peer, "toss iterator peer ptr");
25704    }
25705    ao2_iterator_destroy(&i);
25706 }
25707 
25708 /*! \brief Send all known registrations */
25709 static void sip_send_all_registers(void)
25710 {
25711    int ms;
25712    int regspacing;
25713    if (!regobjs)
25714       return;
25715    regspacing = default_expiry * 1000/regobjs;
25716    if (regspacing > 100)
25717       regspacing = 100;
25718    ms = regspacing;
25719    ASTOBJ_CONTAINER_TRAVERSE(&regl, 1, do {
25720       ASTOBJ_WRLOCK(iterator);
25721       ms += regspacing;
25722       AST_SCHED_REPLACE_UNREF(iterator->expire, sched, ms, sip_reregister, iterator, 
25723                         registry_unref(_data, "REPLACE sched del decs the refcount"),
25724                         registry_unref(iterator, "REPLACE sched add failure decs the refcount"),
25725                         registry_addref(iterator, "REPLACE sched add incs the refcount"));
25726       ASTOBJ_UNLOCK(iterator);
25727    } while (0)
25728    );
25729 }
25730 
25731 /*! \brief Send all MWI subscriptions */
25732 static void sip_send_all_mwi_subscriptions(void)
25733 {
25734    ASTOBJ_CONTAINER_TRAVERSE(&submwil, 1, do {
25735       ASTOBJ_WRLOCK(iterator);
25736       AST_SCHED_DEL(sched, iterator->resub);
25737       if ((iterator->resub = ast_sched_add(sched, 1, sip_subscribe_mwi_do, ASTOBJ_REF(iterator))) < 0) {
25738          ASTOBJ_UNREF(iterator, sip_subscribe_mwi_destroy);
25739       }
25740       ASTOBJ_UNLOCK(iterator);
25741    } while (0));
25742 }
25743 
25744 /*! \brief Reload module */
25745 static int sip_do_reload(enum channelreloadreason reason)
25746 {
25747    time_t start_poke, end_poke;
25748    
25749    reload_config(reason);
25750    ast_sched_dump(sched);
25751 
25752    start_poke = time(0);
25753    /* Prune peers who still are supposed to be deleted */
25754    ao2_t_callback(peers, OBJ_NODATA | OBJ_UNLINK | OBJ_MULTIPLE, peer_is_marked, NULL,
25755          "callback to remove marked peers");
25756    
25757    ast_debug(4, "--------------- Done destroying pruned peers\n");
25758 
25759    /* Send qualify (OPTIONS) to all peers */
25760    sip_poke_all_peers();
25761 
25762    /* Register with all services */
25763    sip_send_all_registers();
25764 
25765    sip_send_all_mwi_subscriptions();
25766 
25767    end_poke = time(0);
25768    
25769    ast_debug(4, "do_reload finished. peer poke/prune reg contact time = %d sec.\n", (int)(end_poke-start_poke));
25770 
25771    ast_debug(4, "--------------- SIP reload done\n");
25772 
25773    return 0;
25774 }
25775 
25776 /*! \brief Force reload of module from cli */
25777 static char *sip_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
25778 {
25779    
25780    switch (cmd) {
25781    case CLI_INIT:
25782       e->command = "sip reload";
25783       e->usage =
25784          "Usage: sip reload\n"
25785          "       Reloads SIP configuration from sip.conf\n";
25786       return NULL;
25787    case CLI_GENERATE:
25788       return NULL;
25789    }
25790 
25791    ast_mutex_lock(&sip_reload_lock);
25792    if (sip_reloading) 
25793       ast_verbose("Previous SIP reload not yet done\n");
25794    else {
25795       sip_reloading = TRUE;
25796       sip_reloadreason = (a && a->fd) ? CHANNEL_CLI_RELOAD : CHANNEL_MODULE_RELOAD;
25797    }
25798    ast_mutex_unlock(&sip_reload_lock);
25799    restart_monitor();
25800 
25801    return CLI_SUCCESS;
25802 }
25803 
25804 /*! \brief  Part of Asterisk module interface */
25805 static int reload(void)
25806 {
25807    if (sip_reload(0, 0, NULL))
25808       return 0;
25809    return 1;
25810 }
25811 
25812 /*! \brief SIP Cli commands definition */
25813 static struct ast_cli_entry cli_sip[] = {
25814    AST_CLI_DEFINE(sip_show_channels, "List active SIP channels or subscriptions"),
25815    AST_CLI_DEFINE(sip_show_channelstats, "List statistics for active SIP channels"),
25816    AST_CLI_DEFINE(sip_show_domains, "List our local SIP domains"),
25817    AST_CLI_DEFINE(sip_show_inuse, "List all inuse/limits"),
25818    AST_CLI_DEFINE(sip_show_objects, "List all SIP object allocations"),
25819    AST_CLI_DEFINE(sip_show_peers, "List defined SIP peers"),
25820    AST_CLI_DEFINE(sip_show_registry, "List SIP registration status"),
25821    AST_CLI_DEFINE(sip_unregister, "Unregister (force expiration) a SIP peer from the registry"),
25822    AST_CLI_DEFINE(sip_show_settings, "Show SIP global settings"),
25823    AST_CLI_DEFINE(sip_show_mwi, "Show MWI subscriptions"),
25824    AST_CLI_DEFINE(sip_cli_notify, "Send a notify packet to a SIP peer"),
25825    AST_CLI_DEFINE(sip_show_channel, "Show detailed SIP channel info"),
25826    AST_CLI_DEFINE(sip_show_history, "Show SIP dialog history"),
25827    AST_CLI_DEFINE(sip_show_peer, "Show details on specific SIP peer"),
25828    AST_CLI_DEFINE(sip_show_users, "List defined SIP users"),
25829    AST_CLI_DEFINE(sip_show_user, "Show details on specific SIP user"),
25830    AST_CLI_DEFINE(sip_qualify_peer, "Send an OPTIONS packet to a peer"),
25831    AST_CLI_DEFINE(sip_show_sched, "Present a report on the status of the sched queue"),
25832    AST_CLI_DEFINE(sip_prune_realtime, "Prune cached Realtime users/peers"),
25833    AST_CLI_DEFINE(sip_do_debug, "Enable/Disable SIP debugging"),
25834    AST_CLI_DEFINE(sip_set_history, "Enable/Disable SIP history"),
25835    AST_CLI_DEFINE(sip_reload, "Reload SIP configuration"),
25836    AST_CLI_DEFINE(sip_show_tcp, "List TCP Connections")
25837 };
25838 
25839 /*! \brief PBX load module - initialization */
25840 static int load_module(void)
25841 {
25842    ast_verbose("SIP channel loading...\n");
25843    /* the fact that ao2_containers can't resize automatically is a major worry! */
25844    /* if the number of objects gets above MAX_XXX_BUCKETS, things will slow down */
25845    peers = ao2_t_container_alloc(hash_peer_size, peer_hash_cb, peer_cmp_cb, "allocate peers");
25846    peers_by_ip = ao2_t_container_alloc(hash_peer_size, peer_iphash_cb, peer_ipcmp_cb, "allocate peers_by_ip");
25847    dialogs = ao2_t_container_alloc(hash_dialog_size, dialog_hash_cb, dialog_cmp_cb, "allocate dialogs");
25848    threadt = ao2_t_container_alloc(hash_dialog_size, threadt_hash_cb, threadt_cmp_cb, "allocate threadt table");
25849    
25850    ASTOBJ_CONTAINER_INIT(&regl); /* Registry object list -- not searched for anything */
25851    ASTOBJ_CONTAINER_INIT(&submwil); /* MWI subscription object list */
25852 
25853    if (!(sched = sched_context_create())) {
25854       ast_log(LOG_ERROR, "Unable to create scheduler context\n");
25855       return AST_MODULE_LOAD_FAILURE;
25856    }
25857 
25858    if (!(io = io_context_create())) {
25859       ast_log(LOG_ERROR, "Unable to create I/O context\n");
25860       sched_context_destroy(sched);
25861       return AST_MODULE_LOAD_FAILURE;
25862    }
25863 
25864    sip_reloadreason = CHANNEL_MODULE_LOAD;
25865 
25866    if(reload_config(sip_reloadreason)) /* Load the configuration from sip.conf */
25867       return AST_MODULE_LOAD_DECLINE;
25868 
25869    /* Prepare the version that does not require DTMF BEGIN frames.
25870     * We need to use tricks such as memcpy and casts because the variable
25871     * has const fields.
25872     */
25873    memcpy(&sip_tech_info, &sip_tech, sizeof(sip_tech));
25874    memset((void *) &sip_tech_info.send_digit_begin, 0, sizeof(sip_tech_info.send_digit_begin));
25875 
25876    /* Make sure we can register our sip channel type */
25877    if (ast_channel_register(&sip_tech)) {
25878       ast_log(LOG_ERROR, "Unable to register channel type 'SIP'\n");
25879       io_context_destroy(io);
25880       sched_context_destroy(sched);
25881       return AST_MODULE_LOAD_FAILURE;
25882    }
25883 
25884    /* Register all CLI functions for SIP */
25885    ast_cli_register_multiple(cli_sip, ARRAY_LEN(cli_sip));
25886 
25887    /* Tell the RTP subdriver that we're here */
25888    ast_rtp_proto_register(&sip_rtp);
25889 
25890    /* Tell the UDPTL subdriver that we're here */
25891    ast_udptl_proto_register(&sip_udptl);
25892 
25893    /* Register dialplan applications */
25894    ast_register_application_xml(app_dtmfmode, sip_dtmfmode);
25895    ast_register_application_xml(app_sipaddheader, sip_addheader);
25896    ast_register_application_xml(app_sipremoveheader, sip_removeheader);
25897 
25898    /* Register dialplan functions */
25899    ast_custom_function_register(&sip_header_function);
25900    ast_custom_function_register(&sippeer_function);
25901    ast_custom_function_register(&sipchaninfo_function);
25902    ast_custom_function_register(&checksipdomain_function);
25903 
25904    /* Register manager commands */
25905    ast_manager_register2("SIPpeers", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_sip_show_peers,
25906          "List SIP peers (text format)", mandescr_show_peers);
25907    ast_manager_register2("SIPshowpeer", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_sip_show_peer,
25908          "Show SIP peer (text format)", mandescr_show_peer);
25909    ast_manager_register2("SIPqualifypeer", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_sip_qualify_peer,
25910          "Show SIP peer (text format)", mandescr_show_peer);   /*! \todo Fix this XXX This must be all wrong XXXX */
25911    ast_manager_register2("SIPshowregistry", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_show_registry,
25912          "Show SIP registrations (text format)", mandescr_show_registry);
25913    ast_manager_register2("SIPnotify", EVENT_FLAG_SYSTEM, manager_sipnotify,
25914          "Send a SIP notify", mandescr_sipnotify);
25915    sip_poke_all_peers();   
25916    sip_send_all_registers();
25917    sip_send_all_mwi_subscriptions();
25918 
25919    /* And start the monitor for the first time */
25920    restart_monitor();
25921 
25922    ast_realtime_require_field(ast_check_realtime("sipregs") ? "sipregs" : "sippeers",
25923       "name", RQ_CHAR, 10,
25924       "ipaddr", RQ_CHAR, 15,
25925       "port", RQ_UINTEGER2, 5,
25926       "regseconds", RQ_INTEGER4, 11,
25927       "defaultuser", RQ_CHAR, 10,
25928       "fullcontact", RQ_CHAR, 35,
25929       "regserver", RQ_CHAR, 20,
25930       "useragent", RQ_CHAR, 20,
25931       "lastms", RQ_INTEGER4, 11,
25932       SENTINEL);
25933 
25934    return AST_MODULE_LOAD_SUCCESS;
25935 }
25936 
25937 /*! \brief PBX unload module API */
25938 static int unload_module(void)
25939 {
25940    struct sip_pvt *p;
25941    struct sip_threadinfo *th;
25942    struct ast_context *con;
25943    struct ao2_iterator i;
25944 
25945    ast_sched_dump(sched);
25946    
25947    /* First, take us out of the channel type list */
25948    ast_channel_unregister(&sip_tech);
25949 
25950    /* Unregister dial plan functions */
25951    ast_custom_function_unregister(&sipchaninfo_function);
25952    ast_custom_function_unregister(&sippeer_function);
25953    ast_custom_function_unregister(&sip_header_function);
25954    ast_custom_function_unregister(&checksipdomain_function);
25955 
25956    /* Unregister dial plan applications */
25957    ast_unregister_application(app_dtmfmode);
25958    ast_unregister_application(app_sipaddheader);
25959    ast_unregister_application(app_sipremoveheader);
25960 
25961    /* Unregister CLI commands */
25962    ast_cli_unregister_multiple(cli_sip, ARRAY_LEN(cli_sip));
25963 
25964    /* Disconnect from the RTP subsystem */
25965    ast_rtp_proto_unregister(&sip_rtp);
25966 
25967    /* Disconnect from UDPTL */
25968    ast_udptl_proto_unregister(&sip_udptl);
25969 
25970    /* Unregister AMI actions */
25971    ast_manager_unregister("SIPpeers");
25972    ast_manager_unregister("SIPshowpeer");
25973    ast_manager_unregister("SIPqualifypeer");
25974    ast_manager_unregister("SIPshowregistry");
25975    ast_manager_unregister("SIPnotify");
25976    
25977    /* Kill TCP/TLS server threads */
25978    if (sip_tcp_desc.master)
25979       ast_tcptls_server_stop(&sip_tcp_desc);
25980    if (sip_tls_desc.master)
25981       ast_tcptls_server_stop(&sip_tls_desc);
25982 
25983    /* Kill all existing TCP/TLS threads */
25984    i = ao2_iterator_init(threadt, 0);
25985    while ((th = ao2_t_iterator_next(&i, "iterate through tcp threads for 'sip show tcp'"))) {
25986       pthread_t thread = th->threadid;
25987       th->stop = 1;
25988       pthread_kill(thread, SIGURG);
25989       pthread_join(thread, NULL);
25990       ao2_t_ref(th, -1, "decrement ref from iterator");
25991    }
25992    ao2_iterator_destroy(&i);
25993 
25994    /* Hangup all dialogs if they have an owner */
25995    i = ao2_iterator_init(dialogs, 0);
25996    while ((p = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
25997       if (p->owner)
25998          ast_softhangup(p->owner, AST_SOFTHANGUP_APPUNLOAD);
25999       ao2_t_ref(p, -1, "toss dialog ptr from iterator_next");
26000    }
26001    ao2_iterator_destroy(&i);
26002 
26003    ast_mutex_lock(&monlock);
26004    if (monitor_thread && (monitor_thread != AST_PTHREADT_STOP) && (monitor_thread != AST_PTHREADT_NULL)) {
26005       pthread_cancel(monitor_thread);
26006       pthread_kill(monitor_thread, SIGURG);
26007       pthread_join(monitor_thread, NULL);
26008    }
26009    monitor_thread = AST_PTHREADT_STOP;
26010    ast_mutex_unlock(&monlock);
26011 
26012    /* Destroy all the dialogs and free their memory */
26013    i = ao2_iterator_init(dialogs, 0);
26014    while ((p = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
26015       dialog_unlink_all(p, TRUE, TRUE);
26016       ao2_t_ref(p, -1, "throw away iterator result"); 
26017    }
26018    ao2_iterator_destroy(&i);
26019 
26020    /* Free memory for local network address mask */
26021    ast_free_ha(localaddr);
26022 
26023    clear_realm_authentication(authl);
26024 
26025 
26026    if (default_tls_cfg.certfile)
26027       ast_free(default_tls_cfg.certfile);
26028    if (default_tls_cfg.cipher)
26029       ast_free(default_tls_cfg.cipher);
26030    if (default_tls_cfg.cafile)
26031       ast_free(default_tls_cfg.cafile);
26032    if (default_tls_cfg.capath)
26033       ast_free(default_tls_cfg.capath);
26034 
26035    ASTOBJ_CONTAINER_DESTROYALL(&regl, sip_registry_destroy);
26036    ASTOBJ_CONTAINER_DESTROY(&regl);
26037    ASTOBJ_CONTAINER_DESTROYALL(&submwil, sip_subscribe_mwi_destroy);
26038    ASTOBJ_CONTAINER_DESTROY(&submwil);
26039 
26040    ao2_t_ref(peers, -1, "unref the peers table");
26041    ao2_t_ref(peers_by_ip, -1, "unref the peers_by_ip table");
26042    ao2_t_ref(dialogs, -1, "unref the dialogs table");
26043    ao2_t_ref(threadt, -1, "unref the thread table");
26044 
26045    clear_sip_domains();
26046    ast_free_ha(global_contact_ha);
26047    close(sipsock);
26048    sched_context_destroy(sched);
26049    con = ast_context_find(used_context);
26050    if (con)
26051       ast_context_destroy(con, "SIP");
26052    ast_unload_realtime("sipregs");
26053    ast_unload_realtime("sippeers");
26054 
26055    return 0;
26056 }
26057 
26058 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, "Session Initiation Protocol (SIP)",
26059       .load = load_module,
26060       .unload = unload_module,
26061       .reload = reload,
26062           );